SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM

Introduction

 
In the previous article, we created a login page and wrote the code for the login button. We learned how a user logs in and goes to the next page. But we did this without any database connectivity. Now, in this article, we will connect or configure our app with the Firebase database. We will check if the user exists in the database or not. If the user exists, then the user can log into the system. If a user does not exist, then he/she can register or create the new account.
 
Purpose
 
The main purpose of this article is to learn how to perform CRUD (Create, Read, Update, Delete) operations with Firebase.
 

What is Firebase?

 
Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users.
 
Firebase is a back-end platform for building Web, Android, and iOS applications. It offers a real-time database, different APIs, multiple authentication types, and hosting platforms. This is an introductory tutorial which covers the basics of the Firebase platform and explains how to deal with its various components and sub-components.
 

Build apps with Firebase

  • Real-time Database
  • Storage
  • Notifications
  • Authentication
  • Hosting

Setting up a Xamarin.Forms project

 
As you know, we already created a login page in the previous article so we will continue using that project.
 
Now, open the XF_Login.sln project solution.
 

Create a project in Firebase

 
In this step, create a project in Firebase. Go to the following link.
 
Click “Add Project”.
 
Add a new project here
 
Now, give the project a name and select your country. Then, read the terms. Afterward, click “Create project”.
 
Type the name of your project and click on the "Create New Project".
 
Now, your project is ready. Click “Continue”.
 
In this step, choose Database under the Project Overview. Now, click “Create database”.
 
In this step, write the read and write rules.
  1. {  
  2.     /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */  
  3.     “  
  4.     rules”: {  
  5.         “.read”: “auth == null”,  
  6.         “.write”: ”auth == null”  
  7.     }  
  8. }  
Now, your Firebase Realtime Database is ready. You can use your database API URI in your project.
 
Now, come back to our project. We already have created a login page but we need to create a signup page to add a new user. So, let’s create a signup page.
 
Step 1
 
Now first, we will create a Model which contains the attribute of users, like email and password in our case. Model is nothing but a class. Each class represents one table inside the database. So, let’s go ahead and define a class. So inside our XF_Login project and right-click on it and at first, create a new folder named as Model because all model classes are going to define inside of it. And then, inside this folder, I am going to add a new class.
 
Right-click on Models folder and select Add ->Class. This opens a new dialog box.Give a name to Users.cs.
 
Now, write the following code inside the Users class to define its members. The only thing that we need is to set some properties. Each of the properties is going to be a column inside of the table. And right now we only need two columns (Email and Password).
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Text;    
  4.     
  5. namespace XF_Login.Models    
  6. {    
  7.    public class Users    
  8.     {    
  9.         public string Email { getset; }    
  10.         public string Password { getset; }    
  11.     }    
  12. }    
Step 2
 
Select the Views folder, right-click, and then click "Add New Item" and select the Content Page by entering the name XF_SignUpPage.xaml, and write the following code.
  1. <?xml version="1.0" encoding="utf-8" ?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"    
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"    
  4.              x:Class="XF_Login.View.XF_SignUpPage">    
  5.     <ContentPage.Content>    
  6.         <StackLayout>    
  7.             <Entry x:Name="Emailentery" Placeholder="Email" Text="{Binding Email}" Keyboard="Email"    
  8.                  />    
  9.             <Entry x:Name="passwordentery" Placeholder="Password" Text="{Binding Password}"     
  10.                    IsPassword="True"/>    
  11.             <Entry x:Name="cfmpasswordentery" Placeholder="Re_Enter Password" Text="{Binding ConfirmPassword}"     
  12.                    IsPassword="True" />    
  13.             <Button x:Name="signup" Text="SignUp" Command="{Binding SignUpCommand}" HorizontalOptions="Center"/>    
  14.         </StackLayout>    
  15.     </ContentPage.Content>    
  16. </ContentPage>    
Step 3
 
Now, add the following NuGet packages.
 
FirebaseDatabase.net
 
These packages are going to allow us to easily connect to these kinds of services and easily use the features that these services have.
 
Add FirebaseDatabase.net NuGet
 
Go to Solution Explorer and select your solution. Right-click and select “Manage NuGet Packages for Solution”. Search for “FirebaseDatabase.net” and add Package. Remember to install it for each project (.NET Standard, Android, iOS, and UWP).
 
