How to refer to developer-specific variables in the project file?

115 Views Asked by At

I'm working with a specific solution template. This template makes use of a powershell script, called through the .csproj project file, for building the application. I would like to use an environment variable, or something of the sort, which will not be synchronized to the git repository. This is because of some settings which have to differ in the powershell script between developers.

Most info I find out there is about using environment variables in your .cs files, but that is not where I'm trying to use them here. Furthermore I have come across several ways of using local variables, and it's difficult for me to tell what to use. There's launchSettings.json, Settings.settings, and I believe another one I'm now forgetting. launchSettings.json also has several options within itself, commandLineArgs and Environment variables.

I know how to create a local .txt file and read that out with the powershell script, but it seems to me like there should be a more built-in "proper" way of going about this.

This is the relevant line in the .csproj file:

<Exec Command="PowerShell -ExecutionPolicy Bypass -File installScript.ps1 -someArguments myArguments/>

Further context: From what I've been able to find myself, and as linked below, using $(MyVariable) in .csproj should give the value of the desired env variable? But if so I have been unable to get that to work.

I have tried adding env variables through VS '22 "Debug > Project Debug Properties > Environment Variables", yielding the below launchSettings.json:

{
  "profiles": {
    "ProjectName": {
      "commandName": "Project",
      "environmentVariables": {
        "MyVariable": "MyValue"
      }
    }
  }
}

Then trying:

<Exec Command="PowerShell -ExecutionPolicy Bypass -File installScript.ps1 -MyArgument &quot;$(MyVariable)&quot;/>

Results in an empty field: powershell output

Executing deployment script...
PowerShell -ExecutionPolicy Bypass -File installScript.ps1 **** -MyArgument ""
1

There are 1 best solutions below

0
Jineapple On

You can use the secrets manager: https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=windows

In Visual Studio, you can right-click a project to manage user secrets, which override appsettings(.development).json

Or you can use the dotnet cli: dotnet user-secrets set "Movies:ServiceApiKey" "12345"

As the name implies, it's intended for secrets that shouldn't be committed to version control, but I think it works fine as well for this. You can also set a key in appsettings.json, e.g. "ServiceApiKey": "SetInSecretsJson" to remind the developer where it's stored.

You can then access the variable from PowerShell like this:

(dotnet user-secrets list | Select-String 'Movies:ServiceApiKey = (.*)').Matches[0].Groups[1].Value

Combine this with calling your PowerShell script and I believe this should achieve your goal.