Let’s get started with Azure Function for Dynamics 365 CRM: Part 1
In this blog, we will learn how to create an Azure Function App to connect it with Dynamics 365 CRM and perform the CRUD operation in Dynamics 365 CRM.
First, we will create an Azure Function project for Dynamics 365 CRM from Visual Studio, and below are the steps for the same.
Open Visual Studio and create a new Azure Function Project. Filter platform as Azure, select Azure Function, and click on Next.
Name your project and click on Create button.
After clicking on Create, you will get the below screen where you need to select the Trigger and Azure Function v1 (.Net Framework) and click on Create.
In my case, the Azure Function trigger will be Http Trigger which means when an azure function will receive an HTTP request it will trigger.
Your Azure Project will be created and the following will be the structure of the project.
Now, we will create Azure Function to connect with the Dynamics 365 CRM we need to add the required NuGet Package [Microsoft.CrmSdk.CoreAssemblies]. To add the NuGet Package right-click on the Project and click on Manage Nuget packages.
Add Microsoft.CrmSdk.CoreAssemblies in your Project.
Following is the code to connect the Dynamics 365 CRM. Currently, we are going to use the credential by specifying them in the C# Code or you can use it as constant.
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel.Description;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace CRM.AzureFunction.Integration
{
public static class Function1
{
[FunctionName("Function1")]
public static Task RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = null)] HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
IOrganizationService service = null;
#region Credentials Code
//Credentials
string URL = "Dynamics CRM URL";
string userName = "userName";
string password = "passWord";
#endregion
try
{
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
OrganizationServiceProxy ornaziationServiceProxy = new OrganizationServiceProxy(new Uri("" + URL + "/XRMServices/2011/Organization.svc"), null, clientCredentials, null);
ornaziationServiceProxy.Timeout = new TimeSpan(0, 10, 0);
service = ornaziationServiceProxy;
if (service != null)
{
Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
if (userid != Guid.Empty)
{
log.Info("Connection Established Successfully...");
}
}
else
{
log.Error("Failed to Established Connection!!!");
}
}
catch (Exception ex)
{
log.Error("Exception caught - " + ex.Message);
}
return Task.CompletedTask;
}
}
}
Later in the series, we will learn how to use Environment Variable and pass the credential more secure way in Azure Function using Azure Key Vault. [Stay tuned..!!]
Now, select the code and Refactor the code and make the connection function that will return the IOrganizationService if the connection is established else return null.
Now, the final code will be as below:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel.Description;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace CRM.AzureFunction.Integration
{
public static class Function1
{
[FunctionName("Function1")]
public static Task RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = null)] HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
IOrganizationService service = Connection(log);
if(service != null)
{
//If Connection is established
}
return Task.CompletedTask;
}
private static IOrganizationService Connection(TraceWriter log)
{
IOrganizationService service = null;
#region Credentials Code
//Credentials
string URL = "Dynamics CRM URL";
string userName = "userName";
string password = "passWord";
#endregion
try
{
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
OrganizationServiceProxy ornaziationServiceProxy = new OrganizationServiceProxy(new Uri("" + URL + "/XRMServices/2011/Organization.svc"), null, clientCredentials, null);
ornaziationServiceProxy.Timeout = new TimeSpan(0, 10, 0);
service = ornaziationServiceProxy;
if (service != null)
{
Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
if (userid != Guid.Empty)
{
log.Info("Connection Established Successfully...");
}
}
else
{
log.Error("Failed to Established Connection!!!");
}
}
catch (Exception ex)
{
log.Error("Exception caught - " + ex.Message);
}
return service;
}
}
}
Now, we will create a customer with a Hardcoded name when the function is triggered with an HTTP request. Update the existing code with the below code:
if(service != null)
{
//If Connection is establised
Entity account = new Entity("account");
account["name"] = "Created from the azure function";
service.Create(account);
}
Testing:
We will require the API testing tool, here I am using Postman and the following is the link to download “Postman”. https://www.postman.com/downloads/
To test the application, click on the Start button on top of Navbar as mentioned below in the screenshot [Button will have Project Name]. It will take a few minutes to Load the Azure Emulator
Following is the screen you will be able to see and copy the URL highlighted in the red below and paste that URL in Postman.
Open the Postman and click on the create a new tab;
Select request as POST and paste the URL:
After pasting the URL, click on Send
You will get the following response on the Azure Function Tool and Postman
If there any error or issue with the Azure Function code, the request will be failed and will be displayed on both Azure Function Tool and Postman [Status will be “4**” or “5**” ]
Now, we will take look at Dynamics 365 CRM environment and check whether the account is created or not.
We are justing getting started with Azure Function for Dynamics 365 CRM and stay tuned for more in this series.
Upcoming blogs
1. How to use Dynamics 365 Credentials securely using Azures Function.
2. How to create Dynamics 365 integration with Third-party Applications.
Many more……