Search This Blog

Saturday, January 22, 2022

Using/Calling Dynamics 365 Web Api for Integration and console Application in C#

 As per Microsoft Dynamics 365 V9.X release it has been advised to use Dynamics CRM WebApi for any integration with Dynamics CRM and in code written outside Plugin and Custom workflows as Microsoft has deprecated Dynamics SDK for integration purposes.

To use Dynamics web API we need to first register an application in Azure AD and get the client ID and (Secret Key or use username and password of the User instead of the secret key).

So to connect web API on any .net application you need to be ready with.

Cmponents Required

Where to Find?

Example

Client Id        (Guid)

On Register of APP

“edb0f75d-9540-****-****-259e0d289148”

Client Secret (Random Number Generator)

On Register of APP

 

 

“jVE[Ek_CPxml@****@OULHs1g7b493?=”

Username & Password of User(If secret key is not there)

OAuth 2.0 v1 Endpoints

On Register of APP

https://login.microsoftonline.com/d245e842-b71e-42df-**** -176555cfb904/oauth2/token

Crm Api URL

From CRM Resource Center

https://4***ember2019.crm*.dynamics.com/api/data/v9.1

References Required to Connect.

IdentityModel.Clients.ActiveDirectory (From Nuget)References Required to Connect.

  • Json

Code to connect to Web API.

A basic example to Retrieve account and contact record and create contact records in CRM.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Text;
using Newtonsoft.Json;
 
namespace MyFirstWebAPI.Controllers
{
    public class CrmController : ApiController
    {
        static string serviceUri = "https://3november2019.crm8.dynamics.com/";
        //static string redirectUrl = "http://localhost:64884/";
 
        static string apiVersion = "9.1";
        static string crmapiUrl = $"{serviceUri}/api/data/v{apiVersion}/";
        private void GetAuthToken()
        {
 
            // TODO Substitute your app registration values that can be obtained after you
            // register the app in Active Directory on the Microsoft Azure portal.
            //Connect to crm API using Username and Password with oAuth 2.0 v1 Endpoints.
            //string clientId = "e36bb8ae-b29b-4d36-8fa8-45de01f0993b"; // Client ID after app registration
            //string userName = "g***@*******uk.onmicrosoft.com";
            //string password = "*******XHJg";
            //var credentials = new UserPasswordCredential(userName, password);
            //string authority = "https://login.microsoftonline.com/03b9cd1b-6cfc-4c45-****-1092fd6f0e26/oauth2/authorize";  //oAuth 2.0 v1 Endpoints
            //var context = new AuthenticationContext(authority, false);
            //var authResult = context.AcquireTokenAsync(resource: serviceUri, clientId, credentials).Result;
 
            //Connect to crm API using secretKey with oAuth 2.0 v1 Endpoints.
            string clientId = "edb0f75d-****-****-bcce-259e0d289148";
            string appKey = "jVE[Ek_****@w8Ov@OULHs1g7b493?="; //Client Secret
            ClientCredential credentials = new ClientCredential(clientId, appKey);
            var authResult = new AuthenticationContext(authority, true).AcquireTokenAsync(serviceUri, credentials).Result;
            //return authResult.AccessToken;
            string guid = RetrieveAccounts(authResult.AccessToken);
 
            CreateContacts(authResult.AccessToken, guid);
        }       
 
        private void CreateContacts(string accessToken, string guid)
        {
            try
            {
                JObject contact1 = new JObject{
                                            { "firstname", "Sanket" },
                                            { "lastname", "Sinha" },
                                            { "emailaddress1", "nowsanket@gmail.com" }
                                            };
 
                contact1["jobtitle"] = "Junior Developer";
                contact1.Add("modifiedby@odata.bind", "/systemusers(5ef22367-aa3f-4bbe-b490-39b332c9e6a8)");
                contact1.Add("gendercode", 1);
 
                HttpClient httpClient = new HttpClient();
                //Default Request Headers needed to be added in the HttpClient Object
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                //Set the Authorization header with the Access Token received specifying the Credentials
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 
                httpClient.BaseAddress = new Uri(crmapiUrl);
 
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "contacts")
                {
                    Content = new StringContent(contact1.ToString(), Encoding.UTF8, "application/json")
                };
 
                HttpResponseMessage response = httpClient.SendAsync(request).Result;
                if (response.IsSuccessStatusCode) //204
                {
                    var entityUri = response.Headers.GetValues("OData - EntityId").FirstOrDefault();
                }
 
            }
            catch (Exception)
            {
 
                throw;
            }
        }
 
        public string RetrieveAccounts(string authToken)
        {
            string guid = string.Empty;
            HttpClient httpClient = new HttpClient();
            //Default Request Headers needed to be added in the HttpClient Object
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
            //Set the Authorization header with the Access Token received specifying the Credentials
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
 
            httpClient.BaseAddress = new Uri(crmapiUrl);
              //Examples of different filters here.
              //var response = httpClient.GetAsync("accounts?$select=name&$top=1").Result;
             //var response = httpClient.GetAsync("accounts?$select=name&$top=1").Result;
            //var response = httpClient.GetAsync("contacts?$select=fullname&$expand=parentcustomerid_account($select=accountid,name,createdon,emailaddress1,address1_telephone1)&$filter=emailaddress1 eq 'nowsanket@gmail.com'&$top=1").Result;
            var response = httpClient.GetAsync("importfiles?$select=successcount,name").Result;
            if (response.IsSuccessStatusCode)
            {
                var accounts = response.Content.ReadAsStringAsync().Result;
 
                var jRetrieveResponse = JObject.Parse(accounts);
 
                dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
 
                foreach (var data in collContacts.value)
                {
                    //You can change as per your need here
                    guid = data.importfileid.Value;
                    Console.WriteLine("Contact Name – " + data.name.Value);
                }
 
            }
            return guid;
        }
    }
}

 


