Introduction
Environment variables are a great way to store global variables that differ in each of your environment. Some common use cases are storing the AppID so it can be referenced in your flows or maybe a Sharepoint site url if you are storing data there. They’re stored on the Dataverse under the EnvironmentVariableDefinition and EnvironmentVariableValue table.
Whilst they’re built into Power Automate and you can access them relatively easy, if you need to reference them in a traditional plugin or custom workflow activity, you’ll need use FetchXML to retrieve them.
Code Snippet
protected override void Execute(CodeActivityContext context)
{
try
{
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
// Use the context service to create an instance of IOrganizationService.
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);
string appID = GetEnvironmentVariable(service, "appID");
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.ToString());
}
}
private string GetEnvironmentVariable(IOrganizationService service, string envVariableName)
{
string fetchXml = string.Empty;
EntityCollection result = null;
string envVariableValue = string.Empty;
fetchXml = String.Format(@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"">
<entity name=""environmentvariablevalue"">
<attribute name=""environmentvariablevalueid"" />
<attribute name=""value"" />
<link-entity name=""environmentvariabledefinition"" from=""environmentvariabledefinitionid"" to=""environmentvariabledefinitionid"" link-type=""inner"">
<attribute name=""displayname"" />
<filter type=""and"">
<condition attribute=""displayname"" operator=""eq"" value=""{0}"" />
</filter>
</link-entity>
</entity>
</fetch>", envVariableName);
result = service.RetrieveMultiple(new FetchExpression(fetchXml));
if (result != null && result.Entities.Count > 0)
{
envVariableValue = result.Entities[0].GetAttributeValue<string>("value");
}
return envVariableValue;
}
Explanation
So under Execute method, we have the standard boilerplate code to get the classes to be able to access the DataVerse.
Inside the GetEnvironmentVariable method is really where all the action is. It takes a parameter called envVariableName and then we make a call using FetchXML to retrieve the Environment Value with that name.
Top comments (0)