How do I connect my MAUI app to a Firestore database? (via service account json file)

Viewed 719

Creating a MAUI app and trying to connect it to the Firestore. I'm following the advice here to download a service account JSON file and set the GOOGLE_APPLICATION_CREDENTIALS environment variable.

I downloaded my service file from my firebase project online, renamed it to GoogleAppCredentials.json, and then included it in my MAUI project with the Build Action "MauiAsset" like so:

GoogleAppCredentials location

My cs file then references the file:

string path = "GoogleAppCredentials.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);

But when I run the app on Android Emulator I get the following error:

System.AggregateException
  Message=One or more errors occurred. (Error reading credential file from location GoogleAppCredentials.json: Could not find file '/GoogleAppCredentials.json'.
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS)

And on Windows Machine...

System.AggregateException
  Message=One or more errors occurred. (Error reading credential file from location GoogleAppCredentials.json: Could not find file 'C:\WINDOWS\system32\GoogleAppCredentials.json'.
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS)

So with MAUI, how do I properly copy GoogleAppCredentials.json into the app (if not MauiAsset, what else?) and then reference it in the .cs file?

1 Answers

Creating a MAUI app and trying to connect it to the Firestore. I'm following the advice here to download a service account JSON file and set the GOOGLE_APPLICATION_CREDENTIALS environment variable.

This .NET Client is for backend services. You can install it and it can start to run, but they are designed to be used in .net services in the Google Cloud environment.

MAUI is a Multi-targeted project which adds the ability to hold all codebase in the project insted of adding a separate project per platform as it is in Xamarin. The multi-target project steal is built to specific platform artifacts with platform binding. For example, net6.0-android included android bindings with all standard Android ecosystems.

To integrate with Firebase Firestore you need to use Android guidelines and libraries: Xamarin.Firebase.Firestore and configure google-services.json with GoogleServicesJson build action, but in MAUI you need to do this in the Platform/Andoroid location.

My csproj contains this configurations

<ItemGroup>
    <None Remove="Platforms\Android\google-services.json" />
</ItemGroup>
<ItemGroup>
    <GoogleServicesJson Include="Platforms\Android\google-services.json" />
</ItemGroup>

For my project, I do not target WinUI so I using this Lib for accessing Firestore Plugin.CloudFirestore

Related