Silverlight HTTP POST - silverlight

I am just trying to perform an http post on http://www.test.com/test.asp?test1=3. Here is the code I have been trying to use:
private void pif_test_conn()
{
Uri url = new Uri("http://www.test.com/test.asp?test1=3", UriKind.Absolute);
if (httpResult == true)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
return ;
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
MessageBox.Show("Using HttpWebRequest: " + resultString, "Found", MessageBoxButton.OK);
}
}
When I execute this code my program triggers the Application_UnhandledException event. Not sure what I am doing wrong.

Are you trying to post to another host? That behavior could lead to XSS security problems, so that isnt available.
string responseValue = "";
AutoResetEvent syncRequest = new AutoResetEvent(false);
Uri address = new Uri(HtmlPage.Document.DocumentUri, "/sample.aspx");
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
// Send packet data
using (Stream post = request.EndGetRequestStream(getRequestResult))
{
post.Write(buffer, 0, buffer.Length);
post.Close();
}
// wait for server response
request.BeginGetResponse(getResponseResult =>
{
WebResponse response = request.EndGetResponse(getResponseResult);
responseValue=new StreamReader(response.GetResponseStream()).ReadToEnd();
syncRequest.Set();
}, null);
}, null);
syncRequest.WaitOne();
MessageBox.Show(
"Using WebRequest: " + responseValue,
"Found", MessageBoxButton.OK);
HTH

You can only send HTTP requests to the domain that your app comes from.
This restriction prevents XSS attacks.

With regard to Rubens' answer,
If you leave in the SyncRequest.WaitOne() call, the call deadlocks, at least in Silverlight 4.0.

In order to send an HTTP POST, you need to write the POST data to the request by calling the BeginGetRequestStream method.
This is probably why you're getting an exception; please tell us what exception you're geting for a more specific answer.

Related

Salesforce test web service call

Here is the code for a helper function
public class SalesforceHelper {
public static void waitCall(String timeout){
System_Settings__c lnpSetting = System_Settings__c.getValues('System Properties');
String endpoint=lnpSetting.Base_Endpoint_URL__c + 'salesforceHelper/wait?timeout=' + timeout;
system.debug('====endpoint======'+endpoint);
HttpRequest httpReq=new HttpRequest();
HttpResponse httpResp = new HttpResponse();
Http http = new Http();
httpReq.setMethod('GET');
httpReq.setEndpoint(endpoint);
String username=lnpSetting.Endpoint_Username__c;
String password=lnpSetting.Endpoint_Password__c;
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
httpReq.setHeader('Authorization', authorizationHeader);
httpReq.setHeader('content-type','application/json; charset=utf-8');
httpReq.setTimeout(120000);
try{
httpResp = http.send(httpReq);
System.debug('Wait response' + httpResp);
} catch (Exception e) {
system.debug(LoggingLevel.Error, 'Error HTTP response code = ' + httpResp.getStatusCode() + '; calling '+endpoint );
}
}
}
Basically this method just using HttpRequest and HttpResponse to call the endpoint URL, and the endpoint URL is web service, and it will just return 200 after the timeout that specified in the parameter.
Now the question is, I need to write a test case to cover this method, and I don't know how to write it.. I don't know how to mock the httpcallout properly, because this method doesn't return HttpResponse, and since the code is freeze right now, I cannot modified my class to make the test case work.
So any other way I can create the test class for this method?
You should definitely be able to use standard Http Callout Mock:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
The only difference would be that you'd only set stats code:
// Create a fake response
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;
and check for response code:
System.assertEquals(200, res.getStatusCode());

NancyFX on Krestrel - Response Stream Closed

