Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use set Environment Variables in Xamarin.Forms from App Center

I have a Xamarin Forms app which is being built using App Center. The app contains some code that looks like:

var secret= "secretvaluegoeshere";

I then use the secret to communicate with an API. Now I want to extract that secret from code so as not to having it in source control and inject it when building on App Center. Environment Variables seem like they should solve this very problem but the examples in the docs don't mention how they can get into code (only nuget and gradle config). Is there a way to do what I want with Environment Variables or should I be doing this another way?

like image 664
Adam Cooper Avatar asked Jul 31 '18 20:07

Adam Cooper


People also ask

How do I use App Center in Xamarin form?

Add new -> Add new app Here add your “App name”, Description, in this window you can select your OS and Platform. I am using Xamarin so I select Xamarin in Platform and Android in OS. After that click on “Add new app" button. If you able see this screen that means you have successfully created your App in AppCenter.

How do I set Environment Variables in Visual Studio?

To access this page, select a project node in Solution Explorer, select Project > Properties from the Visual Studio menu, and then select the Environment Variables tab. Specifies the name of an environment variable that will be used when the project is built or when the project is run from Visual Studio.

How do I set Environment Variables in MSBuild?

Click on System and Security and then on System. In the left pane, click on Advanced system settings. At the very bottom of the pop up, click on Environment Variables. Edit the Path variable and append the folder's path that contains the MSBuild.exe to it (e.g., ;C:\Windows\Microsoft.NET\Framework64\v4.


1 Answers

So it turns out this is surprisingly easy by following these steps:

Install the Mobile.BuildTools NuGet package in your project.

Add a secrets.json file in the root of your project (this should be excluded from source control using .gitignore).

Add your secret to the secrets.json file, so in my case I'm going to add a SearchApiKey, obviously you can add as many secrets as you want:

{
  "SearchApiKey": "SUPERSECRETGOESHERE"
}

Build your project and this will generate a static class called Secrets with a property SearchApiKey, you can find it under the obj folder if you want to have a look at it.

You can now access this class and it's properties in your code so I just do:

var secret = Secrets.SearchApiKey;

Finally to pass the secret into your build on AppCenter you need to add an Environment Variable that matches the property name prepended with Secret_ so in my case it's name is Secret_SearchApiKey and set it's value.

You can check out the Mobile.BuildTools GitHub repository for more information.

like image 152
Adam Cooper Avatar answered Sep 21 '22 23:09

Adam Cooper