Monday, 24 May 2021

Console app with oAuth

CRUD Operation in Console Application using C# in Dynamics 365





public CrmServiceClient ConnectWithOAuth() { Console.WriteLine("Connecting to D365 Server..."); string authType = "OAuth"; string userName = "
XX@XXXX.onmicrosoft.com"; string password = "XXXXXXXX"; string url = "https://xxx.crm.dynamics.com"; string appId = "44fbace3-81ad-42f2-a76a-a7d377fec266"; string reDirectURI = "https://localhost"; 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); return svc; 

} 











public void PerformCRUD(CrmServiceClient svc)

{ //CREATE var myContact = new Entity("contact"); myContact.Attributes["lastname"] = "Learn"; myContact.Attributes["firstname"] = "Softchief"; myContact.Attributes["jobtitle"] = "Consultant"; Guid RecordID = svc.Create(myContact); Console.WriteLine("Contact create with ID - " + RecordID); //RETRIEVE Entity contact = svc.Retrieve("contact", new Guid("df4df113-746c-eb11-a812-000d3a3b1114"), new ColumnSet("firstname", "lastname")); Console.WriteLine("Contact lastname is - " + contact.Attributes["lastname"]); //Retrieve Multiple Record QueryExpression qe = new QueryExpression("contact"); qe.ColumnSet = new ColumnSet("firstname", "lastname"); EntityCollection ec = svc.RetrieveMultiple(qe); for (int i = 0; i < ec.Entities.Count; i++) { if (ec.Entities[i].Attributes.ContainsKey("firstname")) { Console.WriteLine(ec.Entities[i].Attributes["firstname"]); } } Console.WriteLine("Retrieved all Contacts..."); //UPDATE Entity entContact = new Entity("contact"); entContact.Id = RecordID; entContact.Attributes["lastname"] = "Facts"; svc.Update(entContact); Console.WriteLine("Contact lastname updated"); //DELETE svc.Delete("contact", RecordID); //Execute Entity acc = new Entity("account"); acc["name"] = "Soft"; var createRequest = new CreateRequest() { Target = acc }; svc.Execute(createRequest); //Execute Multiple var request = new ExecuteMultipleRequest() { Requests = new OrganizationRequestCollection(), Settings = new ExecuteMultipleSettings { ContinueOnError = false, ReturnResponses = true } }; Entity acc1 = new Entity("account"); acc1["name"] = "Soft1"; Entity acc2 = new Entity("account"); acc2["name"] = "Soft2"; var createRequest1 = new CreateRequest() { Target = acc1 }; var createRequest2 = new CreateRequest() { Target = acc2 }; request.Requests.Add(createRequest1); request.Requests.Add(createRequest2); var response = (ExecuteMultipleResponse)svc.Execute(request); }

No comments:

Post a Comment

Introduction to Dynamics 365 CE Data Migration using ADF

Dynamics 365 CE Data Migration using ADF can be necessary for various reasons, such as archiving historical data, integrating with other sys...