Step 4
 
It’s time for us to connect the Firebase database that we have created, to our Xamarin.Forms application. To connect with firebase we are going to add a new class in the ViewModel folder.
 
Right-click on ViewModel folder and select Add ->Class. This opens a new dialog box. Give a name as FirebaseHelper.cs.
 
Now write the following code in FirebaseHelper class,
  1. using Firebase.Database;    
  2. using Firebase.Database.Query;    
  3. using System;    
  4. using System.Collections.Generic;    
  5. using System.Diagnostics;    
  6. using System.Linq;    
  7. using System.Text;    
  8. using System.Threading.Tasks;    
  9. using XF_Login.Models;    
  10.     
  11. namespace XF_Login.ViewModel    
  12. {    
  13.    public class FirebaseHelper    
  14.     {    
  15. //Connect app with firebase using API Url  
  16.       public static FirebaseClient firebase = new FirebaseClient("your database API URI");    
  17.     
  18.         //Read All    
  19.         public static async Task<List<Users>> GetAllUser()    
  20.         {    
  21.             try    
  22.             {    
  23.                 var userlist = (await firebase    
  24.                 .Child("Users")    
  25.                 .OnceAsync<Users>()).Select(item =>    
  26.                 new Users    
  27.                 {    
  28.                     Email = item.Object.Email,    
  29.                     Password = item.Object.Password    
  30.                 }).ToList();    
  31.                 return userlist;    
  32.             }    
  33.             catch(Exception e)    
  34.             {    
  35.                 Debug.WriteLine($"Error:{e}");    
  36.                 return null;    
  37.             }    
  38.         }    
  39.     
  40.         //Read     
  41.         public static async Task<Users> GetUser(string email)    
  42.         {    
  43.             try    
  44.             {    
  45.                 var allUsers = await GetAllUser();    
  46.                 await firebase    
  47.                 .Child("Users")    
  48.                 .OnceAsync<Users>();    
  49.                 return allUsers.Where(a => a.Email == email).FirstOrDefault();    
  50.             }    
  51.             catch(Exception e)    
  52.             {    
  53.                 Debug.WriteLine($"Error:{e}");    
  54.                 return null;    
  55.             }    
  56.         }    
  57.     
  58.         //Inser a user    
  59.         public static async Task<bool> AddUser(string email,string password)    
  60.         {    
  61.             try    
  62.             {    
  63.     
  64.     
  65.                 await firebase    
  66.                 .Child("Users")    
  67.                 .PostAsync(new Users() { Email = email, Password = password });    
  68.                 return true;    
  69.             }    
  70.             catch(Exception e)    
  71.             {    
  72.                 Debug.WriteLine($"Error:{e}");    
  73.                 return false;    
  74.             }    
  75.         }    
  76.     
  77.         //Update     
  78.         public static async Task<bool> UpdateUser(string email,string password)    
  79.         {    
  80.             try    
  81.             {    
  82.     
  83.     
  84.                 var toUpdateUser = (await firebase    
  85.                 .Child("Users")    
  86.                 .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();    
  87.                 await firebase    
  88.                 .Child("Users")    
  89.                 .Child(toUpdateUser.Key)    
  90.                 .PutAsync(new Users() { Email = email, Password = password });    
  91.                 return true;    
  92.             }    
  93.             catch(Exception e)    
  94.             {    
  95.                 Debug.WriteLine($"Error:{e}");    
  96.                 return false;    
  97.             }    
  98.         }    
  99.     
  100.         //Delete User    
  101.         public static async Task<bool> DeleteUser(string email)    
  102.         {    
  103.             try    
  104.             {    
  105.     
  106.     
  107.                 var toDeletePerson = (await firebase    
  108.                 .Child("Users")    
  109.                 .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();    
  110.                 await firebase.Child("Users").Child(toDeletePerson.Key).DeleteAsync();    
  111.                 return true;    
  112.             }    
  113.             catch(Exception e)    
  114.             {    
  115.                 Debug.WriteLine($"Error:{e}");    
  116.                 return false;    
  117.             }    
  118.         }    
  119.     
  120.     }    
  121. }    
That’s it. Our Firebase helper class is ready. We are going to use this to perform CRUD operations.
 
Step 5
 
Now, open the LoginViewModel class and change the code a little bit. We only make changes in the Login function.
 
Replace the code with the following.
  1. private async void Login()    
  2.        {    
  3.            //null or empty field validation, check weather email and password is null or empty    
  4.                
  5.            if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))    
  6.             await App.Current.MainPage.DisplayAlert("Empty Values""Please enter Email and Password""OK");    
  7.            else    
  8.            {    
  9.                //call GetUser function which we define in Firebase helper class    
  10.                var user = await FirebaseHelper.GetUser(Email);    
  11.                //firebase return null valuse if user data not found in database    
  12.                if(user!=null)    
  13.                if (Email == user.Email && Password == user.Password)    
  14.                {    
  15.                await  App.Current.MainPage.DisplayAlert("Login Success""""Ok");    
  16.                    //Navigate to Wellcom page after successfuly login    
  17.                    //pass user email to welcom page    
  18.                 await   App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));    
  19.                }    
  20.                else    
  21.                await  App.Current.MainPage.DisplayAlert("Login Fail""Please enter correct Email and Password""OK");    
  22.                else    
  23.                    await App.Current.MainPage.DisplayAlert("Login Fail""User not found""OK");    
  24.            }    
  25.        }    
Step 6
 
Now we add a new user in the database to create a new user account. To insert data in the database, we call AddUser function that we define in Firebase helper class and pass user email and password. So first we are going to create a new class inside the ViewModel folder.
 
Right-click on ViewModel folder and select Add ->Class. This opens a new dialog box. Give a name as SignUpVM.
 
In this class we are going to define some properties, a method and a command for signup button. Let’s do it.
  1. public class SignUpVM: INotifyPropertyChanged    
  2.    {    
  3.        private string email;    
  4.        public string Email    
  5.        {    
  6.            get { return email; }    
  7.            set    
  8.            {    
  9.                email = value;    
  10.                PropertyChanged(thisnew PropertyChangedEventArgs("Email"));    
  11.            }    
  12.        }    
  13.        private string password;    
  14.     
  15.        public event PropertyChangedEventHandler PropertyChanged;    
  16.     
  17.        public string Password    
  18.        {    
  19.            get { return password; }    
  20.            set    
  21.            {    
  22.                password = value;    
  23.                PropertyChanged(thisnew PropertyChangedEventArgs("Password"));    
  24.            }    
  25.        }    
  26.     
  27.        private string confirmpassword;    
  28.        public string ConfirmPassword    
  29.        {    
  30.            get { return confirmpassword; }    
  31.            set    
  32.            {    
  33.                confirmpassword = value;    
  34.                PropertyChanged(thisnew PropertyChangedEventArgs("ConfirmPassword"));    
  35.            }    
  36.        }    
  37.        public Command SignUpCommand    
  38.        {    
  39.            get    
  40.            {    
  41.                return new Command(() =>     
  42.                {    
  43.                    if (Password == ConfirmPassword)    
  44.                        SignUp();    
  45.                    else    
  46.                         App.Current.MainPage.DisplayAlert("""Password must be same as above!""OK");    
  47.                } );    
  48.            }    
  49.        }    
  50.        private async void SignUp()    
  51.        {    
  52.            //null or empty field validation, check weather email and password is null or empty    
  53.     
  54.            if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))    
  55.                await App.Current.MainPage.DisplayAlert("Empty Values""Please enter Email and Password""OK");    
  56.            else    
  57.            {    
  58.                //call AddUser function which we define in Firebase helper class    
  59.                var user = await FirebaseHelper.AddUser(Email,Password);    
  60.                //AddUser return true if data insert successfuly     
  61.                if (user)    
  62.                {    
  63.                    await App.Current.MainPage.DisplayAlert("SignUp Success""""Ok");    
  64.                    //Navigate to Wellcom page after successfuly SignUp    
  65.                    //pass user email to welcom page    
  66.                    await App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));    
  67.                }    
  68.                else    
  69.                    await App.Current.MainPage.DisplayAlert("Error""SignUp Fail""OK");    
  70.                   
  71.            }    
  72.        }    
  73.    }    
Step 7
 
Now we have to bind the members that we define in SignUpVM with SignUpPage. It is the same as we do in the Login Page.
  1. public partial class XF_SignUpPage : ContentPage    
  2.   {    
  3.       SignUpVM signUpVM;    
  4.       public XF_SignUpPage()    
  5.       {    
  6.           InitializeComponent();    
  7.           signUpVM = new SignUpVM();    
  8.           //set binding    
  9.           BindingContext = signUpVM;    
  10.       }    
  11.   }    
Step 8
 
The user now can create a new account and can log in with this account. But what if the user wants to change the password or wants to delete the account permanently, how can the user do it? Let’s write code for it, it’s so easy. First, we update the user password. We use login with email, we pass this email to welcome page so that we can search user in the database on the basis of this email. As you know the update and delete operations are performed when the user logs in with the account so these operations are performed in the welcome page. For that we are going to create a new view model for welcome page. Let’s create a new class inside the ViewModel folder.
 
Right-click on ViewModel folder and select Add ->Class. This opens a new dialog box. Give a name as WelcomeVM.
 
Write the following code,
  1. public Command UpdateCommand  
  2.       
  3.     {  
  4.          get { return new Command(Update); }  
  5.       }  
  6.     private async void Update()    
  7.           {    
  8.               try    
  9.               {    
  10.                   if (!string.IsNullOrEmpty(Password))    
  11.                   {    
  12.                       var isupdate = await FirebaseHelper.UpdateUser(Email, Password);    
  13.                       if (isupdate)    
  14.                           await App.Current.MainPage.DisplayAlert("Update Success""""Ok");    
  15.                       else    
  16.                           await App.Current.MainPage.DisplayAlert("Error""Record not update""Ok");    
  17.                   }    
  18.                   else    
  19.                       await App.Current.MainPage.DisplayAlert("Password Require""Please Enter your password""Ok");    
  20.               }    
  21.               catch (Exception e)    
  22.               {    
  23.         
  24.                   Debug.WriteLine($"Error:{e}");    
  25.               }    
  26.           }    
