xaml page doesn't wait for HttpWebResponse - c#

In my Windows Phone 7 application I'm getting data from web service.
So on start of my application I check is my data is setted in Local Storage and if it's not (first run) I have made request by HttpWebRequest and wait for response.
SetupAppData(); //chack in local storage
if (CheckNetworkConnection(false))
if (appData == null)
GetAppData();
...
public void GetAppData()
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(RequestData_Completed, request);
}
...
In RequestData_Completed I set request data and invoke request.BeginGetResponse(ResponseData_Completed, request);
Then when my response come back to the application I change it to my object and use in application.
But my problem is that I use this data in my xaml view before response come back. And I don't know how to make my view to wait for response.
I have tried to create some bool value isDataSetted, set it on true when my response come back and check its value in while loop but it block app and response never was handled.
Is there any solution for this issue?

Just have RequestData_Completed fire an event after the data is processed, and have your UI respond when the event occurs.

Related

Need to call method as soon as server starts responding to my HttpWebRequest

I need to call a method in new thread for ex: mymethod() as soon as server starts responding to my HttpWebRequest.
I am using below to send http requst and getting response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MyUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Now what i need is for my request when server starts responding as soon as i need to call a method mymethod() in new thread. But problem is I don't know how to detect that server has started responding (started responsestream ) to my request.
What is the way that tell me that server started responding and I can call my method.
Target framework: is .net framework 4.5 and my project is Windows Form application.
The closest I can think of is using HttpClient and passing a HttpCompletionOption.ResponseHeadersRead, so you can start receiving the request once the headers are sent and later start processing the rest of the response:
public async Task ProcessRequestAsync()
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(
url,
HttpCompletionOption.ResponseHeadersRead);
// When we reach this, only the headers have been read.
// Now, you can run your method
FooMethod();
// Continue reading the response. Change this to whichever
// output type you need (string, stream, etc..)
var content = response.Content.ReadAsStringAsync();
}

How do I resend a "failed" WebRequest?

I send POST and GET WebRequest that should support longer periods of internet being down. The idea is to queue the failed (timedout) webrequest and to try to resend them periodically until the internet is up again and all queued WebRequests are sent.
However, I seems that I cannot just reuse the old WebRequest. Do I need to set it up again?
IAsyncResult result = request.BeginGetResponse (o => {
callCallback (o);
}, state);
When request is just setup using:
var request = HttpWebRequest.Create (String.Format (#"{0}/{1}", baseServiceUrl, path));
request.Method = "GET";
request.ContentType = "application/xml; charset=UTF-8";
request.Headers.Add ("Authority", account.Session);
return request;
it works fine. But after a timeout (and request.Abort ();) and calling BeginGetResponse() on the same webrequest just freezes.
You cannot call BeginGetResponse() multiple times on the same HttpWebRequest. I'm not sure whether that's support on .NET, but it's not possible with Mono's implementation (and not something that'd be easy to change).
See also Can I reuse HttpWebRequest without disconnecting from the server? - the underlying network connection will be reused.

How to stop receive response when send a request to webServer by Httpwebrequest

I use to send POST request and get response by this way:
response = (HttpWebResponse)request.GetResponse();
But, I just want to send request, I don't care what response is. Size of response package can be up to 500Kb ~ 1Mb, It wastes lots of time. How can I send request and then stop receive response immediately. Thanks so much!
If your only concern is the time it takes to receive the response, and not the bandwidth being used, you could get the response asynchronously.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx
The example given is a bit complicated, but the general idea is that your program will not wait for the response to be downloaded when BeginGetResponse is called, like it would if you just called GetResponse. The first method that you pass to BeginGetResponse is the name of a method (called a "callback") that will get called when the response eventually is fully downloaded. This is where you'd put your code to check the HTTP response code, assuming you cared about that. The 2nd parameter is a "state" object that gets passed to your callback method. We'll use this to make sure everything gets cleaned up properly.
It would look something like this:
private void YourMethod()
{
// Set up your request as usual.
request.BeginGetResponse(DownloadComplete, request);
// Code down here runs immediately, without waiting for the response to download
}
private static void DownloadComplete(IAsyncResult ar)
{
var request = (HttpWebRequest)ar.AsyncState;
var response = request.EndGetResponse(ar);
// You can check your response here to make sure everything worked.
}
I assume you are sending a GET request to the server. Change it to a HEAD request.
var request = System.Net.HttpWebRequest.Create("http://...");
request.Method = "HEAD";
request.GetResponse();
This will only return the length of the content. See How to get the file size from http headers for more info.

HttpWebRequest setting host to garbage but still getting OK response

I am using an HttpWebRequest and passing in an Address which is an IP. I then set the host to a garbage value. When I call GetResponse() I am getting an OK even though I would expect this to fail since the host is garbage.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://10.10.10.10/Default.aspx"));
request.Host = "blah.blah.blah";
request.ContentType = "text/xml";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK) { /*always enters here */ }
}
Why is the response coming back as OK? Shouldn't the garbage host cause this to fail?
HttpWebRequest.Host Property:
Get or set the Host header value to use in an HTTP request independent from the request URI.
Using the Host property to explicitly specify a custom Host header value also affects areas caching, cookies, and authentication. When an application provides credentials for a specific URI prefix, the applications needs to make sure to use the URI containing the value of the Host header, not the target server in the URI.
So there is no effect of .Host to the general request, you change some additional behavior.

Can I send an empty HTTP POST WebRequest object from C# to IIS?

Do I need to just slap some random garbage data in a WebRequest object to get by the HTTP status code 411 restriction on IIS?
I have an HttpPost action method in an MVC 3 app that consumes a POST request with all the relevant information passed in the querystring (no body needed).
[HttpPost] public ActionResult SignUp(string email) { ... }
It worked great from Visual Studio's built in web host, Cassini. Unfortunately, once the MVC code was live on IIS [7.5 on 2008 R2], the server is pitching back an HTTP error code when I hit it from my outside C# form app.
The remote server returned an error:
(411) Length Required.
Here is the calling code:
WebRequest request = WebRequest.Create("http://somewhere.com/signup/?email=a#b.com");
request.Method = "POST";
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream)) {
// Do something with responseReader.ReadToEnd();
}
Turns out you can get this to go through by simply slapping an empty content length on the request before you send it.
WebRequest request = WebRequest.Create("http://somewhere.com/signup/?email=a#b.com");
request.Method = "POST";
request.ContentLength = 0;
Not sure how explicitly giving an empty length vs. implying one makes a difference, but IIS was happy after I did. There are probably other ways around this, but this seems simple enough.
I believe you are required to set a Content-Length header anytime you post a request to a web server:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.contentlength.aspx
You could try a GET request to test it.

Categories