In my codebehind file I call this function:
private void loginAction(object sender, TappedRoutedEventArgs e)
{
Webservice webservice = new Webservice();
webservice.getUser(txtLogin.Text, txtPass.Text);
}
Then in webservice I do this:
public void getUser(String user, String password)
{
String strUrl = String.Format("http://*******/nl/webservice/abc123/members/login?email={0}&password={1}",user,password);
startWebRequest(strUrl, loginCallback);
}
private async void loginCallback(IAsyncResult asyncResult)
{
try
{
ReceiveContext received = GetReceiveContextFromAsyncResult(asyncResult, "User");
if (received != null && received.Status == 200)
{
await UserDataSource.AddUser(received.Data);
}
else
{
throw new Exception("failedddd");
}
}
catch (Exception e)
{
}
}
What I want to do now is when an exception is thrown, show a messagebox. And when I got a status 200 I navigate to the next page in de code behind file.
My question is now, how do i'm going to know this in my code behind file?
Many thanks in advance!
EDIT I also have these helper methods:
#region HELPERS
private void startWebRequest(string url, AsyncCallback callback)
{
// HttpWebRequest.RegisterPrefix("http://",WebRequestCreator.ClientHttp);
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
// start the stream immediately
httpWebRequest.AllowReadStreamBuffering = false;
// asynchronously get a response
httpWebRequest.BeginGetResponse(callback, httpWebRequest);
}
private ReceiveContext GetReceiveContextFromAsyncResult(IAsyncResult asyncResult, string context)
{
// Request afleiding van de AsyncState uit het ontvangen AsyncResult
HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse httpWebResponse = null;
try
{
// Response afleiden uit de Resuest via de methode EndGetResponse();
httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);
string responseString;
// using == IDisposable (automatische GC)
using (StreamReader readStream = new StreamReader(httpWebResponse.GetResponseStream()))
{ //Stream van de response gebruiken om een readstream te maken.
responseString = readStream.ReadToEnd();
}
// Release the HttpWebResponse
//httpWebResponse.Dispose();
return new ReceiveContext(int.Parse(responseString.Substring(10, 3)), responseString);
}
catch (WebException wex)
{
Debug.WriteLine(String.Format("{0} kon niet opgehaald worden: {1}", context, wex.Message));
}
catch (JsonReaderException jrex)
{
Debug.WriteLine(String.Format("{0} opgehaald van server, maar de json kon niet geparsed worden: {1}", context, jrex.Message));
}
catch (FormatException fex)
{
Debug.WriteLine(String.Format("{0} opgehaald van server, maar de gegevens kloppen niet: {1}", context, fex.Message));
}
catch (ArgumentOutOfRangeException arex)
{
Debug.WriteLine(String.Format("{0} opgehaald van server, maar de context is leeg: {1}", context, arex.Message));
}
return null;
}
public sealed class ReceiveContext
{
public ReceiveContext(int status, string data)
{
this.Status = status;
this.Data = data;
}
public int Status { get; private set; }
public string Data { get; private set; }
}
#endregion
The code bellow use API Windows.Web.Http.HttpClient (Microsoft recommend to use this API to connect REST service)
public class Result
{
public HttpStatusCode Status { get; set; }
public string Data { get; set; }
}
public async Task<Result> LoginAsync(string user, string password)
{
var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://*******/nl/webservice/abc123/members/login?email="+ user + "&password="+ password));
var result = await http.SendRequestAsync(request);
var data = new Result {Status = result.StatusCode};
if (result.StatusCode== HttpStatusCode.Ok && result.Content!=null)
{
data.Data = await result.Content.ReadAsStringAsync();
}
return data;
}
In your code behind:
var result2 = await LoginAsync("", "");
if (result2.Status == HttpStatusCode.Ok)
{
//Status code 200
//navigate to other page
}
else if(result2.Status == HttpStatusCode.BadRequest)
{
//Status code 400
//your code
}
Since you are getting a Json response would recommend you add Newtonsoft nuget package to your project first.
Now earlier we used to add a service reference but now we can easily do it using
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://*******/nl/webservice/abc123/members/login?email="+ user + "&password="+ password));
var resultlogin = await response.Content.ReadAsStringAsync(); //this is usually string type
var obj = JsonConvert.DeserializeObject<UserLogin.RootObject>(resultbrand);
//I usually define my own custom C# class using json2csharp.com or you can use Json.Deserialize also.
class UserLogin
{
public class User
{
public string UserName { get; set; }
public string Email { get; set; }
}
public class RootObject
{
public string tag { get; set; }
public int success { get; set; }
public int error { get; set; }
public string uid { get; set; }
public User User { get; set; }
}
}
Now most important for the namespace used should be
using System.Net.Http;
and not
using Windows.Web.Http;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With