1. Prerequisites
- Install the Dynamics 365 SDK assemblies. You can install the necessary NuGet packages, such as:
Microsoft.CrmSdk.CoreAssembliesMicrosoft.CrmSdk.XrmTooling.CoreAssembly- Register your app in Azure Active Directory (AAD) to retrieve the client ID, client secret, and tenant ID.
2. Code Implementation
The following code demonstrates how to authenticate and interact with Dynamics 365 CRM using the CRM SDK:
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
class Program
{
static void Main(string[] args)
{
string clientId = "Your_Client_ID";
string clientSecret = "Your_Client_Secret";
string tenantId = "Your_Tenant_ID";
string crmUrl = "https://Your_CRM_Organization.crm.dynamics.com/";
// Create connection string
string connectionString = $@"
AuthType=ClientSecret;
ClientId={clientId};
ClientSecret={clientSecret};
TenantId={tenantId};
Url={crmUrl};";
// Establish connection
CrmServiceClient serviceClient = new CrmServiceClient(connectionString);
if (serviceClient.IsReady)
{
Console.WriteLine("Connected to CRM successfully!");
// Example: Retrieve accounts
IOrganizationService service = serviceClient.OrganizationServiceProxy;
QueryExpression query = new QueryExpression("account")
{
ColumnSet = new ColumnSet("name", "accountnumber")
};
EntityCollection results = service.RetrieveMultiple(query);
foreach (var entity in results.Entities)
{
Console.WriteLine($"Account Name: {entity.GetAttributeValue<string>("name")}, Account Number: {entity.GetAttributeValue<string>("accountnumber")}");
}
}
else
{
Console.WriteLine($"Failed to connect: {serviceClient.LastCrmError}");
}
}
}
3. Explanation
- Authentication: The connection string uses AAD authentication with the client ID, client secret, and tenant ID.
- Connection:
CrmServiceClientestablishes a connection to Dynamics 365. - Query: The
QueryExpressionretrieves data from the CRM, such as accounts in this example.
Note : This article was created with assistance from AI and there could be mistakes / error


