How to – Call Dynamics CRM from Azure Functions


Update -26 – Sep- 2018

https://nishantrana.me/2018/09/26/changing-the-target-runtime-version-of-azure-functions/

https://nishantrana.me/2018/09/25/the-type-or-namespace-name-xrm-could-not-be-found-are-you-missing-a-using-directive-or-an-assembly-reference-error-while-using-azure-functions-2-x/

 

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/

</p>
<p>{<br />
"frameworks": {<br />
"net46":{<br />
"dependencies": {<br />
"Microsoft.CrmSdk.CoreAssemblies": "8.2.0.2"<br />
}<br />
}<br />
}<br />
}</p>
<p>

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)

</p>
<p>using System.Net;<br />
using Microsoft.Xrm.Sdk;<br />
using Microsoft.Xrm.Sdk.Client;</p>
<p>public static async Task Run(HttpRequestMessage req, TraceWriter log)<br />
{<br />
log.Info("C# HTTP trigger function processed a request.");</p>
<p>// parse query parameter<br />
string firstname = req.GetQueryNameValuePairs()<br />
.FirstOrDefault(q =&gt; string.Compare(q.Key, "firstname", true) == 0)<br />
.Value;</p>
<p>string lastname = req.GetQueryNameValuePairs()<br />
.FirstOrDefault(q =&gt; string.Compare(q.Key, "lastname", true) == 0)<br />
.Value;</p>
<p>IServiceManagement orgServiceManagement = ServiceConfigurationFactory.CreateManagement(new Uri("https://nishutrial.crm.dynamics.com/XRMServices/2011/Organization.svc"));</p>
<p>AuthenticationCredentials authCredentials = new AuthenticationCredentials();<br />
authCredentials.ClientCredentials.UserName.UserName = "abc@abc.onmicrosoft.com";<br />
authCredentials.ClientCredentials.UserName.Password = "*****";<br />
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);</p>
<p>OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);<br />
Entity contact = new Entity("contact");<br />
contact.Attributes["firstname"] = firstname;<br />
contact.Attributes["lastname"] = lastname;<br />
var contactId = organizationProxy.Create(contact);<br />
// Get request body<br />
dynamic data = await req.Content.ReadAsAsync();</p>
<p>string fullname = "";<br />
return fullname == null<br />
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")<br />
: req.CreateResponse(HttpStatusCode.OK, "Contact created in CRM " + contactId.ToString());<br />
}</p>
<p>

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..

 

Advertisements
Advertisement

Author: Nishant Rana

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

13 thoughts on “How to – 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

  2. i am new to Azure Functions APP and I have tried the same. Application is throwing error. Unable to compile the code. Here is the error
    [Error] Function compilation error
    Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
    at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 314
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionLoader.cs : 55
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync(Boolean isInvocation) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 183
    2018-11-29T15:45:00.135 [Error] run.csx(8,5): error CS0305: Using the generic type ‘IServiceManagement’ requires 1 type arguments
    2018-11-29T15:45:00.182 [Error] run.csx(8,75): error CS0411: The type arguments for method ‘ServiceConfigurationFactory.CreateManagement(Uri)’ cannot be inferred from the usage. Try specifying the type arguments explicitly.
    2018-11-29T15:45:00.224 [Error] run.csx(11,17): error CS0012: The type ‘ClientCredentials’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.
    2018-11-29T15:45:00.273 [Error] run.csx(12,17): error CS0012: The type ‘ClientCredentials’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.
    2018-11-29T15:45:00.336 [Error] run.csx(15,50): error CS0012: The type ‘ClientCredentials’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’.
    2018-11-29T15:45:00.380 [Error] run.csx(20,5): error CS1061: ‘ILogger’ does not contain a definition for ‘Info’ and no extension method ‘Info’ accepting a first argument of type ‘ILogger’ could be found (are you missing a using directive or an assembly reference?)
    2018-11-29T15:45:00.431 [Error] Executed ‘Functions.TimerTrigger1’ (Failed, Id=b748564c-f12e-4098-9379-56937f57a4f5)
    Script compilation failed.

    Like

  3. Hi,

    I am unable to find the template you have mention webhook + Api + C#, can you write the steps to use that template.

    is that template comes with any subscription?

    Regards,
    Shahbaaz

    Like

Leave a Reply to Nishant Rana Cancel reply

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog & Website of Paul Andrew

Technical Leadership Centred Around the Microsoft Data Platform

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Dynamics 365 Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog

Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Knowhere365

Specific topics by Django Lohn on the whole Microsoft365 Stack

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue MVP

A Microsoft Business Applications MVP

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.

CRM Keeper

Dynamics 365 Customer Engagement, CRM, Microsoft CRM, Dynamics CRM

EVOLVED365

Step into the world of a Dynamics 365 Consultant

Dianamics PCF Lady

Diana & Dynamics 365 & Power Platform

%d bloggers like this: