Tuesday, May 31, 2022

Connect to Dynamics 365 using console application/OAuth

In this blog, I have explained step by step process to connect to Dynamics 365 using the Console Application and using OAuth.

Before we proceed below are some prerequisites that need to be taken care of:

  1. Visual Studio 2015/2017/2019
  2. CRM SDK Nuget Packages
  3. D365 Application
  4. AppId - Get it from Azure Portal : https://portal.azure.com/



Let's Begin...

Note: First Create a ConsoleApp (.NET Framework) project.

In Visual Studio: Go to File -> New -> Project -> ConsoleApp (.NET Framework) -> Next -> Fill Project Name and other details -> Create




1. Add the NuGet package for Microsoft.CrmSdk.XrmTooling.CoreAssembly in the project.

Xrm.Tooling is the preferred way to connect to Dataverse, because of many benefits – we can define connection string, thread safety, support for X.509 certificate authentication, support for secure storage of sign-in credentials and reuse, etc.

2. In App.config file Add below XML code

<?xml version="1.0" encoding="utf-8"?>
<configuration>
       <appSettings>
             <add key="UserKey" value="XXXX.onmicrosoft.com" />
             <add key="UserPassword" value="XXXXX" />
             <add key="Environment" value="https://XXXXXXX.crm.dynamics.com/" />
       </appSettings>
       <startup>
             <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
       </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Clients.ActiveDirectory" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.9.0" newVersion="5.2.9.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

</configuration>


3.  Navigate to Program.cs file and add the below code to connect to D365

using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace D365ConsoleAppCRUDOperation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Console Application Started!");
            try
            {
                //Step 1 - Retrieving CRM Essential Information.
                string sEnvironment = System.Configuration.ConfigurationManager.AppSettings["Environment"].ToString();
                string sUserKey = System.Configuration.ConfigurationManager.AppSettings["UserKey"].ToString();
                string sUserPassword = System.Configuration.ConfigurationManager.AppSettings["UserPassword"].ToString();
                //Step 2- Creating A Connection String.
                string conn = $@" Url = {sEnvironment};AuthType = OAuth;UserName = {sUserKey}; Password = {sUserPassword};AppId = 6cc5df06-10fc-474c-8db6-5ccd36950af6;RedirectUri = app:https://localhost;LoginPrompt=Auto; RequireNewInstance = True";
                Console.WriteLine("Operating Environment : " + sEnvironment);
                //Step 3 - Obtaining CRM Service.
                using (var service = new CrmServiceClient(conn))
                {
                    if (service.IsReady)
                    {
                        Console.WriteLine("Operating Environment Connected Successfully....");
                        //Executing YOUR CRM OPERATIONS.
                    }
                    else
                    {
                        Console.WriteLine("Operating Environment Connection failed....");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Occured : " + ex.Message);
            }
        }
    }
}

 4. Build and Run your code



That's all...

Thank you !!!!

Happy ConsoleApping...

Keep D365ing...