Json Request working only my computer (VB.Net desktop app. Project) - json

I have a json request in my vb.net desktop app project (.net framework 4.5.2). This codes working every time correcctly in my computerand i saw response json string every time.
But i tried run in other machines, not worked. Response is every time nothing in other machines. Any ideas on the reason for this?
Dim wcOrders As List(Of Woocomerce.Root)
Net.ServicePointManager.ServerCertificateValidationCallback = Function() True
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
Dim client = New RestClient("https://[??myhost??].com.tr/wp-json/wc/v3/orders?context=view")
client.Timeout = -1
Dim request = New RestRequest(Method.[GET])
request.AddHeader("Authorization", "Basic [MyAuth.Info]")
Dim response As IRestResponse = client.Execute(request)
wcOrders = JsonConvert.DeserializeObject(Of List(Of Woocomerce.Root))(response.Content)
If IsNothing(wcOrders) Then
MsgBox("not")
ElseIf wcOrders.Count = 0 Then
MsgBox("0")
MsgBox(response.Content)
Else
MsgBox(wcOrders.Count)
End If

Related

Vb.Net Get Resposnes form called API using WebClient

Currently, I am developing a web service which going to be called post JSON. It works fine and I got my records posted without any issue.
My issue is to display the response. I used UploadData to send .. Do I need to use download data to receive? What if I need to show in the response in MessageBox.
Note that I am expecting a response in JSON format as well. Let me know at least the concept ? First I guess, I need to receive the response and I will deserialize it.
Here is my current code. Working fine but I can't show the response.
Public Function postData(ByVal JsonBody As String) As Boolean
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte
Try
Dim APIusername As String = "XXXXX"
Dim APIPassword As String = "XXXXX"
webClient.Headers("content-type") = "application/json"
webClient.Credentials = New System.Net.NetworkCredential(APIusername, APIPassword)
reqString = Encoding.Default.GetBytes(JsonBody)
resByte = webClient.UploadData(Me.urlToPost, "post", reqString)
resString = Encoding.Default.GetString(resByte)
Console.WriteLine(resString)
' Here I need to show the responses
webClient.Dispose()
Return True
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return False
End Function
I have used http request instead of web client and it works.

Add json object into http request as body in vb.net

I've one API in vb.net and i want to make HTTP request to another API from one of my methods. I've created an instance of WebClient class and added my headers but the problem is i could not add my json object as body into HTTP request. Here is my code.
Dim webc As New WebClient
webc.Headers.Add("Content-Type: application/json")
webc.Headers.Add("Authorization: " + testHeader)
webc.Headers("x-iyzi-rnd") = random_string
Dim url = "https://sandbox-api.iyzipay.com/"
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim html As Byte() = webc.DownloadData(url)
Dim utf As UTF8Encoding = New UTF8Encoding()
Dim response As String = utf.GetString(html)

How should this HTTP request for oAuth token be formatted?

In a VB .net environment, I am making the following call, trying to implement the authorize step of an OAuth process to connect to an Accelo API (a time-entry and billing type of app). I'm trying to get an access token:
Dim jsonstring = "{'Content-Type':'Application/x-www-Form-urlencoded',
'authorization':'Basic MDBhM...GbG5oLlZB'}"
Dim data = Encoding.UTF8.GetBytes(jsonstring)
Dim result_post = SendRequest(New Uri("https://ourinfo.api.accelo.com/oauth2/v0/token"), data, "application/json", "POST")
with the function defined as this:
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
and I keep receiving an error on this line:
Dim response = req.GetResponse().GetResponseStream()
Saying
"System.Net.WebException: 'The remote server returned an error: (400) Bad Request.'"
It seems to me like a syntax error or something in the way my calling method is formed or the format of the parameters passed. I got the HTTP request code suggestion/format from here:
How to POST a JSON to a specific url using VB.NET?
and I'm using the Accelo API to set the content-type and authorization "basic" part where the string is encoded in Base 64. This is a service application so i'm supposed to be able to get the token in 1-step (no user confirmation is required). I already have a "token" from when I registered, but the API still indicates I should do this code. i'm following this:
https://api.accelo.com/docs/?_ga=2.218971609.1390377756.1568376911-2053161277.1565440093#service-applications
Can anyone tell me what exactly I'm doing wrong here? I'm confused and this is the first time I'm trying to implement OAuth.
There is some example code in the API documentation that looks like this:
POST /oauth2/v0/token HTTP/1.1
Host: planet-express.api.accelo.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic {client_credentials}
grant_type=client_credentials
scope=read(staff)
And I'm not sure the difference between the = and : syntax purposes. I was not able to search and find any answers to whether I'm calling everything correctly. Should I be passing the scope and grant_type in the JSON string, or setting it as a property on "req" object in the "SendRequest" function? I know that the grant_type is supposedly required but how do I set it?
What's the token I received initially when I registered, if I'm supposed to get a token this way?
I got it working with the help of a colleague. Apparently I was confusing header data and the json "data,"and I was not formatting the data correctly either. I should have been looking at the WebResponse too, not only the WebRequest. I changed my code to the following, which works now:
Sub SendRequestGetAccess()
Dim req As WebRequest = WebRequest.Create(uri)
req.Method = "POST"
req.Headers.Add("Authorization", "Basic " & "MDB....")
req.ContentType = "Application/x-www-Form-urlencoded"
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response As WebResponse = req.GetResponse()
Console.WriteLine((CType(response, HttpWebResponse)).StatusDescription)
Dim dataStream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
'Dim firstItem = jsonResult.Item("data").Item(0).Value(Of String)("token")
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(responseFromServer)
Dim _itemvalue = j("itemkey")
End Sub
And I had to use dashes instead of colons in my json data:
Dim jsonstring = "grant=creds" & "&scope=read"
Dim data = Encoding.UTF8.GetBytes(jsonstring)
SendRequestGetAccess(New Uri("https...site.com/oauth2/v0/token"), data)

