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.
- {
- /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
- “
- rules”: {
- “.read”: “auth == null”,
- “.write”: ”auth == null”
- }
- }
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).
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace XF_Login.Models
- {
- public class Users
- {
- public string Email { get; set; }
- public string Password { get; set; }
- }
- }
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.
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="XF_Login.View.XF_SignUpPage">
- <ContentPage.Content>
- <StackLayout>
- <Entry x:Name="Emailentery" Placeholder="Email" Text="{Binding Email}" Keyboard="Email"
- />
- <Entry x:Name="passwordentery" Placeholder="Password" Text="{Binding Password}"
- IsPassword="True"/>
- <Entry x:Name="cfmpasswordentery" Placeholder="Re_Enter Password" Text="{Binding ConfirmPassword}"
- IsPassword="True" />
- <Button x:Name="signup" Text="SignUp" Command="{Binding SignUpCommand}" HorizontalOptions="Center"/>
- </StackLayout>
- </ContentPage.Content>
- </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,
- using Firebase.Database;
- using Firebase.Database.Query;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using XF_Login.Models;
- namespace XF_Login.ViewModel
- {
- public class FirebaseHelper
- {
- //Connect app with firebase using API Url
- public static FirebaseClient firebase = new FirebaseClient("your database API URI");
- //Read All
- public static async Task<List<Users>> GetAllUser()
- {
- try
- {
- var userlist = (await firebase
- .Child("Users")
- .OnceAsync<Users>()).Select(item =>
- new Users
- {
- Email = item.Object.Email,
- Password = item.Object.Password
- }).ToList();
- return userlist;
- }
- catch(Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- return null;
- }
- }
- //Read
- public static async Task<Users> GetUser(string email)
- {
- try
- {
- var allUsers = await GetAllUser();
- await firebase
- .Child("Users")
- .OnceAsync<Users>();
- return allUsers.Where(a => a.Email == email).FirstOrDefault();
- }
- catch(Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- return null;
- }
- }
- //Inser a user
- public static async Task<bool> AddUser(string email,string password)
- {
- try
- {
- await firebase
- .Child("Users")
- .PostAsync(new Users() { Email = email, Password = password });
- return true;
- }
- catch(Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- return false;
- }
- }
- //Update
- public static async Task<bool> UpdateUser(string email,string password)
- {
- try
- {
- var toUpdateUser = (await firebase
- .Child("Users")
- .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
- await firebase
- .Child("Users")
- .Child(toUpdateUser.Key)
- .PutAsync(new Users() { Email = email, Password = password });
- return true;
- }
- catch(Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- return false;
- }
- }
- //Delete User
- public static async Task<bool> DeleteUser(string email)
- {
- try
- {
- var toDeletePerson = (await firebase
- .Child("Users")
- .OnceAsync<Users>()).Where(a => a.Object.Email == email).FirstOrDefault();
- await firebase.Child("Users").Child(toDeletePerson.Key).DeleteAsync();
- return true;
- }
- catch(Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- return false;
- }
- }
- }
- }
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.
- private async void Login()
- {
- //null or empty field validation, check weather email and password is null or empty
- if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
- await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
- //call GetUser function which we define in Firebase helper class
- var user = await FirebaseHelper.GetUser(Email);
- //firebase return null valuse if user data not found in database
- if(user!=null)
- if (Email == user.Email && Password == user.Password)
- {
- await App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
- //Navigate to Wellcom page after successfuly login
- //pass user email to welcom page
- await App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));
- }
- else
- await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
- else
- await App.Current.MainPage.DisplayAlert("Login Fail", "User not found", "OK");
- }
- }
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.
- public class SignUpVM: INotifyPropertyChanged
- {
- private string email;
- public string Email
- {
- get { return email; }
- set
- {
- email = value;
- PropertyChanged(this, new PropertyChangedEventArgs("Email"));
- }
- }
- private string password;
- public event PropertyChangedEventHandler PropertyChanged;
- public string Password
- {
- get { return password; }
- set
- {
- password = value;
- PropertyChanged(this, new PropertyChangedEventArgs("Password"));
- }
- }
- private string confirmpassword;
- public string ConfirmPassword
- {
- get { return confirmpassword; }
- set
- {
- confirmpassword = value;
- PropertyChanged(this, new PropertyChangedEventArgs("ConfirmPassword"));
- }
- }
- public Command SignUpCommand
- {
- get
- {
- return new Command(() =>
- {
- if (Password == ConfirmPassword)
- SignUp();
- else
- App.Current.MainPage.DisplayAlert("", "Password must be same as above!", "OK");
- } );
- }
- }
- private async void SignUp()
- {
- //null or empty field validation, check weather email and password is null or empty
- if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
- await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
- //call AddUser function which we define in Firebase helper class
- var user = await FirebaseHelper.AddUser(Email,Password);
- //AddUser return true if data insert successfuly
- if (user)
- {
- await App.Current.MainPage.DisplayAlert("SignUp Success", "", "Ok");
- //Navigate to Wellcom page after successfuly SignUp
- //pass user email to welcom page
- await App.Current.MainPage.Navigation.PushAsync(new WelcomPage(Email));
- }
- else
- await App.Current.MainPage.DisplayAlert("Error", "SignUp Fail", "OK");
- }
- }
- }
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.
- public partial class XF_SignUpPage : ContentPage
- {
- SignUpVM signUpVM;
- public XF_SignUpPage()
- {
- InitializeComponent();
- signUpVM = new SignUpVM();
- //set binding
- BindingContext = signUpVM;
- }
- }
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,
- public Command UpdateCommand
- {
- get { return new Command(Update); }
- }
- private async void Update()
- {
- try
- {
- if (!string.IsNullOrEmpty(Password))
- {
- var isupdate = await FirebaseHelper.UpdateUser(Email, Password);
- if (isupdate)
- await App.Current.MainPage.DisplayAlert("Update Success", "", "Ok");
- else
- await App.Current.MainPage.DisplayAlert("Error", "Record not update", "Ok");
- }
- else
- await App.Current.MainPage.DisplayAlert("Password Require", "Please Enter your password", "Ok");
- }
- catch (Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- }
- }
Similarly we write code for delete operstion. We simply call DeleteUser function inside WelcomeVM that we define in FirebaseHelper class.
- public Command DeleteCommand
- {
- get { return new Command(Delete); }
- }
- private async void Delete()
- {
- try
- {
- var isdelete = await FirebaseHelper.DeleteUser(Email);
- if (isdelete)
- await App.Current.MainPage.Navigation.PopAsync();
- else
- await App.Current.MainPage.DisplayAlert("Error", "Record not delete", "Ok");
- }
- catch (Exception e)
- {
- Debug.WriteLine($"Error:{e}");
- }
- }
Step 9
We define a property of type command for logout button named LogoutCommand.
- public Command LogoutCommand
- {
- get
- {
- return new Command(() =>
- {
- App.Current.MainPage.Navigation.PopAsync();
- });
- }
- }
Step 10
And finally we set binding for Welcome Page with WelcomeVM, just like we do in Login and SignUp Page.
- public partial class WelcomPage : ContentPage
- {
- WelcomePageVM welcomePageVM;
- public WelcomPage (string email)
- {
- InitializeComponent ();
- welcomePageVM = new WelcomePageVM(email);
- BindingContext = welcomePageVM;
- }
- }
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


