Archive

Archive for the ‘Organization Web Service’ Category

Dynamics CRM: Get current user information

September 5th, 2013 No comments

    One of the most frequently used operation with OrganizationServiceProxy is to get information about the current user. For simplicity such operation could be implemented as an extension to the OrganizationServiceProxy class. So, let’s put the following code somewhere in a project:

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;

namespace dotNetFollower
{
    public static class OrganizationServiceProxyExtensions
    {
        public static WhoAmIResponse GetCurrentUser(this OrganizationServiceProxy proxy)
        {
            return (WhoAmIResponse)proxy.Execute(new WhoAmIRequest());
        }
    }
}

How to use the extension is shown below:

var serverConnection = new ServerConnectionEx();
serverConnection.DoInOrganizationServiceProxyContext(crmConfiguration, proxy =>
{
	Guid userId = proxy.GetCurrentUser().UserId;

	// do something else
});

The code above supposes that you use the ServerConnection helper class in your project. The ServerConnectionEx class, in turn, is derived from ServerConnection and described in the article Dynamics CRM: How to connect to CRM through the code.

More elegant way, as for me, is to add a lazy-loading property to a class derived from OrganizationServiceProxy. But in this case we have to make a lot of small changes within the ServerConnection class as the class creates and operates the instance of OrganizationServiceProxy. So, the derived class in this case looks like the following:

using System;
using System.ServiceModel.Description;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

namespace dotNetFollower
{
  public class OrganizationServiceProxyEx : OrganizationServiceProxy
  {
    private WhoAmIResponse _whoAmIResponse;

    public WhoAmIResponse CurrentUser
    {
      get { return _whoAmIResponse ?? 
              (_whoAmIResponse = (WhoAmIResponse) Execute(new WhoAmIRequest())); }
    }

    public OrganizationServiceProxyEx(IServiceConfiguration<IOrganizationService> serviceConfiguration, 
                             ClientCredentials clientCredentials)
        : base(serviceConfiguration, clientCredentials)
    {            
    }
    public OrganizationServiceProxyEx(IServiceConfiguration<IOrganizationService> serviceConfiguration,
                                    SecurityTokenResponse securityTokenResponse)
        : base(serviceConfiguration, securityTokenResponse)
    {            
    }
    public OrganizationServiceProxyEx(IServiceManagement<IOrganizationService> serviceManagement,
                                    ClientCredentials clientCredentials)
        : base(serviceManagement, clientCredentials)
    {            
    }
    public OrganizationServiceProxyEx(IServiceManagement<IOrganizationService> serviceManagement,
                                    SecurityTokenResponse securityTokenResponse)
        : base(serviceManagement, securityTokenResponse)
    {            
    }
    public OrganizationServiceProxyEx(Uri uri, Uri homeRealmUri, ClientCredentials clientCredentials,
                                    ClientCredentials deviceCredentials)
        : base(uri, homeRealmUri, clientCredentials, deviceCredentials)
    {            
    }
  }
}

The next step is to open CrmServiceHelpers.cs and replace all mentions of OrganizationServiceProxy with OrganizationServiceProxyEx. Then do the same for ServerConnectionEx in case you use it. Or you can just take the demonstration project, where all required changes are applied. Download it here – ConnectToCrm2.zip.

Below is how to use the CurrentUser property exposed by the custom proxy class:

var serverConnection = new ServerConnectionEx();
serverConnection.DoInOrganizationServiceProxyContext(SampleCrmConfiguration, proxy =>
{
	Guid userId = proxy.CurrentUser.UserId;
	
	// do something else
});

Dynamics CRM: How to connect to CRM through the code

August 22nd, 2013 No comments

    Starting development for Microsoft Dynamics CRM 2011, the first challenge we face is how to connect to the CRM. Communication with Microsoft Dynamics CRM 2011 through the code mostly comes to interaction with two Web Services supplied by the CRM: so-called Discovery (IDiscoveryService) and Organization (IOrganizationService) Web Services. For a certain Microsoft Dynamics CRM installation the URL to the IDiscoveryService is unique. To be more precise, it’s unique for an on-premise installation while for Microsoft Dynamics CRM Online it might be one of a few variants depending on the world region. Read more about possible URLs to the Discovery Web Service here. In the same time, a single Microsoft Dynamics CRM installation can host multiple business organizations on multiple servers. Accessing data for a particular organization through the IOrganizationService, we have to use the URL specified for that organization.

