RestSharp on Windows Phone with Request Parameters - windows-phone-7

I'm working on Windows phone client for one service with Oauth1 API.
In API docs I have something like this:
url: http://example.com/iphone/json/users/
method: GET
parameters:
page_num=[int] - page number, >=1, default=1.
For default page num everything works well:
RestClient HabraClient = new RestClient("http://habrahabr.ru");
HabraClient.Authenticator = OAuth1Authenticator.ForProtectedResource("xxx", "yyyyyy", App.Tokens.Key, App.Tokens.Secret);
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
When I execute this request I receive correct response with data.
But if I add parameter (uncomment TokenRequest.AddParameter("page_num", 2); ) I receive "Invalid signature". I have tried to send both int and string parameter.
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
I receive message "Invalid signature". I have tried string parameter too:
TokenRequest.AddParameter("page_num", "2");
API provider told me, that I have a problem with signature base
string http://oauth.net/core/1.0/#sig_base_example
So, how can i view it? Or maybe you can help me to solve all this
problem?

I think you are breaking the request structure... better to check the request over Fiddler, but try to write something like
var TokenRequest = new RestRequest("/iphone/json/users/?page_num=2", Method.GET);
instead of
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
Hope, it would help.

Related

Outlook Add-in - AttachmentId is malformed

We've been having issues intermittently where we get an error when downloading email item content from EWS "AttachmentId is malformed". This is for ItemAttachment (Especially .eml files)
We could not figure why or how this is happening and noticed that the ones that were failing had + and / in the id's. Searching across the web landed me on this article. Although this article is from 2015, wondering if this is still happening.
This article blew my mind and made sense (kind of) and implementing the conversion of + -> _ and / -> - worked fine, for a while.
We are now receiving the same error 'AttachmentId is malformed' and again could not find why, I removed the custom sanitizer function that replaces these characters and it started working again.
I have no idea what and why is this happening and how to reliably get attachment content. Currently, I've moved the sanitizer into the catch handler, so if for some reason the AttachmentId fails, we'll retry it by sanitizing it. Will have to keep an eye on how many fail.
Any light on this issue will be really appreciated.
Update 1.0 - Sample Code
Front-end
//At this point we've got the email and got the files
//We call EWS only if file.type == Office.MailboxEnums.AttachmentType.Item
//For all other files we call REST endpoint ~ Office.context.mailbox.restUrl + '/v2.0/'......
//Sample code below if only for EWS call
let files = this.email.attachments || [];
files.map(file => {
this._getEmailContent(file)
.then(res => {
return res;
});
})
//Get content from EWS
_getEmailContent(file, _failed){
//attachmentId
//Most of the times this will be fine, but at times when Id has a `+` or `/` if fails, Was expecting the convertToEwsId to handle any sanitization required.
let attachmentId = Office.context.mailbox.convertToEwsId(file.id, Office.MailboxEnums.RestVersion.v2_0);
return this.getToken(EWS)
.then(token => {
return this.http.post(`${endpoint}/downloadAttachment`,{
token: token,
url: Office.context.mailbox.ewsUrl,
id: attachmentId
},{
responseType: 'arraybuffer',
}).then(res => res.data);
}).catch(err => {
attachmentId = attachmentId.replace(/\+/g, "_");
this._getEmailContent(attachmentId, true);
})
}
Back-end
[HttpPost]
public DownloadAttachment(Request model){
var data = service.DownloadAttachment(model);
if(data == null)
{
return BadRequest("Error downloading content...");
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
return data;
}
}
//Inside service
public byte[] DownloadAttachment(Request request){
var ser = new ExchangeService
{
Credentials: request.token,
Url = request.url
}
//Here it fails intermittently, returning AttachmentId is malformed.
var attachment = ser.GetAttachments(new [] {request.attachmentId}, null, null).First();
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
fileAttachment.Load();
return fileAttachment.Content;
}
}

I have an error calling AWS API Gateway Websocket Route using wscat or via node.js

I create a websocket and then a custom route. Before publishing I need to select an integration for $disconnect and $default, for both I choose Mock (I have also tried default Lambda functions), this allows me to publish.
I then use wscat to call
wscat -c wss://t0p5b2xpm3.execute-api.us-east-1.amazonaws.com/prod
the socket connects successfully,then i try to call the route
{"action":"echo", "data":"test response body"}
and get the following error.
{"message": "Internal server error", "connectionId":"aDH97cQJoAMCI8Q=", "requestId":"aDIAhGE8oAMFoEg="}
anyone have any ideas please?
thanks,
Matt
For a lambda function, you need to return a statusCode of 200 for $connect, $disconnect, $default, and custom routes. A trivial javascript example:
module.exports.handler = async (event) => {
return {
statusCode: 200,
};
};
exports.handler = async (event) => {
// TODO implement
let time = "undefined";
let state = "undefined";
if (event.body !== null && event.body !== undefined) {
let body = JSON.parse(event.body);
if (body.time && body.state)
{
time = body.time;
state = body.state;
}
}
const response = {
statusCode: 200,
body: JSON.stringify({time:time, state: state}),
};
return response;
};
In case of API-Gateway you won't be able to modify the response as json as in Get and Post, so you can use this code to fetch time and state from the coming json object. Connect using wscat -c link and then send your json as {"time":"22:32","state":"LA"}
Try to put in $default to make sure that you are receiving the sending the right way.
Good luck!

