I am running from a problem while iterating over class properties.
I have my first class:
class Item
private _UIN as integer = 0
private _Name as string = ""
private _Category as ItemCategory = new ItemCategory()
public Property UIN() as integer
public property Name() as string
public property Category() as ItemCategory
end class
Now when i iterate over the class properties from following code
Dim AllProps As System.Reflection.PropertyInfo()
Dim PropA As System.Reflection.PropertyInfo
dim ObjA as object
AllProps = new Item().getType().getProperties()
for each propA in AllProps
ObjA = PropA.GetValue(myObj, New Object() {})
debug.write ObjA.GetType().Name
next
I get UIN, Name, ItemCategory but i expected UIN, Name and Category.
I am a bit unclear about this and dun know why this is happening? What should i do to correct it?
I get UIN, Name, ItemCategory
That doesn't make sense. You're retrieving the names of the underlying type of the property, you should've gotten something like System.String, System.Int32 and ItemCategory.
If it's the property names you're after, you can just use PropertyInfo.Name, in your case:
AllProps = new Item().getType().getProperties()
for each propA in AllProps
debug.write propA.Name
next
Related
I have a class object which looks like this:
Public Class item
Public Property ID
Public Property Name
Public Property Description
Public Property Type
Public Property Alias
End Class
I am currently storing these as a dictionary like this:
Public Class Items
Public ReadOnly dict Dictionary(Of String, item) From {
{"A", New item With {.Name = "Object A", .Description = "Object A description"}},
{"B", New item With {.Name = "Object B", .Description = "Object B description"}},
{"C", New item With {.Alias = "A"}}
}
Public Function GetItem(ByVal ID As String) As item
Return If(dict.ContainsKey(ID), idct.Item(ID), Nothing)
End Function
End Class
The complexity is that sometimes an item will not have any properties itself but instead has an .Alias property which says "All of my properties are the same as item with this ID, check that object instead".
How should I write my class object item so that this code returns "Object A":
Dim newItem As item = GetItem("C")
Debug.WriteLine(item.Name)
Object C is an alias of Object A so I should return some properties (not always all of them) for Object A instead of Nothing.
A way around this is by adding the below function to the Items class:
Public Function GetItemDescription(ByVal ID As String) As String
If dict.ContainsKey(ID) Then
If dict.Item(ID).Description = "" Then
Return GetItemDescription(dict.Item(ID).Alias)
Else
Return dict.Item(ID).Description
End If
Else
Return ""
End If
End Function
However this doesn't feel like the correct way as then I have to repeatedly call a set of Items.GetPropertyXYZ functions rather than directly referencing the object (e.g. item.Description would have to be GetItemDescription("C")
Is my solution acceptable from a design persepctive, or is there a better way to achieve this?
Try this:
Public Function GetItem(ByVal [alias] As String) As item
Return dict.Where(Function(a) a.Key = [alias]).Select(Function(b) b.Value).FirstOrDefault
End Function
Edit 1
Certainly it returns the "C" item because its wrong. Sorry.
This one works (Tested):
Public Function GetItem(ByVal ID As String) As item
Dim itm As item = dict.Where(Function(a) a.Key = ID).Select(Function(b) b.Value).FirstOrDefault
Return If(itm IsNot Nothing, If(itm.Alias IsNot Nothing, dict(itm.Alias), itm), Nothing)
End Function
JQSOFT's answer does achieve a similar thing, however I've since realised a more granular way I can achieve the same result.
Private Property _description As String
Public Property Description As String
Get
If _Description = "" Then
If [Alias] IsNot Nothing Then
Return dict.Item([Alias]).Description
Else
Return ""
End If
Else
Return _description
End If
End Get
Set(value As String)
_description = value
End Set
End Property
This way allows me to specify whether I return the data from Object A at property level, rather than returning an entirely different object.
Also, .Alias is a terrible property name as it's also a keyword, I'm going to use .Synonym.
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
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
Is there a way to get value of a object properties with a propertyinfo object?
psudo code:
propertyinfoObject = Text
myobject.toCommand(propertyinfoObject)
The psudo code above should do the same as
myobject.Text
My goal is to create a simpel Properties form that will work on any object (Later I will use keywords to filter out what options I want the use to see).
My real code
Public Class PropertiesForm
Dim propertyInfoVar() As PropertyInfo
Dim Properties As New Form2
Dim listItem As New ListViewItem
Dim stringarray() As String
Public Sub New(ByRef sender As Object)
propertyInfoVar = sender.GetType().GetProperties()
For Each p In propertyInfoVar
stringarray = {p.Name.ToString, #INSERT VALUE SOMEHOW HERE#}
listItem = New ListViewItem(stringarray)
Properties.ListView1.Items.Add(listItem)
Next
Properties.Visible = True
End Sub
EDIT
Just use propertyGrid as suggested below!
The standard PropertyGrid already does all that for you. Filtering properties is not so obvious, here's how:
The control includes a BrowsableAttributes property which allows you to specify that only properties with the specified attribute value should be shown. You can use existing attributes, or custom ones. This is specifically for tagging visible props:
<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyGridBrowsableAttribute
Inherits Attribute
Public Property Browsable As Boolean
Public Sub New(b As Boolean)
Browsable = b
End Sub
End Class
Apply it to an Employee class to hide pay rates or anything else:
Public Class Employee
<PropertyGridBrowsable(True)>
Public Property FirstName As String
...
<PropertyGridBrowsable(False)>
Public Property PayRate As Decimal
<PropertyGridBrowsable(False)>
Public Property NationalInsuranceNumber As String
Test code:
Dim emp As New Employee With {.Dept = EmpDept.Manager,
.FirstName = "Ziggy",
.PayRate = 568.98D,
...
.NationalInsuranceNumber = "1234567"
}
propGrid.BrowsableAttributes = New AttributeCollection(New PropertyGridBrowsableAttribute(True))
propGrid.SelectedObject = emp
BrowsableAttributes is a collection, so you can add several.
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