App hangs when not being debugged in Visual Studio - c#

I have this app which authenticates a user with external web service and should navigate to a different view once authenticated.
The authentication is done in a HttpWebRequest:
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create("http://webservice");
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(CheckLogin), request);
}
Then here is the callback:
private void CheckLogin(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
bool success = false;
try
{
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
if (responseString.Contains("ok"))
{
success = true;
}
streamResponse.Dispose();
streamRead.Dispose();
response.Dispose();
}
catch (Exception e)
{
}
request.Abort();
request = null;
if (success)
{
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Frame.Navigate(typeof(Main2));
}).AsTask().Wait();
}
}
This is working perfectly when debugging in Visual Studio but when I have published the application and installed the package, it hangs on Frame.Navigate. I guess this is because the CheckLogin method is not running in the UI thread.
Any ideas on how to Frame.Navigate(..) in a background thread?

It seems to be no real problems between Dispatcher.RunAsync and Frame.Navigate. So I assume you're not looking in the right direction.
Maybe your page's content is faulty, instead of the navigation.

Related

why UI freezes during long running operations [duplicate]

This question already has answers here:
WinForm Application UI Hangs during Long-Running Operation
(3 answers)
Closed 8 years ago.
I'm studying c# and tried other solutions that I've found on stackoverflow.. But I failed..
I'm trying to check if an URL exists when click a button.
When the button is clicked, a progressBar is set to marquee and the verification begins.
But the system stops until the result backs..
Here is the button click:
private void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
if (RemoteFileExists("http://www.gofdisodfi.com/"))
{
// OK
}
else
{
//FAIL
}
}
And here is the check:
private bool RemoteFileExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
You could use the "async and await" syntax for asynchronous action. It won't freeze the UI
private async void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
var result = await RemoteFileExists("http://www.google.com/");
if (result)
{
// OK
MessageBox.Show("OK");
}
else
{
//FAIL
MessageBox.Show("Fail");
}
}
private async Task<bool> RemoteFileExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
You can read more about it here: http://blog.stephencleary.com/2012/02/async-and-await.html

How can I prevent UI freezing while using HttpWebRequest?

I have a progressBar on my form and a button.
When user clicks this button, the progressBar should be styled as "marquee" and the program begins to check is an URL is valid or not.. OK.
But when I click the button, the UI freezes until the HttpStatusCode returns true or false...
Here is the check code:
private bool RemoteFileExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
And here is the button click code:
private async void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
var result = RemoteFileExists("http://www.google.com/");
if (Completed)
{
//ok
}
else
{
//not ok
}
}
The UI freezes because you are executing the RemoteFileExists method on the UI thread and receiving a response from a HttpWebRequest takes some time.
To solve this you have to execute RemoteFileExists in a different thread than the UI thread.
As your button1_Click method is already declared async the easiest way would be to declare RemoteFileExists as async too.
Then you can use the HttpWebRequest.GetResponseAsync method to asynchronously receive the response object.
private async Task<bool> RemoteFileExists(string url)
{
try
{
HttpWebRequest request = WebRequest.CreateHttp(url);
request.Method = "HEAD";
using(var response = (HttpWebResponse) await request.GetResponseAsync())
{
return (response.StatusCode == HttpStatusCode.OK);
}
}
catch
{
return false;
}
}
Also when dealing with IDisposables you should take care of releasing all used resources by using the using statement or calling Dispose().
If you are using .NET Framework 4+ you can also use WebRequest.CreateHttp(string) to create your HttpWebRequest.
Putting it simple just use this:
private void button1_Click(object sender, EventArgs e)
{
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
Thread thread = new Thread(() => RemoteFileExists("http://www.google.com/"));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
And do the check inside RemoteFileExists .

Windows Phone 8.1 print result of an HTTP request

I can not print or process the data that I receive after making an HTTP request.
This is the code I wrote:
private void Button_Click(object sender, RoutedEventArgs e)
{
String jsonUri = "hxxp://xxxxx/zzzz/yyyyyy; //censured
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(jsonUri);
request.BeginGetResponse(GetDataCallback, request);
}
void GetDataCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
WebResponse response = request.EndGetResponse(result);
testo.Text = response.GetResponseStream().ToString();
}
}
I tried various solutions but I just can not print the result.
apache I see the call, and the data from the app I could see that coming

Windows Phone 8: passing data from PHP page to windows phone 8 app

I need to send some data from php page to windows phone 8(C#) and need to display it.
Here is my wp8 side Code :
private void Track_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(attackUri);
request.BeginGetResponse(Showtext, request);
}
}
void Showtext(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(result);
var txt = request.Content.ReadAsStringAsync();
//to display data passed from PHP page
MessageBox.Show(txt.Result);
}
catch (WebException e)
{
}
}
}
I'm not quite sure, where you got your request.Content from, but it does not seem to be WP8 native.
Try the following. This is how it always worked for me:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.google.de"));
request.BeginGetResponse(ShowText, request);
private void ShowText(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string content = streamReader.ReadToEnd();
Debug.WriteLine(content);
}
}

HTTP Request Not found error windows phone

I have a HTML page hosted on a local Apache server and I'm trying to make a HTTP web request to the page using the below code. The code runs into a web exception, and throws an invalid argument exception too. This happens in the piece of code used to get the data from the stream in the catch section of the code:
private void b1_Click_1(object sender, RoutedEventArgs e)
{
System.Uri targetUri = new System.Uri(#"http://192.168.1.4/san/index1.html");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
try
{
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
string results = httpwebStreamReader.ReadToEnd();
//TextBlockResults.Text = results; //-- on another thread!
// Dispatcher.BeginInvoke(() => TextBlockResults.Text = results);
}
myResponse.Close();
}
catch (WebException ex)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
Debug.WriteLine(reader.ReadToEnd());
}
}
}
Are you trying to access the page from the emulator or the device? If it's the device, you need to make sure that the web page is accessible from a secondary device. That is - make sure that port 80 is open for LAN access.

Categories