VB.Net Deserializing JSON to Datatable is Empty - json

Public Shared Function GetVolsForMU(ByVal MU As String) As DataTableReader
Dim dataSet As New DataSet
Dim responseData As String
Try
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim reader As StreamReader
request = HttpWebRequest.Create("https://myapi/" & MU)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
request.Headers.Add("Authorization", "Bearer " & ConfigurationManager.AppSettings("BearerToken"))
request.ReadWriteTimeout = 11000
response = request.GetResponse
reader = New StreamReader(response.GetResponseStream)
responseData = reader.ReadToEnd
Catch ex As Exception
My.Utility.LogManager.LogError("VolunteerDAL", "GetVolsForMU", ex)
My.Utility.LogManager.LogInfo("VolunteerDAL", "GetVolsForMU MU was: " & MU)
Throw New My.Exceptions.APIException("Error Calling API.")
End Try
If responseData Is Nothing Then
Return Nothing
End If
Dim volunteers = JsonConvert.DeserializeObject(Of DataTable)(responseData)
Dim tableReader As DataTableReader = dataSet.CreateDataReader(volunteers)
Return tableReader
End Function
My volunteers variable is returning as = {}
responseData = "[{""userId"":""93e4098c-db55-3245-accb-40fe48cd0330"",""firstName"":""Test"",""lastName"":""Tester"",""middleName"":""Super"",""preferredName"":""Test"",""displayName"":""Test"",""pmNumber"":""89332220"",""eMail"":""test#gmail.com"",""username"":""testAPI"",""startDate"":null,""lastLogin"":""2020-08-12T16:25:38.173"",""inactive"":null,""assignmentId"":""334dadbb-bf34-4b92-1783-08da7a5bd456"",""roleId"":""B6CD23CA-7EBF-40FC-99AB-6F91999ABEF5"",""jobName"":""Volunteer"",""jobCodeGroupName"":""Volunteer"",""mU"":""2430"",""expirationDate"":""2023-08-31T00:00:00"",""active"":true}]"
The DataTableReader is coming up empty based off of volunteers not being deserialized correctly. Thanks for any help!
Here's what I ended up with to get it to work.
Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
Dim table As New DataTable()
Dim fields() = GetType(T).GetProperties()
For Each field As PropertyInfo In fields
table.Columns.Add(field.Name, If(Nullable.GetUnderlyingType(field.PropertyType), field.PropertyType))
Next
For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each field As PropertyInfo In fields
row(field.Name) = If(field.GetValue(item) Is Nothing, DbNull.Value, field.GetValue(item))
Next
table.Rows.Add(row)
Next
Return table
End Function
Public Shared Function GetVolsForMU(ByVal MU As String) As DataTableReader
Dim dataSet As New DataSet
Dim responseData As String
Try
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim reader As StreamReader
request = HttpWebRequest.Create("https://myapi/" & MU)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
request.Headers.Add("Authorization", "Bearer " & ConfigurationManager.AppSettings("BearerToken"))
request.ReadWriteTimeout = 11000
response = request.GetResponse
reader = New StreamReader(response.GetResponseStream)
responseData = reader.ReadToEnd
Catch ex As Exception
My.Utility.LogManager.LogError("VolunteerDAL", "GetVolsForMU", ex)
My.Utility.LogManager.LogInfo("VolunteerDAL", "GetVolsForMU MU was: " & MU)
Throw New My.Exceptions.APIException("Error Calling API.")
End Try
If responseData Is Nothing Then
Return Nothing
End If
Dim listOfUserAssignments = JsonConvert.DeserializeObject(Of List(Of UserAssignment))(responseData)
Dim volunteers = ConvertToDataTable(listOfUserAssignments)
Dim tableReader As DataTableReader = dataSet.CreateDataReader(volunteers)
Return tableReader
End Function
The code above is what ended up working for me.

Related

Weird error accessing an API that returns JSON string

