How to obtain values from list - asp.net

Hi Guys
Can anyone help me out with this problem i have a list of object that is formatted in the image attached above and i have to get the IDNO, Affected Id and the date values

Since deserialization will return anonymous type(in your case), you have two options: Either deserialize it to a strong type (by defining a type) or else fetch the value using Reflection since types and properties are not known.
In your case you can get the value through reflection like this:-
Dim _data As List(Of Object) = ...
Dim firstObject = _data.FirstOrDefault()
Dim type As Type = firstObject.GetType()
Dim idmoValue = type.GetProperty("IDMO").GetValue(firstObject)
Sample Fiddle.

Related

How to check both the objects are same in Vb.net

I am trying to compare to two objects of same type and determine they identical. I have
objA IS objB
also
objA.Equals(objB)
but every time I am getting false. Here is the code I am trying
Public Class RowsDetails
Property RelatedEmployee As String = String.Empty
Property RelatedNumberAs String = String.Empty
Property Type As String = String.Empty
Property ReportType As String = String.Empty
Property status As String = String.Empty
Property Term As String = String.Empty
Property Currency As String = String.Empty
End Class
All the properties have same values in objA and objB. I have gone over some of the articles that explained about implementing IEquatable(of T).
But they mostly looked like custom logic.
I was wondering is there a simple way to do this ?
Thanks In advance.
Any time you compare two Objects a method for determining equivalence must be established.
there are 3 main forms of equivalence:
Type equivalence: done with the TypeOf operator. who's behavior can be found here
Reference equivalence: done with the is operator. found here
Value Equality (which seems to be what your trying to do) requires that a comparement method is defined. Other wise it will take its best guess at doing so, by using the default Equals() method.
If none of these work for you then you HAVE to define your own method of comparing.
the only other way of doing so, other than implementing IEquatable() or overloading Equals(), would be taking a hash of both objects and comparing those.
Object.Equals(Object) is what is called when you call objA.Equals(objB). What is compared is, are they pointing to the same object.
Dim objA as New RowDetails()
Dim objB = objA
Now they are both pointing to the same object. So...
objA.Equals(objB)
returns True
But using the New keyword on both will create 2 different references so they will not be equal with the default implementation of .Equals
Add something like the following to you RowDetails class.
Public Overrides Function Equals(obj As Object) As Boolean
Dim rowDet As RowsDetails = TryCast(obj, RowsDetails)
If rowDet Is Nothing Then
Return False
'The AndAlso will short circuit as soon as it finds a false
ElseIf RelatedEmployee = rowDet.RelatedEmployee AndAlso RelatedNumber = rowDet.RelatedNumber AndAlso Type = rowDet.Type Then 'and the rest of the properties
Return True
End If
Return False
End Function

Visual basic and Json.net Web request

Basically what im trying to do is make a program that list game information for league of legends.. using there API to extract data. how this works is you Search there username and it returns an integer linked to that account, you then use that integer to search for all of the information for that account, EG account level, wins, losses, etc.
I've run into a problem i can't seem to figure out.. Please not that I'm very new to Json.net so have little experience about working with it.. Below is how the search for the user ID is found, The First section is the Username Minus Any spaces in the name the next is the ID which is the information i require.
{"chucknoland":{"id":273746,"name":"Chuck Noland","profileIconId":662,"summonerLevel":30,"revisionDate":1434821021000}}
I must be declaring the variables wrong in order to obtain the data as everything i do it returns as 0.
these are the following class i have to store the ID within
Public Class ID
Public Shared id As Integer
Public Shared name As String
End Class
Looking at a previous example seen here Simple working Example of json.net in VB.net
They where able to resolve there issue by making a container class with everything inside it.. My problem is that The data i seek i always changing.. The first set will always be different to the "Chucknoland" that's displayed in the example.. is someone able to explain how i could go about extracting this information?
Please note that the variables rRegion has the value of what server there on, Chuck Noland is on OCE, and sSearch is the Username.. Due to Problems with API keys i had to remove the API key from the code... But the URL returns the Json Provided.
'URL string used to grab Summoner ID
jUrlData = "https://oce.api.pvp.net/api/lol/" + rRegion + "/v1.4/summoner/by-name/" + sSearch +
' Create a request for URL Data.
Dim jsonRequest As WebRequest = WebRequest.Create(jUrlData)
'request a response from the webpage
Dim jsonResponse As HttpWebResponse = CType(jsonRequest.GetResponse(), HttpWebResponse)
'Get Data from requested URL
Dim jsonStream As Stream = jsonResponse.GetResponseStream()
'Read Steam for easy access
Dim jsonReader As New StreamReader(jsonStream)
'Read Content
Dim jsonResponseURL As String = jsonReader.ReadToEnd()
jUrlString = jsonResponseURL
this is the request i have to obtain the information, and this is the code i tried to use to display the ID for that json.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim obj As ID
obj = JsonConvert.DeserializeObject(Of ID)(jUrlString)
MsgBox(obj.id)
End Sub
Is anyone able to explain how i can go about getting this to work?
One way to handle this would be to get the item into a Dictionary where the keys are the property names.
The class you have is not quite right unless you only want name and id and not the rest of the information. But using a Dictionary you wont need it anyway. The "trick" is to skip over the first part since you do not know the name. I can think of 2 ways to do this, but there are probably more/better ways.
Since json uses string keys pretty heavily, create a Dictionary, then get the data from it for the actual item:
jstr = ... from whereever
' create a dictionary
Dim jResp = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jstr)
' get the first/only value item
Dim jobj = jResp.Values(0) ' only 1 item
' if you end up needing the name/key:
'Dim key As String = jResp.Keys(0)
' deserialize first item to dictionary
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jobj.ToString)
' view results
For Each kvp As KeyValuePair(Of String, Object) In myItem
Console.WriteLine("k: {0} v: {1}", kvp.Key, kvp.Value.ToString)
Next
Output:
k: id v: 273746
k: name v: Chuck Noland
k: profileIconId v: 662
k: summonerLevel v: 30
k: revisionDate v: 1434821021000
Using String, String may also work, but it would convert numerics to string (30 becomes "30") which is usually undesirable.
While poking around I found another way to get at the object data, but I am not sure if it is a good idea or not:
' parse to JObject
Dim js As JObject = JObject.Parse(jstr)
' 1 = first item; 2+ will be individual props
Dim jT As JToken = js.Descendants(1)
' parse the token to String/Object pairs
Dim myItem = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(jT.ToString)
Same results.

