Pass property to access using .NET - vb.net

I'm fairly sure this is possible, but what I want to do is have a generic method where I can pass in an object along with a Expression that will tell the method which Property to use in it's logic.
Can anyone get me started on the syntax for something like this?
Essentially what I would like to code is something like:
Dim firstNameMapper as IColumnMapper = new ColumnMapper(of Author)(Function(x) x.FirstName)
Dim someAuthorObject as new Author()
fistNameMapper.Map("Richard", someAuthorObject)
Now the mapper object would know to set the FirstName property to "Richard".
Now using a Function here won't work, I know this... I'm just trying to give an idea what I'm trying to work towards.
Thanks for any help!

You could use expression trees to implement this behavior, but it would be a lot simpler to pass the ColumnMapper a slightly different function. Instead of using expression that reads the property, you could give it a function that sets the value of the property:
Dim firstNameMapper as IColumnMapper = _
new ColumnMapper(of Author)(Sub(x, newValue) _
x.FirstName = newValue _
End Sub)
I think this syntax is new in Visual Studio 2010 (but I'm not a VB expert). Anyway, the type of the parameter would be Action<Author, string> and you could simply invoke it anytime you needed from the ColumnMapper to set the property.
Using expression trees, you'd have to construct expression that sets the property and compile it at runtime, so I think the additional few bits of code above are easier way to solve the problem.

Okay, so I have implemented an analogous solution (i'm not using 2010 so I can't use Tomas' solution directly) but although it compiles, the property does not seem to be set. So here are all the pieces:
Module Module1
Sub Main()
Dim inputSource() As String = {"Richard", "Dawkins"}
Dim firstNameMapper As New ColumnMapper(Of Author)(Function(obj, value) obj.FirstName = value, 0)
Dim lastNameMapper As New ColumnMapper(Of Author)(Function(obj, value) obj.LastName = value, 1)
Dim theAuthor As New Author
firstNameMapper.map(inputSource, theAuthor)
lastNameMapper.map(inputSource, theAuthor)
System.Console.WriteLine(theAuthor.FirstName + " " + theAuthor.LastName)
System.Console.ReadLine()
End Sub
End Module
Public Class ColumnMapper(Of T As {Class})
Dim _propertyMapper As Action(Of T, String)
Dim _columnIndex As Int32
Public Sub New(ByVal mapAction As Action(Of T, String), ByVal columnNumber As Int32)
_propertyMapper = mapAction
_columnIndex = columnNumber
End Sub
Public Sub map(ByVal sourceFields As String(), ByRef destinationObject As T)
_propertyMapper(destinationObject, sourceFields(_columnIndex))
End Sub
End Class
Public Class Author
Private _firstName As String
Private _lastName As String
Public Property FirstName() As String
Get
Return _firstName
End Get
Set (ByVal value As String)
_firstName = value
End Set
End Property
Public Property LastName() As String
Get
Return _lastName
End Get
Set (ByVal value As String)
_lastName = value
End Set
End Property
End Class
Any idea why the property is not being set?

Not sure why the solution using inline 'Function' doesn't work. Perhaps someone more versed in the inner workings of vb.net can explain it, but if you implement the main module as below, it works. Thanks Tomas for pointing me in the right direction!
Module Module1
Sub Main()
Dim mapAction As Action(Of Author, String)
Dim inputSource() As String = {"Richard", "Dawkins"}
Dim firstNameMapper As New ColumnMapper(Of Author)(AddressOf setFirstName, 0)
Dim lastNameMapper As New ColumnMapper(Of Author)(AddressOf setLastName, 1)
Dim theAuthor As New Author
firstNameMapper.map(inputSource, theAuthor)
lastNameMapper.map(inputSource, theAuthor)
System.Console.WriteLine(theAuthor.FirstName + " " + theAuthor.LastName)
System.Console.ReadLine()
End Sub
Public Sub setFirstName(ByVal obj As Author, ByVal value As String)
obj.FirstName = value
End Sub
Public Sub setLastName(ByVal obj As Author, ByVal value As String)
obj.LastName = value
End Sub
End Module

Related

EF marking entities as modified with no changes

Using proxies in EF6.1.3 with the following code (VB.NET): -
Dim DB As New BMContext
Dim sl = DB.StockLevels.First
Dim ee = (From e In DB.ChangeTracker.Entries Where e.Entity Is sl).Single
sl.Level = sl.Level
Checking ee.State before the final line correctly gives a state of Unmodified. After that line it shows as Modified even though the property has been set to what it already was. This even triggers an UPDATE when I call SaveChanges!
Data class code: -
Public Class StockLevel
Public Overridable Property ID As Integer
Public Overridable Property Level As Integer?
End Class
Obviously my actual code is rather a lot more complex as this example is pretty pointless other than demonstrating the problem.
"change-tracking proxies mark a property as modified whenever any value is written to it."
From source
Basically, since you're assigning a value to this property (even though it is the exact same value), you are receiving a Modified state.
I've ended up writing this to call before SaveChanges, although I find it a bit ridiculous that I need to...
Public Class DbEntityModification
Public ReadOnly Property FieldName As String
Public ReadOnly Property OriginalValue As Object
Public ReadOnly Property CurrentValue As Object
Public Sub New(FieldName As String, OriginalValue As Object, CurrentValue As Object)
_FieldName = FieldName
_OriginalValue = OriginalValue
_CurrentValue = CurrentValue
End Sub
End Class
<Extension()> Public Function GetChangedValues(e As DbEntityEntry) As IDictionary(Of String, DbEntityModification)
Dim ret As New Dictionary(Of String, DbEntityModification)
For Each propname In e.CurrentValues.PropertyNames
Dim nv = e.CurrentValues.Item(propname)
Dim ov = e.OriginalValues.Item(propname)
Dim Changed = False
If ov Is Nothing Then
Changed = nv IsNot Nothing
ElseIf Not ov.Equals(nv) Then
Changed = True
End If
If Changed Then
Dim m As New DbEntityModification(propname, ov, nv)
ret.Add(propname, m)
End If
Next
Return ret
End Function
<Extension()> Public Sub MarkUnchangedAnyUnchangedEntities(ees As IEnumerable(Of DbEntityEntry))
For Each ee In ees
If ee.State = EntityState.Modified Then
If GetChangedValues(ee).Keys.Count = 0 Then
ee.State = EntityState.Unchanged
End If
End If
Next
End Sub
<Extension()> Public Sub MarkUnchangedAnyUnchangedEntities(context As DbContext)
context.ChangeTracker.Entries.MarkUnchangedAnyUnchangedEntities()
End Sub

Create Custom Class Dynamically

I am working on a project where I need to create a multitude of custom classes to interact properly with an API (While I know there might be questions on why, and such, but the short is it has to be this way).
Is there a way to create a complete custom class dynamically on the fly? So instead of
class person
Private _Height
Property Height As Integer
Get
Return _Height
End Get
Set(value As Integer)
_Height = value
End Set
End Property
'Continue for all properties of person
I would like to be able to create a new object and through other input create this dynamically.
dim NewClass as object
dim NewProperty as property
NewProperty.name="Height"
NewProperty.datatype=string
NewClass.AddProperty(NewProperty)
Is this possible? It would save me a lot of time if it is.
I don't like late binding but there are options (I like my option strict on). Like using the DynamicObject or the ExpandoObject class. Your question is vague so I have no idea if it can work.
Sub Main()
Dim test As Object = New SampleDynamicClass()
test.SomeProperty = "123"
Console.WriteLine(test.SomeProperty)
Console.ReadLine()
End Sub
Public Class SampleDynamicClass
Inherits DynamicObject
Private _values As New Dictionary(Of String, String)
Public Sub New()
End Sub
Public Function GetPropertyValue(ByVal propertyName As String) As String
Return _values(propertyName)
End Function
Public Function SetPropertyValue(ByVal propertyName As String, ByVal value As Object) As Boolean
If _values.ContainsKey(propertyName) Then
_values(propertyName) = value.ToString()
Else
_values.Add(propertyName, value.ToString())
End If
Return True
End Function
Public Overrides Function TryGetMember(ByVal binder As GetMemberBinder,
ByRef result As Object) As Boolean
result = GetPropertyValue(binder.Name)
Return If(result Is Nothing, False, True)
End Function
Public Overrides Function TryInvokeMember(ByVal binder As InvokeMemberBinder,
ByVal args() As Object,
ByRef result As Object) As Boolean
result = GetPropertyValue(binder.Name)
Return If(result Is Nothing, False, True)
End Function
Public Overrides Function TrySetMember(binder As SetMemberBinder, value As Object) As Boolean
Return SetPropertyValue(binder.Name, value)
End Function
Dim person = New With {Key .Height = 12}
Dim personTypes = New With {Key .Happy = 1, .Sad = 2}
Dim personsAndTypes = New With {Key .Person = person, .Type = personTypes}
The question is kind of vague, but if you have no need for other fields and methods, or reuse Anonymous Types

Detecting or preventing assignment operator to a class

Is there any way to make a class can be only initialized at declaration.
Public Class AnyValue
Private value As Int32
Public Sub New(ByVal aValue As Int32)
value = aValue
End Sub
End Class
'I want to be able to do this:
Dim val As New AnyValue(8)
'But not this.
val = New AnyValue(9)
Or it is possible to stop the assignment or detect when the operator = is used.
Lets just say this - No, you can't do what you want. The closest thing to it that I can think of, is to hide the constructor and give static access to the consumer as follows:
Public Class AnyValue
Private value As Int32
Private Sub New(ByVal aValue As Int32) ' Note - private constructor
value = aValue
End Sub
Public Shared Function Create(ByVal aValue As Int32) As AnyValue
Return New AnyValue(aValue)
End Function
End Class
'This will not work
Dim val As New AnyValue(8)
'This will not work
val = New AnyValue(9)
' This will work
Dim val As AnyValue = AnyValue.Create(8)
Now, if you look at this method of object creation, you can see that you can set all sort of rules for object construction. So, the client has very little input on the construction itself because how you construct the object is totally controlled by the object itself.

Casting substrings with linq into a list of object and than sorting it base on property in vb.net

This have to be in vb.net linq, i'm pretty sure I could do it in c#, but I cant find any good enough translator to help me ... even the answers I find here in SO seems to only be written in linq, hence the question which might be a duplicate of a c# one.
That being said, considering these 2 classes :
Public class User
Public Property Name() As String
Public Property Teams As TeamList
Public sub New(d as string, results as TeamList)
me.name = d
me.Teams = results
end sub
end class
Public Class TeamList
Public Property TeamName() As String
Public Property fullscore() As list(of object)
Public sub New(name as string, value as list(of string))
me.TeamName = name
me.fullscore = value
me.fullscore = getFullScore(value) (return a list of object)
end sub
End Class
I'm struggling in the final steps of my linq -to - object : (you can copy /paste this in linqpad)
Sub Main
dim Definition as new Dictionary(of String, object)
definition.add("user1_redTeam-02", new object)
definition.add("user1_redTeam-01", new object)
definition.add("user1_blueTeam-03", new object)
definition.add("user2_redTeam-01", new object)
definition.add("user1_redTeam-03", new object)
definition.add("user1_blueTeam-01",new object)
definition.add("user2_blueTeam-01", new object)
definition.add("user1_blueTeam-02", new object)
definition.add("user2_redTeam-02", new object)
Dim q3 = (From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_")(0)) _
Select New With _
{.UserName = userlists.Key, _
.animationList = (From scList In userlists.GroupBy(Of String)(Function(s) s.Split("-")(0)) _
Select New With {.Team = scList.Key, _
.Score = scList.ToList()})})
q3.dump()
End Sub
this is the result :
now, all I want is to sort the .score attribute (just a simple .sort(), and instead of returning an anonymous q3 object, which I,m cluless to transform, I'd like the q3 to be a list(of User)
it think it should looks like this ... but I cant make it works, i always gets some linq conversion errors :
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Linq.IGrouping2[System.String,System.String],UserQuery+User]' to type 'System.Collections.Generic.List`1[UserQuery+User]'.
Dim q3 as List(of User)= (From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_")(0)) _
Select New User(userlists.Key, (From scList In userlists.GroupBy(Of String)(Function(s) s.Split("-")(0)) _
Select New TeamList(scList.Key, scList.ToList()))))
Your code examples seem to be incorrect - for example, it seems like User.Teams should be a list of some type, not a TeamList object, which isn't really a list. Anyway, with a little modification, this is what I came up with - maybe it's close to what you were looking for (a list of users with the scores sorted). You can paste into LINQPad to run it.
Sub Main
Dim Definition As New Dictionary(of String, Object)
definition.add("user1_redTeam-02", New Object)
definition.add("user1_redTeam-01", New Object)
definition.add("user1_blueTeam-03", New Object)
definition.add("user2_redTeam-01", New Object)
definition.add("user1_redTeam-03", New Object)
definition.add("user1_blueTeam-01",New Object)
definition.add("user2_blueTeam-01", New Object)
definition.add("user1_blueTeam-02", New Object)
definition.add("user2_redTeam-02", New Object)
Dim q3 = (
From userlists In Definition.Keys.GroupBy(Function(s) s.Split("_"c)(0))
Select New User(
userlists.Key,
(From scList In userlists.GroupBy(Function(s) s.Split("-"c)(0))
Select New Team(scList.Key.Split("_"c)(1), scList.OrderBy(Function(s) s).ToList())).ToList()
)
).ToList()
q3.dump()
End Sub
' Define other methods and classes here
Public class User
Public Property Name() As String
Public Property Teams() As List(Of Team)
Public Sub New(d As String, results As List(Of Team))
Me.Name = d
Me.Teams = results
End Sub
End Class
Public Class Team
Public Property TeamName() As String
Public Property FullScore() As List(Of String)
Public Sub New(name As String, value As List(Of String))
Me.TeamName = name
Me.FullScore = value
End Sub
End Class

VB.NET CType: How do I use CType to change an object variable "obj" to my custom class that I reference using a string variable like obj.GetType.Name?

The code below works for the class that I hard coded "XCCustomers" in my RetrieveIDandName method where I use CType. However, I would like to be able to pass in various classes and property names to get the integer and string LIST returned. For example, in my code below, I would like to also pass in "XCEmployees" to my RetrieveIDandName method. I feel so close... I was hoping someone knew how to use CType where I can pass in the class name as a string variable.
Note, all the other examples I have seen and tried fail because we are using Option Strict On which disallows late binding. That is why I need to use CType.
I also studied the "Activator.CreateInstance" code examples to try to get the class reference instance by string name but I was unable to get CType to work with that.
When I use obj.GetType.Name or obj.GetType.FullName in place of the "XCCustomers" in CType(obj, XCCustomers)(i)
I get the error "Type 'obj.GetType.Name' is not defined" or "Type 'obj.GetType.FullName' is not defined"
Thanks for your help.
Rick
'+++++++++++++++++++++++++++++++
Imports DataLaasXC.Business
Imports DataLaasXC.Utilities
Public Class ucCustomerList
'Here is the calling method:
Public Sub CallingSub()
Dim customerList As New XCCustomers()
Dim customerIdAndName As New List(Of XCCustomer) = RetrieveIDandName(customerList, "CustomerId", " CustomerName")
'This code below fails because I had to hard code “XCCustomer” in the “Dim item...” section of my RetrieveEmployeesIDandName method.
Dim employeeList As New XCEmployees()
Dim employeeIdAndName As New List(Of XCEmployee) = RetrieveIDandName(employeeList, "EmployeeId", " EmployeeName")
'doing stuff here...
End Sub
'Here is the method where I would like to use the class name string when I use CType:
Private Function RetrieveIDandName(ByVal obj As Object, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
Dim selectedItems As List(Of IntStringPair) = New List(Of IntStringPair)
Dim fullyQualifiedClassName As String = obj.GetType.FullName
Dim count As Integer = CInt(obj.GetType().GetProperty("Count").GetValue(obj, Nothing))
If (count > 0) Then
For i As Integer = 0 To count - 1
'Rather than hard coding “XCCustomer” below, I want to use something like “obj.GetType.Name”???
Dim Item As IntStringPair = New IntStringPair(CInt(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerId").GetValue(CType(obj, XCCustomers)(i), Nothing)), _
CStr(CType(obj, XCCustomers)(i).GetType().GetProperty("CustomerName").GetValue(CType(obj, XCCustomers)(i), Nothing)))
selectedItems.Add(Item)
Next
End If
Return selectedItems
End Function
End Class
'+++++++++++++++++++++++++++++++
' Below are the supporting classes if you need to see what else is happening:
Namespace DataLaasXC.Utilities
Public Class IntStringPair
Public Sub New(ByVal _Key As Integer, ByVal _Value As String)
Value = _Value
Key = _Key
End Sub
Public Property Value As String
Public Property Key As Integer
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomer
Public Property CustomerId As Integer
Public Property CustomerName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCCustomers
Inherits List(Of XCCustomer)
Public Sub New()
PopulateCustomersFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployee
Public Property EmployeeId As Integer
Public Property EmployeeName As String
End Class
End Namespace
'+++++++++++++++++++++++++++++++
Namespace DataLaasXC.Business
Public Class XCEmployees
Inherits List(Of XCEmployee)
Public Sub New()
PopulateEmployeesFromDatabase()
End Sub
Public Sub New(ByVal GetEmpty As Boolean)
End Sub
End Class
End Namespace
From MSDN
CType(expression, typename)
. . .
typename : Any expression that is legal
within an As clause in a Dim
statement, that is, the name of any
data type, object, structure, class,
or interface.
This is basically saying you can't use CType dynamically, just statically. i.e. At the point where the code is compiled the compiler needs to know what typename is going to be.
You can't change this at runtime.
Hope this helps.
Since List(Of T) implements the non-generic IList interface, you could change your function declaration to:
Private Function RetrieveIDandName(ByVal obj As System.Collections.IList, ByVal idPropName As String, ByVal namePropName As String) As List(Of IntStringPair)
And then your troublesome line would become (with also using the property name parameters):
Dim Item As IntStringPair = New IntStringPair(CInt(obj(i).GetType().GetProperty(idPropName).GetValue(obj(i), Nothing)), _
CStr(obj(i).GetType().GetProperty(namePropName).GetValue(obj(i), Nothing)))
Of course, you could still have the first parameter by Object, and then attempt to cast to IList, but that's up to you.
ctype is used to convert in object type.