Search This Blog

Friday, February 25, 2022

Please use oAuth2.0 authentication in Dynamics 365 / CDS – Console App

 If you are facing error while connecting Dynamics 365 from Console Application then use OAuth to connect using below code. update your code as per below.

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;

namespace MFACRUDD365
{
    class Program
    {
        static void Main(string[] args)
        {
            string authType = "OAuth";
            string userName = "XXX@XXX.onmicrosoft.com";
            string password = "XXX@XXX";
            string url = "https://XXX.crm.dynamics.com";
            string appId = "51f81489-12ee-4a9e-aaae-a2591f45987d";
            string reDirectURI = "app://58145B91-0C36-4500-8554-080854F2AC97";
            string loginPrompt = "Auto";
            string ConnectionString = string.Format("AuthType = {0};Username = {1};Password = {2}; Url = {3}; AppId={4}; RedirectUri={5};LoginPrompt={6}",
                                                    authType,userName,password,url,appId,reDirectURI,loginPrompt);

            CrmServiceClient svc = new CrmServiceClient(ConnectionString);

            if (svc.IsReady)
            {
                PerformCRUD(svc);
            }
        }

        private static void PerformCRUD(CrmServiceClient svc)
        {
            //CREATE
            var myContact = new Entity("contact");
            myContact.Attributes["lastname"] = "Sample";
            myContact.Attributes["firstname"] = "Contact";
            Guid RecordID = svc.Create(myContact);
            Console.WriteLine("Contact created...");


            //RETRIEVE
            Console.WriteLine("Retrieving Contact...");
            Entity contact = svc.Retrieve("contact", RecordID, new ColumnSet("firstname", "lastname"));
            Console.WriteLine("Contact First Name:"+ contact["firstname"]);

            //UPDATE
            Console.WriteLine("Updating Contact...");
            Entity entContact = new Entity("contact");
            entContact.Id = RecordID;
            entContact.Attributes["lastname"] = "Sample New";
            svc.Update(entContact);
            Console.WriteLine("Contact updated");

            //DELETE
            Console.WriteLine("Contact Deleting");
            svc.Delete("contact", RecordID);
            Console.WriteLine("Contact Deleted");
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment