Monday, 17 May 2021

Sample code to connect to CDS / Dynamics 365 / CE using OAuth

 Sample code for quick reference for connecting to CDS through a console application using OAuth

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

Xrm.Tooling is the preferred way to connect to CDS, 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.

Note –

Here we will be using the sample AppId and Redirect URI.

Sample Code- 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
 
namespace SampleConsoleApp
{
class Program
{
static void Main(string[] args)
{
string ConnectionString = "AuthType = OAuth; " +
"Username = [username]@[domain].onmicrosoft.com;" +
"Password = [password]; " +
"Url = https://[orgname].crm.dynamics.com;" +
"AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;" +
"RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;" +
"LoginPrompt=Auto";
 
CrmServiceClient svc = new CrmServiceClient(ConnectionString);
 
if (svc.IsReady)
{
var myContact = new Entity("contact");
myContact.Attributes["lastname"] = "Test";
myContact.Attributes["firstname"] = "User1";
svc.Create(myContact);
}
}
}
}

For .NET Framework 4.5.2 – we need to explicitly specify Tls1.2 as the default protocol. 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

.NET Framework 4.6.2 uses TLS 1.2 as the default protocol.

No comments:

Post a Comment

How to Call an Action through Power Automate(MS Flow)

  Introduction As Microsoft is providing us more flexibility with Power Automate (MS Flow), recently we found that now we can call the Actio...