Register application in azure active directory

 

Why we need to Register our application in Azure?

  1. To integrate your dynamics CRM with any other application using Dynamics CRM web API.
  2.  To get the Client Id and Secret Key for any application which we used in these integrations.

You also need to have the access of Azure Active directory.

Steps to register the new application in Azure AD

Follow the below-listed steps to register the application.

Steps to register the Application.

Step 1

 Go to the Azure portal URL and select the Azure Active Directory on the Left-hand side Navigation home page.

https://portal.azure.com/

 
How To Register The App In Azure Active Directory

Step 2

From the Azure Active Directory overview/Default/Homepage select ‘App Registration’ again from the left-hand navigation.
 
How To Register The App In Azure Active Directory

Step 3

On the App Registration pane, click on the ‘New Application Registration’ button.
 
How To Register The App In Azure Active Directory

Step 4

Provide all the information on the Create pane of App Registration.
 
Input NameDescriptionExample
NameProvide the name for your Application.MyFirstWebAPI
Supported account typesYou can select as per your requirementI selected for my current organization directory only
Sign in URLLogin URLhttp://localhost:64884/

Once the Apps get created, you will be redirected to the home page of your newly build API.
Keep a copy of the Application ID,Object ID and tenant ID.

 

Step 5

Once your app got created you need to first provide the permission from the API permission option.

Now, click on + Add a permission, then choose the Dynamics CRM from the grid view.

Now you can select the type of API for which you are registering this APP, I selected Dynamics CRM here.

After selecting the Dynamcis CRM, I need to provide the type of Access, I provided;
1. Delegated Permission
2. user_impersonation

After providing all the values, you can click on Add Permission Button and then your final Add permission screen should appear like this:


 

Step 6

Now you can move towards adding the application a password while ceiling , which you can do by adding a secret Key to your Application, So when a user try to access the API he also need to provide this secret key in it’s code header.

WE will now click on Certificates & secrets Option on the Left hand side navigation

You can click on the +New client secret button and you will be asked to add the description and the timeline or the expiry for this secret key. After that you click on the create button and it will generate the random key for you.

That’s all the basic configuration you need to perform here on the Azure. No you can collect all the data you need from the azure app such as Client ID(Application ID), Tenant ID, Object ID, Enpoints O Auth and Secret Key.

Step 7:

Now we need to collect the Endpoints value from the App we registered, you need to go to your WEB-API overview page there you will Endpoints button on top. you can click on that and can store the OAuth 2.0 authorization endpoints (v2). Copy and store both authorize and token link.

Create Application User in Dynamics to access the Web-API

log into your Dynamics 365 CRM environment and open the User entity in there and select the Application Users from the View.

Click on the new button to create a new application user provide the User Name and copy the Application ID of the web-Api which we copied earlier to the application ID in user form . Once you add the Application ID, the other two fields will get auto-populated. You can save the User form now.
After creating the user in CRM , you need to provide the security role to the User as per your access need.
Whatever access the application user have in CRM, those operation can only be done using the Web-API so be sure on your requirement.

Once everything is done you can all these to start building your web-Api.