Forum Xamarin.Forms

Xamarin Forms Login connected to web api.. crashes

Hi everyone I have designed a simple login form on my mobile app, but when I enter login username and password and click login button, the app crashes. I dont know why it crashes :( So basically what it does is: User enters username and password. and the app retrieves username and password stored in web api from aspnet core web (on web api I have used username as the primary key to store on user infos. And here are my codes. Please help Thank you!

This is my login page

`public partial class LoginPage : ContentPage
{
UserViewModel viewModel;
User user;
UserService userService;
public LoginPage()
{
user = new User();
InitializeComponent();
viewModel = new UserViewModel();
userService = new UserService();
}
async void OnSignUpButtonClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new SignUpPage());
}
private async void Login_clicked(object sender, EventArgs e)
{
bool userstatus;
bool passstatus;
var Username_in = usernameEntry.Text;
var Password_in = passwordEntry.Text;
user = await userService.GetUser(Username_in);
var Password = user.Password;
var Username = user.Username;
if (user != null)
{
userstatus = Username_in == Password;
passstatus = Password_in == Password;
if (userstatus && passstatus)
{
user.isLoggedIn = true;
ToMain();
}
else
messageLabel.Text = "Username does not match password";

        }
        else
            messageLabel.Text = "User does not exist";

    }
    /*private async Task<User>GetUserInfo(string username)
    {
        user = await GetUserInfo(username);
        return user;

    }
    */
    bool AreCredentialsCorrect(User user)
    {
        return user.Username == Constants.Username && user.Password == Constants.Password;
    }


    async void ToMain()
    {
        Application.Current.Properties["User"] = user as User;
        App.IsUserLoggedIn = true;
        Navigation.InsertPageBefore(new Main(), this);
        await Navigation.PopAsync();
    }


}`

Backend code called User Service

`public class UserService : IUserStore
{
HttpClient client;
IEnumerable users;
bool conn;

    public UserService()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri($"{App.AzureBackendUrl}/");
        conn = App.IsConnected;
        //recall Isconnceted from App.xaml.cs. 


    }


    public async Task<IEnumerable<User>> GetAllUsers()
    {   
        //Retrieve user info only if there is network connection. 
        if(conn)
        {
            var user_Serialized = await client.GetStringAsync($"api/user");
            users = await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<User>>(user_Serialized));
        }

        return users; 
    }

    public async Task<User> GetUser(string username)
    {
        if(username != null && conn)
        {
            var user_serialized = await client.GetStringAsync($"api/item/{username}");
            return await Task.Run(() => JsonConvert.DeserializeObject<User>(user_serialized));

        }
        return null;
    }

    //TODO
    //Include a case where User accont with given name already exists. 

    public async Task<bool> RegisterUser(User user)
    {
        if (user == null || conn)
            return false;
        var user_serialized = JsonConvert.SerializeObject(user);
        var request = await client.PostAsync($"api/user", new StringContent(user_serialized, Encoding.UTF8, "application/json"));
        return request.IsSuccessStatusCode;

    }

    public async Task<bool> UpdateUser(User user)
    {
        if (user == null || user.Username == null || conn)
            return false;
        var user_serialized = JsonConvert.SerializeObject(user);
        var middleware = Encoding.UTF8.GetBytes(user_serialized);
        var cont = new ByteArrayContent(middleware);
        var request = await client.PutAsync(new Uri($"api/user/{user.Username}"), cont);

        return request.IsSuccessStatusCode;

    }

    public async Task<bool>DeleteUser(string username)
    {
        if (string.IsNullOrEmpty(username) && !conn)
            return false;

        var response = await client.DeleteAsync($"api/user/{username}");

        return response.IsSuccessStatusCode;
    }



}`

Interface used on User service,, IUserservice

public interface IUserStore<T> { Task<IEnumerable<User>> GetAllUsers(); Task<User> GetUser(string username); Task<bool> RegisterUser(User user); Task<bool> UpdateUser(User user); Task<bool> DeleteUser(string username); }

Answers

  • JohnHardmanJohnHardman GBUniversity admin

    @kimjh3437

    A crash is an unhandled exception. Post the full details of the exception (you'll see them in the Output window of Visual Studio when debugging).

    Have you stepped through the code in the debugger. Which line throws the exception?

  • kimjh3437kimjh3437 Member ✭✭

    I don't get any errors on the output when I debug, but when I run the app on my device, (when click login button) the app crashes and exits out of the app

  • JohnHardmanJohnHardman GBUniversity admin

    @kimjh3437 said:
    I don't get any errors on the output when I debug, but when I run the app on my device, (when click login button) the app crashes and exits out of the app

    (1) Does a debug build of your app crash when running without debugging?
    (2) Do you use App Center (see https://appcenter.ms/ ), HockeyApp, or any other system for capturing details of exceptions in release builds?
    (3) On which platforms does the crash occur?
    (4) Have you got the crash logs from the device? (e.g. for iOS see https://help.apple.com/xcode/mac/8.0/#/dev85c64ec79 )

  • kimjh3437kimjh3437 Member ✭✭

    oh apparently, I accidentally incorrectly capitalized one of the routs in backend. After fixing it, this works perfectly fine.

    Thank you for your time! Your debug build helped!

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    Please mark your reply as answer, it will help others who have similar issue.

Sign In or Register to comment.