ian.blair@softstuff

My technical musings

Updating your CRM V9 connection code

I had a client ring me in a bit of a panic as their CRM system had upgraded to V9 over the weekend and the forms integration I had built for them ages ago had stopped working. The kept getting a 'Connection forcibly closed' error every time they tried to submit a form.
Fortunately I had recoded the connection part when they went to Dynamics365 from CRM2016 so it looked like this.
 
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
      }else{
         throw new invalidoperationexception(conn.LastCRMError);
      }
}

To make it work with CRM V9 turned out to be quite simple.
Firstly I had to install .NET v 4.6 on the server that was running the code, previously it was on 4.5.2. Next I had to install the new versions of the Microsoft.Xrm.Sdk.dll, and the Microsoft.Xrm.Tooling.Connector from NuGet as there doesn't seem to be the a huge SDK download anymore.
 
NuGet packages to install
Microsoft.CrmSdk.CoreAssemblies     v9.x
Microsoft.CrmSdk.XrmTooling.CoreAssembly   v9.x
 
Then the code needs 2 new lines for it to work.
Add a using System.Net; line, then as the new connections need TLS1.2 force this in the line
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
anywhere before you actually make the connection. So the code should now look like
 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Tooling.Connector;
using System.ServiceModel;
using System.Net;

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
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
      }else{
         throw new invalidoperationexception(conn.LastCRMError);
      }
}
 
And you are done. 
Easy.