Convert curl to vb.net/c# - vb.net

How can I convert the code below to vb.net/c#?
I've tried the various examples found online but cant seem to get it going?
curl -H "Accept: application/json+v6" -H "x-api-key: <api_key>" \https://some.thing.uk/fred/prices\?productcode=ZZ99ABC
I expect it to return some results but I keep getting Forbidden (403).

I think RestSharp will be your best bet. It will work for C# or vb.net. I am fairly new to the use of RestSharp but it has worked well for me. You might have to tweak the code below a little bit since I can't test this answer without an api key but it should get you started. You will also need to install RestSharp via Nuget first and then import it into your class.
Dim key As String = 'your api key'
Dim client As New RestClient("https://some.thing.uk/fred/prices")
Dim pagesrequest = New RestRequest("\?productcode=ZZ99ABC" & "&x-api-key:" & key, Method.GET)
Dim response As IRestResponse = client.Execute(pagesrequest)
Dim textresponse As String = response.Content
'Display the response so you can check it.
textbox1.text=textresponse
Also, "\?productcode=ZZ99ABC" doesn't look right to me. You might want to try it withoug the "\".

Related

MS Access API Request

This is my first post here though have been using the great advice/solutions here for years so am very grateful. But this one, I can't find solution for.
I have an MS access front end/back end in use for various office admin tasks and records. Much of the data my office works with on a daily basis is cloud based. However API access is provided with app key and secret key. I have no issues using the API explorer with these keys, but can't get anything through code (VBA). I keep reading it is perfectly possible to do this with VBA which is why I kept trying different solutions, but now need help. (I have replaced URL and keys etc)
Dim myObj As New MSXML2.XMLHTTP60
Dim url, endPoint, params, tickers, appKey, secretKey As String
url = "theURL.com"
endPoint = "theEndPoint"
params = "id="
tickers = "1"
appKey = "12345678"
secretKey = "12345678"
myObj.Open "GET", url, False
myObj.setRequestHeader "Content-Type", "application/json"
myObj.setRequestHeader "app-key", appKey
myObj.setRequestHeader "secret-key", secretKey
myObj.send
This returns "App Key is required." I have tried various solutions including converting keys to Base64, putting the keys within the Open request, sending the keys as part of the send request etc. Always get "App Key is required" when reading response. I know in this code I have't actually requested anything but that returns same message when I do. I just wanted to keep what I posted simple.
Any help at all is greatly appreciated as this would allow great deal of automation for our office.
Thanks
James

Format this GET request in VB.NET code behind?

I am trying a "GET" method to request a count of activities from the Accelo API here:
https://api.accelo.com/docs/?http#count-activities
And although i've used a very similar POST method to successfully get the access token using an authentication method, I cannot for the life of me figure out how to get the count of activities. The API says to use "GET" and past the access token as "bearer..." and I've also tried doing a post and getting the stream first, tried sending in some data and accessing the "list activities" endpoint instead...nothing is working. everything I do returns the error "400. Bad Request."
I've tried passing data in a query string format directly in the URI, and tried passing no data since its a GET function. It looks to me like I'm following the API exactly.
Dim data2 = Nothing ' Encoding.UTF8.GetBytes(jsonstring)
Dim _list = GetListOfActivities(New Uri("https://example.api.accelo.com/api/v0/activities/count.xml"), data2, _AccessToken)
Dim reqa As WebRequest = WebRequest.Create(uri)
' reqa.Method = "GET"
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
reqa.Headers.Add("Authorization", "Bearer " & _AccessToken)
reqa.ContentType = "application/x-www-form-urlencoded"
'reqa.ContentLength = jsonDataBytes.Length
' Dim streama = reqa.GetRequestStream()
' streama.Write(jsonDataBytes, 0, jsonDataBytes.Length)
'streama.Close()
Dim responsea As WebResponse = reqa.GetResponse()
Console.WriteLine((CType(responsea, HttpWebResponse)).StatusDescription)
I must be formatting the request wrong - please help?
My problem turned out to be something stupid, and literally beyond the scope of what I posted here. I had specified a "scope" in my initial request to get the access token that was set to read-only "staff" data (I had copied-and-pasted their example online into my code, for other parameters like grant type, and I brought the scope along with it), and in this scenario here I was trying to access "activities" data and not "staff" data. I would have thought I'd get a permissions-related error, instead of "bad request" which confused me, but anyway it works now.
The above code - actually with this line:
reqa.Method = "GET"
instead of this line:
reqa.Headers.Add("GET", "/api/v0/activities/count.xml HTTP/1.1")
Works just fine since I changed my scope to read(all) in my initial web method getting the access token.

Invalid Session ID from SalesForce REST API

I'm making a call to the SalesForce REST Api.
However, I have a very weird error. Initially I wrote this in a VB.NET Module file. Everything was working correctly, as soon as I put the method in a class I keep getting the darn Invalid Session ID error. The error doesn't seem to suggest which part of the code is failing.
I am using RestSharp to facilitate the call to the SalesForce API, and I know for a fact it works because in the Module file I am able to fetch the data that I need.
I do not understand the rationale about why it works in the Module file but not in a class file.
Anyways, here is the code that I've placed in both the class file and the Module file to facilitate the call:
client = New RestClient(_strURI)
request = New RestRequest(Method.POST)
request.AddParameter("grant_type", "password")
request.AddParameter("client_id", _strClientID)
request.AddParameter("client_secret", _strClientSecret)
request.AddParameter("redirect_uri", _strRedirectUrl)
request.AddParameter("username", _strUserName)
request.AddParameter("password", _strPassword & _strSecurityToken)
'Dim response As IRestResponse
Dim response As IRestResponse = Nothing
response = client.Execute(request)
'This is the offending line in the class file..it returns back a HTTP 200 yet gives me that Session Invalid error
If response.StatusCode <> HttpStatusCode.BadRequest Then
token = JsonConvert.DeserializeObject(Of TokenResponse)(response.Content)
Dim listViewResults As String = HttpGet(token.instance_url & "/services/data/v38.0/sobjects/Contact/listviews", "")
I am unsure whether this is a permission issue or more of a programming error; because in both cases all of the authentication strings are the same. At the moment I've hardcoded it to point to a test profile. So I can't pinpoint what exactly I am doing wrong?
Any help would suffice.
Stupid me,
Anyways shortly after I posted this I went and took a brisk walk outside of the office. Turned out to be a misnomer.
I had the same HttpGet method defined in the module file and forgot to copy and paste that into the class file. When I actually stepped through it, it threw an Exception inside.
Turned out the only fix needed was to put that method into the class file.

VBA http get request response is gibberish

I tried to search for a quick answer to this but I did not see a response...so I apologize if this is redundant.
I am pretty new to VBA and only use it to pull data from APIs to make my life easier.
My question is about the response im getting from a particular API. HEre is the code im using:
Dim URL As String: URL = "API URL HERE in json format"
Dim Http As New WinHttpRequest
Dim Resp As String
Http.Open "GET", URL, False
Http.Send
Resp = Http.ResponseText
Debug.Print Resp
So the Resp text is complete gibberish...is this a security thing? I pass a security key successfully when I use it in the browser so I assumed it was not that.... I have used this exact method on numerous APIs but this is the first time I have seen this garbled response. FYI the url I am using works just fine in a browser.
The Resp looks like this for example:
gõi:?ñq¢²^2?7AÄ??æºz³Gs=ΠÜ?¬«¤%?$ÖÉ'q¯¼|?¼²ôue¦½Þ"HË!ø5[4]s½?·Þ.OÛÃBh×?4"rÊÊ[r7
Thanks for any help!
Khauna

If it isn't Base64, what might it be?

Original Question
I'm using an API to get a thumbnail image that I uploaded. Instead of providing me with a url to the image, the service returns me a garbles text string that I thought was Base64. However, all of my attempts to decode this string have failed. Does anyone have any ideas of what object types the service might be returning me? If it's not base64, what would it be?
screenshot on imgur of the API response
Answer to Original Question
#Andrew Tran: pointed out that the response I was getting looked like it was the raw binary data for the png file. This helped correct my lack of experience with Base64 and led me to some further research.
First Attempt at downloading the file
Dim path As String = "C:\Users\username\lpImages\img1.png"
Dim fs As FileStream = File.Create(path)
Dim info As Byte() = New UTF8Encoding(True).GetBytes(thumbnail)
fs.Write(info, 0, info.Length)
fs.Close()
This never worked... so I talked with a coworker and finally realized my mistake
I had been using an abstracted class to call the API and had glazed over the fact that under the hood the "request" method was actually reading the return stream into a string. The service returned the image png file as a stream, but the request method was converting this raw stream. Once I created a different request method I was able to get the png as a stream. From there it was relatively easy to use it as I intended: attaching the images as LinkedResources to an email that I then send out.
Original request method code
response = theRequest.GetResponse
Dim reader As StreamReader = New StreamReader(response.GetResponseStream)
lp_response.response = reader.ReadToEnd
New request code I wrote instead
lp_response.response = theRequest.GetResponse.GetResponseStream
VB.Net code to handle the stream (this is just a snippet where I'm building a List of LinkedResources to pass to my email function; just to give an idea of how I'm using it)
Dim document As Stream = LPApi.GetDocumentThumbnail(d("id").ToString)
Dim mediaType As String = Utils.GetContentType(Path.GetExtension(d("file_name")))
Dim lrDocument As New LinkedResource(document, mediaType)
lrDocument.ContentId = d("id").ToString
Thanks to everyone who commented. I'm pretty inexperienced when it comes to the deeper architecture of web requests/responses and data serialization. Any good learning resources would be helpful; otherwise I'll just keep Googling :)
It doesn't look like it's being encoded at all.
The IHDR chunk start is clearly visible and in plaintext at the start of the file.
It's probably not a good idea to use HttpWebRequest to download binary data, then convert the response to a string, just to try to convert that string back into binary data to save it to a file.
If you're getting an HttpWebResponse object, you should be able to use HttpWebResponse.GetResponseStream to get a stream for the image data. Then you should be able to copy the image data straight into your filestream using Stream.CopyTo.