httpwebrequest BeginGetResponse callback fires in 60 Seconds WP7 - windows-phone-7

I am trying to fetch some data to WP7 device using a websevice.
I am using HttpWebRequest object to get the data from my service... everything works well on WP7 Emulator, but when i try to run the application on WP7 device BeginGetResponse callback fires after 1 min/60 seconds with response status "Not Found".
But if service returns data before 60 seconds then it works on WP7 device as well....
i have crated a sample web service with a sample method which has Thread.Sleep for two minutes it works on WP7 Emulator but not working on WP7 device....
did anybody faces any issue like this before???
Please help me out.
Thanks,
SK

I am using below code to hit the service... same code is working on WP7 Emulator but on WP7 device...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = method;
request.Headers["SOAPAction"] = #"http://tempuri.org/HelloWorldT";
request.Headers["KeepAlive"] = "true";
var res = request.BeginGetRequestStream(
new AsyncCallback((streamResult) =>
{
soapRequestEnvelope = #"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HelloWorldT xmlns='http://tempuri.org/' xmlns:a='http://schemas.datacontract.org/2004/07/WindowsFormsApplication1.ServiceReference1' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'/></s:Body></s:Envelope>";
byte[] requestBytes = Encoding.UTF8.GetBytes(soapRequestEnvelope);
try
{
using (Stream requestStream = request.EndGetRequestStream(streamResult))
{
requestStream.Write(requestBytes, 0, Encoding.UTF8.GetByteCount(soapRequestEnvelope));
}
}
catch (Exception e)
{
}
request.BeginGetResponse(new AsyncCallback((ar) =>
{
try
{
HttpWebRequest Request = (HttpWebRequest)ar.AsyncState;
if (Request != null)
{
using (HttpWebResponse webResponse = (HttpWebResponse)Request.EndGetResponse(ar))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string text = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
}), request);
}), request);

Related

Consume WCF Rest Service Json data across all platform using Shared Code

We were developing a sample MWC application with the logic of Business ,DataAccess,Data Layers.
In core Project we used the following code for consuming data from json parsing. This code works fine for Xamarin.Android and Xamarin.iOS, but for windows phone it shows error as 'System.Net.WebRequest does not contain a definition for GetResponse and no extension method for GetResponse...'
We tried to use Async methods for consuming WCF Rest service json data, but it returned as null before the completed method called.
Is it possible to wait and get data from completed method to return the json collection? if no please suggest how to achieve the same.
public String login<T>(T item) where T : BusinessLayer.Contracts.IBusinessEntity, new()
{
var request = HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "get";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string nss = content.ToString();
check = nss;
return nss;
}
}
return Check;
}
Edit: I have included the sample code of Async function.
Before Executing the DownloadStringCompleted event it returns null value. We need that DownloadStringCompleted output string for further process.
Note: We were following the logic of Tasky in Xamarin
async Task<string> AccessTheWebAsync(string url)
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += (sender, e) =>
{
string data = (string)e.Result;
check = data;
};
webClient.DownloadStringAsync(new Uri(url));
return check;
}
public async Task<string> login<T>(T item) where T : BusinessLayer.Contracts.IBusinessEntity, new()
{
return check = await AccessTheWebAsync(item.url);
}
Your asynchronous code is not using Task correctly. It should use TaskCompletionSource to get the job done:
Task<string> AccessTheWebAsync(string url)
{
var source = new TaskCompletionSource<string>();
var webClient = new WebClient();
webClient.DownloadStringCompleted += (sender, e) =>
{
source.TrySetResult((string)e.Result);
};
webClient.DownloadStringAsync(new Uri(url));
return source.Task;
}
Before, your function was returning before the event fired. Using the task source wraps it in a task properly and fixes this problem.
You will also need to hook up the error event and call TrySetException to finish the implementation.

How to set Timeout for httpwebrequest in windows phone 8 app?

i am developing an windows phone 8 app , in my app i am calling services and downloading some data into my app .
i am using httpwebrequest for request, but i am not able to set timeout to my httpwebrequest object.
This is how i have created and used my httpwebrequest :-
public async Task<string> ServiceRequest(string serviceurl, string request, string methodname)
{
string response = "";
try
{
var httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
httpwebrequest.Method = "POST";
httpwebrequest.Headers["SOAPAction"] = "http://tempuri.org/" + iTestservice + "/" + methodname + "";
httpwebrequest.ContentType = "text/xml";
byte[] data = Encoding.UTF8.GetBytes(request);
using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream, httpwebrequest.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
response = await httpRequest(httpwebrequest);
}
catch (Exception ex)
{
return null;
}
return response;
}
public async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
My Doubt is :-
1) How can i set timeout property to Httpwebrequest ??
2)What are the different ways in which i can set the timeout property in my windows phone 8 app ??
Please let me know .
Thanks in Advance.
You can't use HttpWebRequest.Timeout on Windows Phone because it doesn't exist for that platform.
If you're open to using a beta library, you could install HttpClient via NuGet and use its Timeout property.
Otherwise, you're probably best off to use TaskEx.Delay, which is part of Microsoft.Bcl.Async. After installing that library, you would replace this line:
response = await httpRequest(httpwebrequest);
with this:
var httpTask = httpRequest(httpwebrequest);
var completeTask = await TaskEx.WhenAny(httpTask, TaskEx.Delay(5000));
if (completeTask == httpTask)
return await httpTask;
else
return null; // timeout
You can use HttpStatusCode.HttpStatusCode is an enum which can be used to get the type of error in HttpWebRequest.
catch(WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
if(response.StatusCode==HttpStatusCode.GatewayTimeout)
{
}
}
The GatewayTimeout indicates that an intermediate proxy server timed out while waiting for a response from another proxy or the origin server.For more information you can refer to the msdn
site for this.Hope it helps

