FluorineFx Inspect AMF Header - amf

Currently, using Flex using FluorineFx to connect .Net back end. On the flex side I am injecting a custom value into the AMF3 header. Does anyone know how to get to the AMF header on the .Net side after FluorineFx has parsed the request? It is not apparent to me if FluorineFx gives me access to the AMF3 message after it has parsed it.

This works for me:
var amfMessage =
(AmfBaseMessage) OperationContext.Current.RequestContext.RequestMessage;
var header = amfMessage.AmfHeaders.FirstOrDefault(x => x.Name == "HeaderName");
var headerValue = header.Content as string;
Just replace HeaderName and as string as the appropriate name and type for your needs.

Related

Get "API key is missing" error when querying account details to Mailchimp API 3.0 using RestSharp

When using RestSharp to query account details in your MailChimp account I get a "401: unauthorized" with "API key is missing", even though it clearly isn't!
We're using the same method to create our RestClient with several different methods, and in all requests it is working flawlessly. However, when we're trying to request the account details, meaning the RestRequest URI is empty, we get this weird error and message.
Examples:
private static RestClient CreateApi3Client(string apikey)
{
var client = new RestClient("https://us2.api.mailchimp.com/3.0");
client.Authenticator = new HttpBasicAuthenticator(null, apiKey);
return client;
}
public void TestCases() {
var client = CreateApi3Client(_account.MailChimpApiKey);
var req1 = new RestRequest($"lists/{_account.MailChimpList}/webhooks", Method.GET);
var res1 = client.Execute(req1); // works perfectly
var req2 = new RestRequest($"automations/{account.MailChimpTriggerEmail}/emails", Method.GET);
var res2 = client.Execute(req2); // no problem
var req3 = new RestRequest(Method.GET);
var res3 = client.Execute(req3); // will give 401, api key missing
var req4 = new RestRequest(string.Empty, Method.GET);
var res4 = client.Execute(req4); // same here, 401
}
When trying the api call in Postman all is well. https://us2.api.mailchimp.com/3.0, GET with basic auth gives me all the account information and when debugging in c# all looks identical.
I'm trying to decide whether to point blame to a bug in either RestSharp or MailChimp API. Has anyone had a similar problem?
After several hours we finally found what was causing this..
When RestSharp is making the request to https://us2.api.mailchimp.com/3.0/ it's opting to omit the trailing '/'
(even if you specifically add this in the RestRequest, like: new RestRequest("/", Method.GET))
so the request was made to https://us2.api.mailchimp.com/3.0
This caused a serverside redirect to 'https://us2.api.mailchimp.com/3.0/' (with the trailing '/') and for some reason this redirect scrubbed away the authentication header.
So we tried making a
new RestRequest("/", Method.GET)
with some parameters (req.AddParameter("fields", "email")) to make it not scrub the trailing '/', but this to was failing.
The only way we were able to "fool" RestSharp was to write it a bit less sexy like:
new RestRequest("/?fields=email", Method.GET)

AngularJS setting headers on GET Request

I'm implementing a login authentication and the backend developer wants me to pass along the key value pairs in the header when i make a GET request. I'm new to AngularJS and I think my problem is the format of my header. I'm able to get a status 200 in Advanced Rest client (chrome extension for testing apis) with this format below. That is the raw format of the key value pairs if i put curly brackets around them or quotes or even a comma it throws an error so i'm very certain that should be the correct format.
identity: foo
password: bar
I've done every format possible to try to replicate it in the above example. So in my Code it goes like this, and i always get an error.
var config = {headers:{'identity': 'foo', 'password':'bar'}};
this.GetUser = function (config) {
return $http.get($rootScope.endPoint + '/user/email_token)', config);
};
you can do it like this:
$http.defaults.headers.common['identity'] = 'foo';
$http.defaults.headers.common['password'] = 'bar';
and call the api without additional properties
this.GetUser = function () {
return $http.get($rootScope.endPoint + '/user/email_token)');
};

Receiving null parameters from request in JSP file when are being sent

