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

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. rules”: {
  4. “.read”: “auth == null”,
  5. “.write”: ”auth == null
  6. }
  7. }
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. namespace XF_Login.Models
  5. {
  6. public class Users
  7. {
  8. public string Email { get; set; }
  9. public string Password { get; set; }
  10. }
  11. }
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. namespace XF_Login.ViewModel
  11. {
  12. public class FirebaseHelper
  13. {
  14. //Connect app with firebase using API Url
  15. public static FirebaseClient firebase = new FirebaseClient("your database API URI");
  16. //Read All
  17. public static async Task<List<Users>> GetAllUser()
  18. {
  19. try
  20. {
  21. var userlist = (await firebase
  22. .Child("Users")
  23. .OnceAsync<Users>()).Select(item =>
  24. new Users
  25. {
  26. Email = item.Object.Email,
  27. Password = item.Object.Password
  28. }).ToList();
  29. return userlist;
  30. }
  31. catch(Exception e)
  32. {
  33. Debug.WriteLine($"Error:{e}");
  34. return null;
  35. }
  36. }
  37. //Read
  38. public static async Task<Users> GetUser(string email)
  39. {
  40. try
  41. {
  42. var allUsers = await GetAllUser();
  43. await firebase
  44. .Child("Users")
  45. .OnceAsync<Users>();
  46. return allUsers.Where(a => a.Email == email).FirstOrDefault();
  47. }
  48. catch(Exception e)
  49. {
  50. Debug.WriteLine($"Error:{e}");
  51. return null;
  52. }
  53. }
  54. //Inser a user
  55. public static async Task<bool> AddUser(string email,string password)
  56. {
  57. try
  58. {
  59. await firebase
  60. .Child("Users")
  61. .PostAsync(new Users() { Email = email, Password = password });
  62. return true;
  63. }
  64. catch(Exception e)
  65. {
  66. Debug.WriteLine($"Error:{e}");
  67. return false;
  68. }
  69. }
  70. //Update
  71. public static async Task<bool> UpdateUser(string email,string password)
  72. {
  73. try
  74. {
  75. var toUpdateUser = (await firebase
  76. .Child("Users")
  77. .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
  78. await firebase
  79. .Child("Users")
  80. .Child(toUpdateUser.Key)
  81. .PutAsync(new Users() { Email = email, Password = password });
  82. return true;
  83. }
  84. catch(Exception e)
  85. {
  86. Debug.WriteLine($"Error:{e}");
  87. return false;
  88. }
  89. }
  90. //Delete User
  91. public static async Task<bool> DeleteUser(string email)
  92. {
  93. try
  94. {
  95. var toDeletePerson = (await firebase
  96. .Child("Users")
  97. .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
  98. await firebase.Child("Users").Child(toDeletePerson.Key).DeleteAsync();
  99. return true;
  100. }
  101. catch(Exception e)
  102. {
  103. Debug.WriteLine($"Error:{e}");
  104. return false;
  105. }
  106. }
  107. }
  108. }
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. if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
  5. await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
  6. else
  7. {
  8. //call GetUser function which we define in Firebase helper class
  9. var user = await FirebaseHelper.GetUser(Email);
  10. //firebase return null valuse if user data not found in database
  11. if(user!=null)
  12. if (Email == user.Email && Password == user.Password)
  13. {
  14. await App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
  15. //Navigate to Wellcom page after successfuly login
  16. //pass user email to welcom page
  17. await App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));
  18. }
  19. else
  20. await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
  21. else
  22. await App.Current.MainPage.DisplayAlert("Login Fail", "User not found", "OK");
  23. }
  24. }
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(this, new PropertyChangedEventArgs("Email"));
  11. }
  12. }
  13. private string password;
  14. public event PropertyChangedEventHandler PropertyChanged;
  15. public string Password
  16. {
  17. get { return password; }
  18. set
  19. {
  20. password = value;
  21. PropertyChanged(this, new PropertyChangedEventArgs("Password"));
  22. }
  23. }
  24. private string confirmpassword;
  25. public string ConfirmPassword
  26. {
  27. get { return confirmpassword; }
  28. set
  29. {
  30. confirmpassword = value;
  31. PropertyChanged(this, new PropertyChangedEventArgs("ConfirmPassword"));
  32. }
  33. }
  34. public Command SignUpCommand
  35. {
  36. get
  37. {
  38. return new Command(() =>
  39. {
  40. if (Password == ConfirmPassword)
  41. SignUp();
  42. else
  43. App.Current.MainPage.DisplayAlert("", "Password must be same as above!", "OK");
  44. } );
  45. }
  46. }
  47. private async void SignUp()
  48. {
  49. //null or empty field validation, check weather email and password is null or empty
  50. if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
  51. await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
  52. else
  53. {
  54. //call AddUser function which we define in Firebase helper class
  55. var user = await FirebaseHelper.AddUser(Email,Password);
  56. //AddUser return true if data insert successfuly
  57. if (user)
  58. {
  59. await App.Current.MainPage.DisplayAlert("SignUp Success", "", "Ok");
  60. //Navigate to Wellcom page after successfuly SignUp
  61. //pass user email to welcom page
  62. await App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));
  63. }
  64. else
  65. await App.Current.MainPage.DisplayAlert("Error", "SignUp Fail", "OK");
  66. }
  67. }
  68. }
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. get { return new Command(Update); }
  4. }
  5. private async void Update()
  6. {
  7. try
  8. {
  9. if (!string.IsNullOrEmpty(Password))
  10. {
  11. var isupdate = await FirebaseHelper.UpdateUser(Email, Password);
  12. if (isupdate)
  13. await App.Current.MainPage.DisplayAlert("Update Success", "", "Ok");
  14. else
  15. await App.Current.MainPage.DisplayAlert("Error", "Record not update", "Ok");
  16. }
  17. else
  18. await App.Current.MainPage.DisplayAlert("Password Require", "Please Enter your password", "Ok");
  19. }
  20. catch (Exception e)
  21. {
  22. Debug.WriteLine($"Error:{e}");
  23. }
  24. }
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. get { return new Command(Delete); }
  4. }
  5. private async void Delete()
  6. {
  7. try
  8. {
  9. var isdelete = await FirebaseHelper.DeleteUser(Email);
  10. if (isdelete)
  11. await App.Current.MainPage.Navigation.PopAsync();
  12. else
  13. await App.Current.MainPage.DisplayAlert("Error", "Record not delete", "Ok");
  14. }
  15. catch (Exception e)
  16. {
  17. Debug.WriteLine($"Error:{e}");
  18. }
  19. }
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
<<Previous Article