Call Dynamics CRM from Azure Functions

Let us take a look at a simple Azure Function that refers our CRM assemblies and creates contact record in CRM.

Log in to Azure Portal, search for Function App and create a Function App.

Here we have specified WebHook + API and CSharp Template. Click on Create this function.

Select the function app, go to Platform features tab and click on App Service Editor.

Right click the function and add a new file named project.json. It is within this file we will refer our Nuget Packages that we need in our function.

https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp

Here we will reference the following Nuget Package for CRM

https://www.nuget.org/packages/Microsoft.CrmSdk.CoreAssemblies/


{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.CrmSdk.CoreAssemblies": "8.2.0.2"
}
}
}
}

Back in our Function when we click on Save or Run, we can see the required assemblies being installed in our Log.

The sample code for the Azure Function (just for simplicity the values are all hardcoded)


using System.Net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");

// parse query parameter
string firstname = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "firstname", true) == 0)
.Value;

string lastname = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "lastname", true) == 0)
.Value;

IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("https://nishutrial.crm.dynamics.com/XRMServices/2011/Organization.svc"));

AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = "abc@abc.onmicrosoft.com";
authCredentials.ClientCredentials.UserName.Password = "*****";
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
Entity contact = new Entity("contact");
contact.Attributes["firstname"] = firstname;
contact.Attributes["lastname"] = lastname;
var contactId = organizationProxy.Create(contact);
// Get request body
dynamic data = await req.Content.ReadAsAsync<object>();

string fullname = "";
return fullname == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, "Contact created in CRM " + contactId.ToString());
}

Let us now test our function.

The function expects 2 query string parameter firstname and lastname and creates the contact record in CRM.

In our CRM, we can see the contact record created.

Hope it helps..

 


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

5 thoughts on “Call Dynamics CRM from Azure Functions”

  1. I get this error when using my own CRM url and credentials:
    Exception while executing function: Functions.HttpTriggerCSharp1 -> An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. -> Authentication Failure

    Like

    1. I receive similar:
      2017-08-03T22:47:55.933 Exception while executing function: Functions.HttpTriggerCSharp1. mscorlib: Access is denied.

      I was able to track it down to line 25 in the source outlined above:
      OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);

      I’ve tried to wrap that in a try/catch to learn more about the failure, but it behaves as if there’s no try/catch present and the exact same result happens each time.

      Like

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s