Before Update


After Update


John DuranPosted Sep 19, 2022, 2:18 PM
Hi! Do you have a tutorial with offline database using firebase realtime database and Xamarin? Thank you!
S RoyPosted Nov 27, 2020, 1:58 PM
Was looking for example of Firebase authentication.net in xamarin. Any suggestions?
S RoyPosted Nov 27, 2020, 1:57 PM
U can save to preferences. Rather than sqlite.
Xander LuusPosted Aug 1, 2020, 4:11 AM
Can you please send me the code?
Gia Hiếu CaoPosted Jun 15, 2020, 11:11 PM
Excuse me sir , why i always get null value at getUser() event my data in firebase have value
Ivette Rivera GonzalezPosted May 19, 2020, 4:33 PM
Hi I'm learning about this, I wanted to download the code but apparently it was removedcan you share it please [email protected]
Purnama FamiliaPosted May 10, 2020, 1:03 PM
Hi sir,I am new to Xamarin.Forms and your article is very helpful for me to build an apps. So, I have question to ask, how can i just automatically being login when i already register the email. Because when i open the apps, it need me to register back and it just like one time register and login only. Hope you can help or provided any solution to that. Thank you for the knowledge!
Shiwam karnPosted Apr 24, 2020, 10:12 AM
How can i authenticate the user to get token.. pls provide article on that too
Lama SammanPosted Feb 8, 2020, 12:28 PM
Its not connecting, how to know wheres my problem? i
Efgan HuseynovPosted Dec 5, 2019, 6:16 PM
I would like possible only with real email adress.. fake no
Efgan HuseynovPosted Dec 5, 2019, 6:15 PM
Only maybe [email protected] and 12345 register?? or free email adress?
Julian TremontPosted Oct 28, 2019, 3:06 PM
You are great!
THE BYTTLEPosted Jul 20, 2019, 1:22 AM
It,s a great honer to have you sir for help. Please keep writing these excellent article these are very help full for us. My best regards.
Logesh PalaniPosted Jul 18, 2019, 11:12 AM
Nice Article !