I get an error when executing the following code:
Public Function GetNumberInfo(ByVal pPhoneNumber As String) As PhoneInformation
Dim url As String = "https://api.phonevalidator.com/api/v3/phonesearch?apikey=[My_API_Key]&phone=" & pPhoneNumber & "&type=fake,basic"
DebugLog("App:Registration (RegistrationMOD.vb/GetNumberInfo) - DEBUG URL string: " & url)
Dim request = CType(WebRequest.Create(url), HttpWebRequest)
Dim myReader As StreamReader
request.Method = "GET"
request.Accept = "application/json"
request.ContentType = "application/json; charset=utf-8;"
' The error occurs on the execution of this line.
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
myReader = New System.IO.StreamReader(response.GetResponseStream)
Dim responseString As String = ""
responseString = myReader.ReadToEnd
Dim j As JavaScriptSerializer = New JavaScriptSerializer()
Dim MyPhone As PhoneInformation = j.Deserialize(Of PhoneInformation)(responseString)
Return MyPhone
End Function
The strange this is, this EXACT same code executes fine in a test console app I created to test my conversion from c# code to vb code. I log all errors generated by the application and the following log entry details are what's in the log:
Debug log entries:
App:Registration/CreateAccount - An error occurred executing CheckPhone, the error is: The underlying connection was closed: An unexpected error occurred on a receive.
App:Registration/CreateAccount - Phone number submitted: 7029270000
Trace: System.Net.WebException(0x80131509): The underlying connection was closed: An unexpected error occurred on a receive.
at Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Method TargetProcedure, Object[] Arguments, Boolean[] CopyBack, BindingFlags Flags)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at Registration.RegistrationMod.GetNumberInfo(String pPhoneNumber) in C:\Users\Presc\Documents\Visual Studio 2013\Projects\Registration\Registration\RegistrationMod.vb:line 20
at Registration.CreateAccount.CheckPhone(String pPhoneNumber) in C:\Users\Presc\Documents\Visual Studio 2013\Projects\Registration\Registration\CreateAccount.aspx.vb:line 241
Line:20 Filename: RegistrationMod.vb
Line:241 Filename: CreateAccount.aspx.vb
This error occurrs on the execution of the line:
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
The debug log entry generated for the url string generated by the app to be submitted to the API is:
App:Registration (RegistrationMOD.vb/GetNumberInfo) - DEBUG URL string: https://api.phonevalidator.com/api/v3/phonesearch?apikey=[My_API_Key]&phone=7029270000&type=fake,basic
I don't understand how it could work in the console app and not in this app. The console app code is:
Imports System.IO
Imports System.Net
Imports Nancy.Json
Module TestCodeMOD
Public Function GetNumberInfo(ByVal pPhoneNumber As String) As PhoneInformation
Dim url As String = "https://api.phonevalidator.com/api/v3/phonesearch?apikey=[My_API_Key]&phone=" & pPhoneNumber & "&type=fake,basic"
Dim request = CType(WebRequest.Create(url), HttpWebRequest)
Dim myReader As StreamReader
request.Method = "GET"
request.Accept = "application/json"
request.ContentType = "application/json; charset=utf-8;"
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
myReader = New System.IO.StreamReader(response.GetResponseStream)
Dim responseString As String = ""
responseString = myReader.ReadToEnd
Dim j As JavaScriptSerializer = New JavaScriptSerializer()
Dim MyPhone As PhoneInformation = j.Deserialize(Of PhoneInformation)(responseString)
Return MyPhone
End Function
End Module
I execute the function like so:
Sub Main()
Dim MyPhone As PhoneInformation
MyPhone = GetNumberInfo("7029270000")
End Sub
The console app executes without any errors and populates the PhoneInformation class instance with the expected data. I'm at a loss as to what's going on and I'm open to suggestions.

How can I post a JSON object using a Dictionary?

Here is the JSON content that needs to be posted.
{
"getcart": {
"version": "1.0",
"account": "6566",
"username": "112",
"password": "xxxxxxxx",
"cartid": "57044d79",
} }
Code:
Dim jsonPost As New JsonPost("https://www.example.aspx")
Dim dictData As New Dictionary(Of String, Object)
dictData.Add("version", "1.0")
dictData.Add("account", "6566")
dictData.Add("username", "112")
dictData.Add("password", "xxxxxxxx")
dictData.Add("cartid", "57044d79")
Dim json As JObject = JObject.Parse(JsonPost.postData(dictData))
Dim response As String = JsonPost.postData(dictData)
MsgBox(response)
The error I'm getting:
Error reading JObject from JsonReader. Path'',line 0 postion 0
How can I fix this?
I couldn't do it using the dictionary. But I was able to post it as a string.
The main issue was declaring a JSON string that contains an object in Visual Basic. Here is how I did it:
Dim JsonData As String = "{'getcart':{
'version':'1.0',
'account':'6566',
'username':'112',
'password':'xxxxxxxx',
'cartid':'57044d79',
}}"
Dim Uri As String = "https://www."
Dim data = Encoding.UTF8.GetBytes(JsonData)
Dim result_post = SendRequest(New Uri(Uri), data, "application/json", "POST")
MsgBox(result_post)
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function

