Betfair NG API Navigation Application Menu error - vb.net

I am trying to create a Betfair app written in VB.NET using Betfair NG API.
I am trying to request the navigation menu in VB.NET utilizing the following instructions, here, but I get error 400 Bad request. Could someone send me a code for doing so?
Sub GetNavigatorManu(ByVal SessToken As String, ByVal AppKey As String)
Dim request As HttpWebRequest = Nothing
Dim response As HttpWebResponse = Nothing
Dim strResponseStatus As String = ""
Try
request = WebRequest.Create(New Uri("https://api.betfair.com/exchange/betting/rest/v1/en/navigation/menu.json"))
request.Accept = "application/json"
request.Method = "GET"
request.KeepAlive = True
request.ContentType = "application/json"
request.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
request.Headers.Add("Accept-Encoding", "gzip,deflate")
request.Headers.Add("X-Authentication", SessToken)
request.Headers.Add("X-Application", AppKey)
response = request.GetResponse()
Display the status below
strResponseStatus = "Status is " & CType(response, HttpWebResponse).StatusCode
Catch ex As Exception
MsgBox("CreateRequest Error" & vbCrLf & ex.Message)
End Try
MsgBox(strResponseStatus)
End Sub

Related

VB.NET ~ PUT WebRequest raising exceptions when trying to GetResponse of it

I am getting TWO exceptions. The first one in the regular code and the second into the exception handling block.
I have this function (below) that supposed to change user settings in a Web API using PUT method. Everything runs fine until the point that I try to get a response from the web request. Then it raises the first exception (unknown) and when I try to handle the error I get a second exception "Object reference not set to an instance of an object".
As far as I know normally what will cause this error is the attempt of getting a response of an unassigned web request, but in this case it IS assigned and the Uri is valid. All the credentials for authorization are correct too.
This is my code:
Try
Dim webRequest As System.Net.HttpWebRequest
webRequest = System.Net.HttpWebRequest.Create(InternalSettings.APIurl + "/config")
webRequest.Headers("Authorization") = InternalSettings.APIpwd
webRequest.Headers("API-Application-Key") = InternalSettings.APIkey
webRequest.Method = "PUT"
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = ""
postData += "SaveAllCustomersData=false"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'The next line will raise an unknown exception
Dim myHttpWebResponse As HttpWebResponse = webRequest.GetResponse
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
Catch ex As WebException
'The next line will raise a "Object reference not set to an instance of an object" exception
Dim resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
Dim obj = JsonConvert.DeserializeObject(resp)
Return False
End Try
If you are using basic authentification you can try something like this:
Dim strUrl As String = InternalSettings.APIurl + "/config"
Dim request As WebRequest = DirectCast(WebRequest.Create(strUrl), HttpWebRequest)
Dim strResponse As String = ""
Dim byteAuth() As Byte = Encoding.UTF8.GetBytes(InternalSettings.APIkey & ":" & InternalSettings.APIpwd)
Dim strPost As String = "SaveAllCustomersData=false"
Dim bytePost() As Byte = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "PUT"
request.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(byteAuth))
Using sw = New StreamWriter(request.GetRequestStream())
sw.Write(bytePost, 0, bytePost.Length)
sw.Flush()
Using response As HttpWebResponse = request.GetResponse()
Using sr = New StreamReader(response.GetResponseStream())
strResponse = sr.ReadToEnd()
End Using
End Using
End Using

Visual basic HttpWebRequest getting SendFailure error

I have tried many of the recommendations here and am still getting SendFailure error.
Here is the code - it's straight forward web request
Dim request As HttpWebRequest
Dim webAddress As String = "https://www.google.com"
'webAddress = "https://www.yahoo.com"
ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Tls
ServicePointManager.ServerCertificateValidationCallback = _
New RemoteCertificateValidationCallback(AddressOf AcceptAllCertifications)
request = DirectCast(WebRequest.Create(webAddress), HttpWebRequest)
request.ReadWriteTimeout = 5500
request.Timeout = 5500
request.KeepAlive = False
request.Method = "GET"
Using response = request.GetResponse()
sr = New StreamReader(response.GetResponseStream())
activated = sr.ReadToEnd()
Console.WriteLine("activated says: " + activated)
resp = Split(activated, ",")
sr.Close()
response.Close()
End Using
For the google request, I get the page content in the 'activate' var, and I get a visit hit in the certificate callback function.
For the yahoo request I get an immediate WebException Status 4: SendFailure. There is no hit on the certificate callback function.
Why is this happening? I can not figure it out. I am using VisualStudio 2010.

Connect to WebRequest Server

I'm trying to connect to TNT's server for making XML request.
First I'm trying to just make a successful connection (before trying to send anything).
According to TNT everything is set up ok. So I'm thinking it's on my end.
I'm using the code below. But it just comes back with, that it's unauthorized.
Dim request As WebRequest = WebRequest.Create("https://express.tnt.com/expressconnect/track.do?version=3")
Dim authInfo As String = ("username" + (":" + "password"))
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo))
request.Headers("Authorization") = ("Basic " + authInfo)
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
Try
Dim response As WebResponse = request.GetResponse
Console.Write(response)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
Can anyone help or shed any light on what i am doing wrong?

Creating new tasks with the Wrike API and VB.net

I'm having trouble creating new Wrike tasks using VB.net and the Wrike API. I however, am able to connect to Wrike to GET a list of folders so I know I'm able to successfully authenticate.
Link to task creation docs:
https://developers.wrike.com/documentation/api/methods/create-task
The only required field is "Title"
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
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(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try
Here is the error I'm receiving:
System.Net.WebException: The remote server returned an error: (400) Bad Request
Once I made the suggested changes, everything works good.
Dim accessToken As String = API_Token
Dim apiVersion As String = "v4"
Dim ApiBaseUrl As String = "https://www.wrike.com"
Dim folderID As String = "Some Folder ID Here"
Dim address As String = ApiBaseUrl & "/api/" & apiVersion & "/folders/" & folderID & "/tasks"
Dim result As String
Dim task_str_ As String = "importance=Normal&description=Test task description&dates={""start"":""2019-07-24"",""due"":""2019-07-30""}&title=Task Created With VS&status=Active"
Try
Dim request As HttpWebRequest = TryCast(WebRequest.Create(address), HttpWebRequest)
request.Headers.Add("Authorization", "Bearer " & accessToken)
request.Method = "POST"
request.ContentLength = task_str_.Length
request.ContentType = "application/x-www-form-urlencoded"
Using requestWriter2 As New StreamWriter(request.GetRequestStream())
requestWriter2.Write(task_str_)
End Using
Dim webResp As WebResponse = request.GetResponse()
Using reader = New StreamReader(webResp.GetResponseStream)
result = reader.ReadToEnd()
End Using
TextBox1.Text = (result)
Catch ex As Exception
TextBox1.Text = ex.ToString
End Try

Error Handling with HTTPWebRequests, VB.NET

I've looked around and couldn't find an answer so I thought i'd ask it here.
I have a program the calls an API with login info passed in the header and the server returns some info upon authentication. The problem is if the user creds are incorrect, the program crashes and throws an exception. The error is 401. How do it catch this, and tell the user?
My code is:
Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)
request.Method = "GET"
request.Headers.Add("authorization", "Bearer " + AccessToken)
request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
MessageBox.Show(responseContent)
End Using
End Using
Thanks.
Use a try catch statement
try
'My error prone code
catch ex as Exception
'Handle my error
end try
Try
Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)
request.Method = "GET"
request.Headers.Add("authorization", "Bearer " + AccessToken)
request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
MessageBox.Show(responseContent)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try