Using Environment Variables in Dynamics 365 CRM – Part 2

Sending
User Review
0 (0 votes)

Introduction

In our previous blog, we understood the background and the purpose of the Environment Variable.

In this blog we will see how to use it in our day to day solutions.

As we make use of Plugins, Workflows, Scripts, Power Automate, etc. in our day-to-day solutions, let’s see how to access and use the environment variables in each one of them.

Plugins/Workflows

In our previous blog, we created an Environment Variable with the schema name ‘new_apiurl’. Now, there could be Plugins and Workflows where we might need to use the value stored. Using the below methods we can get the value from the environment variable:

///<summary>

///This method will be used to get the details of

/// Environment Variable Definition with the schema name new_apiurl

///</summary>

///<param name=”service”></param>

///<param name=”context”></param>

///<param name=”tracing”></param>

///<returns></returns>

privatestringGetEnvironmentVariableDefinition(IOrganizationService service,ITracingService tracing)

{

#region (*Local Variable*)

stringfunctionName = “GetVariableDefinition”;

stringfetchXml = string.Empty;

EntityCollection definition = null;

string value = string.Empty;

#endregion

try

{

//Trace

tracing.Trace(“Inside ” + functionName);

//Create the fetch xml query

fetchXml = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’false’>” +

“<entity name=’environmentvariabledefinition’>” +

“<attribute name=’environmentvariabledefinitionid’ />” +

“<attribute name=’schemaname’ />” +

“<attribute name=’createdon’ />” +

“<order attribute=’schemaname’ descending=’false’ />” +

“<filter type=’and’>” +

“<condition attribute=’schemaname’ operator=’eq’ value=’new_apiurl’ />” +

“</filter>” +

“</entity>” +

“</fetch>”;

//Retrieve the Environment Variable Definition with schemaname = new_apiurl

definition = service.RetrieveMultiple(newFetchExpression(fetchXml));

//If the definition is found

if (definiton != null&&definiton.Entities.Count> 0)

{

//Call the method to get the Current Value associated to the Environment Variable Definition

value = GetEnvironmentVariableValue(definiton.Entities[0], service, context, tracing);

}

}

catch (InvalidPluginExecutionExceptionipex)

{

thrownewInvalidPluginExecutionException(functionName + ipex.Message);

}

catch (FaultExceptionfex)

{

thrownewFaultException(functionName + fex.Message);

}

catch (Exception ex)

{

thrownewException(functionName + ex.Message);

}

return value;

}

///<summary>

///This method will be used to get the Current value

/// associated to the environment definition

///</summary>

///<param name=”entityDefinition”></param>

///<param name=”service”></param>

///<param name=”context”></param>

///<param name=”tracing”></param>

///<returns></returns>

privatestringGetEnvironmentVariableValue(EntityentityDefinition, IOrganizationService service, ITracingService tracing)

{

#region (*Local Variable*)

stringfunctionName = “GetEvValue”;

stringfetchXml = string.Empty;

EntityCollection values = null;

stringcurrentValue = string.Empty;

#endregion

try

{

//Create the fetch xml query

fetchXml = “<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’false’>” +

“<entity name=’environmentvariablevalue’>” +

“<attribute name=’environmentvariablevalueid’ />” +

“<attribute name=’value’ />” +

“<attribute name=’createdon’ />” +

“<attribute name=’schemaname’ />” +

“<attribute name=’environmentvariabledefinitionid’ />” +

“<order attribute=’createdon’ descending=’true’ />” +

“<filter type=’and’>” +

“<condition attribute=’environmentvariabledefinitionid’ operator=’eq’ value=’” + entityDefinition.Id + “‘ />” +

“</filter>” +

“</entity>” +

“</fetch>”;

//Retrieve the Environment Variable value associated to the Environment Variable Definition

values = service.RetrieveMultiple(newFetchExpression(fetchXml));

if (values != null&&values.Entities.Count> 0)

{

//Get the Current Value associated to the Environment Variable Definition

currentValue = values.Entities[0].GetAttributeValue<string>(“value”);

}

}

catch (InvalidPluginExecutionExceptionipex)

{

thrownewInvalidPluginExecutionException(functionName + ipex.Message);

}

catch (FaultExceptionfex)

{

thrownewFaultException(functionName + fex.Message);

}

catch (Exception ex)

{

thrownewException(functionName + ex.Message);

}

returncurrentValue;

}

Scripts

Similarly, we can also query the value of environment variable in a script as shown below -here, we have created a method where we are using the OData query to query the Environment Variable records.

getValue = (executionContext: Xrm.Events.EventContext): void => {

//Local Variables

letfunctionName: string = “onLoad”;

let query: string = “”;

letenvValue: string = “”;

letalertStrings: any = null;

letalertOptions: any = null;

try {

//Create the query to get the Environment Variable Definition with schemaname “new_apiurl”

query = “?$filter=schemanameeq ‘new_apiurl’”;

//Retrieve the Environment Variable Definition with schemaname “new_apiurl”

Xrm.WebApi.retrieveMultipleRecords(“environmentvariabledefinition”, query).then(

function (definition) {

//Create the query to get the Environment Variable Value associated to the definition with schemaname “new_apiurl”

query = “?$filter=_environmentvariabledefinitionid_valueeq ‘” + definition.entities[0][“environmentvariabledefinitionid”] + “‘”;

Xrm.WebApi.retrieveMultipleRecords(“environmentvariablevalue”, query).then(

function (value) {

envValue = value.entities[0][“value”];

},

function (error) {

alertStrings = { text: functionName + ” :: ” + ex.message };

Xrm.Navigation.openAlertDialog(alertStrings);

});

},

function (error) {

alertStrings = { text: functionName + ” :: ” + ex.message };

Xrm.Navigation.openAlertDialog(alertStrings);

});

}

catch (ex) {

alertStrings = { text: functionName + ” :: ” + ex.message };

Xrm.Navigation.openAlertDialog(alertStrings);

}

}

Power Automate

We can even use the Environment Variables in the Power Automate as below.

  • We selected the List records action from Common Data Service connectorUsing Environment Variables

Here we have used the filter query schemanameeq ‘new_apiurl’and set the Top Count =1to get the Environment Variable Definition with schema name as “new_apiurl”.

  • Then using the value of the Environment Variable Definition retrieved in the previous step, we retrieved the associated Environment Variable Value using the filter query as schemanameeq ‘new_apiurl'<expression>’ here the <expression>will be outputs(‘EVDefinitions’)[‘body/value’]?[0]?[‘environmentvariabledefinitionid’].Here as well we have kept the Top Count as 1 as there can be only one Environment Variable Value associated to a Definition.

Using Environment Variables

  • Finally, as can be seen from the screenshot below, we have used the retrieved Environment Variable Value (i.e. the value of the variable “new_apiurl”) in the URI of the HTTP request connector as outputs(‘EVValue’)[‘body/value’]?[0]?[‘value’] .

Using Environment Variables

Security

One thing to be noted is that to make use of the environment variables in any of the above, the user in context must have the privileges to access both the entities i.e. Environment Variable Definition and Environment Variable Value. The privilege assigned to the entity Environment Variable Definition gets inherited by the entity Environment Variable Value as well. So you only see the entity Environment Variable Definition while assigning the privilege from the security role as below.

Using Environment Variables

Conclusion

Thus Environment Variables can be made use of in our day to day scenarios.