Get /Put Device Alias using Teamviewer REST API

Im looking to get a list of all the devices on my work admin teamviewer account using vb.net. I would also like to be able to change the "Alias" of a given device using it's device id. i know very little about API's. i found the following example but i am not sure how to adapt it to get the json response.
instead of the accesstoken, i believe i need to use the client id and secret id along with the authorization code in order to use this. if i run it in it's current start i get a 401 unauthorized error. Any help would be appreciated.
i also have no idea how to use "PUT" to change the Alias using the device id which will both be entered in textboxes. ex alias = textbox1.text and device_id = textbox2.text
Private Sub SurroundingSub()
Dim accessToken As String = "xxxxxxxxxxxxxxxxxxx"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Bearer", accessToken)
request.Method = "GET"
Dim webResp As WebResponse = request.GetResponse()
Catch __unusedException1__ As Exception
msgbox(__unusedException1__.ToString)
End Try
End Sub
Here is the Get all devices code:
Private Sub get_teamviewer_devices()
Dim accessToken As String = "XXXXXXXXXXXXXXXXXXXXX"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices"
Dim result_json As String = Nothing
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "GET"
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result_json = reader.ReadToEnd()
End Using
TextBox1.Text = result_json
Catch __unusedException1__ As Exception
MsgBox(__unusedException1__.ToString)
End Try
End Sub
Here is the PUT portion to change an alias:
Public Sub change_alias(ByVal device_id As String, ByVal alias_str As String)
Dim accessToken As String = "XXXXXXXXXXXXXXXXXXXXX"
Dim apiVersion As String = "v1"
Dim tvApiBaseUrl As String = "https://webapi.teamviewer.com"
Dim address As String = tvApiBaseUrl & "/api/" & apiVersion & "/devices/" & device_id
Dim result As String
Dim alias_str_ As String = Chr(34) & alias_str & Chr(34)
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "PUT"
request.ContentType = "application/json"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write("{""Alias"" : " & alias_str_ & "}")
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch __unusedException1__ As Exception
MsgBox(__unusedException1__.ToString)
End Try
End Sub

How to parse json and read in vb.net