500 Internal Error when sending a POST request to Api

So my goal is to send a HttpRequest to api, it returns a 500 internal server error.
According to them, other companies are succesfully using this Api, so it should work in theory. I send the json example string I use to test if it works, they confirmed it is correct. So what could cause the Error?
Public Function SendStringToHttpServer(dataString As String, uriString As String, credentials As NetworkCredential) As String
Dim resultInfo As String
Dim request As HttpWebRequest = CType(WebRequest.Create(uriString), HttpWebRequest)
request.Credentials = credentials
request.Timeout = 6000
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(dataString)
request.ContentType = "application/json"
request.ContentLength = byteArray.Length
Try
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
Return "done"
End Function
Note: I saw there are some similiar threads, like this. But I use it exactly the same way, so it SHOULD work but doesn't -.-
(Beside the fact that i have strict on and therefore cast explicitly)
EDIT: About the authentification methods: This works definitly, since if I use wrong username or password in the credenitals I get a 403: authorized Error and not a 500.
Furthermore the read request works just fine. Read request is very similiar just a basic HttpRequest which only requires the url and credentials.
EDIT 2: So I read that it can be tied to HttpRequest automaticlly adding and "Expect:100-continue" to the header.I prevent this now
ServicePointManager.Expect100Continue = False
But it still gives a 500 Error.

Programatically fill TFS New Bug workitem from VBA

I am wondering if it is possible to have VBA (Access) open a TFS Bug report webpage and fill in the description ?
While I am able to open the page I have not yet found a way to populate the description and potently other fields.
Perhaps one of the experts knows?
I wouldn't try to do what you are working on.
One, trusting a buggy application to correctly report its own bugs isn't a great idea. But beyond that you will be trying to attach Access to TFS.
That being said you can do this entirely automated. Put in some error trapping and then what you are looking to do is how to call TFS APIs. But you may or may not have to install some third part tools etc.
Starting point TFS API
The way I finally did it is to use a dll to interface between access and tfs...
For anyone trying to do the same here is the code...
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Common
Imports System.Runtime.InteropServices
<ComClass(TFSInterOp.ClassId, TFSInterOp.InterfaceId, TFSInterOp.EventsId)> Public Class TFSInterOp
Public Const ClassId As String = "14306fc5-1492-42d6-a032-bc4348508dd3"
Public Const InterfaceId As String = "288339cb-0c2e-45fd-8005-e5fed401f0cc"
Public Const EventsId As String = "723327dc-7777-44e4-b291-9299027665eb"
Public Sub New()
End Sub
Public Function InsertBugWorkItem(Title As String, Desc As String) As String
Dim tfsServer As String = My.Settings("TfsFullPath").ToString ' {YOUR TFS SERVER PATH}
Dim strAssUser As String = My.Settings("AssignTo").ToString
Dim teamFoundationServer1 As Microsoft.TeamFoundation.Client.TfsTeamProjectCollection = Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory.GetTeamProjectCollection(New Uri(tfsServer))
Dim workItemStore1 As New WorkItemStore(teamFoundationServer1)
teamFoundationServer1.Authenticate()
Dim WorkItemStore As WorkItemStore = New WorkItemStore(tfsServer)
Dim tfsProject As Project = WorkItemStore.Projects(0)
Dim wIType As WorkItemType = tfsProject.WorkItemTypes("Bug")
Dim workItem As WorkItem = New WorkItem(wIType)
Dim wiStore = teamFoundationServer1.GetService(Of WorkItemStore)()
Dim Project = wiStore.Projects
Dim Area = Project.Item(0).AreaRootNodes("BITS").Id ' The project to add the work item to
' Prefill items
workItem.Title = Title
workItem.Description = Desc
workItem.AreaId = Project.Item(0).AreaRootNodes("BITS").Id
workItem.Fields("Assigned To").Value = strAssUser
workItem.Fields("System Info").Value = "Access V 1.1.25"
workItem.Fields("Repro Steps").Value = Desc
Dim result As ArrayList = workItem.Validate()
If result.Count > 0 Then
Return (result(0).ToString + "There was an error adding this work item to the work item repository")
Else
workItem.Save()
End If
' Open the new item in explorer
Dim myService = teamFoundationServer1.GetService(Of TswaClientHyperlinkService)()
Dim myUrl = myService.GetWorkItemEditorUrl(workItem.Id)
Dim oProcess As New System.Diagnostics.Process()
oProcess.StartInfo.FileName = myUrl.ToString
oProcess.Start()
Return "OK"
End Function
End Class