Windows phone: what to do with webresponse object? - windows

I am trying to create a simple rss feed reader. I got this webresponse object but how to extract text,links from this?
WebResponse response = request.EndGetResponse(result);
Also,can anyone tell me what is the underlying framework behind all the working of windows phone 8.Is it known as Silverlight?I want to know it so that I can make relevant Google searches and don't bother you people time and again?

It depends on what you want to do with it. You will need to get the Stream and then from there can turn it into a string (or other primitive type), just Json.Net to convert from json to an object, or you can use the stream to create an image.
using (var response = webRequest.EndGetResponse(asyncResult))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
// need a string?
string result = reader.ReadToEnd();
// Need to convert from json?
MyObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(result);
}
}

Related

Xamarin [RestSharp] + [Xam.Plugin.Media] upload model containing image

I'm trying to upload an image from xamarin.forms and using restsharp for api service.
RestRequest uploadPostRestRequest = new RestRequest("post/create/", Method.POST);
uploadPostRestRequest.AddJsonBody(uploadPostRequest);
and this is my model UploadPostRequest
public class UploadPostRequest
{
public string content;
public byte[] image;
}
Question - Is it right to set image type as byte[]?
Would server accept this or would restsharp manage it?
If RestSharp has a nice control with this, can I just put MediaFile from Xam.Plugin.Media so I can upload it right over?
Xam.Plugin.Media is used for picking images from mobile device.
Too many options, so, that's why I'm looking for good advice.
Has anyone experienced this same issue before? please help.
For additional info, I cant use System.IO.File, Xamarin.Forms wont let me use it.
When the Xam.Plugin.Media finish loading the media either from the Camera or from the Library it returns a MediaFile. This object can be converter to a byte array with something like this:
byte[] byteArray;
using (var memoryStream = new MemoryStream ())
{
mediaFile.GetStream ().CopyTo (memoryStream);
mediaFile.Dispose ();
byteArray = memoryStream.ToArray ();
}
Now you have the byte array you just need to pass it to the method that will upload the image to your backend.

creating ISearchResponse<T> from json string for unit test

is there a way I can create ISearchResponse to simulate return by elastic search from JSON string? I need to write unittests for my API. The API building the query has histogram, date filters etc and hence response will be as per that and I want to simulate that.
Thanks
You can deserialize json into an instance of ISearchResponse<T> with
ISearchResponse<T> searchResponse = null;
using (var stream = File.OpenRead("path-to-json.json"))
{
searchResponse = client.Serializer.Deserialize<SearchResponse<T>>(stream);
}
If this is stub data, I'd be more inclined to have a stub implementation of ISearchResponse<T> in code as opposed to deserializing json to create an instance; maybe a little easier to maintain.

Globally formatting .net Web Api response

I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.
Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.
public IHttpActionResult GetServices()
{
var data = _dataService.Get(); //retrieves data from a service
var result = JsonConvert.DeserializeObject(data); //convert to object
return Ok(result);
}
What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.
On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.
HttpConfiguration configuration = new HttpConfiguration();
var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DefaultContractResolver();
Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?
Thanks
If you want to just pass through the json (Option A), you can do this
public IHttpActionResult GetServices() {
var json = _dataService.Get(); //retrieves data from a service
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return ResponseMessage(response);
}

Read both key values and files from multipart from data post request in ASP.NET WebAPI

I have an endpoint that needs to accept a file upload and also some other information from the client request. With the following code I can upload the file successfully but can't seem to figure out how to read the other info.
I make a test request from Postman with the following form data:
image -- myimage.jpg -- of type File
email -- a#b.com -- of type Text
The backend code looks like this:
[HttpPost]
public async Task<HttpResponseMessage> SharePhoto()
{
try
{
var provider = new MultipartMemoryStreamProvider();
var data = await Request.Content.ReadAsMultipartAsync(provider);
// this is how I get the image which I am succesfully passing to EmailService
var item = (StreamContent)provider.Contents[0];
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
String emailAddress;
EmailService.SendSharedPhoto(emailAddress, stream);
return Request.CreateResponse();
}
}
catch
{
// do stuff
}
}
In this example I am able to access provider.Contents[1] but can't seem to be able to get the value from it into emailAddress. I'm thinking it may be possible to use the same trick as the await item.CopyToASync(stream) from the image upload, but I'm hoping I can get a simpler solution to that. Any ideas?
I just barely answered a very similar question to this yesterday. See my answer here complete with sample controller code.
The method I ended up using is:
If the form elements are strings (and it worked for me since the mobiel frontend took responsability for input data) you can do this:
var streamContent = (StreamContent)provider.Contents[1];
var memStream = new MemoryStream();
await streamContent.CopyToAsync(memStream);
var actualString = Encoding.UTF8.GetString(x.ToArray());
If however the field needs to represent a collection of items, like for example the email list: ["a#b.com", "x#c.com"], etc a JavaScriptSerializer can be user, like so:
var streamContent = (StreamContent)provider.Contents[1];
var emailAddresses = await str.ReadAsStringAsync();
var jsSerializer = new JavaScriptSerializer();
var deserializedData = jsSerializer.Deserialize<string[]>(emailAddresses);
Note that this is nowhere near safe, though it is few lines of code and happens to work.

Returning Raw Json in ElasticSearch NEST query

I'm doing a small research about a client for elastic search in .net and I found that NEST is one of the most supported solutions for this matter.
I was looking at Nest's docummentation and I couldn´t find a way to output a raw json from a query and avoid the serialization into an object, because I'm using angularJs in the front end I don´t want to overload the process of sending the information to the client with some unnecessary steps.
......and also I'd like to know how can I overrdide the serialization process?
I found that NEST uses Json.NET which I would like to change for the servicestack json serielizer.
thanks!
Hi Pedro you can do this with NEST
var searchDescriptor = new SearchDescriptor<ElasticSearchProject>()
.Query(q=>q.MatchAll());
var request = this._client.Serializer.Serialize(searchDescriptor);
ConnectionStatus result = this._client.Raw.SearchPost(request);
Assert.NotNull(result);
Assert.True(result.Success);
Assert.IsNotEmpty(result.Result);
This allows you to strongly type your queries, but return the string .Result which is the raw response from elasticsearch as string to your
request can be an object or the string so if you are OK with the internal json serialize just pass searchDescriptor directly
Use RequestResponseSerializer instead of Serializer.
var searchDescriptor = ...;
...
byte[] b = new byte[60000];
using (MemoryStream ms = new MemoryStream(b))
{
this._client.RequestResponseSerializer.Serialize(searchDescriptor , ms);
}
var rawJson = System.Text.Encoding.Default.GetString(b);

Resources