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
Related
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.
I'm having a problem with JSON deserialization hope you can help me.
I have a JSON that have the following information:
{
"object":"list",
"more":false,
"data":[
{
"object":"number",
"id":"1",
"code":"1",
"name":"One",
},
{
"object":"number",
"id":"2",
"code":"2",
"name":"Two",
}
...
So I've a created a simple app so I can use that information:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim uri As New Uri(uriString)
'Make Request
Dim Request As HttpWebRequest = HttpWebRequest.Create(uri)
Request.Method = "GET"
'Get Response
Dim Response As HttpWebResponse = Request.GetResponse()
'Read Response
Dim Read = New StreamReader(Response.GetResponseStream())
Dim Raw As String = Read.ReadToEnd()
'Convert response
Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(Raw)
For Each item In dict
MsgBox(item)
MsgBox(item("code"))
TextBox1.Text += item("code").ToString + " - " + item("name").ToString + vbNewLine
Next
End Sub
It seems I get the response, since the Read I get the JSON, but after that, I can't get the information listed in that JSON. What I'm doing wrong?
You are not de-serializing properly. Your dict is empty like that.
This will work as intended.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uriString As String = "API URL"
Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString))
Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
Dim JSON_Obj1 As Object = New JavaScriptSerializer().DeserializeObject(JSON_Response)
Dim Test1 as String = JSON_Obj1("data")(0)("code")
For Each item In JSON_Obj1("data")
Debug.Print(item("code"))
Next
End Sub
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")
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
I use this script to get geocodes for any address in germany:
Public Function getGoogleMapsGeocode(sAddr As String) As String
Dim xhrRequest As XMLHTTP60
Dim sQuery As String
Dim domResponse As DOMDocument60
Dim ixnStatus As IXMLDOMNode
Dim ixnLat As IXMLDOMNode
Dim ixnLng As IXMLDOMNode
' Use the empty string to indicate failure
getGoogleMapsGeocode = ""
Set xhrRequest = New XMLHTTP60
sQuery = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
sQuery = sQuery & Replace(sAddr, " ", "+")
xhrRequest.Open "GET", sQuery, True
xhrRequest.send
Set domResponse = New DOMDocument60
domResponse.LoadXML xhrRequest.responseText
Set ixnStatus = domResponse.SelectSingleNode("//status")
If (ixnStatus.Text <> "OK") Then
'Exit Function
End If
Set ixnLat = domResponse.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat")
Set ixnLng = domResponse.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng")
getGoogleMapsGeocode = ixnLat.Text & ", " & ixnLng.Text
End Function
When I type the query string into the browser it returns a valid xml response with the geocodes. If I let vba do it, I get an error. Is there something I should know?
responseText :
"<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>INVALID_REQUEST</status>
</GeocodeResponse>
" : String : Modul8.getGoogleMapsGeocode