I have this code in my project:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = rawresp
and TextBox2 gets the JSON code correctly.
and this is my JSON code example:
{
"id":174543706,
"first_name":"Hamed",
"last_name":"Ap",
"username":"hamed_ap",
"type":"private"
}
My question:
How to get 174543706 from JSON code ("id") into TextBox3.Text???
You could use JavaScriptSerializer which is in System.Web.Script.Serialization.
Imports System.Web.Script.Serialization
Module Module1
Sub Main()
Dim s As String
Try
Dim rawresp As String = "{""id"":174543706,""first_name"":""Hamed"",""last_name"":""Ap"",""username"":""hamed_ap"",""type"":""private""}"
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("id")
Catch ex As Exception
End Try
End Sub
End Module
try this code :
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(rawresp)
Dim firstItem = jsonResulttodict.item ("id")
hope it help you !!
How to get 174543706 from JSON code ("id") into TextBox3.Text?
{
"id": 174543706,
"first_name": "Hamed",
"last_name": "Ap",
"username": "hamed_ap",
"type": "private"
}
Sorry if my reply was late. I hope my answer can help someone who's still confused.
So what you do was get the response and read the JSON.
After you do ReadToEnd():
Dim xr As XmlReader = XmlReader.Create(New StringReader(rawresp))
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(rawresp)
Then What you need to do is to read the data from the response. you do like this:
Dim res As String = JsonConvert.SerializeXmlNode(doc)
Dim ThisToken As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(res)
Dim response As String = ThisToken("response").ToString()
Dim ThisData As JObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JObject)(response)
After that yo can get the data from the response and convert it into string
Dim idx As String = ThisData("id").ToString()
// the value of idx will be: 174543706
Then last you can put it into Texbox3.Text.
JSON can be parsed using adding Newtonsoft.Json.dll reference
Code :
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim json As String = New System.Net.WebClient().DownloadString("http://time.jsontest.com/")
Dim parsejson As JObject = JObject.Parse(json)
Dim thedate = parsejson.SelectToken("date").ToString()
txt1.Text = "Date Is "+thedate
End Sub
End Class
Reference : Narendra Dwivedi - Parse JSON
This works:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("https://url.to.my.json"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
textbox2.text = JObject.Parse(rawresp)("id")

Bitfinex API with VBnet

Here is what I've come up with so far:
Sub GetData()
Try
Dim method As String = calldata("/balances")
MsgBox(method)
Catch ex As Exception
End Try
End Sub
Function calldata(ByVal Method As String) As String
Dim logincookie As CookieContainer
Try
Dim pKey As String = "CODE HERE"
Dim sKey As String = "SECRET CODE HERE"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://api.bitfinex.com/v1/"), HttpWebRequest)
Dim randomn As String = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
'//Dependant upon Method
Dim postData As String = "method=" & Method & "&nonce=" & randomn
Dim tempcookies As New CookieContainer
'//Start Encryption
Dim KeyByte() As Byte = Encoding.ASCII.GetBytes(sKey)
Dim HMAcSha As New HMACSHA384(Encoding.ASCII.GetBytes(sKey))
Dim messagebyte() As Byte = Encoding.ASCII.GetBytes(postData)
Dim hashmessage() As Byte = HMAcSha.ComputeHash(messagebyte)
Dim Sign As String = BitConverter.ToString(hashmessage)
Sign = Sign.Replace("-", "")
'//Generate Post Information
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.Headers.Add("X-BFX-APIKEY", pKey)
postReq.Headers.Add("X-BFX-PAYLOAD")
postReq.Headers.Add("X-BFX-SIGNATURE", LCase(Sign))
postReq.CookieContainer = tempcookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
postReq.ContentLength = messagebyte.Length
'//Send Request
System.Net.ServicePointManager.Expect100Continue = False
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(messagebyte, 0, messagebyte.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempcookies.Add(postresponse.Cookies)
logincookie = tempcookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
'The Response Text
Dim thepage As String = postreqreader.ReadToEnd
thepage = thepage.Replace(Chr(34), Chr(39))
Return thepage
Catch
Return False
End Try
End Function
I can't figure out the payload portion. This script is a modified version of what I'm using for other API's. Here is the Bitfinex API info
https://www.bitfinex.com/pages/api
Is everything right except pay load? How do I complete "payload = parameters-dictionary -> JSON encode -> base64" portion of the API details?
Try this.
Sub GetData()
Try
Dim method As String = calldata("/balances")
MsgBox(method)
Catch ex As Exception
End Try
End Sub
Function calldata(ByVal Method As String) As String
Dim logincookie As CookieContainer
Try
Dim pKey As String = "CODE HERE"
Dim sKey As String = "SECRET CODE HERE"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://api.bitfinex.com/v1/balances"), HttpWebRequest)
Dim randomn As String = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
'//Dependant upon Method
Dim postData As String = "{""request"": ""/v1" & Method & """,""nonce"": """ & randomn & """,""options"":{}}"
Dim tempcookies As New CookieContainer
Dim payload As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(postData))
'//Start Encryption
Dim KeyByte() As Byte = Encoding.ASCII.GetBytes(sKey)
Dim HMAcSha As New HMACSHA384(Encoding.ASCII.GetBytes(sKey))
Dim messagebyte() As Byte = Encoding.ASCII.GetBytes(payload)
Dim hashmessage() As Byte = HMAcSha.ComputeHash(messagebyte)
Dim Sign As String = BitConverter.ToString(hashmessage)
Sign = Sign.Replace("-", "")
'//Generate Post Information
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.Headers.Add("X-BFX-APIKEY", pKey)
postReq.Headers.Add("X-BFX-PAYLOAD", payload)
postReq.Headers.Add("X-BFX-SIGNATURE", LCase(Sign))
postReq.CookieContainer = tempcookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
postReq.ContentLength = messagebyte.Length
'//Send Request
System.Net.ServicePointManager.Expect100Continue = False
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(messagebyte, 0, messagebyte.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempcookies.Add(postresponse.Cookies)
logincookie = tempcookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
'The Response Text
Dim thepage As String = postreqreader.ReadToEnd
thepage = thepage.Replace(Chr(34), Chr(39))
Return thepage
Catch e As Exception
Return False
End Try
End Function