How To Access Data In A Class Within A Class With VB.NET - vb.net

I am relatively new to VB.NET Classes that define data structures. Also the terminology is a little unfamiliar.
I have defined the following Class structures:
Public Class CatalogInfoDef
Public CatalogName As String
Public CatalogYear As String
Public CatalogNumber As String
End Class
Public Class ParameterDef
Public Country As String
Public GeographicArea As String
Public Catalogs As List(Of CatalogInfoDef)
Public Class IssueDate
Public Month As String
Public Day As String
Public Year As String
End Class
Public Class Size
Public Width As String
Public Height As String
End Class
Public Printer As String
Public SearchKeywords As List(Of String)
Public Class OtherInfo
Public Condition As String
Public PrintMethod As String
End Class
End Class
In the Main Form I have the definition: Private ParameterInfo as New ParameterDef
I am able to insert data into the fields that are in the main Class, Country, etc.. However, I am having problems inserting data into fields such as: IssueDate (Month, Day, Year).
How do I access the data in these Class fields? Am I missing some parameter? Is there a better way to define ParameterDef?

What you're doing is defining classes within a class when it sounds like you want to define a property of a custom class. Something more along the lines of:
Public Class ParameterDef
Public Property Country As String
Public Property GeographicArea As String
Public Property Catalogs As List(Of CatalogInfoDef)
Public Property IssueDate As DateTime
Public Property Size As Size
Public Property Printer As String
Public Property SearchKeywords As List(Of String)
Public Property OtherInfo As OtherInfo
End Class
Public Class OtherInfo
Public Condition As String
Public PrintMethod As String
End Class
Then when you go to set the properties it would be:
Private ParameterInfo as New ParameterDef() With {
.Country = "...",
.GeographicArea = "..."
.Catalogs = New CatalogInfoDef() With {
.CatalogName = "...",
.CatalogYear = "...",
.CatalogNumber = "..."
},
.IssueDate = New DateTime(year, month, day) ' replace with actual values
.Size = New Size(width, height) ' replace with actual values
.Printer = "...",
.SearchKeywords = New List(Of String)(),
.OtherInfo = New OtherInfo() With {
.Condition = "...",
.PrintMethod = "..."
}
}
Also, notice how I removed your custom Date and Size class. This is because those classes already exist in the System and System.Drawing namespaces respectively.

Related

SQL query works in navicat but not work in vb.net

I am trying to get data using GROUP BY statement:
SELECT nama_penerbit
FROM DigitalBook.digitalbook.ebook
ORDER BY nama_penerbit
and store this value.
Using navicat
but did not get the value when I try to get in controller in VB.NET:
<Route("api/Ebooks/GetAllPenerbit")>
<HttpGet>
Function GetAllPenerbit() As Results.JsonResult(Of List(Of ebook))
Dim kategoriEbookRepository As New EbookReposity
Dim d = kategoriEbookRepository.PenerbitEbookRepository()
Return Json(d)
End Function
This is my model class:
Public Function PenerbitEbookRepository() As List(Of ebook)
Dim sql = "Select nama_penerbit From Digitalbook.digitalbook.ebook Group by nama_penerbit"
Dim datas As New List(Of ebook)
Try
datas = db.Database.SqlQuery(Of ebook)(sql).ToList
Catch ex As Exception
End Try
Return datas
End Function
This is my class
<Table("digitalbook.ebook")>
Partial Public Class ebook
<Key>
<StringLength(50)>
Public Property id_ebook As String
<StringLength(500)>
Public Property judul As String
Public Property id_kategori_ebook As Guid?
<StringLength(255)>
Public Property pengarang As String
<StringLength(255)>
Public Property nama_penerbit As String
End Class
i created a new class with the same property, then i used it on controller and model, it works fine
This is my new class
Partial Public Class getebook
Public Property id_ebook As String
Public Property judul As String
Public Property id_kategori_ebook As Guid?
Public Property pengarang As String
Public Property nama_penerbit As String
End Class
My Controller
<Route("api/Ebooks/GetAllPenerbit")>
<HttpGet>
Function GetAllPenerbit() As Results.JsonResult(Of List(Of getebook))
Dim kategoriEbookRepository As New EbookReposity
Dim d = kategoriEbookRepository.PenerbitEbookRepository()
Return Json(d)
End Function
My Model
Public Function PenerbitEbookRepository() As List(Of getebook)
Dim sql = "Select Distinct nama_penerbit From Digitalbook.digitalbook.ebook"
Dim datas As New List(Of getebook)
Try
datas = db.Database.SqlQuery(Of getebook)(sql).ToList
Catch ex As Exception
End Try
Return datas
End Function

VB.NET Json request

