Blog

  • Home
  • Blog
  • How to Manipulate Environment Variables in C#

How to Manipulate Environment Variables in C#

March 11, 2024
In an application like a CRM, it is quite common to have configuration variables for different reasons. Whether it is URLs that point to other application or secret APIs or key ... The uses are diverse.
Fortunately Microsoft knows how to respond with the right solutions to problems, and the acceleration of the pace of releases allows us to benefit from new features much more often.

In this article, I would like to present to you how to read and define the values of environmental variables from a plugin C#.

In fact, the environment variable feature does not come in a single table, but in two tables :

  • Environment Variable Definition
  • Environment Variable Value

When you create a new Environment Vaiable in your solution, this actualy creates the environment variable Définition. Which can be deployed later with you solution. If you want to maintain different values for all environments the definition is enought to be imported in the solutions. You probably won't need to deploy the values.

The code below will help you initiate and set the variable values in the target environment.

public static void SetEnvVariable(IOrganizationService service, string variableName, string variableValue) { // Search for Variable Definition by name QueryExpression queryDefinition = new QueryExpression("environmentvariabledefinition"); queryDefinition.ColumnSet = new ColumnSet("environmentvariabledefinitionid"); queryDefinition.Criteria.AddCondition("schemaname", ConditionOperator.Equal, variableName); EntityCollection definitionResults = service.RetrieveMultiple(queryDefinition); if (definitionResults.Entities.Count > 0) { Entity definition = definitionResults.Entities[0]; // Research the environment variable by its name QueryExpression query = new QueryExpression("environmentvariablevalue"); query.ColumnSet = new ColumnSet("environmentvariablevalueid", "value"); query.Criteria.AddCondition("schemaname", ConditionOperator.Equal, variableName); EntityCollection results = service.RetrieveMultiple(query); if (results.Entities.Count > 0) { Entity variable = results.Entities[0]; variable["value"] = variableValue; // Updates the value of the environment variable service.Update(variable); } else { Entity variable = new Entity("environmentvariablevalue"); variable["environmentvariabledefinitionid"] = new EntityReference("environmentvariabledefinition", definition.Id); variable["schemaname"] = variableName; variable["value"] = variableValue; // Creates the value of the environment variable service.Create(variable); } } }