I've a JSP app. It uploads a file, but to do so the user has to authenticate using a name and a password. So my JSP file starts with:
//0.2.- We get the password
String password = (String) request.getParameter("pass"); // -> This returns NULL
//0.3.- We get the "uvus"
String uvus = (String) request.getParameter("uvus"); //-> This also returns NULL
//More code
So I'm trying to know why am I getting null from those variables.
I went to the form I was uploading, and look for the data that was being sent. Using Firefox Debug Tools, I saw:
So in fact, it was being sent.
As additional info, I'm building the request like this:
var pUvus = document.getElementById("uvus").value;
var pPassword = document.getElementById("pass").value;
var file = document.getElementById("userFile");
var formData = new FormData();
formData.append("upload", file.files[0]);
formData.append("uvus", pUvus);
formData.append("pass", pPassword);
xmlhttp.open("POST","uploadFile.jsp",true);
xmlhttp.send(formData);
At last, I would like to say that I can get vars from application object in the same JSP with no errors, and have received in another pair of JSP files vars at request object without more problems, so I think my fault should be in the way I'm building the request in Ajax, but I've no more clue about that...
Anyone can guide me?
Thanks for your help
Update: #rickz asked for how do I get the file and parse the request (what is done after my problem, trying to get the objects from the request scope):
List items;
items = servlet_up.parseRequest(request);
for(int i=0;i<items.size();i++)
{
FileItem item = (FileItem) items.get(i);
if (! item.isFormField())
{
request.getParameter() won't work for a multipart/form-data request.
If you are using org.apache.commons.fileupload then you should be using something like
if(item.isFormField()){
name = item.getFieldName();
...
}

Do Get request with a complex type parameter in the request body with web api

I want to do an integration test for the below action.
How can I pass my requestDto object in the integration test?
Neither the GetAsync nor SendAsync method has an overload parameter to pass a custom object to the server.
[Route("{startDate:datetime}")]
[HttpGet]
public HttpResponseMessage Get(DateTime startDate, [FromBody]LessonplannerGetRequest request)
{
request.StartDate = startDate;
var lessonplannerResponse = _service.GetPeriodsByWeekStartDate(request);
return Request.CreateResponse<LessonplannerResponse>(HttpStatusCode.OK, lessonplannerResponse);
}
[Test]
public void Get_Lessons_By_Date()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, _server.BaseAddress + "/api/lessonplanner/2014-01-14");
var myRequestDto = new LessonplannerGetRequest();
// Act => QUESTION: HOW do I pass the myRequestDto ???
var response = _client.SendAsync(request, new CancellationToken()).Result;
// Assert
Assert.That(response.StatusCode == HttpStatusCode.OK);
}
UPDATE
As Darrel Miller said:"Technically HTTP says you can send a body, it just says the body doesn't mean anything and cannot be used. HttpClient won't let you send one."
I post here my integration test with HttpClient doing a Get request with complex type + FromBody:
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, _server.BaseAddress + "/api/lessonplanner/2014-01-14");
var myRequestDto = new LessonplannerGetRequest{ FirstDayOfWeek = DayOfWeek.Sunday, SchoolyearId = 1, StartDate = DateTime.Today};
request.Content = new ObjectContent<LessonplannerGetRequest>(myRequestDto, new JsonMediaTypeFormatter());
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
var response = _client.SendAsync(request, new CancellationToken()).Result;
// Assert
Assert.That(response.StatusCode == HttpStatusCode.OK);
Of course is this is not the Http way some might consider doing it differentlly sending complex type via FromUri/query string.
HTML specifications says you cannot send a GET with a body.
HTTP specs allows it.
WebAPI allows it, because it is a service/REST and implements HTTP but not HTML, but many clients and browser won't allow it because they implement both specs and try to be strict.
As for the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) itself, it states:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
(e.g. if you do a <form> with GET, it will parse all the form params and set them in the query string ?a=b).
In term of pure HTTP and in the context of REST services, nothing prevents that behavior, but not all clients will be able to handle it. It's mostly a best-practice advise when it comes to REST/WebAPI to not handle body data from HttpGet, only URI data (the opposite, POST /action?filter=all is usually tolerated for metadata/action qualifiers, but that's another discussion).
So yeah, it's at your own risk, even if used only internally. As not all clients handle it (e.g. HttpRequestMessage), so you might run into trouble like you have.
You should NOT pass a GET body with HTTPClient.

GWT FormPanel method replaced by input parameter

We've discovered a strange new bug in a GWT application I'm maintaining, and I'm not sure when it became an issue. Possibly with a new Firefox version.
We're sending a POST request to the server using a FormPanel, essentially like many examples I've seen online. But since we actually want a PUT request, one of the hidden input parameters is named "method" and has a value of "put".
Now, when I look at the request in Fiddler coming from Firefox, it is being transformed into a GET request with all the parameters in the QueryString. In IE and Chrome, the parameters are in the body of a POST request.
I've displayed the value of FormPanel.getMethod() in an alert, and in IE and Chrome the string "post" is displayed, whereas in firefox it is showing "object HTMLInputElement". Unfortunately, hosted mode debugging does not work with this project.
It obviously looks like the FormPanel's getMethod() function is returning the hidden input parameter named method instead of the actual form's method in Firefox.
Technically I should avoid changing the servlet as this is from an OpenSource project that we use, though I've found I can fix the issue by changing the hidden input parameter's name to "_method" on both ends.
Has anyone ever seen anything like this? I can't find anything in Google.
UPDATE: We're using GWT 2.3 in case that helps
Some insight can be found here Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
I would also suggest using XMLHttpRequest. In this case you [most probably] don't have to change anything on the server side.
In case if you use Submit button, you can write in its clickHandler function:
submitMyForm(yourTextBox.getText(), self);
// self - is the instance of main class (named UploadForm here), needs to be passed here for future reference
and then some more (you can adapt this for your needs):
private native void submitMyForm(String text, UploadForm handler)/*-{
var fd = new FormData();
fd.append("textValue", text);
var xhr = new XMLHttpRequest();
var upload = xhr.upload;
readyStateChangeHandler = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var serverResponse = eval(xhr.responseText); // optional
handler.#com.project.UploadForm::onUploadIsDone(Lcom/google/gwt/core/client/JavaScriptObject;)(serverResponse);
} else {
handler.#com.project.UploadForm::onUploadFailed(I)(status);
}
}
};
xhr.onreadystatechange = readyStateChangeHandler;
xhr.open("PUT", yourActionUrlHere);
xhr.send(formData);
}-*/;

Resources