First, we will create an Azure Function project for Dynamics 365 CRM from Visual Studio, and below are the steps for the same.
Create Azure Function Project:
- Open Visual Studio and create a new Azure Function Project.
- Filter the platform as Azure, select Azure Function, and click Next.
- Name your project and click the Create button.
Select Trigger and Framework:
- After clicking on Create, you will see a screen where you need to select the trigger and the Azure Function version.
- Choose HTTP Trigger and Azure Function v1 (.Net Framework), then click Create.
- In this case, the Azure Function trigger will be HTTP Trigger, which means the function will be triggered when it receives an HTTP request.
Project Structure:
- Your Azure Function project will be created, and it will have the following structure.
Add NuGet Package:
- To connect with Dynamics 365 CRM, you need to add the required NuGet Package [Microsoft.CrmSdk.CoreAssemblies].
- Right-click on the project and select Manage NuGet Packages.
- Add Microsoft.CrmSdk.CoreAssemblies to your project.
Connecting to Dynamics 365 CRM:
- Now that the project is set up, we will add the code to connect to Dynamics 365 CRM. For simplicity, we are specifying the credentials directly in the C# code, although you could use constants or a more secure method like Azure Key Vault for managing secrets.
Prerequisites
Before we dive into the code, ensure you have the following in place:
- Azure App Registration: Register a new app in Azure for Dynamics 365. This app registration will provide the necessary ClientId and ClientSecret for authentication. You can refer to this guide for detailed steps.
- Azure Function Setup: Create a new Azure Function in Visual Studio or the Azure portal. Ensure that it compiles correctly before proceeding to implement the connection logic.
Code Snippet for Connecting to Dataverse
Below is an updated and optimized code snippet for connecting to Dataverse from an Azure Function running on .NET Core 3.1 or later.
using System;
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 Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;
namespace DataverseConnectionFunction
{
public static class DataverseConnection
{
[FunctionName("DataverseConnection")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
Guid contactId = Guid.Empty;
try
{
// Azure AD App registration credentials
string clientId = "***********-fdd5-44cd-*****-***********";
string clientSecret = "khv8Q~B4qvMudtK****************************";
string environment = "your_environment_name"; // e.g., org1234.crm.dynamics.com
// Connection string for Dataverse
var connectionString = @$"AuthType=ClientSecret;Url=https://{environment}.dynamics.com;
ClientId={clientId};ClientSecret={clientSecret};RequireNewInstance=true";
// Initialize Dataverse Service Client
using var serviceClient = new ServiceClient(connectionString);
if (serviceClient.IsReady)
{
// Create a new contact entity
Entity contact = new Entity("contact")
{
["firstname"] = "Demo",
["lastname"] = "Azure Function"
};
// Create the contact record in Dataverse
contactId = serviceClient.Create(contact);
}
else
{
log.LogError("Dataverse Service Client is not ready. Check connection string or credentials.");
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
catch (Exception ex)
{
log.LogError($"An error occurred: {ex.Message}");
return new ObjectResult($"Error: {ex.Message}") { StatusCode = StatusCodes.Status500InternalServerError };
}
return new OkObjectResult($"Contact Record created with ID: {contactId}");
}
}
}
Service Client Initialization: The ServiceClient from the Microsoft.PowerPlatform.Dataverse.Client namespace is used to connect to Dataverse. This client is a modern replacement for the CrmServiceClient, offering improved performance and more features.
Entity Creation: The code creates a simple contact record in Dataverse. You can extend this functionality to perform more complex operations as needed.
Error Handling: Proper error handling is included to ensure that any issues during the connection or record creation process are logged and returned as an appropriate HTTP response.
Deploying and Testing the Azure Function
- Publish the Azure Function: Once you’ve implemented and tested the function locally, publish it to Azure. This can be done directly from Visual Studio or through the Azure portal.
- Test with Postman or Browser: After deployment, you can test the function using Postman or directly via a web browser. Simply invoke the function’s URL, and if everything is set up correctly, you should see a success message indicating that the contact record has been created in Dataverse.
Conclusion
By following the steps outlined in this blog, you can efficiently connect to Microsoft Dataverse from an Azure Function using the new Dataverse Service Client. This approach provides a streamlined and modern way to interact with Dynamics 365 data, leveraging the full power of Azure Functions and .NET Core.
- Sachin Sen
https://www.linkedin.com/in/sachin-sen-5b48091b9/
