Thursday 13 May 2021

Connect CRM Online Web API from Console Application

 

Connect CRM Online Web API from Console Application

Hi folks , Today I will demonstrate how to connect Dynamics CRM online Web API from Console Application.

Usage: In Dynamics CRM 9.0 SDK , we can’t directly use IOrganizationService in  third party applications to consume CRM Metadatas, To overcome this scenario we can use CRM Web API request in Console Application which can be used in project as Task Schedular , Web Jobs etc.

Step 1: Create Native App In Azure Active Directory.

Navigate to portal.azure.com -> Azure Active Directory -> App registration -> New Application Registration

1.PNG

2.PNG

Once the App is created in Azure AD, Click and Open the app and Copy the Application Id as shown below.

3.PNG

Navigate To Settings -> Required Permission -> Click Add

4.PNG

Select an API -> Then In the Available option Select Dynamics CRM Online (Microsoft CRM) as shown below

5.PNG

Select Delegated Permission for Dynamics CRM App as shown below.

6.PNG

After Adding the Delegated Permission, Click on Grant Permissions Button and Click Yes as shown below.

7.PNG

Now we have successfully created CRM Web Api App in Azure AD.

Step 2: Create a Console Application and Add the below Code to get the Access Token for accessing the Azure Native App (We created before).

string crmUrl = "https://testxxx.crm.dynamics.com";
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(crmUrl)).Result;
 string resourceUrl = ap.Resource;
 string authorityUrl = ap.Authority;
 AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
 UserCredential cred = new UserCredential("test@test.com");

//Application Id of the Native App Created
string applicationId = """00000000-0000-0000-0000-000000000000"
AuthenticationResult authToken = await authContext.AcquireTokenAsync(resourceUrl, applicationId, cred);
 string crmToken = authToken.AccessToken;

 

Step 3: Add the Below Line of Codes To Access CRM Web API:

In this Example i am going to Create a CRM Record using CRM Web Api Patch Method.

Create a method to Create CRM Record and In Return get the Guid of the Created Record:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static async TaskCreateCRMRecords()
 {
 string entityName = "contacts";
 JObject jParam = new JObject();
 jParam["name"] = "Herald Jeramiah";
 jParam["fielname1"] = "xxxxx";
 jParam["fielname2"] = "xxxxx";
 string entityid = (new Guid()).ToString();
HttpResponseMessage data = await GetResponseForCreateQuery(entityName, jParam);
 if (data.IsSuccessStatusCode == true && data.Headers.Location.Segments[4] != null)
 {
entityid = data.Headers.Location.Segments[4].Replace(entityName, "").Replace("(", "").Replace(")", "");
 }
 else
 {
 Trace.TraceError("Error: ", data.ReasonPhrase, jParam.ToString());
 }
 return new Guid(entityid);
 }

Now Add the Below functions to create HTTP Request by Adding Header Values and Get the HTTP Response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static async Task GetResponseForCreateQuery(string entityPluralName, JObject _jParam)
{
string token = await GetToken(crmUrl);
HttpResponseMessage createResponse = null;
try
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 2, 0);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
createResponse = await SendAsJsonAsync(httpClient, new HttpMethod("PATCH"), crmUrl + "/v9.0/" + entityPluralName, _jParam);
}
catch (HttpRequestException ex)
{
Trace.TraceError(ex.Message.ToString());
}
return createResponse;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private static async Task SendAsJsonAsync (HttpClient client, HttpMethod method, string requestUri, T value)
 {
       HttpResponseMessage asyncResponse = null;
       string content;
       try
       {
         if (value.GetType().Name.Equals("JObject"))
             { content = value.ToString(); }
         else
         {
              content = JsonConvert.SerializeObject(value, new JsonSerializerSettings()
              { DefaultValueHandling = DefaultValueHandling.Ignore });
          }
         HttpRequestMessage request = new HttpRequestMessage(method, requestUri);
         request.Content = new StringContent(content);
         request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
         asyncResponse = await client.SendAsync(request);
      }
     catch (Exception ex)
     {
         Trace.TraceError(ex.Message.ToString());
     }
 }

Using above code we can create a CRM Entity Record using CRM Web API.

Hope It’s Helpful. Happy CRMing

No comments:

Post a Comment

SSDT for Visual Studio (VS) 2015

In this course, we will learn to implement and build a SSRS Report in Dynamics CRM. The Microsoft’s Dynamics 365 CRM and Model Driven PowerA...