Hi Friends, Happy New Year 2022
Follow the below steps to do CRUD operations in console app using web Api.
Step 1: Go to https://portal.azure.com
Click on Azure Active Directory, next Click on App registrations
Click New Application Registration
Next fill the details and click on create
Next click on "all Apps"
Open "Sample App" click on settings then Click on "Required permissions"
Click on Add button and add "Dynamics CRM Online" and give "DELEGATED PERMISSIONS" and Click "Save"
Now Come back to "Keys" and create secret Key, when you click on save secret key will be generated then copy that key in notepad
Go Back to App and copy application id in notepad
Click on endpoints and copy "OAUTH 2.0 AUTHORIZATION ENDPOINT"
Come back to Active Directory and create User in Azure and copy password in notepad
Step 2:
Come back to CRM and go to users.
In the view Click on "Application user" and click on "+ new button".
username and primary email should be same as that we created in Azure.
Paste the application id which we copied to the notepad and click on save then give admin role for that user.
Configuration part is completed now coming to the coding part. Create new class(ex : webapihelper)
step 3:
=============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net;
using Newtonsoft.Json.Linq;
namespace CRUD_Using_Web_Api
{
class webapihelper
{
string _ClientId = "cefc4d69-0008-4841-a38f-81cf2c29a2e8";
string _ClientSecret = "15Dt6Kc31N8/D4M0zVoIZ6jyyvxwmwHJB+Kre1DIxow=";
string _Resource = "delldell.api.crm8.dynamics.com";
string _Authority = "login.microsoftonline.com/.../authorize";
string _Api = "delldell.api.crm8.dynamics.com/.../v9.1";
string accounturi = string.Empty;
public HttpClient GetHttp()
{
HttpClient httpClient = new HttpClient();
AuthenticationContext authContext = new AuthenticationContext(_Authority);
AuthenticationResult authResult;
ClientCredential credentials = new ClientCredential(_ClientId, _ClientSecret);
try
{
authResult = authContext.AcquireToken(_Resource, credentials);
httpClient.BaseAddress = new Uri(_Resource);
httpClient.Timeout = new TimeSpan(0, 2, 0);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
return httpClient;
}
catch (Exception ex)
{
return null;
}
}
public async Task CreateContactOld(HttpClient httpClient)
{
string accounturi = string.Empty;
JObject account = new JObject();
account.Add("name", "delldell");
account.Add("telephone1", "9874561230");
account.Add("websiteurl", "www.delldell.com");
account.Add("address1_city", "Hyderabad");
HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, "delldell.api.crm8.dynamics.com/.../accounts");
request1.Content = new StringContent(account.ToString(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response1 = await httpClient.SendAsync(request1);
if (response1.StatusCode == HttpStatusCode.NoContent)
{
Console.WriteLine("Account created" + account.GetValue("name"));
// Console.Read();
HttpResponseHeaders responseheaders = response1.Headers;
accounturi = responseheaders.Location.AbsoluteUri;
}
else
{
Console.WriteLine("failed to create Account");
}
//update
JObject accountupdate = new JObject();
accountupdate.Add("name", "ABC");
accountupdate.Add("telephone1", "5588223");
accountupdate.Add("websiteurl", "www.abc.com");
accountupdate.Add("address1_city", "Banglore");
HttpRequestMessage updateRequest1 = new HttpRequestMessage(new HttpMethod("PATCH"), accounturi);
updateRequest1.Content = new StringContent(accountupdate.ToString(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage updateResponse1 = await httpClient.SendAsync(updateRequest1);
if (updateResponse1.StatusCode == HttpStatusCode.NoContent) //204
{
Console.WriteLine("Account updated");
HttpResponseHeaders responseheaders1 = updateResponse1.Headers;
accounturi = responseheaders1.Location.AbsoluteUri;
}
else
{
Console.WriteLine("could not update Account");
}
//Retriving account
string querystring = "?$select=name,telephone1,websiteurl,address1_city";
HttpResponseMessage retrieveresponse = await httpClient.GetAsync(accounturi + querystring);
if (retrieveresponse.StatusCode == HttpStatusCode.OK)
{
JObject retrievedaccount = JsonConvert.DeserializeObject<JObject>(await retrieveresponse.Content.ReadAsStringAsync());
Console.WriteLine("name: " + retrievedaccount.GetValue("name"));
Console.WriteLine("City: " + retrievedaccount["address1_city"]);
// Console.Read();
}
//Deleting the created account
HttpResponseMessage deleteResponse1;
//HttpContent lastBadResponseContent = null;
deleteResponse1 = await httpClient.DeleteAsync(accounturi);
Console.WriteLine("Account Deleted");
Console.Read();
}
}
}
===========
Now in main method, create instance of the created class and call the method(CreateContactOld) in the main method.
using System.Threading.Tasks;
using System.Net.Http;
namespace CRUD_Using_Web_Api
{
class Program
{
private static void Main(string[] args)
{
webapihelper web = new webapihelper();
HttpClient ht = web.GetHttp();
Task.WaitAll(Task.Run(async () => await web.CreateContactOld(ht)));
}
}
}
Debugg and do checking of the record in advanced find, because in delete operation it will delete the same record that you created.
Nuget Packages: Microsoft.IdentityModel.Clients.ActiveDirectory and install older version like 2.29.0
No comments:
Post a Comment