Convert JSon to dynamic object in VB.Net - asp.net

I am using VB.Net and calling salesforce API. It returns very ugly JSON which I am not able to deserialize. I have a following code using JSON.Net
Dim objDescription As Object = JsonConvert.DeserializeObject(Of Object)(result)
objDescription contains many properties, one on=f them in fields. But when I write something like objDescription.fields it gives me error.
objDescription.fields Public member 'fields' on type 'JObject' not found. Object
I am not very sure but I think it C# allow to convert any JSON to dynamic object. How can I use it in VB.Net?

You can turn Option Strict Off and use ExpandoObject which is recognized by JSON.NET. In order to leverage the dynamic features you can use a variable of type object.
Option Strict Off
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of System.Dynamic.ExpandoObject)("{""Id"":25}")
Dim test As Integer = jsonData.Id
Console.WriteLine(test)
End Sub
If you would like to use JObject because you need some of its features, you can index the JObject instead.
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of Object)("{""Id"":25}")
Dim test = jsonData("Id")
Console.WriteLine(test)
End Sub

Related

How do I write a VB.Net method to filter a URLs?

I am attempting to write a method using VB.NET that will allow me to read in a URL and compare it to a list. If it is one of the URLs on the list then Bing Tracking conversion will be applied.
At the moment I can only think do write it as a comaparative method, comapring the current URL with the ones that require tracking (a list). This, however, sems a little long winded.
Each page may have a different querystring value/page id, there for its fundamental to get exactly the right page for the tracking to be applied to.
Any Ideas?
Sorry I really am a novice when developing functions in VB.Net
If I were to use th Contains() function then I would imagine that it would look a little something like this:
Private sub URL_filter (ByVal thisPage As ContentPage, brandMessage? As Boolean) As String
Dim url_1 As String = "/future-contact thanks.aspx"
Dim url_2 As String = "/find-enquiry thanks.aspx?did=38"
Dim url_3 As String = "/find-enquiry-thanks.aspx?did=90"
Dim url_4 As String = "/find-enquiry-thanks.aspx?did=62"
Dim result as String
result = CStr (url_1.Contains(current_URL))
txtResult.Text = result
End Sub
If I were to use this then what type of loop would I have to run to check all the URLs that are in my list against the current_URL? Also where would I define the current_URL?
You can use the Contains() function to check if the list contains the given value. You could also implement a binary search, but it is probably overkill for your purposes. Here is an example:
Dim UrlList As New List(Of String)
UrlList.Add("www.example2.net") 'Just showing adding urls to the list
UrlList.Add("www.example3.co.uk")
UrlList.Add("www.exampletest.com")
Dim UrlToCheck As String = "www.exampletest.com" 'This is just an example url to check
Dim result As Boolean = UrlList.Contains(UrlToCheck) 'The result of whether it was found
Make sure to add these imports Imports System and Imports System.Collections.Generic
Disclaimer: I have no experience with VB.NET

How to change the serializer of WebMethod parameters

Ive discovered an issue in some of our old web code. The problem is that the default serializer isnt serializing the date properly. I want to use JSON.Net in order to serialize the parameters for the web methods in our aspx code. But im not sure how to tell it to use JSON.NET instead of using the default serializer.
Here is an example snipit of our code
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function EditApplication(ByVal Application As ApplicationModel, ByVal Country As String, ByVal Language As String) As jsonResponse
Dim r As New jsonResponse
Dim g As New ApplicationRequest
g.country = Country
g.locale = Language
g.platform = "Android"
g.timestamp = ""
g.transactionid = "abc123"
....
So I need ApplicationModel to serialize using JSON.Net. Thanks for your help.
Not sure if this will be helpful (since this is taken from the REST web service) but you can define it on OperationContract like this one below:
System.ServiceModel.Web.WebMessageFormat.Json
<OperationContract()> _
<WebGet(responseformat:=System.ServiceModel.Web.WebMessageFormat.Json)> _

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)

Using ParseQueryString function to get values from QueryString

I needed to get values out of a string in a QueryString format, that is such as: data1=value1&data2=value2...
Someone suggested I used HttpUtility.ParseQueryString to get the value, I've searched and searched but I can't find any documentation or implementation of this and the Microsoft documentation for it doesn't explain how it works, can someone tell me hwat I'm doing wrong, my code is below;
Public Shared Sub ProcessString(ByVal Vstring As String)
Dim var As NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = var.QueryString("VNAME")
End Sub
MSDN has an example.
' Parse the query string variables into a NameValueCollection.
Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = qscoll("VNAME")
A NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
I found the problem, I was referencing everything fine but I was doing it in a separate .VB dependency file, once I did it on the actual code behind of the aspx form that solved the problem and it all worked. So now I'm just passing the string from Codebehind as a specialised.NameValue collection in to the function.

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