Dynamics 365 XrmTooling Connect with User Credentials in C#

Paul Nieuwelaar, 04 June 2020

In a previous blog post, I talked about how to connect to the Dynamics 365 SDK with the new XrmTooling nuget package, and stepped through the best way to connect using an Azure App Registration with Client ID and Secret.

In this blog post I’m going to explore a couple of other ways to connect, if you still want to or need to use traditional user credentials.

Connect using Connection String (Username, Password, and Server URL)

This method is probably the easiest to use, as you can instantly see which environment you’re connecting to, and with which user. However, by using a dedicated user account, you run the risk of passwords expiring, or MFA being enabled which will break the connection which is why connecting with an Application User is still preferred. If you can’t get access to Azure, or if you’re just doing a throwaway console app for example, then this may be an acceptable quick solution.

string serverUrl = "https://org.crm6.dynamics.com";
string userName = "user@org.onmicrosoft.com";
string password = "password"; // This should be encrypted

CrmServiceClient sdk = new CrmServiceClient($"Url={serverUrl}; Username={userName}; Password={password}; AuthType=Office365");

if (sdk != null && sdk.IsReady)
{
    sdk.Execute(new WhoAmIRequest());
}

Connect using Credentials (Org Unique Name, Username, Password, and Region)

This is like the connection string method, except it uses a proper constructor built into the CrmServiceClient class, rather than just building a custom connection string. This still uses a dedicated user account, so it has the same issues with MFA and password expiry, and it’s a little less user friendly in terms of seeing which environment you’re dealing with, but if you’re not comfortable using a connection string then this is a decent alternative.

string orgName = "org12345678";
string userName = "user@org.onmicrosoft.com";
string password = "password"; // This should be encrypted
string region = "Oceania";

CrmServiceClient sdk = new CrmServiceClient(userName, CrmServiceClient.MakeSecureString(password), region, orgName, true, true, null, true);

if (sdk != null && sdk.IsReady)
{
    sdk.Execute(new WhoAmIRequest());
}

Note: Valid values for region are NorthAmerica, EMEA, APAC, SouthAmerica, Oceania, JPN, CAN, IND, and NorthAmerica2.

There are several other connection options available on the CrmServiceClient class, including connecting using a certificate, so if can’t achieve exactly what you wanted using the methods I’ve shown here, or by using an Application User shown in my other blog, then feel free to take a look at the CrmServiceClient class to see if anything else fits your needs.