locked
Xamarin Authenticating Android to Web API RRS feed

  • Question

  • User45690240 posted

    I was wondering if anyone could give me some advice, I am trying to just register a using via Android and I am having problems, can someone take a look at my code and give me some pointers, or what I am doing wrong, been up all night.

    Register Activity

    namespace SwaggsterFE
    {
        [Activity(Label = "SwaggsterFE", MainLauncher = true, Icon = "@drawable/icon")]
        public class RegisterActivity : Activity
        {
            //int count = 1;
    
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Register);
    
                // Get our button from the layout resource,
                // and attach an event to it
                Button button = FindViewById<Button>(Resource.Id.btnRegister);
    
                button.Click += Button_Click;
    
                //button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
            }
    
            private async void Button_Click(object sender, EventArgs e)
            {
                // Get email and password from edittext boxes
    
                EditText mEmail = FindViewById<EditText>(Resource.Id.reg_email);
                EditText mPassword = FindViewById<EditText>(Resource.Id.reg_password);
                EditText mConfirmed = FindViewById<EditText>(Resource.Id.reg_confirpassword);
    
    
                string Email = mEmail.Text.ToString();
                string Password = mPassword.Text.ToString();
                string Confirmed = mConfirmed.Text.ToString();
    
    
                RegisterService rs = new RegisterService();
                bool result = await rs.Register(Email, Password, Confirmed);
    
            }
        }
    }

     

    Register Service

    namespace SwaggsterFE.Services
    {
        class RegisterService
        {
            public async Task<bool> Register(string username, string password, string confirmPassword)
            {
                RegisterModel model = new RegisterModel
                {
                    ConfirmPassword = confirmPassword,
                    Password = password,
                    UserName = username
                };
    
                HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Account/Register", Constants.BaseAddress)));
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Accept = "application/json";
                string json = JsonConvert.SerializeObject(model);
                byte[] bytes = Encoding.UTF8.GetBytes(json);
                using (Stream stream = await request.GetRequestStreamAsync())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
    
                try
                {
                    await request.GetResponseAsync();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
    }

    Android Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="SwaggsterFE.SwaggsterFE" android:versionCode="1" android:versionName="1.0">
      <uses-sdk android:minSdkVersion="16" />
      <application android:label="SwaggsterFE"></application>
    
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    </manifest>

    Thanks in advance

    Thursday, May 19, 2016 1:17 PM

Answers

  • User36583972 posted

    Hi PsyChotic,

    From your description, I have some suggestions in the below.

    Firstly, you should make sure your Android register code works well.

    Then, I found in your RegisterService class, you will call Web API and send register message.

    You can use HttpClient to call Web API.

      using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
                {
    
                    RegisterModel model = new RegisterModel
                    {
                        ConfirmPassword = confirmPassword,
                        Password = password,
                        UserName = username
                    };
    
                    var url = string.Format("{0}/{1}?", "http://localhost:29679/", "api/Account/Register");
                    HttpResponseMessage response = client.PostAsJsonAsync(url, model).Result;
                    var responseData = response.Content.ReadAsStringAsync().Result;
                    var status = ((int)response.StatusCode).ToString();
                    if (status == "200")
                    {
                        var result = default(Object);
                        try
                        {
                            if (!string.IsNullOrEmpty(responseData))
                                result = JsonConvert.DeserializeObject<Object>(responseData);
    
                            Response.Write("Result: " + result);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    else
                    {
                    }
                }

    At last, debug your code to find which error will happen. You could also share us more relevant code and message to help us reproduce the problem.

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 20, 2016 3:04 AM

All replies

  • User36583972 posted

    Hi PsyChotic,

    From your description, I have some suggestions in the below.

    Firstly, you should make sure your Android register code works well.

    Then, I found in your RegisterService class, you will call Web API and send register message.

    You can use HttpClient to call Web API.

      using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
                {
    
                    RegisterModel model = new RegisterModel
                    {
                        ConfirmPassword = confirmPassword,
                        Password = password,
                        UserName = username
                    };
    
                    var url = string.Format("{0}/{1}?", "http://localhost:29679/", "api/Account/Register");
                    HttpResponseMessage response = client.PostAsJsonAsync(url, model).Result;
                    var responseData = response.Content.ReadAsStringAsync().Result;
                    var status = ((int)response.StatusCode).ToString();
                    if (status == "200")
                    {
                        var result = default(Object);
                        try
                        {
                            if (!string.IsNullOrEmpty(responseData))
                                result = JsonConvert.DeserializeObject<Object>(responseData);
    
                            Response.Write("Result: " + result);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    else
                    {
                    }
                }

    At last, debug your code to find which error will happen. You could also share us more relevant code and message to help us reproduce the problem.

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 20, 2016 3:04 AM
  • User45690240 posted

    Thanks Yohann

    I figured out what the issue was the code is working fine, the problem was on my end.

    Wednesday, May 25, 2016 8:12 PM