Most of the time we work with data (entity records) and metadata (entities, attributes, relationships, etc.) of our organization(s), so the IOrganizationService is a primary Web Service to deal with. The IDiscoveryService, in turn, is generally used to get the right URL to an Organization Web Service. So, the initial connection process could be divided into two stages:

  • a client application grabs CRM‘s server name, protocol (http or https) and port (if applicable), and user credentials (login and password), then sends request to the IDiscoveryService. The IDiscoveryService Web Service determines the organizations that the user is a member of and sends the information about found organizations back to the client. Among other things the information includes actual URLs to Organization Web Services. The client application chooses one organization to interact with and fetches out the URL to the corresponding IOrganizationService;
  • the client application connects to IOrganizationService using the URL and manages data and metadata of the organization;

Often after the initial connection the received URL to IOrganizationService is stored somewhere to be used next times as it allows omitting the interaction with Discovery Web Service. However, we have to bear in mind that, in boundaries of a particular installation of Microsoft Dynamics CRM or Microsoft Dynamics CRM Online, the location of servers and organizations may change due to some datacenter management or load balancing. Therefore, we should use IDiscoveryService from time to time since it provides the actual URL to the IOrganizationService that serves our organization at a given moment. For example, we could try refreshing our connection string for IOrganizationService when we fail to access organization using the URL received previously.

To develop for Microsoft Dynamics CRM 2011, Microsoft provides with the Software Development Kit (SDK), which contains a good set of samples to start playing with CRM. After the SDK has been installed, the samples are usually available at SDK\SampleCode\CS. The most of the sample solutions connect to CRM by means of the special class called ServerConnection and defined in the SDK\SampleCode\CS\helpercode\CrmServiceHelpers.cs. The ServerConnection implements all typical steps necessary to connect to CRM: obtains user credentials, communicates with Discovery Web Service to get list of organizations accessible for user, allows user to pick an organization, creates an IOrganizationService proxy and refreshes the WCF connection security token from time to time. The code for connecting to CRM through the ServerConnection class usually looks like the following:

...
using Microsoft.Crm.Sdk.Samples;
using Microsoft.Xrm.Sdk.Client;
...
// Obtain the user logon credentials,  send request to Discovery Web Service, 
// pick out an organization and then get the target organization's Web address
ServerConnection serverConnect = new ServerConnection();
ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

// Connect to the Organization service. 
using (OrganizationServiceProxy serviceProxy = ServerConnection.GetOrganizationProxy(config))
{
	// Enable early-bound type support.
	serviceProxy.EnableProxyTypes();

	// do something useful
}

The ServerConnection uses the DeviceIdManager class inside. The class defined in the SDK\SampleCode\CS\helpercode\DeviceIdManager.cs is intended to register a computing device with Microsoft account (Windows Live ID) and needed only for authentication in Microsoft Dynamics CRM Online. So, to use the ServerConnection we have to add both CrmServiceHelpers.cs and DeviceIdManager.cs files to a project.

The ServerConnection.Configuration class is to encapsulate all information needed for setting up a connection to Discovery Web Service. Based on the object of ServerConnection.Configuration, ServerConnection creates a proxy for IOrganizationService.

Note, however, since ServerConnection is designed to work within sample console-based applications, it has some “features” that are not applicable for other types of projects. For example, the following could be placed among such “features”: prompting user to type credentials in the console window; persisting CRM server connection information to a file C:\Users\<username>\AppData\Roaming\CrmServer\Credentials.xml for later reuse; storing user password in the Windows Credential Manager. Fortunately, all of the mentioned points might be overcome by creating a class inherited from the ServerConnection and by implementing our own mechanism of reading parameters required for establishing a connection to CRM. The custom class shown below exposes the methods that parse the xml string containing connection parameters and return a proper instance of ServerConnection.Configuration. That allows keeping parameters wherever we want, we are not bound to the file system or Windows Credential Manager anymore. That’s quite important if we plan to use the code in Windows Azure, for example.

using System;
using System.Linq;
using System.ServiceModel.Description;
using System.Xml.Linq;
using Microsoft.Crm.Sdk.Samples;
using Microsoft.Crm.Services.Utility;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;

