Windows phone 8 dev: HttpWebRequest.BeginGetResponse callback never called - c#

I'm starting windows phone 8 development on my Windows 8 machine and test on the emulator that comes with visual studio 2012. I have a main page with one button on it. Upon pressing the button, it makes a http request.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string uriString = "http://209.143.33.109/mjpg/video.mjpg?camera=1";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var req = ar.AsyncState as HttpWebRequest;
var response = (HttpWebResponse)req.EndGetResponse(ar);
var responseStream = response.GetResponseStream();
}
I set a breakpoint on OnGettingResponse. But when I press the button, the breakpoint is never hit.
Am I missing anything obvious here?

I was facing the same issue that my callback was not being called even after waiting too long.
I found this stackoverflow answer https://stackoverflow.com/a/15041383 and modified my code accordingly. The actual problem in that question was that asker wants to have some timeout functionality in the HttpWebRequest under Windows Phone 8. Having timer was irrelevant for me, so I just took the following part of code:
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;
}
and modified my call to this method as:
var response = await httpRequest(request);
This is now working fine for me.
I also double checked that ID_CAP_NETWORKING is check in WMAppManifest.xml and internet is working on my emulator.

Related

Requests POI from a location using Xamarin (Android)

Im trying to create an android app with xamarin.I want the user to be able to input an address/location and receive POI (Points of Interest) near it (within a certain radius).
I know google places api can do this, does xamarin have built in capability for something like this? Can I somehow interface with the Google Places api?
Or is there something I don't know about? Thanks for the help!
Use HTTPWebRequest class to create a request to Google API, code snippet:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=7500&types=library&sensor=false&key=AIzaSyD3jfeMZK1SWfRFDgMfxn_zrGRSjE7S8Vg") as HttpWebRequest;
webRequest.Timeout = 20000;
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(RequestCompleted), webRequest);
}
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
var resp = r.ReadToEnd();
}
}
copy over from here... pretty straightforward and simple...

WP8 Fast App Resume with Asynchronous methods

In my windows phone 8 app i am using asynchronous methods to retrieve data from server.
After implementing Fast App Resume functionality another problem rose for me. The asynchronous method that retrieves data from server throws the exception of type System.Net.WebException when it resumes.
The steps to reproduce the problem is you just hit the start button when the app is loading data by asynchronous method.
For example i have a page that loads notification of user. I called the async void GetNotifications() method that further calls below method to retrieve response string.
public async Task<string> Get(string URL)
{
var request = WebRequest.Create(new Uri(URL)) as HttpWebRequest;
if (APIHelper.APIHandshake != null)
request.Headers["Cookie"] = "ii=" + APIHelper.APIHandshake.Sid + ";";
return await httpRequest(request);
}
the implementation of httprequest method is given below.
private 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))
{
//cookieJar = request.CookieContainer;
//responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received.Replace("[{}]", "[]")
.Replace("[{},{}]", "[]")
.Replace("\"subcat_id\":\"\"", "\"subcat_id\":\"0\"");
}
The user just click the menu that opens the notification page and then press the start button of phone instantly to deactivate the app. When user will click on application tile from start menu the exception will be thrown.
Any solution? will deactivating idle mode detection work?
It would probably not be the best solution but It is possible to not cancel the async request by adding this line of code in the InitalizePhoneApplication() method on your app.xaml.cs page.
PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
Read more on this property here
Test it, it should fix the issue but I'm not pretending that's the best thing to do....

HttpClient Task fails to start

I have some very simple code that I have been using in a windows 8 store app without any issue. However When I shared the code with windows phone app It just hangs forever. See sample below. This calls any web url and returns its source as a string. both the post and get methods hang in the same way. any help is much appreciated, Thank you.
public static string GetWebSource(string Url)
{
HttpClient client = new HttpClient();
Task<HttpResponseMessage> Resp = client.GetAsync(Url);
//code hangs on following line forever
//Resp.status always stays at waiting for activation
Task.WaitAll(Resp);
if (Resp.Result.IsSuccessStatusCode)
{
Task<string> response = Resp.Result.Content.ReadAsStringAsync();
Task.WaitAll(response);
return response.Result;
}
return "";
}
public static string PostWebSource(string Url, string data)
{
HttpClient client = new HttpClient();
StringContent sc = new StringContent(data);
Task<HttpResponseMessage> Resp = client.PostAsync(Url, sc);
//code hangs on following line forever
//Resp.status always stays at waiting for activation
Resp.Wait();
if (Resp.Result.IsSuccessStatusCode)
{
Task<string> response = Resp.Result.Content.ReadAsStringAsync();
Task.WaitAll(response);
return response.Result;
}
return "";
}
You should be using an HttpWebRequest on Windows Phone. See this link: http://social.msdn.microsoft.com/Forums/wpapps/en-us/9b4c1ef2-853c-468a-bca8-97477a02583c/httpclient-for-windows-phone-8?forum=wpdevelop

