Connect to Dataverse using Console Application - OAuth Authentication

 We can use CrmServiceClient to connect with Dataverse in .NET code. This service exposes all the Dataverse services to perform operation via code.

With the new changes in Authentication Type of Dataverse it is recommended to use Visual Studio 2019 version which supports MFA as well. Also please note that the .NET Framework 4.6.2 is required as it supports TLS 1.2 to connect.

We will use AuthType as OAuth for this example to connect to our instance which can be set in connection string of the code.

We would require to install latest version of Microsoft.CrmSdk.CoreAssemblies from Nuget to the solution to get reference of all the required assemblies.

Once the Nuget package is installed, we can use below code to connect to Dataverse:


using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Tooling.Connector;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace CDS_OrganizationService

{

    class Program

    {

        static void Main(string[] args)

        {

            string username = "user@domain.onmicrosoft.com";

            string password = "Password";

            string Url = "https://orgurl.crm.dynamics.com/";

            string AppId = "51f81489-12ee-4a9e-aaae-a2591f45987d";

            string RedirectUri = "app://58145B91-0C36-4500-8554-080854F2AC97";

            string connectionString = $"Url={Url};AuthType=OAuth;UserName={username};Password={password};AppId={AppId};RedirectUri={RedirectUri};LoginPrompt=Auto;RequireNewInstance=True;";


            using (var service = new CrmServiceClient(connectionString))

            {


                WhoAmIRequest request = new WhoAmIRequest();

                WhoAmIResponse whoAmIResponse = (WhoAmIResponse)service.Execute(request);

                Console.WriteLine("User Id: {0}",whoAmIResponse.UserId);


                Console.ReadLine();

            }

        }

    }

}


The code will show below output



Comments