This page contains details about connecting to and authenticating with Dynamics 365 CRM (version 2016 and newer), on-premises and online.

Dynamics 365 - CRM 2016

Overview

The Microsoft Dynamics 365 (CRM) SDK provides .NET assemblies that provide the ability to connect (authenticate) to Dynamics CRM and perform data (create/read/update/delete ("CRUD")) and metadata operations.

This section lists the various ways to authenticate to and interact with Dynamics 365 CRM.

CRM Connectivity and Interaction using Microsoft.Xrm.Tooling.Connector

Applies To: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

If you're writing a .NET application, such as a console app, Windows Forms, ASP.NET, WPF or Azure-based application, the CRM SDK provides a class library (named: Microsoft.Xrm.Tooling.Connector) that you can use to authenticate to CRM using a connection string, similar to how .NET applications connect to Microsoft SQL Server using a connection string.

In addition to providing an easy way to authenticate and connect to Dynamics CRM, the same class library provides helper (wrapper) methods that allow for interaction with CRM to perform CRUD operations, work with metadata, etc.

For examples of various CRM connection strings and sample code that utilize the classes in the Microsoft.Xrm.Tooling.Connector assembly, see this page: Sample: Simplified connection quick start using Microsoft Dynamics 365

You can reference the Microsoft.Xrm.Tooling.Connector library in a Visual Studio project by using its NuGet package.

Connecting to CRM and creating an instance of IOrganizationService

The main steps for connecting to CRM using the tooling classes and creating an IOrganizationService instance are:
  1. Get the CRM connection string from the application configuration file (e.g., app.config. web.config, etc.) or build the string in code
    1. Search the SDK for method "GetServiceConfiguration" for sample code on how to retrieve a connection string from configuration.
    2. Be sure to encrypt the password before storing it in a configuration file. You can decrypt it in your application.
  2. With the connection string, create an object of type CrmServiceClient. The CrmServiceClient class provides low-level interaction and wrapper methods to connect to CRM and execute actions.
    1. Code example: CrmServiceClient conn = new Xrm.Tooling.Connector.CrmServiceClient(connectionString);
  3. Cast the proxy client to the IOrganizationService interface.
    1. Code example: IOrganizationService orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
  4. Use the IOrganizationService instance to perform CRUD operations in CRM.




CRM 2015 and Prior Versions

Overview

The Dynamics CRM 2015 (CRM) SDK provides .NET assemblies that provide the ability to connect to Dynamics CRM. Some of these assemblies provide methods for querying CRM organization data (and metadata) and creating, updating and deleting data as well as performing other operations needed to work with organization data, system metadata and system settings.

Simplified connection to Microsoft Dynamics CRM (Developer Extensions)

The Developer Extensions for Dynamics CRM (and CRM Online) use the concept of a connection string to connect to the Microsoft Dynamics CRM server. This is similar to the concept of connection strings used with Microsoft SQL Server. Connection strings are a natural part of the ADO.NET framework and also have native support in configuration files, including the ability to encrypt the configuration sections for maximum security. This encourages you to use a robust model in which Microsoft Dynamics CRM connections are configured at deployment time, and are not hard coded in your application. As such, all APIs in Developer Extensions for Microsoft Dynamics CRM work with a CrmConnection object that uses a connection string to connect to the server. You supply this connection string in the app.config or web.config file for your project.

To add the .NET assemblies necessary to utilize the simplified connection classes, you can add the NuGet package named "Microsoft Dynamics CRM 2013 SDK client and portal assemblies" to your Visual Studio project. This NuGet package contains the official Microsoft.Xrm.Client.dll and Microsoft.Xrm.Portal assemblies, the CrmSvcUtil tool, and the WebsiteCopy tool. The package was authored by the Microsoft Dynamics CRM SDK team.

Microsoft also provides a Visual Studio solution file named "QuickStartCS.sln" in the CRM SDK under \SampleCode\CS\QuickStart\. The solution contains a project named "QuickStart with Simplified Connection" that, in class SimplifiedConnection, demonstrates how to connect to Dynamics CRM with a connection string. You can follow a similar approach in your .NET console applications, Azure web and worker roles, Web API's, etc.

The sequence diagram below shows the interaction of classes in the sample console project "QuickStart with Simplified Connection.csproj".

wiki_sdk_sample_simplifiedconnection.png

Sample Connection Strings

See "Simplified connection to Microsoft Dynamics CRM"

Microsoft's Sample Console Applications: Connectivity Procedures

Most of the C# and VB.NET sample source code in the CRM SDK that performs CRUD operations go through the code path as shown in the diagram below. The sample console applications rely on helper code from SDK file CrmServiceHelpers.cs. The ServerConnection class helps with storing and retrieving previously configured CRM connection details (Organization URI, user name, etc.) and connecting to CRM regardless of whether it is hosted on-premises or in the Cloud. Microsoft's SDK samples need to run with on-premises and CRM Online organizations so that is why the CrmServiceHelpers class provides connectivity to all environments.

See article "Helper code: ServerConnection class" in the CRM SDK for more details regarding the connection helper class. In particular, note that Microsoft recommends against using this code in your own application unless the application, like the samples in the SDK, need to run with a variety of different CRM organizations. Otherwise, it's best to use an authentication/connectivity approach that best fits your application and organization. In many cases, utilizing the functionality in the Developer Extensions provides this needed connectivity functionality.
wiki_sdk_sample_crudoperations_latebinding.png

Note: Most of the CRM SDK sample code can be found under \SDK\SampleCode\CS after you've installed the CRM SDK.

Dynamics CRM Assembly References

Microsoft create a NuGet package for adding Microsoft.Xrm.Sdk.dll and Microsoft.Crm.Sdk.Proxy.dll to your Visual Studio projects. The NuGet package name is "Microsoft Dynamics CRM 2013 SDK core assemblies".

AuthenticateWithNoHelp.cs

This sample shows how to authenticate a user with any Microsoft Dynamics CRM deployment and obtain a reference to the web services. This sample includes support for Microsoft Office 365 users provisioned in Microsoft Dynamics CRM Online. This sample does not rely on the CrmServiceHelpers.cs helper code.

CrmServiceHelpers problem with Office 365

In the Dynamics CRM 2013 SDK releases in 2014, attempting to run the sample console applications that ship with the SDK sometimes lead to the following error message (exception):

The application terminated with an error.
Logon failure: unknown user name or bad password.
Press <Enter> to exit.

On some machines, that error occurs after indicating that you want to create a new configuration and respond "Y" to the question "Is this organization provisioned in Microsoft Office 365 (y/n)".

The problem is coming from the following code lines in CrmServiceHelpers.cs:

                    // For OnlineFederation environments, initially try to authenticate with the current UserPrincipalName
                    // for single sign-on scenario.
                    else if (config.EndpointType == AuthenticationProviderType.OnlineFederation
                        && config.AuthFailureCount == 0
                        && !String.IsNullOrWhiteSpace(UserPrincipal.Current.UserPrincipalName))
                    {
                        config.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;
                        return null;
                    }

The quick fix is to comment out that code, from "else if" through the last brace. This avoid the exception thrown when trying to run the samples. Of course, you lose the benefit of the single sign-on feature in the ServerConnection class in CrmServiceHelpers.cs so if that's important to you then you'll need to work on a better solution.

Connecting to CRM within a Plug-in

You will typically use the following two lines of code in your plug-ins to create an instance of IOrganizationService for CRUD operations.
// Obtain the organization service reference which you will need for web service calls.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);