namespace dotNetFollower
{
  public class ServerConnectionEx : ServerConnection
  {
    /// <summary>
    /// Parses xml string and builds a Configuration object with connection parameters
    /// </summary>
    public Configuration Parse(string xml)
    {
      // read xml and fetch out parameters
      XElement configurationsFromFile = XElement.Parse(xml);
      var xmlConfig = configurationsFromFile.Nodes().First() as XElement;

      var newConfig = new Configuration();
            
      var serverAddress = xmlConfig.Element("ServerAddress");
      if (serverAddress != null && !String.IsNullOrEmpty(serverAddress.Value))
        newConfig.ServerAddress = serverAddress.Value;

      var organizationName = xmlConfig.Element("OrganizationName");
      if (organizationName != null && !String.IsNullOrEmpty(organizationName.Value))
        newConfig.OrganizationName = organizationName.Value;

      var discoveryUri = xmlConfig.Element("DiscoveryUri");
      if (discoveryUri != null && !String.IsNullOrEmpty(discoveryUri.Value))
        newConfig.DiscoveryUri = new Uri(discoveryUri.Value);

      var organizationUri = xmlConfig.Element("OrganizationUri");
      if (organizationUri != null && !String.IsNullOrEmpty(organizationUri.Value))
        newConfig.OrganizationUri = new Uri(organizationUri.Value);

      var homeRealmUri = xmlConfig.Element("HomeRealmUri");
      if (homeRealmUri != null && !String.IsNullOrEmpty(homeRealmUri.Value))
        newConfig.HomeRealmUri = new Uri(homeRealmUri.Value);

      var vendpointType = xmlConfig.Element("EndpointType");
      if (vendpointType != null)
        newConfig.EndpointType = RetrieveAuthenticationType(vendpointType.Value);

      var xElement = xmlConfig.Element("Credentials");
      if (xElement != null && xElement.HasElements)
        newConfig.Credentials = ParseInCredentials(xmlConfig.Element("Credentials"), newConfig.EndpointType);

      if (newConfig.EndpointType == AuthenticationProviderType.LiveId)
        newConfig.DeviceCredentials = DeviceIdManager.LoadOrRegisterDevice();

      var userPrincipalName = xmlConfig.Element("UserPrincipalName");
      if (userPrincipalName != null && !String.IsNullOrWhiteSpace(userPrincipalName.Value))
        newConfig.UserPrincipalName = userPrincipalName.Value;

      // save new configuration in the config property as the property 
      // is used by original ServerConnection
      config = newConfig;

      // get OrganizationUri in case it is not set
      if (newConfig.OrganizationUri == null)
      {
        if(string.IsNullOrEmpty(newConfig.OrganizationName))
          throw new ApplicationException("At least one of OrganizationUri and OrganizationName must be spesified in the xml configuration.");
        GetOrganizationInfo();
      }

      return newConfig;
    }

    ...

    /// <summary>
    /// Gets Organization Web Service url by friendly or unique name of the organization
    /// </summary>
    protected void GetOrganizationInfo()
    {
      using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
      {
        // Obtain organization information from the Discovery service. 
        if (serviceProxy != null)
        {
          // Obtain information about the organizations that the system user belongs to.
          OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);

          if(orgs.Count == 0)
            throw new ApplicationException("User does not belong to any organizations on the specified server");

          // look for a specified organization
          foreach (var organizationDetail in orgs)
          {
            if (string.Equals(organizationDetail.UniqueName, 
                               config.OrganizationName, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(organizationDetail.FriendlyName, 
                               config.OrganizationName, StringComparison.OrdinalIgnoreCase))
            {
              config.OrganizationUri  = 
                       new Uri(organizationDetail.Endpoints[EndpointType.OrganizationService]);
              config.OrganizationName = organizationDetail.FriendlyName;
              return;
            }
          }

          throw new ApplicationException("Couldn't find the " + config.OrganizationName + "organization");
        }
                
        throw new ApplicationException("An invalid server name was specified.");
      }
    }

