Login And SignUp In Xamarin.Forms

Introduction

  • Login: Login is a process of logging in to an application, database, device, etc. Most of the login pages require an email and password to be entered by the users.
  • SignUp: SignUp is a process of signing in to an application. Another term used for SignUp is registration. A user can provide his/her credentials to register himself/herself into the application. A signup form requires a username, email, password, DOB, gender, and other such details for registration.

Procedure

First of all, create a new Web project. In that project, add a class in Models. For this, go to the Solution Explorer, right-click on the model -> add -> class. Give a suitable name to that class, and say “User”. In user.cs, add the following by writing property and double tap on it. Set the datatype and property for that.

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

Now, build the solution before adding a Controller to that model class. After building, add a Controller. For this, go to the Solution Explorer, right-click on controller->add->controller. Add MVC 5 with views using entity frameworks using the same name as in the model class. Click on add. A controller is added to your solution. Now, run your solution. Type http://localhost:61525/Users/Create on the browser. After creating, you will be able to edit, create new, delete, etc.

For webApi add a controller again by following the same procedure and select WebApi 2 controller with actions using entity frameworks. Using the same name as used for the previous controller. A new controller will be added named “User1conroller”. Run your solution. Type http://localhost:61525/api/Users1 this on your browser. You will see,

Output

Output

Procedure for combining Login services to this WebAPI

Go to your computer’s taskbar. Right-click on Visual Studio and open a new project. Select cross-platform. Right-click on your project in Solution Explorer and add a class with the same name, “User”. Add the same properties to that class.

public class User
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

In MainPage.Xaml Design your Login page’s front end. Add the following piece of code.

<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <Entry Placeholder="Email" x:Name="Email" />
    <Entry Placeholder="Password" x:Name="Pass" />
    <Button Text="Login" x:Name="Login" Clicked="Login_Clicked" />
</StackLayout>

Go to Solution Explorer, add a folder of name ServiceHandler and add a class to that folder of name LoginService. Add the following code.

RestClient<User> _restClient = new RestClient<User>();

public async Task<bool> CheckLoginIfExists(string email, string password)
{
    var check = await _restClient.CheckLogin(email, password);
    return check;
}

Certain types of errors occur. If you take your pointer to Task<bool>, a flash bulb appears. Click on it, and add a threading method.

Now add a folder by following the same method with the name RestApiClass and add a class in it named RestClient. Add the following piece of code.

class RestClient<T>
{
    private const string MainWebServiceUrl = "https://jammovies.azurewebsites.net/";
    private const string LoginWebServiceUrl = "https://jammovies.azurewebsites.net/api/UserCredentials/";

    public async Task<bool> CheckLogin(string email, string password)
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync(LoginWebServiceUrl + "email=" + email + "/" + "password=" + password);
        return response.IsSuccessStatusCode;
    }
}

Give permission to HttpClient to flash the bulb by clicking the first option. You have to type <T> after classRestClient.

Now go to MainPage.xaml.cs add the following piece of code in the event created in the Login Button.

private async void Login_OnClicked(object sender, EventArgs e)
{
    LoginService service = new LoginService();
    var getLoginDetails = await service.CheckLoginIfExists(Email.Text, Pass.Text);

    if (getLoginDetails)
    {
        await DisplayAlert("Login Successful", "Username or Password is correct", "Okay", "Cancel");
    }
    else if (Email.Text == null && Pass.Text == null)
    {
        await DisplayAlert("Login failed", "Enter your Email and Password before login", "Okay", "Cancel");
    }
    else
    {
        await DisplayAlert("Login failed", "Username or Password is incorrect or not exists", "Okay", "Cancel");
    }
}

Open the WebApi project, and in User1conroller add the following piece of code.

[HttpGet]
[Route("api/UserCredentials/email={email}/password={password}")]
public async Task<IHttpActionResult> UserDetailsLogin(string email, string password)
{
    User login = await db.Users
        .Where(x => x.Email == email && x.Password == password)
        .SingleOrDefaultAsync();

    if (login == null)
    {
        return NotFound();
    }

    return Ok(login);
}

Run WebApi, copy the link from the browser and paste it into http:// links in the RestClient class.

class RestClient<T>
{
    private const string MainWebServiceUrl = "http://localhost:61525/";
    private const string LoginWebServiceUrl = "http://localhost:61525/api/UserCredentials/";

    public async Task<bool> CheckLogin(string email, string password)
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync(LoginWebServiceUrl + "email=" + email + "/" + "password=" + password);
        return response.IsSuccessStatusCode;
    }
}

Run WebApi first. Then, run the xamarin solution. If you type the correct email and password, I will show a display alert like this.

Login successfull

If you type an incorrect Email and Password it will show the following display alert.

Login failed

The procedure of Combining SignUp Services to WebApi

First of all, create a new Web project. In that project, add a class in Model. For this, go to Solution Explorer and right-click on model -> add -> class. Give a suitable name to that class, and say “User”. In user.cs add the following by writing prop and double tab on it. Set the data type and property for that.

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

Build your solution and add MVC AND WebApi controllers by following the same procedure as described above. Run your solution. Register yourself by creating. After adding MVC and after adding WebApi controller you can see your signup form.

Now, open a new project with cross-platform. First of all, add a class with the same name “User” and give the same properties to the class as given in the web project.

Go to MainPage.xaml and add the signup frontend as

<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
    <Entry Placeholder="First Name" x:Name="First" />
    <Entry Placeholder="Last Name" x:Name="Last" />
    <Entry Placeholder="Email" x:Name="Email" />
    <Entry Placeholder="Password" x:Name="Pass" />
    <Entry Placeholder="Confirm Password" x:Name="Confirm" />
    <Button Text="Register" CornerRadius="3" x:Name="Register" Clicked="Register_Clicked" />
</StackLayout>

Methods for adding ServiceHandler and RestApi are the same.

Go to MainPage.xaml.cs and add the following piece of code in the button event.

LoginService service = new LoginService();
var getLoginDetails = await service.CheckLoginIfExists(Email.Text, Pass.Text);

if (First.Text == null && Last.Text == null && Email.Text == null && Pass.Text == null && Confirm.Text == null)
{
    await DisplayAlert("Registration Failed", "Enter your details", "Okay", "Cancel");
}
else if (getLoginDetails)
{
    await DisplayAlert("Registration Failed", "Already have an account", "Okay", "Cancel");
}
else
{
    await DisplayAlert("Registration successful", "Thanks for using our app", "Okay", "Cancel");
}

Open the WebApi project, and in User1conroller, add the following piece of code.

[HttpGet]
[Route("api/UserCredentials/email={email}/password={password}")]
public async Task<IHttpActionResult> UserDetailsLogin(string email, string password)
{
    User login = await db.Users
        .Where(x => x.Email == email && x.Password == password)
        .SingleOrDefaultAsync();

    if (login == null)
    {
        return NotFound();
    }

    return Ok(login);
}

Run WebApi, copy the link from the browser and paste it into http:// links in the RestClient class.

class RestClient<T>
{
    private const string MainWebServiceUrl = "http://localhost:50226/";
    private const string LoginWebServiceUrl = "http://localhost:50226/UserCredentials/";

    public async Task<bool> CheckLogin(string email, string password)
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync(LoginWebServiceUrl + "email=" + email + "/" + "password=" + password);
        return response.IsSuccessStatusCode;
    }
}

This is the whole procedure. Thank You.


Similar Articles