how to set constructor with List(of Class) parameter - vb.net

Given the scenario where I am building a wrapper for the data I pass to jquery datatables and I have for example, three Classes Orders, OrderDetails and Customers. In datatables, lists of objects are denoted by the variable name aoData, so to construct that I have to pass a List(Of someclass). Since I don't know which class until I pass it how do you do it? is There a GetType that takes the class name as a string? I couldn't find one.
Public Class DataTablesWrapper
Public Sub New(ByRef data As List(Of String))
Me.aaData = data
End Sub
Public Sub New(ByRef data As List(Of some class depending on what data I want wrapped))
Me.aoData = data
End Sub
Public Property aaData As List(Of String)
Public Property aoData As List(Of some class depending on what data I want wrapped)
End Class

I would recommend the use of generics.
In your case it would look like this:
Public Class DataTablesWrapper(Of T)
Public Sub New(ByRef data As List(Of T))
Me.aaData = data
End Sub
Public Property aaData As List(Of T)
End Class
Creating your instance would then look like this:
Sub Main()
Dim stringList As New List(Of String)({"foo", "bar"})
Dim tablesWrapper As New DataTablesWrapper(Of String)(stringList)
End Sub
You don't want to use List(Of Object) due to this reasons.

Related

Bind a detail report to a class model with properties stored in a Dictionary (VB.NET, Devexpress)

I'm trying the example from Devexpress
Dim binding As New XRBinding("Text", dsProducts1, "Products.UnitPrice")
But my models does not have their properties explicitly written in their class. It would take a method GetProperty("column_name_here") to get it's data. I'm wondering if the 3rd parameter of XRBinding can be a method? Like:
Dim binding As New XRBinding("Text", dsProducts1, product.GetProperty("name"))
Additional Info:
All of my model classes extends this Dao class which is responsible in getting data in the database. The Dao class have a protected variable as a Dictionary(Of String, Object) to store the values (key = column name, value = column row value) from the database.
Now when I want to get something in the database, I only call
Dim user As New User // this class extends the Dao class
Dim userId = user.GetProperty("id") // Method to get the value from Dictionary, first parameter is the Dictionary key or column name from the DB
I made this so that I wont have to create every model class and set the properties of that class, as it is kinda cumbersome.
It seems that there are no way to bind to some method. I suggest you to take a look at ExpandoObject dynamic class. The members of this class can be added at runtime. This class implements IDictionary(Of String, Object) interface which you can use to generate properties from your Dictionary(Of String, Object).
Here is example:
Example of base Dao class implementation with protected Dictionary(Of String, Object) property:
Public Class Dao
Private _values As Dictionary(Of String, Object)
Public Sub New()
_values = New Dictionary(Of String, Object)
End Sub
Public Overridable Sub Fill(index As Integer)
_values.Clear()
_values.Add("ID", index)
_values.Add("Product", "Banana " & index)
_values.Add("Price", 123.45 + index)
End Sub
Protected ReadOnly Property Values As Dictionary(Of String, Object)
Get
Return _values
End Get
End Property
End Class
Example of Dao class descendant with DynamicValues property which returns ExpandoObject based on Dictionary(Of String, Object) (you must omit the type of property):
Public Class DynamicDao
Inherits Dao
Private _dynamicValues As ExpandoObject
Public Overrides Sub Fill(index As Integer)
MyBase.Fill(index)
_dynamicValues = New ExpandoObject()
Dim keyValues = DirectCast(_dynamicValues, IDictionary(Of String, Object))
For Each pair In Values
keyValues.Add(New KeyValuePair(Of String, Object)(pair.Key, pair.Value))
Next
End Sub
Public ReadOnly Property DynamicValues ' <= There is no type. In hint is displayed «As Object».
Get
Return _dynamicValues
End Get
End Property
End Class
Usage of DynamicDao class in XtraReport:
Dim list = New List(Of DynamicDao)
For index% = 0 To 9
Dim dao = New DynamicDao()
dao.Fill(index%)
list.Add(dao)
Next
Dim labelID = New XRLabel()
labelID.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.ID"))
Dim labelProduct = New XRLabel()
labelProduct.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.Product"))
labelProduct.LeftF = 50
Dim labelPrice = New XRLabel()
labelPrice.DataBindings.Add(New XRBinding("Text", Nothing, "DynamicValues.Price"))
labelPrice.LeftF = 150
Dim detail = New DetailBand()
detail.Controls.Add(labelID)
detail.Controls.Add(labelProduct)
detail.Controls.Add(labelPrice)
Dim report = New XtraReport()
report.Bands.Add(detail)
report.DataSource = list
report.ShowRibbonPreview()

create a list from a object passed through

Is it possible to create a list ListofOb from the datatype of OB without doing an IF statement to check what object type it is?
Class CustomCLass
Public ListofOb As List(Of Object)
Public Sub New(OB As Object)
ListofOb = New List(Of gettype(OB))
End Sub
End Class

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 Generics "cannot be converted"

For the problem I have these classes:
Public MustInherit Class BaseLeaf(Of T)
Implements IBaseLeaf
// etc
Public Class WebsiteLeaf
Inherits BaseLeaf(Of Headline)
// etc
Public Class WebsiteCollection
Inherits BaseCollection(Of WebsiteLeaf)
// etc
Public Class SubscriptionList
Private mCollection As BaseCollection(Of IBaseLeaf)
Public Sub LoadSubscriptions(ByVal collection As BaseCollection(Of IBaseLeaf))
mCollection = collection
End Sub
In the Main class I am trying to call the following function:
Private Sub FetchSubscriptions(ByVal websites As WebsiteCollection)
gUser.SubscriptionList.LoadSubscriptions(websites)
// code
End Sub
This will access LoadSubscriptions with passing the "websites" variable.
As you can see LoadSubscriptions expects a BaseCollection(Of IBaseLeaf).
The "websites" variable is a WebsiteCollection, which is a BaseCollection(Of WebsiteLeaf(Of Headline)).
Now I am getting the error: Value of type 'WebsiteCollection' cannot be converted to 'BaseCollection(Of IBaseLeaf)'.
What I am doing wrong here?
If class B is a descendent of class A this does not mean that Collection(Of B) is a descendant of Collection(Of A)!
If you have these definitions
Dim stringList As List(Of String)
Public Sub DoSomthingWithList(list As List(Of object))
list.Add(Date.Now)
End Sub
and you could call the method like this
DoSomthingWithList(stringList)
then the method would try to add a Date to the list which is actually a list of strings! Since the parameter is typed as object the date would be boxed (i.e. converted to an object) but not converted to string.
Therefore the collections List(Of X) and List(Of Y) are never compatible, even if Y inherits X.
Let's look at another example
Public Class TestClass
Implements IBaseLeaf
// etc
What happens if you call LoadSubscriptions with a WebsiteCollection?
Public Sub LoadSubscriptions(ByVal collection As BaseCollection(Of IBaseLeaf))
collection.Add(New TestClass())
End Sub

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.