在Power Apps中使用环境变量

我是微软Dynamics 365 & Power Platform方面的工程师/顾问罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复434或者20210219可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!

环境变量(environment variable) 大概在 2019年11月开始Preview,可以参考官方博文:Environment variables available in preview! 。最近已经GA了,可以放心使用了,官方文档请参考:Environment variables available in preview!  。有点很多,官方文档列举的优点如下,我就不翻译了。

  • No need to manually edit configurable values in a production environment.
  • Configure one or more variables in one place and reference like a parameter across multiple solution components.
  • Enter different values while importing solutions to other environments.
  • Update values without a code change.
  • Granular level security managed by Microsoft Dataverse.
  • Unlimited number of variables (max solution size is 29 MB).
  • Service the definitions and the values independently or together.
  • Supported by SolutionPackager and DevOps tools enable continuous integration and continuous delivery (CI/CD).
  • Support for localization.
  • Can be used to control feature flags and other application settings.

如果要创建环境变量,到 make.powerapps.com 中打开的solution中点击New > Environment variable来新建。

可以看到环境变量的新建界面如下,对于稍微复杂一点的数据类型,我很一般喜欢使用 JSON 这种数据类型。

然后程序如何获取环境变量的值呢?我这里列举的代码示例如下:

组织服务版本:

        public static string GetEnvironmentVariableValue(string variableSchemaName, IOrganizationService service, ITracingService tracingService)
        {
            if (string.IsNullOrEmpty(variableSchemaName))
            {
                throw new InvalidPluginExecutionException("环境变量名称为空,中止查询该变量的值!");
            }
            string returnVal = string.Empty;
            var fetchXml = string.Format(@"<fetch version='1.0' mapping='logical' top='1' no-lock='true'>
  <entity name='environmentvariabledefinition'>
    <attribute name='defaultvalue'/>
    <filter type='and'>
      <condition attribute='schemaname' operator='eq' value='{0}'/>
      <condition attribute='statecode' operator='eq' value='0'/>
    </filter>
    <link-entity name='environmentvariablevalue' from='environmentvariabledefinitionid' to='environmentvariabledefinitionid' link-type='outer' alias='varvalue'>
      <attribute name='value'/>
    </link-entity>
  </entity>
</fetch>", variableSchemaName);
            var ec = service.RetrieveMultiple(new FetchExpression(fetchXml));
            if(ec.Entities.Count >= 1)
            {
                if (ec.Entities[0].Contains("varvalue.value"))
                {
                    returnVal = ec.Entities[0].GetAttributeValue<AliasedValue>("varvalue.value").Value.ToString();
                }
                else
                {
                    returnVal = ec.Entities[0].GetAttributeValue<string>("defaultvalue");
                }
            }
            tracingService.Trace($"名称为{variableSchemaName}环境变量的值是{returnVal}");
            return returnVal;
        }

 

通过JavaScript同步获取环境变量值版本:

    function getClientUrl() {
        if (typeof GetGlobalContext == "function" && typeof GetGlobalContext().getClientUrl == "function") {
            return GetGlobalContext().getClientUrl();
        }
        else {
            return Xrm.Utility.getGlobalContext().getClientUrl();
        }
    }

    function getWebAPIPath() {
        return getClientUrl() + "/api/data/v9.2/";
    }

    this.getEnvironmentVariableValueSync = function (variableSchemaName) {
     /// <summary>同步获取环境变量的值</summary>
     /// <param name="variableSchemaName" type="String">环境变量的名称</param>
        var returnVal = "";
        var req = new XMLHttpRequest();
        req.open("GET", encodeURI(getWebAPIPath() + "environmentvariabledefinitions?$select=defaultvalue&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$filter=schemaname eq '" + variableSchemaName + "'&$top=1"), false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var respJson = JSON.parse(req.responseText);
                    if (respJson.value.length === 1) {
                        if (respJson.value[0]["environmentvariabledefinition_environmentvariablevalue"] && respJson.value[0]["environmentvariabledefinition_environmentvariablevalue"].length >= 1) {
                            returnVal = respJson.value[0]["environmentvariabledefinition_environmentvariablevalue"][0].value;
                        }
                        else {
                            returnVal = respJson.value[0].defaultvalue;
                        }
                    }
                }
            }
        };
        req.send();
        return returnVal;
    }

利用 Xrm.WebApi.retrieveMultipleRecords 的代码示例是:

    Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition","?$select=defaultvalue,displayname&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$filter=schemaname eq 'ly_demoev'&$top=1").then(
        function success(result) {
            if (result.entities.length === 1) {
                if (result.entities[0]["environmentvariabledefinition_environmentvariablevalue"] 
                    && result.entities[0]["environmentvariabledefinition_environmentvariablevalue"].length > 0) {
                    console.log("值是" + result.entities[0]["environmentvariabledefinition_environmentvariablevalue"][0].value);
                }
                else if (result.entities[0].defaultvalue) {
                    console.log("值是" + result.entities[0].defaultvalue);
                }
                else {
                    console.log("环境变量的值是空");
                }
            }
        },
        function (error) {
            console.log(error.message);
        }
    ); 
原文地址:https://www.cnblogs.com/luoyong0201/p/Using_Environment_Variable_in_Power_Apps.html