How serialize HttpClient Object in windows phone 8? - c#

I use System.Net.Http.HttpClient Object to login to a forum successfully and do many operations. Then the object may have some state, so I want to reuse the object when the program is been opened again, implementing the automatic login.
I use Json.net to serialize the HttpClient Object to the IsolatedStorage, but not available.
Can somebody help me? Thank you!!
//The code for initializing the HttpClient Object
HttpClientHandler handler = new HttpClientHandler();
handler.UseCookies = true;
HttpCliclient = new HttpClient(handler);
I first serialize the object using Json.net, get the json string:
{"DefaultRequestHeaders":],"BaseAddress":null,"Timeout":"00:01:40","MaxResponseContentBufferSize":2147483647}
Then deserialize the json string to get the object, but the object need logining again to do operations.
using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
string jsonData = JsonConvert.SerializeObject(httpclient);
System.Diagnostics.Debug.WriteLine(jsonData);
using (IsolatedStorageFileStream stream = storeFolder.CreateFile(path))
using (StreamWriter writer = new StreamWriter(stream))
writer.Write(jsonData);
}
using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
string jsonData;
using (IsolatedStorageFileStream stream = storeFolder.OpenFile(path, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
jsonData = reader.ReadToEnd();
HttpClient httpclient = JsonConvert.DeserializeObject<HttpClient>(jsonData);
//need login again to do some operations
}

Don't try and serialize HttpClient. The chances of it working are highly unlikely. Pretty much the only state you might be able to serialize from it are the default request headers. Create a HttpClient Factory method and just serialize out the header information that you want to preserve.

Related

How to get httpcontext.request as it is in .net Core?

I am trying to read request from httpcontext,but it is changing, not same with original request.So it creates problem during hashing on SHA256.When I try to create sha256 on online tools with original request it is okey,but when I take request after reading it from httpcontext.request its is not same hash I create with original request.
What is the exact solution to read request as same as with original request without changing it and convert to string to compute SHA256?
using (var ms = new MemoryStream())
{
await httpContext.Request.Body.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var bodyContent = serializer.Deserialize(jsonTextReader);
//hashing starts here with bodyContent.ToString()
}
}
}

Json to HttpContent using streams

I have a class MyData which is Json serializable by using Json.Net JsonSerializer.Serialize(TextWriter, object). I want to send this data (as json) to a web service via HttpClient.PostAsync.
Because converting the json to string and then sending it as StringContent is (probably) not performant, I want to do it with streams.
I found the class StreamContent, which takes a stream in its constructor. And serializing json into streams should be possible as well. So I tried this:
MyData data = ...; // already filled
string uri = ...; // already filled
HttpClient client = new HttpClient();
JsonSerializer serializer = new JsonSerializer();
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
using (JsonWriter jw = new JsonTextWriter(sw))
{
serializer.Serialize(sw, data);
ms.Flush();
ms.Position = 0;
}
HttpResponseMessage response = client.PostAsync(uri, new StreamContent(ms)).Result;
}
But running this code gives me two exceptions in the line HttpResponseMessage response = ...:
HttpRequestException: Error when copying content into a stream.
ObjectDisposedException: Could not access closed stream.
What am I doing wrong?
If you serialize the object into a MemoryStream, the entire JSON data will be written in the buffer, so there is no significant performance benefit over just serializing into a string and using StringContent.
Your StremWriter disposes the memory stream before the request is sent, that is why you get the exceptions.
You can either move your using statements to be in the same scope as the MemoryStream, or use the StreamWriter's constructor that accepts a boolean parameter to leave the stream open after the writer is disposed.
StreamWriter constructor:
Unless you set the leaveOpen parameter to true, the StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

Receive bson stream in azure function

I have azure function, which accepts huge bson object. It binds to http request and then try to deserialize it using stream with the following code:
using (var stream = new MemoryStream())
{
await request.Content.CopyToAsync(stream);
using (var reader = new BsonDataReader(stream))
{
var serializer = new JsonSerializer();
var readings =
serializer.Deserialize<IEnumerable<ProviderReading>>(reader);
}
}
readings object is always null.
I tested it using the standard ReadAsAsync method:
var test = await request.Content.ReadAsAsync<List<ProviderReading>>(
new[]{new BsonMediaTypeFormatter()});
in that case it deserialize the collection of readings correctly.
Any suggestions?
Using CopyTo (or its async variant) advances both the source's and target's position. That means that by the time you construct the BsonDataReader the input stream is already at its end.
You should reset the stream's position:
stream.Position = 0;

Deserialize Json String to Object

I'm trying to get weather data from online as json and then deserialize the json into an object that I can use. Here's my code:
public static RootObject7 GetWeather7(int zip)
{
var url = "http://api.weatherunlocked.com/api/forecast/us." + zip.ToString() + "?app_id=xxxxxxx&app_key=xxxxxxxxxxxxxxxxxxxxxxx";
var weather = new wunlocked();
string json = weather.getJson(url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
var data = (RootObject7)serializer.Deserialize<RootObject7>(json);
return data;
}
private string getJson(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
throw;
}
}
I'm debugging, and what's happening is my RootObject7 data object is being created, and inside it has a "Forecast" object, which is supposed to contain a list of other information but instead it's null. I've already defined all of the classes (they're long, so if it's important, I'll post them but otherwise I don't think I need to). I've never done anything like this before so most of this came from other code examples on here that I've found, but obviously I didn't put them together correctly, since my object is always null but when I go to the url, there's valid xml there. I'm not sure if I need to be somehow converting the xml to json in my code, or if that is being done somehow? Like I said, I really don't know what I'm doing but if anyone has suggestions, that'd be great.
Try
dynamic data = serializer.Deserialize(json);
and then inspect the data object in the debugger - you may not need to deserialise to a fixed interface to get out the data you need. Using dynamic may also be a more robust solution to deal with upgrades to the service that may make a set interface/object more brittle.

New StreamReader class doesn't accept filename

I have been trying to get out a demo for MVC 6.0 and I find that I can't read a file anymore using StreamReader class as it doesn't accept a string anymore.
So code like this
StreamReader reader= new StreamReader("filename.txt")
is not valid?
I am using .NET Core 1.0
I think they've removed it as a StreamReader shouldn't be responsible for creating streams - it's a violation of the Single Responsibility Principle.
You'll need to create a FileStream or similar in order to get the same functionality
using (var stream = new FileStream(#"C:\temp\test.txt", FileMode.Open))
using (var reader = new StreamReader(stream))
{
// do stuff.
}

Categories