FirebaseExtensions 9.1.0
dotnet add package FirebaseExtensions --version 9.1.0
NuGet\Install-Package FirebaseExtensions -Version 9.1.0
<PackageReference Include="FirebaseExtensions" Version="9.1.0" />
<PackageVersion Include="FirebaseExtensions" Version="9.1.0" />
<PackageReference Include="FirebaseExtensions" />
paket add FirebaseExtensions --version 9.1.0
#r "nuget: FirebaseExtensions, 9.1.0"
#:package FirebaseExtensions@9.1.0
#addin nuget:?package=FirebaseExtensions&version=9.1.0
#tool nuget:?package=FirebaseExtensions&version=9.1.0
Firebase Extension for C#
This library provides convenient extension methods for working with Google Cloud Firestore in your C# applications, simplifying Firebase initialization and document read/write operations.
Installation
This library is assumed to be part of your C# project. Ensure you have the following NuGet packages installed:
FirebaseAdmin
Google.Cloud.Firestore
ReturnPattern
Firebase Project Setup
Before using this library, you need to:
Create a Firebase Project: If you don't have one already, create a new project on the Firebase console.
Create a Service Account:
In the Firebase console, navigate to Project settings → Service accounts.
Click Generate new private key.
This will download a JSON file containing your credentials. Save this file in a secure location, as it contains sensitive information. This file will be used to authenticate your application with Firebase.
Usage
1. Initializing Firebase
Before performing any Firestore operations, you need to initialize the Firebase library by pointing it to your service account JSON file.
using Fishman.Firebase.Extension;
using ReturnPattern;
using Google.Cloud.Firestore;
public class MyFirebaseApp
{
public static void Main(string[] args)
{
// Specify the path to your Firebase service account JSON file
string serviceAccountPath = "path/to/your/serviceAccountKey.json";
// Get the Firebase instance via the static Current property
IFirebase firebaseInstance = Firebase.Current;
// Set the configuration file path
Return setPathResult = firebaseInstance.SetPathFile(serviceAccountPath);
if (setPathResult.IsSuccess)
{
Console.WriteLine("Firebase configuration file path set successfully.");
// Initialize Firebase. It will automatically try to get the ProjectId from the file.
Return initResult = firebaseInstance.Init();
if (initResult.IsSuccess)
{
Console.WriteLine("Firebase initialized successfully.");
// You can now access the FirestoreDb instance
FirestoreDb? db = firebaseInstance.FirestoreDb;
if (db != null)
{
Console.WriteLine($"Connected to Firestore project: {db.ProjectId}");
// Proceed with Firestore operations
}
else
{
Console.WriteLine("Failed to get FirestoreDb instance.");
}
}
else
{
Console.WriteLine($"Firebase initialization failed: {initResult.Message}");
}
}
else
{
Console.WriteLine($"Failed to set Firebase configuration file path: {setPathResult.Message}");
}
}
}
Alternative Initialization with Project ID:
If you prefer to explicitly provide the Project ID, you can do so after setting the file path:
// ... (after getting firebaseInstance and calling SetPathFile) ...
string myProjectId = "your-firebase-project-id";
Return initResult = firebaseInstance.Init(myProjectId);
if (initResult.IsSuccess)
{
Console.WriteLine("Firebase initialized successfully with specified Project ID.");
}
else
{
Console.WriteLine($"Firebase initialization failed: {initResult.Message}");
}
2. Retrieving Firebase Configuration Information
You can retrieve various properties from your service account JSON file using the Firebase.Current
instance:
using Fishman.Firebase.Extension;
using ReturnPattern;
public class ConfigurationReader
{
public static void ReadConfig()
{
// Get the Firebase instance via the static Current property
IFirebase firebaseInstance = Firebase.Current;
// Ensure the file path is set
firebaseInstance.SetPathFile("path/to/your/serviceAccountKey.json");
Return<string> projectId = firebaseInstance.GetProjectId();
if (projectId.IsSuccess)
{
Console.WriteLine($"Project ID: {projectId.Value}");
}
else
{
Console.WriteLine($"Error getting Project ID: {projectId.Message}");
}
Return<string> clientEmail = firebaseInstance.GetClientEmail();
if (clientEmail.IsSuccess)
{
Console.WriteLine($"Client Email: {clientEmail.Value}");
}
else
{
Console.WriteLine($"Error getting Client Email: {clientEmail.Message}");
}
// You can also use the generic GetProperty method
Return<string> universeDomain = firebaseInstance.GetProperty(Firebase.UniverseDomain);
if (universeDomain.IsSuccess)
{
Console.WriteLine($"Universe Domain: {universeDomain.Value}");
}
else
{
Console.WriteLine($"Error getting Universe Domain: {universeDomain.Message}");
}
}
}
3. Writing and Reading Firestore Data
The library provides convenient SetValueAsync
and GetValueAsync
extension methods for DocumentReference
.
Assume you have a data model class:
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Writing Data:
using Fishman.Firebase.Extension;
using Fishman.Firebase.Firestore.Extension; // For extension methods
using Google.Cloud.Firestore;
using ReturnPattern;
using System.Threading.Tasks;
public class FirestoreOperations
{
public static async Task WriteData()
{
// Ensure Firebase is initialized
// IFirebase firebaseInstance = Firebase.Current;
// firebaseInstance.SetPathFile("path/to/your/serviceAccountKey.json");
// firebaseInstance.Init();
FirestoreDb? db = Firebase.Current.FirestoreDb; // Access via Current
if (db == null)
{
Console.WriteLine("FirestoreDb is not initialized.");
return;
}
// Get a reference to a collection and document
CollectionReference usersCollection = db.Collection("users");
DocumentReference userDoc = usersCollection.Document("alisa_id");
// Create an instance of your data model
User alisa = new User { Id = "alisa_id", Name = "Alisa", Age = 30 };
// Set the document data
Return<WriteResult> setResult = await userDoc.SetValueAsync(alisa);
if (setResult.IsSuccess)
{
Console.WriteLine($"Data for Alisa written successfully. Update Time: {setResult.Value!.UpdateTime}");
}
else
{
Console.WriteLine($"Error writing data for Alisa: {setResult.Message}");
}
// Example of using SetOptions (e.g., for merging data)
User updatedAlisa = new User { Name = "Alisa Smirnova" }; // Only updating the name
Return<WriteResult> mergeResult = await userDoc.SetValueAsync(updatedAlisa, SetOptions.MergeAll);
if (mergeResult.IsSuccess)
{
Console.WriteLine($"Data for Alisa merged successfully. Update Time: {mergeResult.Value!.UpdateTime}");
}
else
{
Console.WriteLine($"Error merging data for Alisa: {mergeResult.Message}");
}
}
}
Reading Data:
using Fishman.Firebase.Extension;
using Fishman.Firebase.Firestore.Extension; // For extension methods
using Google.Cloud.Firestore;
using ReturnPattern;
using System.Threading.Tasks;
public class FirestoreOperations
{
public static async Task ReadData()
{
// Ensure Firebase is initialized
// IFirebase firebaseInstance = Firebase.Current;
// firebaseInstance.SetPathFile("path/to/your/serviceAccountKey.json");
// firebaseInstance.Init();
FirestoreDb? db = Firebase.Current.FirestoreDb; // Access via Current
if (db == null)
{
Console.WriteLine("FirestoreDb is not initialized.");
return;
}
// Get a reference to the document
DocumentReference userDoc = db.Collection("users").Document("alisa_id");
// Get the document data and convert it to a User object
Return<User> getResult = await userDoc.GetValueAsync<User>();
if (getResult.IsSuccess)
{
User? retrievedUser = getResult.Value;
if (retrievedUser != null)
{
Console.WriteLine($"Retrieved user: Id={retrievedUser.Id}, Name={retrievedUser.Name}, Age={retrievedUser.Age}");
}
else
{
Console.WriteLine("Retrieved user value is null.");
}
}
else
{
Console.WriteLine($"Error reading user data: {getResult.Message}");
}
}
}
4. Error Handling
The library extensively uses the Return
type from ReturnPattern
to encapsulate operation results. This allows you to check for the success or failure of an operation and retrieve error messages.
Return.IsSuccess
: Checks if the operation was successful.Return.Message
: Contains an error message if the operation failed.Return<T>.Value
: Contains the result of the operation if successful.
5. Resource Cleanup
While Google.Cloud.Firestore
manages its internal resources, you can explicitly free up the cached service account configuration if it's no longer needed (e.g., when your application shuts down or configuration changes). To do this, ensure your Firebase
class implements the IDisposable
interface, then use the Dispose()
method.
using Fishman.Firebase.Extension;
using System; // Add this for IDisposable
public class AppCleanup
{
public static void Main(string[] args)
{
// ... your application logic ...
// Dispose of the cached service account configuration
// Ensure the Firebase class implements IDisposable.
Firebase.Current.Dispose();
Console.WriteLine("Cached service account configuration disposed.");
}
}
We hope this guide helps you get started with the Firebase Extension library!
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- FirebaseAdmin (>= 3.3.0)
- Google.Cloud.Firestore (>= 3.10.0)
- ReturnPattern (>= 9.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.