DEV Community

Imran
Imran

Posted on

Connecting to Dataverse using AuthCode flow and CrmServiceClient

Here a quick example of connecting to Dynamics using CrmServiceClient in Microsoft.CrmSdk.XrmTooling.CoreAssembly

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
namespace Codebug.Dataverse.Connection
{
/// <summary>
/// Before running this application the following needs to be performed.
/// 1. An application registration need to be created with a secret in azure.
/// 2. In the API Permissions section in app registration in azure, Dynamics CRM > user_impersonation needs to be granted.
/// 3. The application then need to be created as app user in dynamics.
/// 4. A security role needs to be added to the user.
/// No redirect uri needs to be set up.
/// <seealso cref="https://docs.microsoft.com/en-us/powerapps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect">Reference for connection string<seealso/>
/// </summary>
class Program
{
/// <summary>
/// for this code to run install Microsoft.CrmSdk.XrmTooling.CoreAssembly from nuget org
/// </summary>
/// <param name="connectionString"></param>
/// <remarks>Both CrmServiceClient and OrganizationWebProxyClient implements IOrganizationService
/// OrganizationWebProxyClient is not disposable and should only be used if the code uses early bound classes. In that case we need
/// OrganizationWebProxyClient to generate the context object. if your application uses late bound using disposable CrmServiceClient is sufficient</remarks>
private static IOrganizationService Connect(string connectionString)
{
var crmClient = new CrmServiceClient(connectionString);
return crmClient.OrganizationWebProxyClient != null
? crmClient.OrganizationWebProxyClient as IOrganizationService
: throw new Exception();
}
static void Main(string[] args)
{
var clientId = "<client id in Azure>";
var secret = "<Secret in azure>";
var dataVerseUrl = "Url for the dynamics 365/DataVerse instance";
var connectionString = $"AuthType=ClientSecret;" + // more on https://docs.microsoft.com/en-us/powerapps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect#connection-string-parameters
$"url={dataVerseUrl};" +
$"ClientId={clientId};" +
$"ClientSecret={secret};" +
$"RequireNewInstance=false;"; // Default is false. If set to true a new connection will be created every time CrmServiceClient is generated.
var orgService = Connect(connectionString);
}
}
}
view raw Program.cs hosted with ❤ by GitHub

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay