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.
- {
-
- “
- 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,
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()
- {
-
-
- if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
- await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
-
- var user = await FirebaseHelper.GetUser(Email);
-
- if(user!=null)
- if (Email == user.Email && Password == user.Password)
- {
- await App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
-
-
- 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()
- {
-
-
- if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
- await App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Email and Password", "OK");
- else
- {
-
- var user = await FirebaseHelper.AddUser(Email,Password);
-
- if (user)
- {
- await App.Current.MainPage.DisplayAlert("SignUp Success", "", "Ok");
-
-
- 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();
-
- 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