Search code examples
c#xamarinxamarin.androidgoogle-vision

Set Environment Variable in Xamarin for Google Cloud API


Right now I'm working on using Google's Cloud Vision API (https://cloud.google.com/dotnet/) with Xamarin in Visual Studio. I am working on making an android app with that and I can't figure out how to set the environment variable for the Cloud API. Google's website says:

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key.

I'm not exactly sure how to do that. I have my code below. When I run it, I get this error:

Unhandled Exception:

System.InvalidOperationException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. occurred

I'm new to C# so sorry if this is a really simple fix. Thank you so much in advance!

public async void AnalyzePicAsync(object sender, EventArgs eventArgs)
{
  string json1 = "";
  //Gets API Credentials
  AssetManager assets = this.Assets;

  using (StreamReader sr = new StreamReader(assets.Open("computer-vision-test-204417-9d2666a5603a.json")))
  {
    json1 = sr.ReadToEnd();
  }
  //Instantiates a client

  GoogleCredential credential = GoogleCredential.FromJson(json1);

  var client = ImageAnnotatorClient.Create();
  // Load the image file into memory
  var image = Image.FromFile(_file.Path);
  // Performs label detection on the image file
  var response = client.DetectLabels(image);
  foreach (var annotation in response)
  {
    if (annotation.Description != null)
        System.Console.WriteLine(annotation.Description);
  }
}

Solution

  • I can't figure out how to set the environment variable for the Cloud API.

    According to Getting Started with Authentication, you can set it by using command prompt

    set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
    

    And the [PATH] is the file path of the JSON file that contains your service account key.

    You could get the service account key in the Google Cloud Platform Console. And you could follow this tutorial to get it.