Having some trouble trying to convert my json data to something usable
my json data
{
"4": {
"name": "Warehouse",
"tenantcode": "242",
"package_id": 1,
"package": "package10",
"ext_length": 4,
"country_id": 91,
"country_code": 61
},
"5": {
"name": "Partners",
"tenantcode": "240",
"package_id": 1,
"package": "package10",
"ext_length": 4,
"country_id": 91,
"country_code": 61
},
"8": {
"name": "Systems",
"tenantcode": "241",
"package_id": 20,
"package": "Systems",
"ext_length": 4,
"country_id": 91,
"country_code": 61
},
VB code
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim json2 As String = (New WebClient).DownloadString("https://myapi")
Dim json As String = json2
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "Name"
this is a far as i got.
i need to know whats the best was to try and use my json data.
build a new class?
Yes, you should build a new class. The data you provided can be deserialized as a Dictionary, so you'd just have to make a class for the details.
Public Class Details
Public Property Name As String
Public Property Tenantcode As String
Public Property Package_id As Integer
Public Property Package As String
Public Property Ext_length As Integer
Public Property Country_id As Integer
Public Property Country_code As Integer
End Class
Then simply deserialize your data into a Dictionary(String, Details)
Dim data = JsonConvert.DeserializeObject(Of Dictionary(Of String, Details))
Visual Studio has a cool feature called Paste JSON as Classes that can be found under Edit > Paste Special > Paste JSON as Classes. If you were to do this, then you would get something that looks like the following:
Public Class Rootobject
Public Property _4 As _4
Public Property _5 As _5
End Class
Public Class _4
Public Property name As String
Public Property tenantcode As String
Public Property package_id As Integer
Public Property package As String
Public Property ext_length As Integer
Public Property country_id As Integer
Public Property country_code As Integer
End Class
Public Class _5
Public Property name As String
Public Property tenantcode As String
Public Property package_id As Integer
Public Property package As String
Public Property ext_length As Integer
Public Property country_id As Integer
Public Property country_code As Integer
End Class
Since the Rootobject is basically acting like an associative array (in PHP) or dictionary (in .NET), then what I would do is get rid of Rootobject and _4, and rename _5 to be something a little more generic. Also, you can use decorators to make the property names conform to a more .NET style if you wanted:
Public Class Record
<JsonProperty("name")>
Public Property Name As String
<JsonProperty("tenantcode")>
Public Property TenantCode As String
<JsonProperty("package_id")>
Public Property PackageId As Integer
<JsonProperty("package")>
Public Property Package As String
<JsonProperty("ext_length")>
Public Property ExtLength As Integer
<JsonProperty("country_id")>
Public Property CountryId As Integer
<JsonProperty("country_code")>
Public Property CountryCode As Integer
End Class
Now what you'd do is create your webclient, download the string, and use DeserializeObject to convert the associative array to a dictionary:
Dim records As Dictionary(Of Integer, Record)
Using client As New WebClient()
Dim payload As String = client.DownloadString("https://myapi")
records = JsonConvert.DeserializeObject(Of Dictionary(Of Integer, Record))(payload)
End Using
Now you can get the object by it's key and access it's properties. E.g.:
If (records.ContainsKey(4)) Then
Console.WriteLine(records(4).Name)
End If

Refer to a Class from within a With VB.net

I have called clientdetails which I wish to return as a whole to the JSONConvert Method to Serialize for JSON.
I have created a Class that has the Property Types I require (TextA,TextB) etc.
I can refer to both TransactionCount and TransactionType because they are part of ClientDetails, however when I try to refer to TextA of Transactions it states that TextA is not a member of ClientDetails - this I know which is why I explicitly state .Transactions.TextA.
If I declare Transactions separate under a new variable then I am able to refer to them however I need them to all be declared under ClientDetails to pass to the Serializer.
Can anyone point me out what I'm doing wrong here? Still learning.
Public Class JSON
Public Shared Function SerializeObject()
Dim clientdetails As New ClientDetails() With {.TransactionCount = "1", .TransactionType = "Q", .Transactions.TextA} 'Unable to Refer to any Property of Transactions.
'Dim Trans As New Transactions()
'Trans.TextA= "Test"
Dim output As String = JsonConvert.SerializeObject(clientdetails, Newtonsoft.Json.Formatting.Indented)
Return output
End Function
End Class
Public Class ClientDetails
Public Property Transactions As New Transactions()
Public Property [TransactionType] As String
Public Property [TransactionCount] As Integer
End Class
Public Class Transactions
Public Property [RecordID] As String
Public Property No As String
Public Property TextA As String
Public Property TextB As String
Public Property Initial As String
Public Property Flag As String
Public Property Sex As String
Public Property Area As String
Public Property Type As String
Public Property IDNO As String
End Class
You can use this syntax:
Dim clientdetails As New ClientDetails() With {.TransactionCount = "1", .TransactionType = "Q", .Transactions = New Transactions() With {.TextA = "Test"}}
Or a more readable code:
Dim trans As New Transactions
trans.TextA = "Test"
Dim clientDetails As New ClientDetails()
With clientDetails
.TransactionCount = "1"
.TransactionType = "Q"
.Transactions = trans
End With

Code to for AutoMapper complex mapping

AutoMapper with VB.NET
I have the following classes below. OrderA With List (Of OrderALineItem) and OrderBList With List (Of OrderB). I want to copy data from OrderA to OrderBList. Which copies ItemName, ItemQty, Price from List (Of OrderALineItem) to List (Of OrderB) and OrderID, CustomerName from OrderA itself. I have found almost all codes in C# and am not able to convert it to vb.net code.
Public Class OrderA
Public Property OrderID As String
Public Property CustomerName As String
Public Property OrderLineItem As List(Of OrderALineItem)
End Class
Public Class OrderALineItem
Public Property ItemName As String
Public Property ItemQty As Integer
Public Property Price As Decimal
End Class
Public Class OrderBList
Public Property OrderBLineItem As List(Of OrderB)
End Class
Public Class OrderB
Public Property OrderID As String
Public Property CustomerName As String
Public Property ItemName As String
Public Property ItemQty As Integer
Public Property Price As Decimal
End Class
My VB.NET code until now is:
Dim mapperConfiguration = New MapperConfiguration(Sub(config)
config.CreateMap(Of OrderALineItem, OrderBList)()
End Sub)
Dim mapper = mapperConfiguration.CreateMapper()
Dim objOrderB = mapper.Map(Of OrderBList)(objOrder.OrderLineItem)
The above code creates and object from copies the data from objOrder.OrderLineItem to OrderBList. That's it.
Can anybody help me out on this in VB.NET.
Note: Am totally new in AutoMapper
Version: AutoMapper 6.2.2.0
Done myself, I hope the code below will be helpful to somebody.
Dim mapperConfiguration = New MapperConfiguration(Sub(config)
config.AddProfile(New CustomProfile_1)
End Sub)
Dim objMapper = mapperConfiguration.CreateMapper()
Dim objOrderB As List(Of Dest_OrderB) = objMapper.Map(Of Src_OrderA, List(Of Dest_OrderB))(objOrderA)
Public Class CustomProfile_1
Inherits Profile
Sub New()
CreateMap(Of Src_OrderALineItem, Dest_OrderB)()
CreateMap(Of Src_OrderA, List(Of Dest_OrderB))() _
.ConstructProjectionUsing(
Function(Src1) Src1.List_Src_OrderALineItem.Select(Function(Src2) New Dest_OrderB _
With {.CustomerName = Src1.CustomerName,
.OrderID = Src1.OrderID,
.ItemName = Src2.ItemName,
.ItemQty = Src2.ItemQty,
.Price = Src2.Price}
).ToList())
End Sub
End Class

Assign direct value to object

I have several properties, for example
Public Property FIRSTNAME As New SQLString("FirstName", 50)
Public Property FULLNAME As New SQLString("Name", 50)
The SQLString object is defined as:
Public Class SQLString
Property SQL_Column As String
Property Limit As Integer
Property Value As String
Public Sub New(SQLcolumn As String, limit_ As Integer)
SQL_Column = SQLcolumn
Limit = limit_
End Sub
Public ReadOnly Property SQL_value() As String
Get
Return "'" & clean(Value, Limit) & "'"
End Get
End Property
End Class
Notice that through this method, each of my properties (e.g. FIRSTNAME) is able to have several sub properties, which is necessary.
To access them, it's simply for example FIRSTNAME.SQL_Column.
This works, however what I would like is to also be able to store a value (e.g. string data type) on the FIRSTNAME property itself, which would make accessing it like:
Dim MyFirstName As String = FIRSTNAME
Rather than:
Dim MyFirstName As String = FIRSTNAME.Value
Which is what I currently have to do.
The only way I can see to do this is to have the SQLString object be set to string (or another data type) by default, like:
Public Class SQLString As String
Obviously the above code does not work, but I'm wondering if there is an equivalent that does?
The default access modifier to a property (ie: Public, Private, etc) is the most restrictive when no access modifier is provided. In SQLString class, since there is not a Public access modifier in front of the properties in the class, they are essentially Private and not accessible from outside of the class.
Adding the access modifier to the properties should fix the issue you see:
Public Property SQL_Column As String
Public Property Limit As Integer
Public Property Value As String
Please tell me the problem for the vote downs - here is a working .NET fiddle of the proposed code changes above (https://dotnetfiddle.net/96o8qm).
Imports System
Dim p as Person = new Person()
p.FIRSTNAME = new SQLString("Test", 1)
p.FIRSTNAME.Value = "Test Value"
Console.WriteLine("Person Value: {0}", p.FIRSTNAME.Value)
Public Class Person
Public Property FIRSTNAME AS SQLString
End Class
Public Class SQLString
Public Property SQL_Column As String
Public Property Limit As Integer
Public Property Value As String
Public Sub New(SQLcolumn As String, limit_ As Integer)
SQL_Column = SQLcolumn
Limit = limit_
End Sub
Public ReadOnly Property SQL_value() As String
Get
Return ""
End Get
End Property
End Class
This yields the output:
Person Value: Test Value
The answer to your question is quite simple; add a CType widening operator.
Example:
Public Class SQLString
Public Shared Widening Operator CType(ByVal s As SQLString) As String
Return If((s Is Nothing), Nothing, s.Value)
End Operator
Public Property Value As String
End Class
Test:
Dim firstName As New SQLString() With {.Value = "Bjørn"}
Dim myName As String = firstName
Debug.WriteLine(myName)
Output (immediate window):
Bjørn