My technical musings

Old vs New Connection Methods in CRM2016/Dynamics 365

With the release of the new version of the Crm2016/Dynamics365 SDK the recommended method to connect to CRM in code has changed.

Originally it was (although other methods were available with connection strings)

using Microsoft.Xrm.Sdk;
using System.ServiceModel.Description;

var url = "http://mycrmsystem/XRMServices/2011/Organization.svc";
var username = "myusername";
var password = “mypassword";
var domain = ""
var organizationUri = new Uri(url);            
var credentials = new ClientCredentials();
credentials.UserName.UserName = domain + username;
credentials.UserName.Password = password;
credentials.Windows.ClientCredential.UserName = username;
credentials.Windows.ClientCredential.Password = password;
credentials.Windows.ClientCredential.Domain = domain;

using (OrganizationServiceProxy _service = new OrganizationServiceProxy(organizationUri, null, credentials, null)) {
// code to do stuff goes here

With the advent of the tooling connector dll and the other changes in the api this should now be changed to:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Tooling.Connector;
using System.ServiceModel;

var connectionString = "url=https://mycrmsystem; Username=myusername; Password=mypassword; authtype=Office365";
CrmServiceClient conn = new CrmServiceClient(connectionString);
using (OrganizationServiceProxy orgService = conn.OrganizationServiceProxy) {
     if (conn.IsReady) {
          // code to do stuff goes here
         throw new invalidoperationexception(conn.LastCRMError);

The key now is the connection string as this determines the connection method with the authtype= parameters.

The example above assumes you are connecting to a Office365 hosted CRM system but if you were connecting to an on-premise active directory system the connection string might be

var connectionString = "url=https://mycrmsystem/myorg; Username=myusername; Password=mypassword; Domain=mydomain; authtype=AD";


The other feature is the .IsReady property, if this is set to true the connection has been successful and can be used for further processing, otherwise the properties .LastCRMError and .LastCRMException can be checked to see what went wrong.