    /// <summary>
    /// Parses xml element to get user name and password
    /// </summary>
    protected static ClientCredentials ParseInCredentials(XElement credentials, 
                             AuthenticationProviderType endpointType)
    {
      ClientCredentials result = null;

      if (credentials.HasElements)
      {
        result = new ClientCredentials();

        switch (endpointType)
        {
          case AuthenticationProviderType.ActiveDirectory:
          {
            result.Windows.ClientCredential = new System.Net.NetworkCredential()
              {
                UserName = credentials.Element("UserName").Value,
                Domain   = credentials.Element("Domain").Value,
                Password = credentials.Element("Password").Value
              };
              break;
          }
          case AuthenticationProviderType.LiveId:
          case AuthenticationProviderType.Federation:
          case AuthenticationProviderType.OnlineFederation:
          {
            result.UserName.UserName = credentials.Element("UserName").Value;
            result.UserName.Password = credentials.Element("Password").Value;
            break;
          }
        }
      }

      return result;
    }
  }
  ...
}

In case the OrganizationUri isn’t set in the xml string the Parse method tries getting the URL from Discovery Web Service using the name specified in the OrganizationName node. The OrganizationName can contain friendly or unique name of the target organization.

Note we need to slightly modify the original ServerConnection class, we need to make protected such its members as RetrieveAuthenticationType (method), GetDiscoveryProxy (method) and config (field) so that they would be accessible from within the derived ServerConnectionEx class.

Below is an example of how the custom ServerConnectionEx could be used:

// the xml string below might be stored to and read from any data source
string crmConfiguration = @"<?xml version=""1.0"" encoding=""utf-8""?>
  <Configurations>
  <Configuration>
    <ServerAddress>MyCrmOnPremise</ServerAddress>
    <OrganizationName>My Company Friendly Name</OrganizationName>
    <DiscoveryUri>http://MyCrmOnPremise/XRMServices/2011/Discovery.svc</DiscoveryUri>
    <OrganizationUri>http://MyCrmOnPremise/MyCompanyFriendlyName/XRMServices/2011/Organization.svc</OrganizationUri>
    <HomeRealmUri />                      
    <Credentials>
      <UserName>dotNetFollower</UserName>
      <Domain>hq</Domain>
      <Password>11111</Password>
    </Credentials>
    <EndpointType>ActiveDirectory</EndpointType>
    <UserPrincipalName />                                        
  </Configuration>
</Configurations>";

// Obtain the target organization's Web address and client credentials from the xml string.
ServerConnectionEx serverConnection = new ServerConnectionEx();
ServerConnection.Configuration configuration = serverConnection.Parse(crmConfiguration);

// Connect to the Organization service. 
using (OrganizationServiceProxy serviceProxy = ServerConnection.GetOrganizationProxy(configuration))
{
	// This statement is required to enable early-bound type support.
	serviceProxy.EnableProxyTypes();

	// do something useful
}

In the example we have a hardcoded xml string with connection parameters, in the reality, however, the string could be stored in whatever data store.

To make the use of ServerConnectionEx more comfortable, let’s add the following two methods to ServerConnectionEx:

public class ServerConnectionEx : ServerConnection
{
	...
	public static void DoInOrganizationServiceProxyContext(Configuration configuration,
							Action<OrganizationServiceProxy> action)
	{
		using (var proxy = GetOrganizationProxy(configuration))
		{
			proxy.EnableProxyTypes();
			action(proxy);
		}
	}

	public void DoInOrganizationServiceProxyContext(string configXml, 
							Action<OrganizationServiceProxy> action)
	{
		Configuration configuration = Parse(configXml);
		DoInOrganizationServiceProxyContext(configuration, action);
	}
	...
}

Now to deal with the OrganizationServiceProxy we can use the code like the following:

string crmConfiguration = ... // the same xml-string as used above

var serverConnection = new ServerConnectionEx();
serverConnection.DoInOrganizationServiceProxyContext(crmConfiguration, proxy =>
{
	// do something
});

Note also that to use CrmServiceHelpers.cs and DeviceIdManager.cs you have to add such references to your project as System.Runtime.Serialization, System.Security, System.ServiceModel, System.DirectoryServices.AccountManagement and Microsoft.IdentityModel. The Microsoft.IdentityModel is a part of Windows Identity Foundation, so install it if it’s not already installed. The dll itself can be found at Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5 or in GAC. And, of course, you need to add references for Microsoft.Crm.Sdk.Proxy and Microsoft.Xrm.Sdk. You can find them in SDK\BIN.

A simple demonstration project you can download here – ConnectToCrm.zip. Among others files it contains the adapted CrmServiceHelpers.cs and DeviceIdManager.cs.