Invalid Session ID from SalesForce REST API - vb.net

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.

Related

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.

What Sanitizes Data From REST/Web APIs?

I have a REST Service built in vb.net running on IIS. I've noticed that the returned data is sanitized or escaped, e.g.:
<script>alert('testing1')</script>
is returned as:
<script>alert('testing1')</script>
Can anyone tell me what is doing the escaping, would it be .net or IIS and can it be switched on or off?
I'm pretty sure you could have a controller method like this..
Function ReturnJavascript() As Net.Http.HttpResponseMessage
Dim resp As New Net.Http.HttpResponseMessage(Net.HttpStatusCode.OK)
resp.Content = New Net.Http.StringContent("<script>alert('testing1')</script>", System.Text.Encoding.UTF8, "text/plain")
Return resp
End Function
Not sure what you are trying to accomplish. If you don't want to return as a response message, you might attempt returning as content set to text/plain.

400 Bad Request - Facebook Graph API - HttpWebRequest

Every time I run the following code I get an exception:
Code
Dim url As String = "https://graph.facebook.com/search?q=" & System.Web.HttpUtility.UrlEncode(_sourceData.Rows(i).Item(0).ToString) & "&type=event&limit=5000"
Dim getFullURL As String = (url & Convert.ToString("&access_token=")) + _appToken
Dim stream As New StreamReader(HttpWebRequest.Create(getFullURL).GetResponse().GetResponseStream())
Dim output As String = stream.ReadToEnd()
stream.Close()
Exception:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (400) Bad Request.
My first thought was that it could be an execution limit Facebook has in place over each of their API access tokens; however, if I copy the contents of the 'getFullURL' string variable during runtime and paste it directly into my internet browser, it works fine. Given that it works to copy-paste into web browser, I'm very stuck on how to continue troubleshooting!
Any advice would be most appreciated.
This was related to me hitting the maximum API calls (200/hr). I had an erroneous loop that kept repeating the API call during my testing that made me hit this limit.

Web Request is a type and cannot be used as an expression

I am making an app for Windows Phone and since I need some login cookies that are saved in Web browser control, I am using the code from here: Grabbing Cookies in Web Browser Control - WP7 to create a HTTPWebRequest and get some JSON data for parsing but I am getting two errors on the last line of this snippet
Dim browser = New WebBrowser()
Dim brwhttp = GetType(WebRequestCreator).GetProperty("BrowserHttp")
Dim requestFactory = TryCast(brwhttp.GetValue(Browser, Nothing), IWebRequestCreate)
Dim uri = New Uri("some-url")
Dim req = requestFactory.Create(uri)
req.Method = "GET"
req.BeginGetResponse(New AsyncCallback(request_CallBack), WebRequest)
(1). 'WebRequest' is a type and cannot be used as an expression.
(2). Delegate 'System.AsyncCallback' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.
How to fix?
UPDATE 1: Fixed Error (2) by adding 'Address Of' before 'request_CallBack' but Error (1) still remains.
UPDATE 2: Fixed all errors but not getting any response (empty). What's wrong with my code?
THe problems are two do with the line req.BeginGetResponse(New AsyncCallback(request_CallBack), WebRequest) This has two problems.
VB.Net does not have true first class functions so you have to use the AddressOf operator the create a delegate. Also the compiler will infer the delegate type so you don't need the constructor
BeginGetResponse takes a state object as the second parameter not a type expression. This is whatever you need in the callback
so:
req.BeginGetResponse(AddressOf request_CallBack, Nothing)
If you need to pass a type to the request callback use
req.BeginGetResponse(AddressOf request_CallBack, GetType(WebRequest))
However this looks like a copying change and what you want may be
req.BeginGetResponse(AddressOf request_CallBack, req)

Upload file to Solr with HttpClient and MultipartEntity

httpclient, httpmime 4.1.3
I am trying to upload a file through http to a remote server with no success.
Here's my code:
HttpPost method;
method = new HttpPost(solrUrl + "/extract");
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
MultipartEntity me = new MultipartEntity();
me.addPart("myfile", new InputStreamBody(doubleInput, contentType, fileId));
method.setEntity(me);
//method.setHeader("Content-Type", "multipart/form-data");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse hr = httpClient.execute(method);
The server is Solr.
This is to replace a working bash script that calls curl like this,
curl http://localhost:8080/solr/update/extract?literal.id=bububu&commit=true -F myfile=#bububu.doc
If I try to set "Content-Type" "multipart/form-data", the receiving part says that there's no boundary (which is true):
HTTP Status 500 - the request was rejected because no multipart boundary was found
If I omit this header setting, the server issues an error description that, as far as I discovered, indicates that the content type was not multipart [2]:
HTTP Status 400. The request sent by the client was syntactically incorrect ([doc=null] missing required field: id).
This is related to [1] but I couldn't determine the answer from it. I was wondering,
I am in the same situation but didn't understand what to do. I was hoping that the MultipartEntity would tell the HttpPost object that it is multipart, form data and have some boundary, and I wouldnt set content type by myself. I didn't quite get how to provide boundaries to the entities - the MultipartEntity doesn't have a method like setBoundary. Or, how to get that randomly generated boundary to specify it in addHeader by myself - no getBoundary methor either...
[1] Problem with setting header "Content-Type" in uploading file with HttpClient4
[2] http://lucene.472066.n3.nabble.com/Updating-the-index-with-a-csv-file-td490013.html
I am suspicious of
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
In the first line, is fileId a string or file pointer (or something else)? I hope it is a string. As for the second line, you can rather set a normal parameter.
I am trying to tackle the HTTP Status 400. I dont know much Java (or is that .Net?)
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error