Similarly we write code for delete operstion. We simply call DeleteUser function inside WelcomeVM that we define in FirebaseHelper class.
  1. public Command DeleteCommand  
  2.       
  3.    {  
  4.          get { return new Command(Delete); }  
  5.    }  
  6.     private async void Delete()    
  7.           {    
  8.               try    
  9.               {    
  10.                   var isdelete = await FirebaseHelper.DeleteUser(Email);    
  11.                   if (isdelete)    
  12.                       await App.Current.MainPage.Navigation.PopAsync();    
  13.                   else    
  14.                       await App.Current.MainPage.DisplayAlert("Error""Record not delete""Ok");    
  15.               }    
  16.               catch (Exception e)    
  17.               {    
  18.         
  19.                   Debug.WriteLine($"Error:{e}");    
  20.               }    
  21.           }    
Step 9
 
We define a property of type command for logout button named LogoutCommand.
  1. public Command LogoutCommand    
  2.         {    
  3.             get    
  4.             {    
  5.                 return new Command(() =>    
  6.                 {    
  7.                      App.Current.MainPage.Navigation.PopAsync();    
  8.                 });    
  9.             }    
  10.         }    
Step 10
 
And finally we set binding for Welcome Page with WelcomeVM, just like we do in Login and SignUp Page.
  1. public partial class WelcomPage : ContentPage    
  2.     {    
  3.         WelcomePageVM welcomePageVM;    
  4.         public WelcomPage (string email)    
  5.         {    
  6.             InitializeComponent ();    
  7.             welcomePageVM = new WelcomePageVM(email);    
  8.             BindingContext = welcomePageVM;    
  9.         }    
  10.     }    
And that’s it -- we are done.
 
I hope you have understood, how to use Firebase Real-time Database with CRUD Operations in Xamarin.Forms.
 
Thanks for reading.
 
Please share your comments and feedback.
 
Happy Coding :)
 

OutPut 

 
SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM
 
SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM
 
Before Update
 
SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM
 
SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM
 
After Update
 
SignUp And Login Form In Xamarin.Forms With Firebase RealTime Database MVVM
 


Similar Articles