Connect to Dynamics CRM with Dataverse from Azure Function

In today's 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 sure 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.

Microsoft Entra ID

We need to select App registration.

 App registration

Fill in the required details and show 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.

Register

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.

Application ID

Request API

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.

Dynamics CRM

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 be impersonated.
  • 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.

Client secret ID

Add a new client secret and select its expiration date.

Expiration Date

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

Add

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/, select your environment, and click on settings as shown in the below screenshot.

Environment

Next, under Users and permissions, click on application users.

Application users

Click on New app user.

New app user

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.

My App

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.

Web API

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 the 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://learn.microsoft.com/en-us/microsoft-sales-copilot/create-contact-crm-sales-copilot.

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

URL

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.

 CRUD operations

Create Azure Function builds appropriately

I am writing below the 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 a post request from Postman, as shown in the below screen.

Local host URl

Params

Code

Below records are created in dynamic in contact entity.

Contact entity

Thank you!


Similar Articles