cancel
Showing results for 
Search instead for 
Did you mean: 
Rahman1005

Connect to Dynamics CRM with Dataverse from Azure Function

In this blog, we'll connect to Dataverse using an Azure function that utilizes the .Net core 6.2 framework.

The prerequisites are listed below.

  • Create a new Dynamics 365 application in Azure.
  • Make that the newly created Azure Function builds appropriately.
  • To establish a connection with the Dataverse, use this sample of code.

Create a new Dynamics 365 application in Azure:

 

We need to register the Dynamics 365 Web API on Azure and use it with an application user. This is particularly useful for those working with custom APIs in CRM.

 

To achieve this, you will need the following components.

  • Azure portal access
  • Application user
  • CRM Admin user

Log in to the Azure portal, search for " Microsoft Entra ID," and click on it.

Rahman1005_0-1719815961428.png

 

We need to select App registration.

Rahman1005_1-1719815961431.png

 

 

Fill in the required details and shown below the preferred options. I selected the first option, which is for single-tenant users only. Once completed, click on "Register." An application (Dynamics 365) will be registered, and its details will be available in the Overview tab.

Rahman1005_2-1719815961435.png

 

Application ID – The Application ID is a unique, unchangeable identifier for this application. Directory (Tenant) ID – The Tenant ID is the identifier of the AAD directory where the application was created. Next, you need to grant permissions to the API. Refer to the screenshot below.

Rahman1005_3-1719815961439.png

 

 

Rahman1005_4-1719815961444.png

 

 

Navigate to API permissions, click on "Add a permission," and select "Dynamics CRM." Choose delegated permissions and check the "user impersonation" option. Finally, click on "Add permissions.

Rahman1005_5-1719815961451.png

 

 

Here are the reasons for enabling user impersonation in the application:

  • The user calls the API with another AAD ID in the header.
  • The user is authenticated as a valid AAD user.
  • Permissions are checked to determine if the user can impersonate.
  • The AAD ID is read from the header.
  • Every call is now made as if it is by the user specified in the AAD ID header (including calls to Graph API, Dynamics CRM, etc.)

After granting permissions, the next step is to create a client secret ID.

Rahman1005_6-1719815961453.png

 

 

Add a new client secret and select its expiration date.

Rahman1005_7-1719815961454.png

 

Click on "Add" to generate a client secret. Please save the client secret in a notepad file. Refer to the screenshot below for guidance.

Rahman1005_8-1719815961456.png

 

We have successfully deployed the Dynamics online Web API. Now, let's proceed to create an application user in CRM.

Navigate to https://admin.powerplatform.microsoft.com/ and select your environment and click on setting as shown in below screen short.

 

Rahman1005_9-1719815961459.png

 

 

Next under Users and permissions click on application users.

Rahman1005_10-1719815961461.png

 

Click on New app user.

Rahman1005_11-1719815961462.png

 

Choose the app registered in Azure, then assign it to the appropriate business unit and add the desired security roles. In my case, I added the admin role to my app.

Rahman1005_12-1719815961463.png

 

Let's test the API on Postman.

To consume the Web API, first, we need to generate an authorization token. This can be done by making a GET API call to the following endpoint:

URL:https://login.microsoftonline.com/<TENANT ID>/oauth2/token

 

Rahman1005_13-1719815961468.png

 

Please include the following parameters in the API body:

  • client_id: This should be the client ID of the registered Azure application.
  • client_secret: This will be the value of the client secret generated in certificate and secrets.
  • resource: The value of this parameter will contain the URL of the CRM instance.
  • grant_type: This parameter will have a value of client_credentials.

The Client Credentials grant type is utilized by clients to obtain an access token outside of the context of a user. Upon making the request above, we will receive an access_token in return with a status code of 200.

I am obtaining CRM contacts by using an odata query in the request provided above. The details of the request are given below. The method used is Get. The URL is

https://org18828102.crm5.dynamics.com/api/data/v9.2/contacts

The above URL can be accessed by navigating to SettingsàCustomization à Developer resources, and finally to Service root URL.

Rahman1005_14-1719815961471.png

 

 

This token is intended for performing CRUD operations via WEBAPI. I will provide an example of a GET request used to retrieve data from CRM.

 

Rahman1005_15-1719815961475.png

 

Create Azure Function builds appropriately:

I am writing below Azure function to create a contact record through the Service client.

The subsequent action involves deploying the Azure function and then conducting a test using Postman or a web browser.

Conducting a test of the Azure function using Postman.

using System;

using System.IO;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Logging;

using Newtonsoft.Json;

using Microsoft.PowerPlatform.Dataverse.Client;

using Microsoft.Xrm.Sdk;

using System.Collections.Generic;

 

namespace CreateContactfromAzurefunction

{

    public static class Function1

    {

        [FunctionName("Createcontactrecord")]

        public static async Task<IActionResult> Run(

    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,

    ILogger log)

        {

            log.LogInformation("C# HTTP trigger function processed a request.");

            var _contactid = new Guid();

            try

            {

                string _clientId = "e69c80b6-615d-4c4f-97c5-88c9306e1aae";

                string _clientSecret = "sPZ8Q~152D_aVvp4TO_Fxem7iTLSP0B4Ab1OOaqI";

                string _environment = "org18828102.crm5";

                var _connectionString = @$"Url=https://{_environment}.dynamics.com;AuthType=ClientSecret;ClientId={_clientId}

                ;ClientSecret={_clientSecret};RequireNewInstance=true";

 

 

                var service = new ServiceClient(_connectionString);

                if (service.IsReady)

                {

                    _contactid = await GetContacts(service);

                }

 

 

            }

            catch (Exception ex)

            {

              return  new  OkObjectResult(ex.Message);

                throw new(ex.Message);

 

            }

            OkObjectResult testrecord = new OkObjectResult("Contact Record created with ID " + Convert.ToString(_contactid));

            return testrecord;

        }

 

        private static async Task<Guid> GetContacts(ServiceClient service)

        {

            Guid _contactid;

            // Create a contact

           

            Entity contact = new Entity("contact")

            {

                ["firstname"] = "Rahman",

                ["lastname"] = "Dynamics CRM"

            };

            _contactid = service.Create(contact);

            return  _contactid;

        }

 

       

    }

}

Copy the local host URl and send post request from postman as shown in below screen.

Rahman1005_16-1719815961477.png

 

Rahman1005_17-1719815961480.png

 

 

Rahman1005_18-1719815961482.png

 

 

Below records is created in dynamic in contact entity.

Rahman1005_19-1719815961484.png

 

 

Thank you...!