I need to use Reflection for this problem.
Just a simple code needed written in ASP.net and reflection.
Reflection is a must.
Please take a look attached file for more info and example.
I just want to make the code below working. Output does not work as expected! Shows the same result!
Public Class JoinTables
Public Class userz_N_user_roles
Public userz As New userz
Public user_roles As New user_roles
End Class
End Class
Public Class userz
Public Shared id As Nullable(Of Integer) = Nothing
Public user_name As String
Public email_email As String
Public user_pass As String
End Class
Public Class user_roles
Public id As Nullable(Of Integer) = Nothing
Public role_name As String
End Class
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim ArrayList_users As New ArrayList
Dim MyUser1 As New userz
myuser1.email_email = "1#test.com"
myuser1.user_name = "myuser1"
myuser1.user_pass = "mypass1"
ArrayList_users.Add(MyUser1)
Dim ArrayList_roles As New ArrayList
Dim MyUserRoles1 As New user_roles
MyUserRoles1.id = "1"
MyUserRoles1.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles1)
Dim myuser2 As New userz
myuser2.email_email = "2#test.com"
myuser2.user_name = "myuser2"
myuser2.user_pass = "mypass2"
ArrayList_users.Add(myuser2)
Dim MyUserRoles2 As New user_roles
MyUserRoles2.id = "1"
MyUserRoles2.role_name = "Admin"
ArrayList_roles.Add(MyUserRoles2)
'############ REFLECTION PART ###############
Dim MyArrayList As New ArrayList 'for Response
Dim MyJoinTableClass As New JoinTables.userz_N_user_roles
Dim t As Type = MyJoinTableClass.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUser1})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles1})
'MsgBox(MyUser1.user_name)
MyArrayList.Add(MyJoinTableClass)
Dim MyJoinTableClass2 As New JoinTables.userz_N_user_roles
t = MyJoinTableClass2.GetType
t.InvokeMember("userz", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {myuser2})
t.InvokeMember("user_roles", BindingFlags.SetField, Nothing, MyJoinTableClass, New Object() {MyUserRoles2})
MyArrayList.Add(MyJoinTableClass)
Dim filledJoinCls1 As New JoinTables.userz_N_user_roles
filledJoinCls1 = MyArrayList(0)
Dim filledJoinCls1_user1 As New userz
filledJoinCls1_user1 = filledJoinCls1.userz
MsgBox(filledJoinCls1_user1.user_name)
Dim filledJoinCls2 As New JoinTables.userz_N_user_roles
filledJoinCls2 = MyArrayList(1)
Dim filledJoinCls2_user2 As New userz
filledJoinCls2_user2 = filledJoinCls2.userz
MsgBox(filledJoinCls1_user1.user_name & " - " & filledJoinCls2_user2.user_name)
End Sub
Output does not work as expected! Shows the same result!
See below,
public class Employee
{
private long emplNbr;
private string name;
public long EmployeeNumber
{
get { return emplNbr; }
set { emplNbr = value; }
}
public string EmployeeName
{
get { return name; }
set { name = value; }
}
}
Creating an Array of Objects
Employee[] StaffMembers = new Employee[2];
Initializing an Array of Objects
StaffMembers[0] = new Employee();
StaffMembers[0].EmployeeNumber = 20204;
StaffMembers[0].EmployeeName = "Harry Fields";
StaffMembers[1] = new Employee();
StaffMembers[1].EmployeeNumber = 92857;
StaffMembers[1].EmployeeName = "Jennifer Almonds";
Related
Public Class Doc
Public TypeDoc As String = ""
Public Property UserFields As New List(Of UserField)
End Class
Public Class UserField
Property Name As String = ""
Property Value As String = ""
End Class
Public Class Example
Public Sub test()
Dim d As New Doc
d.TypeDoc = "Order"
d.UserFields.Add(New UserField With {.Name = "U_Name", .Value = "Jonny"})
d.UserFields.Add(New UserField With {.Name = "U_Surname", .Value = "Goodman"})
Dim Ret As String = JsonConvert.SerializeObject(d)
End Sub
End Class
Desired result "Ret":
{
"TypeDoc": "Order",
"U_Name": "Jonny",
"U_Surname": "Goodman",
}
I hope you understand the example, I was wondering if it was possible to have this result.
Thank you
This is my simple CodeFile vb code for a username and password login form with a redirect to different 'members area' pages:
Public Class MyPage
Inherits Page
Private Structure Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Structure
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred(){New Cred("userone", "passwordone"), New Cred("usertwo", "passwordtwo"), New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Public Sub Page_Load(sender As Object, e As EventArgs)
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
If user IsNot Nothing Then
Session("Admin") = True
Response.Redirect(user.RedirectUrl)
Else
Session("Admin") = False
LtlLogin.Text = "<p>Sorry, you have provided incorrect login details.</p>"
End If
End Sub
End Class
It's on the line:
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
Thanks very much.
David.
The problem is that you are using structure against class for Cred.
Be aware that structures are value types and classes are reference types.
So:
Dim user = _credentials.SingleOrDefault(Function(x) x.Username = UserName.Text AndAlso x.Password = Password.Text)
always return a structure (when nothing found then the members of the structure gets their default values).
You cannot compare a structure to Nothing as ti is not a reference type.
Change structure to class and you will be fine.
Or change the check with:
If Not user.Equals(New Cred) Then
Check this
UPDATE with examples
Class Cred
Imports System.Linq
Module StartupModule
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred() {
New Cred("userone", "passwordone"),
New Cred("usertwo", "passwordtwo"),
New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Sub Main()
Dim userName As String = ""
Dim password As String = ""
Dim crd = _credentials.Where(Function(x) x.Username = userName AndAlso x.Password = password).SingleOrDefault
If crd Is Nothing Then
Console.WriteLine("user is nothing")
Else
Console.WriteLine("user is something")
End If
Console.ReadLine()
End Sub
Private Class Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Class
End Module
Structure Cred
Imports System.Linq
Module StartupModule
Private ReadOnly _credentials As System.Collections.Generic.IEnumerable(Of Cred) = New Cred() {
New Cred("userone", "passwordone"),
New Cred("usertwo", "passwordtwo"),
New Cred("userthree", "passwordthree", "/admin/custom.aspx")}
Sub Main()
Dim userName As String = ""
Dim password As String = ""
Dim crd = _credentials.Where(Function(x) x.Username = userName AndAlso x.Password = password).SingleOrDefault
If crd.Equals(New Cred) Then
Console.WriteLine("user is nothing")
Else
Console.WriteLine("user is something")
End If
Console.ReadLine()
End Sub
Private Structure Cred
Public Username As String
Public Password As String
Public RedirectUrl As String
Public Sub New(un As String, pw As String, Optional ru As String = "/admin/default.aspx")
Username = un
Password = pw
RedirectUrl = ru
End Sub
End Structure
End Module
In my asp.net web service, I have an object class which get data from database, but I counter the following problem when some data is null in database:
(1) If I don't handle the NULL value in database and use the code as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
.Address = dr("ADDRESS") _
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.
(2) if I handle the NULL in database as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
If dr("ADDRESS") = System.DBNull.Value Then
.Address = ""
Else
.Address = dr("ADDRESS") _
End if
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
Compiler Error Message: BC30985: Name of field or property being initialized in an object initializer must start with '.'.
I want to know how to handle the DBNull value for string and date in an object initializer.
You can use Convert.ToString
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim registerDate As Date
If Date.TryParse(Convert.ToString(dr("REGISTER_DATE")), registerDate ) = False Then
'Do what you need to do if the cell is not a valid date time value
End If
detail = New customerInfo() With { _
.CustomerID = Convert.ToString(dr("CUSTOMER_ID")), _
.CustomerName = Convert.ToString(dr("CUSTOMER_NAME")), _
.RegisterDate = registerDate.ToString("dd/MM/yyyy"), _
.Address = Convert.ToString(dr("ADDRESS"))
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Edited based on OP's comment below.
While the other methods would work, I think a re-usable extension method with generics support would be ideal.
You can pass the work off to the extension method and check if the value is equal to the value of DBNull.Value
Public Module DataRowExtensions
<System.Runtime.CompilerServices.Extension>
Public Function GetValueOrDefault(Of TExpectedType)(dr As DataRow, propertyName As String) As TExpectedType
If DBNull.Value.Equals(dr(propertyName)) Then
Return Nothing
End If
Return DirectCast(dr(propertyName), TExpectedType)
End Function
End Module
You can see this DotNetFiddle to see it in action with various data types.
Do make note that the extension method Field<T> does exist and is similar, but it doesn't handle DBNull values.
You can't use an if statement inside an object initializer like that.
You have to instantiate the object, then set the properties in separate lines.
detail = New customerInfo()
'Then in separate lines, populate the properties individually
If dr("ADDRESS") = System.DBNull.Value Then
detail.Address = ""
Else
detail.Address = dr("ADDRESS")
I keep receiving the following error whenever I try to run my code. Are there any suggestions on what may be causing me to not be able to convert? It seems as though both types are the same, so I'm a little confused on this one.
Value of type 'System.Collections.Generic.List(Of CVE)' cannot be converted to 'System.Collections.Generic.List(Of CVE)'
Error is occurring here:
Dim cveList As List(Of CVE)
cveList = CVERepository.GetInstance.ReadAllCVEs
Here's the CVERepository class:
Public Class CVERepository
Private Sub New()
End Sub
Public Shared ReadOnly Property GetInstance As CVERepository
Get
Static Instance As CVERepository = New CVERepository
Return Instance
End Get
End Property
Public Function ReadAllCVEs() As List(Of CVE)
Dim objAdapter As OleDb.OleDbDataAdapter
Dim dtCVE As New DataTable()
Dim strSQL As String
Dim strConn As String
Dim dvCVE As DataView
strConn = ConnectStringBuild()
strSQL = "Select * From CVE"
objAdapter = New OleDb.OleDbDataAdapter(strSQL, strConn)
objAdapter.Fill(dtCVE)
dvCVE = dtCVE.DefaultView
Dim cveList As New List(Of CVE)
'Put it into an object list to make it more managable.
For index = 0 To dvCVE.Count - 1
Dim cve As New CVE
cve.ID = dvCVE(index)("CVEID")
cve.PublishedDate = dvCVE(index)("PublishedDate")
cve.Availability = dvCVE(index)("Availability")
cve.CVSSScore = dvCVE(index)("CVSSScore")
cve.Confidentiality = dvCVE(index)("Confidentiality")
cve.Integrity = dvCVE(index)("Integrity")
cve.Summary = dvCVE(index)("Summary")
cveList.Add(cve)
Next
Return cveList
End Function
Public Shared Function ConnectStringBuild() As String
'Grabbing connection string from web.config
Return System.Configuration.ConfigurationManager.ConnectionStrings("CVEConnectionString").ConnectionString
End Function
End Class
Any suggestion on the error?
just a little change
Dim cveList As List(Of CVE)
cveList.AddRange(CVERepository.GetInstance.ReadAllCVEs)
i am using the Json.net to serialize an object. the specific object is eventInstance.Properties which is the properties of a windows event log.
i am getting a
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property
for C# an example is shown here
string json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
my line of code is below but i am not sure how to make it work in VB or if it is even possible
command.Parameters.AddWithValue("#f18", JsonConvert.SerializeObject(eventInstance.Properties(), New JsonSerializerSettings() {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}))
i get an error that states 'ReferenceLoopHandling' is an enum type and cannot be used as an expression
thanks for the help
You can use below code:
Private Function getJSON(sJSON As String) As String
Dim objNews = New List(Of News)()
Dim news = New News()
news.id = ""
news.title = "blah"
Dim lst = New List(Of Object)()
lst.Add(New With {.video_identifier = "id1"})
lst.Add(New With {.video_identifier = "id2"})
news.video_identifier = lst.ToArray()
objNews.Add(news)
Return Newtonsoft.Json.JsonConvert.SerializeObject(New With {.data = objNews})
End Function
Class News
Public Property title As String
Get
Return _title
End Get
Set
_title = value
End Set
End Property
Private _title As String
Private _sId As String
Public Property id As String
Get
Return _sId
End Get
Set
_sId = value
End Set
End Property
Private _youtube_videos As Object() = New List(Of Object)().ToArray()
Public Property video_identifier As Object()
Get
Return _youtube_videos
End Get
Set
_youtube_videos = value
End Set
End Property
End Class
Public Class YoutubeVideos
Private _video_identifier As String
Public Property video_identifier As String
Get
Return _video_identifier
End Get
Set
_video_identifier = value
End Set
End Property
End Class