HTTPS web request failing

When I run the program contained below the first HTTPS request succeeds, but the second request fails. Both url's are valid and both can be accessed successfully in a browser. Any suggestions as to what needs to be done to access the second url successfully?
using System;
using System.IO;
using System.Net;
public class Program
{
private static void Main(string[] args)
{
var content = "";
bool status;
var url1 = "https://mail.google.com";
var url2 = "https://my.ooma.com";
status = DoHttpRequest(url1, out content);
OutputStatus(url1, status, content);
status = DoHttpRequest(url2, out content);
OutputStatus(url2, status, content);
Console.ReadLine();
}
private static void OutputStatus(string url, bool status, string content)
{
if (status) Console.WriteLine("Url={0}, Status=Success, content length = {1}", url, content.Length);
else Console.WriteLine("Url={0}, Status=Fail, ErrorMessage={1}", url, content);
}
private static bool DoHttpRequest(string url, out string content)
{
content = "";
var request = (HttpWebRequest) WebRequest.Create(url);
try
{
request.Method = "GET";
request.CookieContainer = null;
request.Timeout = 25000; // 25 seconds
var response = (HttpWebResponse) request.GetResponse();
var streamReader = new StreamReader(response.GetResponseStream());
content = streamReader.ReadToEnd();
return true;
}
catch (WebException ex)
{
content = ex.Message;
return false;
}
}
}
Historically, most problems of this description that I've seen occur when you forget to call .Close() on the object returned from GetResponseStream(). The problem exists because when you forget to close the first request, the second request deadlocks waiting for a free connection.
Typically this hang happens on the 3rd request, not the second.
Update: Looking at your repro, this has nothing to do with the order of the requests. You're hitting a problem because this site is sending a TLS Warning at the beginning of the HTTPS handshake, and .NET will timeout when that occurs. See http://blogs.msdn.com/b/fiddler/archive/2012/03/29/https-request-hangs-.net-application-connection-on-tls-server-name-indicator-warning.aspx. The problem only repros on Windows Vista and later, because the warning is related to a TLS extension that doesn't exist in the HTTPS stack on WinXP.
Increse your request TimeOut.
request.Timeout = 60000; //60 second.
May be your network connection is a bit slow. I run with 25 seconds, okay. (Yeah, the second url is a bit longer to get response, than the first one.)

Access Stream Buffer HttpWebRequest

I'm trying to stream radio in a Windows Phone 7 app and for this I'm using ManagedMediaHelpers. The HttpWebRequest to get the continuous stream works but doesn't call the callback Url because of the continuous stream.
How do I access the stream without the help of the callback Url? On other posts some said O need to use reflection but does someone knows hot to implement it? Here is my code:
req = (HttpWebRequest) WebRequest.Create(
"http://streamer-dtc-aa01.somafm.com:80/stream/1018");
// if this is false it will fire up the callback Url
// but the mediastreamsource will throw an exception
// saying the it needs to be true
req.AllowReadStreamBuffering = true;
IAsyncResult result = req.BeginGetResponse(RequestComplete,null);
private void RequestComplete(IAsyncResult r)
{
HttpWebResponse resp = req.EndGetResponse(r) as HttpWebResponse;
Stream str = resp.GetResponseStream();
mss = new Mp3MediaStreamSource(str, resp.ContentLength);
Deployment.Current.Dispatcher.BeginInvoke(() => {
this.me.Volume = 100;
this.me.SetSource(mss);
});
}
Had the same issue, so here is how I solved it:
Getting bytes from continuous streams on Windows Phone 7
It might also be a problem with your URL - make sure that if you run the request outside the application, you are getting the necessary amount of data.

Categories

Resources