Request to Parse API using RestSharp.Portable in Xamarin

I'm having problems trying to do a GET request to Parse REST API using RestSharp.Portable in a PCL Xamarin project.
The problem occurs in the line:
var result = await client.Execute (request);
Throwing an exception and stopping the app (Android).
This is the function i'm using.
public async Task<EventItem> GetAListOfAllEvents ()
{
using (var client = new RestClient (new Uri ("http://api.parse.com"))) {
var request = new RestRequest ("1/classes/Event/2yHLWDUlv3");
request.Method = HttpMethod.Get;
request.AddHeader ("Content-Type", "application/json");
request.AddHeader ("X-Parse-Application-Id", "myAppId");
request.AddHeader ("X-Parse-REST-API-Key", "myAPIparseKey");
var result = await client.Execute (request);
return result;
}
}
I hope someone could help me, thanks.
Remove this line.
request.AddHeader ("Content-Type", "application/json");
Request is failing because of it (probably as you have no actual content in your GET request).

How to access POST data sent from a browser to Rikulo Steam Server

I ask the browser to POST JSON data to the stream v0.5.5 server using ajax. In the server side, how can I receive the data from the ajax request?
My client:(Google Chrome)
void ajaxSendJSON() {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
});
// POST the data to the server
var url = "/news";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.send(mapTOJSON()); // perform the async POST
}
String mapTOJSON() {
print('mapping json...');
var obj = new Map();
obj['title'] = usrTitle.value == null ? "none" : usrTitle.value;
obj['description'] = usrDesc.value == null ? "none" : usrDesc.value;
obj['photo'] = usrPhoto.value == "none";
obj['time'] = usrTime==null ? "none" : usrTime.value;
obj['ip']= '191.23.3.1';
//obj["ip"] = usrTime==null? "none":usrTime;
print('sending json to server...');
return Json.stringify(obj); // convert map to String i.e. JSON
//return obj;
}
My server:
void serverInfo(HttpConnect connect) {
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/news' && request.method == 'POST') {
response.addString('welcome from the server!');
response.addString('Content Length: ');
response.addString(request.contentLength.toString());
} else {
response.addString('Not found');
response.statusCode = HttpStatus.NOT_FOUND;
}
connect.close();
}
Again, I don't want the browser to ask for data from the server!
What am I doing is to asking the browser to submit the JSON data via ajax, and I just don't know how the server (Rikulo Stream v0.5.5) gets the "content" of data? All code is written in Google Dart Language M3. No Javascript!
POST is not supported well in Dart SDK, but Dart team planned to enhance it. Please stargaze it here: issue 2488.
On the other hand, since what you handle is JSON, you can listen to HttpRequest (I'm assuming the latest SDK) and convert List to String and then to JSON. Rikulo Commons provides a utility to simplify the job as follows:
import "package:rikulo_commons/io.dart";
IOUtil.readAsJson(request, onError: connect.error).then((jsonValue) {
//handle it here
});

RestSharp on Windows Phone no set-cookie in response

I have a problem with using the RestSharp client on the Windows Phone device. Starting form the beginning, I have the ASP.NET Web Api service hosted online. I have a request user address: POST: http://my-service-url.com/token where I send Email and Password as a body parameters and I get 201 status code and a cookie in the response. When I do it in fiddler everything works fine. I also have the functional test for my API which is using the RestSharp which is also working correctly:
[Given(#"I fill email and password with correct data and I click log in button")]
public void GivenIFillEmailAndPasswordWithCorrectDataAndIClickLogInButton()
{
//Delete user if he exists
_testUserHelper.DeleteTestUser(TestEmail);
//Create new activated user
Assert.IsTrue(_testUserHelper.CreateTestUser(TestEmail, TestPassword));
//Prepare client
var client = new RestClient(CarRentalsConstants.HostAddress);
var restRequest = new RestRequest("api/token", Method.POST) { RequestFormat = DataFormat.Json };
//Add parameters to request
restRequest.AddBody(new { Email = TestEmail, Password = TestPassword });
//Perform request
_response = client.Execute(restRequest);
}
[When(#"the log in login process finishes")]
public void WhenTheLogInLoginProcessFinishes()
{
Assert.AreEqual(HttpStatusCode.Created, _response.StatusCode, _response.Content);
Assert.IsNotNull(_response.Cookies.SingleOrDefault(q => q.Name == ".ASPXAUTH"););
}
The one above works properly, and the cookie is in the response object.
Now what I try to do on my windows phone looks like this:
var restRequest = new RestRequest("token", Method.POST) {RequestFormat = DataFormat.Json};
restRequest.AddBody(new {Email = email, Password = password});
myWebClient.ExecuteAsync(restRequest, (restResponse, handle) =>
{
switch (restResponse.StatusCode)
{
case HttpStatusCode.Created:
{
var cookie = restResponse.Cookies.SingleOrDefault(q => q.Name == ".ASPXAUTH");
successLogicDelegate(cookie);
}
break;
case HttpStatusCode.BadRequest:
{
HandleBadRequest(restResponse.Content, failureLogicDelegate);
}
break;
default:
msgBox.Show(StringResources.ServerConnectionError);
failureLogicDelegate(null);
break;
}
});
And in this case, the response returns the "Created" status code, but the cookie is then set to null. I have no idea what is happening here, but I am fairly certain that server is sending this cookie, so where does it get lost?
Any help will be really appreciated.

Resources