Enable datagrid dynamic data at runtime

I have a data grid using dynamic data. I 'enable' dynamic data on the page_init event for the page containing the data grid. I would like to be able to set the type of the dynamic data at run time. I have the name of the class to set, as a string. I can't quite figure out how to do this.
I set the dynamic data like this:
Dim myGrid As GridView = DirectCast(retrieveGrid.FindControl("gridResults"), GridView)
myGrid.EnableDynamicData(GetType(*MyEntityNameAsAString*)
Obviously this does not work because I cannot provide my entity name a s a string. How can I convert the string to the entity type? I tried:
Type.GetType(entityname)
And
Type.GetType(AssemblyName.entityname)
And neither seems to work. That is, I can't get the type with either of these statements.
OK, solved it like this... I created a function to get the entity object from the object name:
Public Function GetEntity(ByVal entityName As String) As Object
'Get the assembly
Dim assem As Assembly = Nothing
assem = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory & "/bin/AsbestosEntities.dll")
'Get all classes in the assembly
Dim AllEntities As Type() = assem.GetTypes()
Return AllEntities.FirstOrDefault(Function(e) e.FullName = entityName)
End Function
Then set the grid enable dynamic data based on the result of the function:
Dim EntityType As Type = GetEntity(general_retrieve.gr_entity_set_name)
myGrid.EnableDynamicData(EntityType)

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

updating properties of a class with dynamic references

Sorry for what is probably a very basic question. I have a vb.net class with properties defined as follows:
Private m_Property1 As String
Public Property Property1() As String
Get
Return m_Property1
End Get
Set(ByVal value As String)
If IsNothing(value) Then
m_Property1 = String.Empty
Else
m_Property1 = value
End If
End Set
End Property
I can then set the values as follows:
classname.Property1 = "myvalue"
How do I set the value of a property that is defined dynmically eg
Dim strPropertyName As String = "Property1"
Hope that makes sense.
Thanks,
Josh
You would use reflection
Dim strPropertyName as string = "Property1"
Dim pi As PropertyInfo = myClass.GetType().GetProperty(strPropertyName)
pi.SetValue(myClass.GetType(), "some string", Nothing)
You want to use Reflection in order to do this. VB.NET provides a way to do this if you know the value at compile-time, but for run-time operations, you need to use the GetType keyword in order to get the type of your class (or, use the GetType method on an instance of it if you don't know it).
Then, with that Type instance, you would call GetProperty, passing the string with the name of the property. It will return an PropertyInfo instance which you then call GetValue on, passing the instance of the object in, which will return an Object which you have to cast back to a type you wish to use (if you are).
VB.NET makes a lot of this easier with the CallByName function.
Also, if you know at compile-time what the name of the property is, you can always cast to object and use VB.NET's inherent late binding:
Dim o As Object = <your object>
o.Property1 = ...
VB.NET will perform the late-binding for you.

Resources