Connecting to Microsoft Dynamics CRM Online

Microsoft Dynamics CRM Online provides the same service APIs as the on-premise and IFD deployments. However, because Microsoft Dynamics CRM Online uses Windows Live ID for authentication, you must first obtain a valid ticket before attempting to access the Web service methods.

In addition to using a different authentication method from the on-premise and IFD deployments, writing custom code for Microsoft Dynamics CRM contains some additional differences. At the time of this writing, Microsoft Dynamics CRM Online does not allow the following:

  • You cannot upload custom Web pages, plug-ins, and workflow assemblies to the Microsoft Dynamics CRM Online server.

  • You cannot upload custom report RDL files. You must use the Report Wizard when creating new reports.

  • You cannot use impersonated or delegated API calls.

Despite these restrictions, a developer has ample opportunity to programmatically interact with the Microsoft Dynamics CRM Online with script (as described further in Chapter 7) and with the Web service APIs. We will now examine the options available for communicating with Microsoft Dynamics CRM Online’s APIs.

Windows Live ID provides multiple methods for authenticating a user and retrieving a valid ticket for use with Microsoft Dynamics CRM Online. Some of the main options available are:

  • Identity Client Run-Time Library (IDCRL) Ticket Service Library

  • Federation

More Info

More Info

At the time of printing, the Federation option was not yet available. Visit http://dev.live.com/liveID/default.aspx for more information regarding the Windows Live ID SDK and authentication options.

We will review using the Win32 IDCRL library to obtain a valid Windows Live ID ticket. The Microsoft Dynamics CRM SDK provides the source code to create a .NET wrapper to this library. The source for this can be found at SDKServerHelpersCSIdCrlWrapper. Using this wrapper, you can pass valid Live ID credentials to the LogonManager class and retrieve a ticket that can be used to authenticate Microsoft Dynamics CRM Online.

To get started, you need to perform the following steps:

  1. Download the msidcrl40.dll assembly and install it in %windows%system32 or the output directory of your client-side application.

  2. Create a .NET wrapper around the IDCRL library using the source code provided in the Microsoft Dynamics CRM SDK, and reference the wrapper in your project.

  3. Ensure that the identity of the user is not a network service account. For Web applications, you need to change the application pool’s identity to Local System or a domain user.

  4. For Web applications, ensure that the default proxy is configured.

The code in Example 3-4 demonstrates how to create a CrmService object using the IDCRL library for Microsoft Dynamics CRM Online.

Example 3-4. Microsoft Dynamics CRM Online CrmService utility

public static CrmService GetOnlineCrmService(string userName, string password, string
partner, string environment, string orgName)
{
  CrmDiscoveryService discoveryService = new CrmDiscoveryService();
  discoveryService.Url = "https://dev.crm.dynamics.com/MSCRMServices/2007/Passport/
CrmDiscoveryService.asmx";
  RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
  RetrievePolicyResponse policyResponse =
   (RetrievePolicyResponse)discoveryService.Execute(policyRequest);

  using (LogonManager lm = new LogonManager())
  {
    string passportTicket = lm.Logon(_username, _password, _partner,
      policyResponse.Policy, _environment);

    RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
    crmTicketRequest.OrganizationName = _orgname;
    crmTicketRequest.PassportTicket = passportTicket;

    RetrieveCrmTicketResponse crmTicketResponse =
      (RetrieveCrmTicketResponse)discoveryService.Execute(crmTicketRequest);

    // Create and configure an instance of the CrmService Web service.
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.AuthenticationType = AuthenticationType.Passport;
    token.CrmTicket = crmTicketResponse.CrmTicket;
    token.OrganizationName = crmTicketResponse.OrganizationDetail.OrganizationName;

    CrmService crmService = new CrmService();
    crmService.Url = crmTicketResponse.OrganizationDetail.CrmServiceUrl;
    crmService.CrmAuthenticationTokenValue = token;
    return crmService;
  }
}

Let’s assume the following scenario: each week you need to retrieve the accounts created this current week to import the data into a custom application. Figure 3-4 displays sample output of all accounts opened in the current week from your CRM Online organization.

Retrieving recent accounts from CRM Online

Figure 3-4. Retrieving recent accounts from CRM Online

For demonstration purposes, Example 3-5 simply writes the results to a display but of course you could use this data in different formats or outputs. Be sure to update the _username, _password, and _orgname variables with valid information.

Example 3-5. Accessing Microsoft Dynamics CRM Online

using System;
using System.Xml;
using System.Text;
using System.Web.Services.Protocols;

using Microsoft.Crm.Passport.Sample;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using ProgrammingWithDynamicsCrm4.CrmOnline.CrmSdk.Discovery;


namespace ProgrammingWithDynamicsCrm4.CrmOnline
{
  class Program
  {
    // Replace with valid values for your Online account
    static private string _username = "[email protected]";
    static private string _password = "password";
    static private string _orgname = "orgname";

    static private string _partner = "crm.dynamics.com";
    static private string _environment = "Production";
    static private string ExpiredAuthTicket = "8004A101";

    static void Main(string[] args)
    {
      try
      {
        CrmService crmService = GetOnlineCrmService(_username, _password, _partner,
         _environment, _orgname);

        try
        {
          QueryExpression query = new QueryExpression();

          // Set up standard query expression
          ColumnSet cols = new ColumnSet();
          cols.AddColumns(new string[] { "name", "createdon" });


          // Create the ConditionExpression.
          ConditionExpression condition = new ConditionExpression();
          condition.AttributeName = "createdon";
          condition.Operator = ConditionOperator.ThisWeek;

          // Builds the filter based on the condition
          FilterExpression filter = new FilterExpression();
          filter.FilterOperator = LogicalOperator.And;
          filter.AddCondition(condition);


          query.EntityName = EntityName.account.ToString();
          query.ColumnSet = cols;
          query.Criteria = filter;
          query.AddOrder("name", OrderType.Descending);


          // Retrieve the values from Microsoft CRM.
          BusinessEntityCollection retrieved = crmService.RetrieveMultiple(query);

          // Loop through results and display back to the user.
          foreach (account accountResult in retrieved.BusinessEntities)
          {
            Console.Write(accountResult.name.ToString() + "	");
            Console.WriteLine(accountResult.createdon.date.ToString());
          }
          Console.ReadLine();
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
          // Handle error.
        }
      }

      // Handle any Web service exceptions that might be thrown.
       catch (SoapException ex)
       {
         // Handle the exception thrown from an expired ticket condition.
         if (GetErrorCode(ex.Detail) == ExpiredAuthTicket)
         {
           throw new Exception("The Microsoft Dynamics CRM Online
             ticket has expired.", ex);
         }
         else
         {
           // Handle other exceptions.
           throw new Exception("An error occurred while attempting to authenticate.", ex);
         }
       }
     }

     private static string GetErrorCode(XmlNode errorInfo)
     {
       XmlNode code = errorInfo.SelectSingleNode("//code");
       return (code == null) ? string.Empty : code.InnerText;
     }

     public static CrmService GetOnlineCrmService(string userName, string password,
       string partner, string environment, string orgName)
     {
       //...Get online service code...
     }
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset