Firebase with.Net Core and C#

Hi folks,

Are you developing web applications with .net ? Are you supporting mobile applications to communicate with your applications ? Are you thinking of providing realtime capabilities with your apps? Then I suggest you to read on Firebase Real-Time Dataabses by Google.

"The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client." - Google Firebase Team
Read more: https://firebase.google.com/docs/database/

In this post I'm going to discuss what is firebase but I'm going to discuss how to work with it with .Net C#.
Firebase doesn't provide a separate library or a nugget to work with .Net, so you might find this bit tricky when you have to work with it from the backend.

Senario
To demonstrate the solution I will create a scenario. In my scenario we have created a video call function (which is implemented with OpenTok library) and it allows users to create sessions and invite or remove users to and from sessions.

So golden note: Firebase works like an API which you can communicate with if you have the authority (obviously the google api key). Which means it accepts http requests.

1. Create a new object in the database

public async Task<bool> AddToActiveCalls(OpenTokModel openTokModel, bool callInitiate)
        {
            var _pushSettings = _pushNotificationSender.GetPushSettings();
            string activeUsersUrl = _pushSettings.RealtimeDatabaseURL + "/active_calls/" + openTokModel.SessionId + ".json";

            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                var callUsers = new List<string>();
                callUsers.Add(openTokModel.SenderId);
                callUsers.Add(openTokModel.ReceiverId);

                var activeCall = new ActiveCalls
                {
                    ApiKey = openTokModel.ApiKey,
                    FromUserId = openTokModel.SenderId,
                    FromUserName = openTokModel.Sender,
                    SessionId = openTokModel.SessionId,
                    Token = openTokModel.Token,
                    ToUsers = callUsers
                };

                string activeCallData = JsonConvert.SerializeObject(activeCall);

                var httpContent = new StringContent(activeCallData, Encoding.UTF8, "application/json");
                var method = new HttpMethod("PATCH");
                var request = new HttpRequestMessage(method, activeUsersUrl)
                {
                    Content = httpContent
                };

                await client.SendAsync(request);
                await AddUserToActiveCall(openTokModel.SessionId, Guid.NewGuid());
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

NOTE: If you have used; var method = new HttpMethod("POST");
rather using var method = new HttpMethod("PATCH");

Then, Firebase will create your active call data inside another auto generated node.

2. Update an existing object in the database (Pushing an item to an array)

public async Task AddUserToActiveCall(string sessionId, Guid invitee)
        {
            var _pushSettings = _pushNotificationSender.GetPushSettings();
            string activeUsersUrl = _pushSettings.RealtimeDatabaseURL + "/active_calls/" + sessionId + ".json";

            try
            {
                var client = new HttpClient();
                var result = await client.GetAsync(activeUsersUrl);
                if (result != null)
                {
                    var data = result.Content.ReadAsStringAsync();
                    var activeCall = JsonConvert.DeserializeObject<ActiveCalls>(data.Result);
                    activeCall.ToUsers.Add(invitee.ToString());

                    string activeCallData = JsonConvert.SerializeObject(activeCall);

                    var httpContent = new StringContent(activeCallData, Encoding.UTF8, "application/json");
                    var method = new HttpMethod("PATCH");
                    var request = new HttpRequestMessage(method, activeUsersUrl)
                    {
                        Content = httpContent
                    };

                    await client.SendAsync(request);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

3. Remove an item from an array in object

public async Task<bool> RemoveUserFromActiveCall(string sessionId, Guid user)
        {
            var _pushSettings = _pushNotificationSender.GetPushSettings();
            string activeUsersUrl = _pushSettings.RealtimeDatabaseURL + "/active_calls/" + sessionId + ".json";

            try
            {
                var client = new HttpClient();
                var result = await client.GetAsync(activeUsersUrl);
                if (result != null)
                {
                    var data = result.Content.ReadAsStringAsync();
                    var activeCall = JsonConvert.DeserializeObject<ActiveCalls>(data.Result);
                    activeCall.toUsers.Remove(user.ToString());

                    string activeCallData = JsonConvert.SerializeObject(activeCall);

                    var httpContent = new StringContent(activeCallData, Encoding.UTF8, "application/json");
                    var method = new HttpMethod("PATCH");
                    var request = new HttpRequestMessage(method, activeUsersUrl)
                    {
                        Content = httpContent
                    };

                    await client.SendAsync(request);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

4. Remove an object from firebase database

public async Task<bool> RemoveSessionFromActiveCall(string sessionId)
        {
            var _pushSettings = _pushNotificationSender.GetPushSettings();
            string activeUsersUrl = _pushSettings.RealtimeDatabaseURL + "/active_calls/" + sessionId + ".json";

            try
            {
                var client = new HttpClient();
                var result = await client.GetAsync(activeUsersUrl);
                if (result != null)
                {
                    var data = result.Content.ReadAsStringAsync();
                    var activeCall = JsonConvert.DeserializeObject<ActiveCalls>(data.Result);

                    string activeCallData = JsonConvert.SerializeObject(activeCall);

                    var httpContent = new StringContent(activeCallData, Encoding.UTF8, "application/json");
                    var method = new HttpMethod("DELETE");
                    var request = new HttpRequestMessage(method, activeUsersUrl)
                    {
                        Content = httpContent
                    };

                    await client.SendAsync(request);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

Hope this helps you to solve some problems.
Happy coding...

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#