I'm attempting it make a simple proxy server that will try to stream back data from an IP camera (the IP camera doesn't honor OPTIONS and has some other issues!). I tried doing this using NancyFX and Krestrel with the following proxy module. The idea was to just get 1028 bytes of data in and write it to the output stream asynchronously until canceled.
Here is a sample Nancy Module:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Nancy;
namespace Server.Modules
{
public class Proxy : NancyModule
{
public Proxy() : base("api/proxy")
{
Get("/", ProxyPage);
}
private async Task<Response> ProxyPage(dynamic args, CancellationToken cancellationToken)
{
// Create HttpClient
using (var httpClient = new HttpClient()) // Make this global/cached and indexed by auth code
{
// Handle Authentication
var auth = string.Empty;
if (!string.IsNullOrEmpty(Request.Headers.Authorization) && Request.Headers.Authorization.Contains(" "))
auth = Request.Headers.Authorization.Split(' ')[1];
else if (!string.IsNullOrEmpty(Request.Query.authorization))
auth = Request.Query.authorization;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
// Create Proxy REsponse object
var proxyResponse = new Response();
// Get Async
HttpResponseMessage response = await httpClient.GetAsync(Request.Query["url"],
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
// Set Content Type
proxyResponse.ContentType = response.Content.Headers.ContentType.ToString();
// Set Status Code
proxyResponse.StatusCode = (HttpStatusCode)(int)response.StatusCode;
// Handle stream writing
proxyResponse.Contents = async s =>
{
var result = response.Content.ReadAsStreamAsync();
var data = new byte[1028];
int bytesRead;
while (!cancellationToken.IsCancellationRequested && (bytesRead = await result.Result.ReadAsync(data, 0, data.Length, cancellationToken)) > 0)
{
await s.WriteAsync(data, 0, bytesRead, cancellationToken);
await s.FlushAsync(cancellationToken);
}
response.Dispose();
};
// Return Response container
return proxyResponse;
}
}
}
}
When I run it, I get through the while loop a couple times but then get an exception in FrameResponseStream (Krestrel): "System.ObjectDisposedException: 'Cannot access a disposed object.'" It appears that the stream is being closed (_state = FrameStreamState.Closed -- https://github.com/aspnet/KestrelHttpServer/blob/rel/2.0.0/src/Microsoft.AspNetCore.Server.Kestrel.Core/Internal/Http/FrameResponseStream.cs) prematurely but I cannot figure out why or what I need to change to resolve it!
You should use ResponseContentRead instead of ResponseHeadersRead
HttpResponseMessage response = await httpClient.GetAsync(Request.Query["url"],
HttpCompletionOption.ResponseContentRead, cancellationToken);

HTTP 204 error when sending File in response REST

This is my write to excel method which returns javax.ws.rs.core.Response
public Response writeToExcel(UserDeatilsVOWrapper listBook) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Resource Information");
int rowCount = 0;
createHeaderRow(spreadsheet);
for (UserDetailsVO detailsVO : listBook.getUserDetailsList()) {
Row row = spreadsheet.createRow(++rowCount);
writeBook(detailsVO, row);
}
Response response = null;
try (FileOutputStream outputStream = new FileOutputStream(new File("ResourceInformation.xlsx"))) {
workbook.write(outputStream);
// header required to enable download pop-up and set file name
Response.ok().header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx").build();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
This is my web service:
#POST
#Path(WebServiceConstants.DOWNLOAD_EXCEL)
#Consumes(MediaType.APPLICATION_JSON)
public Response getFile(UserDeatilsVOWrapper wrapper) {
Response respose=new ExportToExcel().writeToExcel(wrapper);
return respose;}
I get a HTTP204 error. I'm using postman. I know, I'm doing a big mistake in write to excel method and when trying to send file along with response.
Also is there any possible way to write a file object on REST response without saving file on server? I'm doing terrible in here. any help is appreciated.
I do not see where you set your file to the response. Normally you would do something like this
File file = new File("ResourceInformation.xlsx"))
// Do your excel-writing here...
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx");
return response.build();

Missing credential from request in OOB application

I'm writing a simple Silverlight application in which I have the following code, which I think is pretty standard:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
var request = new WebClient();
var cred = new NetworkCredential(Server.UserName, Server.Password);
request.Credentials = cred;
request.UseDefaultCredentials = false;
request.DownloadStringCompleted += TestServerCompleted;
var uri = new Uri(Server.GetRequestUrl(Methods.ping));
request.DownloadStringAsync(uri);
Yet when I view the request in Fiddler, no credentials are added to the headers. What am I missing? Shouldn't there be an "Authorization: Basic ..." header in there?
Try with something like this.
HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.UseDefaultCredentials = false;
req.Credentials = ew NetworkCredential(Server.UserName, Server.Passwor
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
return req;
req.BeginGetResponse((IAsyncResult asynchronousResultResponse) =>
{
try
{
HttpWebRequest requestResponse = (HttpWebRequest)asynchronousResultResponse.AsyncState;
HttpWebResponse response = (HttpWebResponse)requestResponse.EndGetResponse(asynchronousResultResponse);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Your response is here in responseString
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (Exception e)
{
Callback(null, e);
}
}, webRequest);
I Hope it can help, even 2 months later...

Facebook Photo Upload in C#?

I am trying to upload an photo to Facebook from a Windows Phone Silverlight application using the Facebook Graph API but I am getting an error: (#324) Requires upload file. Can anyone see anything wrong in my code?
internal void PublishPhoto(System.IO.MemoryStream stream, string message, string accessToken)
{
var requestUriString = string.Format(
CultureInfo.InvariantCulture,
"https://graph.facebook.com/{0}/photos?access_token={1}&message={2}",
"me",
accessToken,
message);
var webRequest = WebRequest.CreateHttp(requestUriString);
webRequest.Method = "POST";
var boundary = "7db3d9202a1";
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.BeginGetRequestStream(new AsyncCallback(delegate (IAsyncResult result)
{
GetRequestStream(stream, boundary, result);
BeginGetResponse(webRequest);
}), webRequest);
}
private static void GetRequestStream(System.IO.MemoryStream imageStream, string boundary, IAsyncResult result)
{
var webRequest2 = result.AsyncState as HttpWebRequest;
using (var requestStream = webRequest2.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.WriteLine("--{0}\r", boundary);
writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
writer.WriteLine("Content-Type: image/jpg\r");
byte[] buffer = imageStream.GetBuffer();
requestStream.Write(buffer, 0, buffer.Length);
writer.WriteLine("\r");
writer.WriteLine("--{0}--\r", boundary);
}
imageStream.Close();
}
}
private static void BeginGetResponse(HttpWebRequest webRequest)
{
webRequest.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult result2)
{
var webRequest2 = result2.AsyncState as HttpWebRequest;
try
{
using (var response = webRequest2.EndGetResponse(result2))
{
using (var responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException we)
{
System.Diagnostics.Debug.WriteLine(we.Message);
using (var responseStream = we.Response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
var errorJson = reader.ReadToEnd();
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookErrorResponse>(errorJson);
System.Diagnostics.Debug.WriteLine("Could not upload image to Facebook: {0}", response.Error.Message);
}
}
}
}), webRequest);
}
}
Try specifying a name of "source" as well as a filename in the Content-Disposition header, i.e.
writer.WriteLine("Content-Disposition: form-data; name=\"source\"; filename=\"sketch.jpg\"\r");
Ok, I was wrong the first time around, but now I have it.
The first problem, which we already took care of above, was that you were missing the "--" before each boundary and the "--" after the last boundary in the POST body.
The second problem is that you're not leaving a blank line after the MIME headers before writing the image content.
The third problem is that you're not flushing the writer before writing the image data to its underlying stream (unless silverlight on a phone is different from normal .NET in auto-flushing StreamWriters).
To sum up, this should work:
writer.WriteLine("--{0}\r", boundary);
writer.WriteLine("Content-Disposition: form-data; filename=\"sketch.jpg\"\r");
writer.WriteLine("Content-Type: image/jpg\r");
writer.WriteLine("\r");
writer.Flush();
byte[] buffer = imageStream.GetBuffer();
requestStream.Write(buffer, 0, buffer.Length);
writer.WriteLine("\r");
writer.WriteLine("--{0}--\r", boundary);

Resources