Invalid Cross thread access in windows phone 7?

void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
XmlReader xmlDoc = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(responseString)));
while (xmlDoc.Read())
{
if (xmlDoc.NodeType == XmlNodeType.Element)
{
if (xmlDoc.Name.Equals("ResponseCode"))
{
responseCode = xmlDoc.ReadInnerXml();
}
}
}
if (Convert.ToInt32(responseCode) == 200)
{
MessageBox.Show("Success");
}
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}
in above code Messagebox.show dispalying "Invalid cross thread access".please tell me how to resolve this...
Dispatcher.BeginInvoke(() =>
MessageBox.Show("Your message")
);
Any interaction with the UI from code needs to be on the dispatcher thread, your callback from the HTTP request will not be running on this thread hence the error.
You should be able to use something like
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.SHow("Success") );
to display the message box
HTH - Rupert.

Windows Phone POST method WebClient class

I am new to this forum as well as Windows Phone Development. I am currently developing an app in which I am working with a Web-Service and I need to make a POST request to a web service.
I am trying to accomplish a user login functionality here for which,
-> http://abc.com/login (URI)
-> (PARAMETERS)
apikey: 32 byte long alpha-numeric
username: 3-15 characters
password: 3-15 characters
So for this I am trying to use WebClient class' UploadStringSync method in order to POST the data. My code is as follows.
WebClient wc1 = new WebClient();
wc1.UploadStringAsync(new Uri("http://abc.com/login"),"POST","?apikey=" + Apikey + "&username=username&password=password");
wc1.UploadStringCompleted += new UploadStringCompletedEventHandler(wc1_UploadStringCompleted);
void wc1_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
Execution stops here at MessageBox line and throws message saying 'The remote server returned an error: NotFound.'
Is there any problem with the way I am passing the parameters? I tried to search for the working implementation everywhere but was unable to find it.
Can anybody help me with this? This is a starting point of my project and really need help on this one. Any help would be much appreciated.
try this:
public void Post(string address, string parameters, Action<string> onResponseGot)
{
Uri uri = new Uri(address);
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(uri);
r.Method = "POST";
r.BeginGetRequestStream(delegate(IAsyncResult req)
{
var outStream = r.EndGetRequestStream(req);
using (StreamWriter w = new StreamWriter(outStream))
w.Write(parameters);
r.BeginGetResponse(delegate(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)r.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
onResponseGot(reader.ReadToEnd());
}
}
}
catch
{
onResponseGot(null);
}
}, null);
}, null);
}
I did this and it worked
WebClient web = new WebClient();
web.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
web.UploadStringAsync((new Uri("http://www.something.com/?page=something")), "POST", string.Format("v1=onevalue&v2=anothervalue"));
web.UploadStringCompleted += web_UploadStringCompleted;
and after upload is complete to get the html i used htmlagilitypack, you can just get the whole html using e.Result
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(e.Result);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//body//table");
MessageBox.Show(node.InnerText);

How to manage timeout using httpWebRequest and method BeginGetRequestStream Windows Phone 7

I have this example working but I want to know how manage timeout for this example exactly. Please help me.
Thanks in advance
public void callREST()
{
Uri uri = new Uri("http://www.domain.com/RestService");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/xml";
request.BeginGetRequestStream(sendXML_RequestCallback, request);
}
private void sendXML_RequestCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
byte[] toSign = Encoding.GetEncoding("ISO-8859-1").GetBytes("<xml></xml>");
using (var strm = req.EndGetRequestStream(result))
{
strm.Write(toSign, 0, toSign.Length);
strm.Flush();
}
req.BeginGetResponse(this.fCallback, req);
}
private void fCallback(IAsyncResult result)
{
var req = result.AsyncState as HttpWebRequest;
var resp = req.EndGetResponse(result);
var strm = resp.GetResponseStream();
//Do something
}
Timeout isn't supported as part of HttpWebRequest in Silverlight / Windows Phone 7.
You'll need to create a Timer and start that at the same time you start the request. If the timer fires before the HWR returns then Abort() the request and assume it timed out.
For more details and an example, see: HttpWebRequest Timeout in WP7 not working with timer

Resources