Tuesday, 18 April 2017

How to read configuration data from an xml web resource via JavaScript?

There are situations where you need to keep some environment specific configuration data (e.g. URLs) in a single location without repeating them in all scripts so that all your form scripts can access them.

This way you need to change those variables in only one location when you go from one environment to the other (i.e. Dev to Test and UAT etc.)

Let’s say you have created an XML web resource named new_ApiConfiguration.xml.
And assume your web resource looks like this:

<SacConsultingApi>
<CreateApiUrl>https://webapi.sacconsulting.com.au/crmdev/api/record?id=</CreateApiUrl>
<UpdateApiUrl>https://webapi.sacconsulting.com.au/crmdev/api/update?recId=</UpdateApiUrl>
<ExpireApiUrl>https://webapi.sacconsulting.com.au/crmdev/api/expire?recId=</ExpireApiUrl>
</SacConsultingApi>

And you can access these configurations inside you custom form scripts by calling the following function.

Declare the variables on top and call the function.

var CreateApiUrl;
var UpdateApiUrl;
var ExpireApiUrl;

function GetWebApiConfigurations() {   
    var serverUrl = Xrm.Page.context.getClientUrl();
    var xmlConfigPath = serverUrl + "/WebResources/new_ApiConfiguration.xml";
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", xmlConfigPath, false);
    xmlHttp.send();
    var doc = xmlHttp.responseXML;
    CreateApiUrl = doc.getElementsByTagName("CreateApiUrl")[0].textContent;
    UpdateApiUrl = doc.getElementsByTagName("UpdateApiUrl")[0].textContent;
    ExpireApiUrl = doc.getElementsByTagName("ExpireApiUrl")[0].textContent;
}

Remember to change the name of the web resource to your web resource name.


This way when you deploy solutions from one environment to the other you don’t need to go and change your configurations in hundred places.

See this post to know how to achieve this via C# code (Plug-ins of custom workflow activity)

No comments:

Post a Comment

How to assign a record to the current user via JavaScript

Recently I got a requirement from the customer to create a ribbon button on a custom entity so that a user can click on that button and get...