Monday, September 15, 2008

Hint: Developing for Multiple MS CRM 4.0 Servers

Ideally CRM custom application development is not being done on production CRM systems. It would be helpful if our custom applications would automatically switch between the appropriate web services of development, staging and production CRM environments.

The method below creates the appropriate CrmServiceUrl using the ServerUrl value in the registry of the CRM server running the custom application.

using Microsoft.Win32;  // For registry access
using crmWebService;    // Your crm webservice reference

// <snip>

    // Create a web service for your organization.     
    CrmService service = InitCRMWebService("MicrosoftCRM");    
    //Use service

// <snip>

    /// <summary>
    /// Get the crmservice for the organization specified
    /// </summary>
    /// <param name="organizationName"></param>
    /// <returns></returns>
    private CrmService InitCRMWebService(string organizationName)
        // Create the CrmServiceUrl from the registry
        RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\MSCRM", false);
        string CrmServiceUrl = (string)key.GetValue("ServerUrl") + @"/2007/crmservice.asmx";
        service = new CrmService();
        service.Credentials = System.Net.CredentialCache.DefaultCredentials;
        service.Url = CrmServiceUrl;
        service.PreAuthenticate = false;
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.AuthenticationType = 0;
        token.OrganizationName = organizationName;

        service.CrmAuthenticationTokenValue = token;
        return service;
For debugging:
  1. Make sure that your local Active Directory account is a CRM user on all of environments that you will debug against.
  2. Export a copy of the MSCRM registry from your CRM server and apply it to your development computer's registry.
  3. Modify the ServerUrl value data to switch between the servers that you are debugging against.


1 comment:

Anonymous said...

Instead of copying the registry branch to the development computer, I use a config file on the development machine. Then in the code, check the existence of the config file; read from the config file if it exists, otherwise read from the registry.

Easier and safer to modify. When deploying, just don't copy the config file to the production server, and you're all done.