Winner's Excogitations

A chronicle of the thoughts, learning experiences, ideas and actions of a tech junkie, .NET, JS and Mobile dev, aspiring entrepreneur, devout Christian and travel enthusiast.

Using the Firebase realtime database with .NET

6 years ago ยท 4 minutes read

bolorundurowb_com/production/article/v58tmldwzvdvz2cttzin

A Brief Aside

Over my over 6 years in the software development space and specifically in the .NET ecosystem, I have noticed a kind of animosity towards Microsoft and the .NET platform. Companies create services and develop libraries for just about every other platform but .NET. The excuse cannot be lack of demand as C# is the 7th most used language and ASP.NET the 4th most used web framework by the Stack Overflow developer survey. Despite my ire with the current situation, I do not think it is wholly undeserved as Microsoft has acted in a similar manner over the years, though the organization under Satya Nadella has changed its approach to collaboration. Hopefully, things improve.

Introduction

Firebase is a Backend-as-a-Service (BaaS) that started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. Arguably, the mostly widely used product in the Firebase suite is their real-time database. The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync between your users in realtime. The Realtime Database is really just one big JSON object that the developers can manage in realtime.

Why Firebase?

For a mobile developer with little backend development skill or for a developer who is time-constrained in delivering a mobile product, Firebase takes away the need for building out a dedicated backend to power your mobile service. It handles authentication if you so desire and data persistence and for officially supported platforms, it even offers fail-safes for data if there is a network connectivity interruption. Sadly, .NET is not currently an officially supported platform. I remember seeing a petition or thread of some sort requesting official support from Google but can't seem to find it. Fortunately, we have a workaround. the fine folks over at step up labs wrote a wrapper around the Firebase REST API which gives us access to our data.

Installation

Now to the juicy bits, we need to install the libraries we need. To the shared .NET standard Xamarin project, run one of the following commands, depending on your preference:

Install-Package FirebaseDatabase.net

or

dotnet add package FirebaseDatabase.net

Handling Data

We need to create a model for the data we need to persist and modify. For that, we create a directory called Models. Next, we create a file Student.cs to hold our Student model as defined below:

public class Student
{
  public string FullName {get; set;}
  public string Age {get; set;}
}

The next step is CRUD (Create, Read, Update and Delete) for our data. In order to keep everything all tidy and such, we create a directory Services and a file StudentService.cs to hold our service logic. Remember, data in Firebase has to be stored as key-value pairs. To add support for persisting data to our service, we do the following:

using System;
using Firebase.Database;
using Firebase.Database.Query;

public class StudentService
{
  private const string FirebaseDatabaseUrl = "https://XXXXXX.firebaseio.com/"; // XXXXXX should be replaced with your instance name
  private readonly FirebaseClient firebaseClient;

  public StudentService()
  {
    firebaseClient = new FirebaseClient(FirebaseDatabaseUrl);
  }

  public async Task AddStudent(Student student)
  {
    await firebaseClient
      .Child("students")
      .PostAsync(student);
  }
}

To make use of our service, we add the following, it can be added to the code-behind files of views or in other services:

...
public StudentService service = new StudentService();
...
var student = new Student
{
  FullName = "John Doe",
  Age = "21 Years"
}
await service.AddStudent(student);

To retrieve the students we have saved to the database, we can add a new method to our StudentService class:

using System.Collections.Generic;
...
public class StudentService
{
  ...

  public async Task<List<KeyValuePair<string, Student>>> GetStudents()
  {
     var students = await DatabaseClient
       .Child("students")
       .OnceAsync<Student>();

      return students?
        .Select(x => new KeyValuePair<string, Student>(x.Key, x.Object))
        .ToList();
  }
}

As you can observe with the data retrieval above, when we push new data to Firebase, a new Id is generated for the record and we can get that Id when we retrieve our data. The Id comes in useful when we need to update data we have on Firebase as shown below:

public class StudentService
{
  ...
  public async Task UpdateStudent(string id, Student student)
  {
     var students = await DatabaseClient
       .Child("students")
       .Child(id)
       .PutAsync(student);
  }
}

Removing an entry is just as easy, we just need the id generated for the entry we need to remove. Update your StudentService class with a method to aid removal as shown below:

public class StudentService
{
  ...
  public async Task RemoveStudent(string id)
  {
     var students = await DatabaseClient
       .Child("students")
       .Child(id)
       .DeleteAsync();
  }
}

Further Reading

The complete source for the samples shown can be found on GitHub. While I touched on the basics of accessing data from firebase, the FirebaseDatabase.net library offers support for more advanced data query options such as LimitToFirst and OrderByKey amongst others. It also offers data streaming similar to that of the official libraries with the System.Reactive.Linq namespace. You can find more in-depth documentation at the project GitHub page.

That's it for now,

Cheers.

Share on:
Using Git Bash with Hyper On Windows
A tutorial on making Git bash the default shell for the Hyper terminal app on Windows
Create A URL Shortener With ASP.NET Core and MongoDB
How to create a custom url shortener with ASP.NET Core as well as optimze performance
Winner-Timothy Bolorunduro
Winner-Timothy Bolorunduro is a senior .NET developer with over 6 years experience helping organizations and individuals build compelling, stable and scalable web applications. Having spent the last three years in a fast-paced startup environment working remotely, he understands what goes into being part of a team that produces value for clients.

Comments