Sunday, February 19, 2012

CRM2011: Get the Right Server URL (Silverlight Version)

After my previous post about how to get the right server URL in CRM JavaScript code, I was asked to provide a translation of the code to C# so that it can be used in Silverlight web resource. So here is post along with the translated code.
public static string GetServerUrl()
{
    var context = GetContext();
    var isOutlookClient = (bool)context.Invoke("isOutlookClient");
    var isOutlookOnline = (bool)context.Invoke("isOutlookOnline");

    var documentUri = HtmlPage.Document.DocumentUri;

    var localServerUrl = string.Format("{0}://{1}:{2}", documentUri.Scheme, documentUri.Host, documentUri.Port);
    if (isOutlookClient && !isOutlookOnline)
    {
        return localServerUrl;
    }

    var baseServerUrl = (string)context.Invoke("getServerUrl");
    var serverUrl = Regex.Replace(baseServerUrl, @"^(http|https):\/\/([_a-zA-Z0-9\-\.]+)(:([0-9]{1,5}))?", localServerUrl);
    return Regex.Replace(serverUrl, @"\/$", string.Empty);
}

// This is the same code that comes from CRM SDK in its SoapForSilverlightSample project.
private static ScriptObject GetContext()
{
    var xrmProperty = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
    if (null == xrmProperty)
    {
        //It may be that the global context should be used
        try
        {
            var globalContext = (ScriptObject)HtmlPage.Window.Invoke("GetGlobalContext");

            return globalContext;
        }
        catch (InvalidOperationException)
        {
            throw new InvalidOperationException("Property \"Xrm\" is null and the Global Context is not available.");
        }
    }

    var pageProperty = (ScriptObject)xrmProperty.GetProperty("Page");
    if (null == pageProperty)
    {
        throw new InvalidOperationException("Property \"Xrm.Page\" is null");
    }

    var contextProperty = (ScriptObject)pageProperty.GetProperty("context");
    if (null == contextProperty)
    {
        throw new InvalidOperationException("Property \"Xrm.Page.context\" is null");
    }

    return contextProperty;
}
If you are talking to CRM SOAP endpoint, you may get the complete URL using the following code.
Uri serviceUrl = new Uri(GetServerUrl() + "/XRMServices/2011/Organization.svc/web");
If you need to talk to CRM REST endpoint, you may get the complete URL using this one.
Uri serviceUrl = new Uri(GetServerUrl() + "/XRMServices/2011/OrganizationData.svc");
Hope this helps.

1 comment: