Wednesday, May 16, 2012

Getting the CRM url for Silverlight based on the browser

When creating Silverlight applications the normal method of retrieving the url for the CRM server that will be used to connect to the REST endpoint is usually based on the CRM url that is stored in the CRM config database and retrieved based on Xrm.Page.context.getServerUrl().

There can often be problems with using this address, for instance in development environments or similar, as the address returned might not be the address used in Internet Explorer. When this happens, Internet Explorer will block the connection to the REST endpoint since it does not connect to the same URL as the webpage that hosts the Silverlight application.

During the latest course I held for some CRM consultants at Evry, we discussed this and one of the attendees, Klas Adolfsson at Evry, was very quick and wrote an alternative to the getServerUrl()-method that bases the url on the hosting browser url instead of the url context variable from CRM.

HtmlPage.Document.DocumentUri.Scheme + "://" + HtmlPage.Document.DocumentUri.Host + "/" + App.Current.Host.InitParams["orgname"];

Edit: There are some relevant comments to this posting below, please read these if this posting is of interest to you.

Gustaf Westerlund
CEO, Chief Architect and co-Founder at CRM-konsulterna AB


  1. This approach is good enough but it has issue - it would not work using the same code for different types of deployments - in case it will work for CRM On-premices (when OrgName in url after host) - it would not work for OnLine and IFD deployments when OrgName is the part of hostname.

  2. A very valid commment Andrii, you are right of course. This is usually only an issue in OnPremise deployments as both Online and IFD have set hostnames that have to be used, as SSL and HTTPS is most often used.

    To create a dynamic solution that takes this into consideration I do believe that you would have to try to sense which implementation type you are running and then use the CRM getServerUrl() based one for Online and IFD and the above one for OnPremise.

    The fact you are mentioning could actually be used as a method to figure out if the system is running in OnPremise or not, as the hostname would contain the orgname in a IFD or Online but not in an OnPremise. If anyone has a simple solution, please share! I checked the but found no matching methods there.