Update -26 – Sep- 2018
https://nishantrana.me/2018/09/26/changing-the-target-runtime-version-of-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/
</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 => string.Compare(q.Key, "firstname", true) == 0)<br /> .Value;</p> <p>string lastname = req.GetQueryNameValuePairs()<br /> .FirstOrDefault(q => 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..
Nice explanation, keep going 🙂
LikeLike
Thanks for posting this up. Any idea if the Microsoft.CrmSdk.CoreAssemblies NuGet package supports CRM 2011?
LikeLike
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
LikeLike
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.
LikeLike
Any recommendations on how we can do this but not have the credentials stored in code?
LikeLike
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.
LikeLike
the above code will work only for version 1 of Azure Function. https://nishantrana.me/2018/09/26/changing-the-target-runtime-version-of-azure-functions/ Which version are you using ?
LikeLike
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
LikeLike
Thanks for posting this up. Any idea if the Microsoft.CrmSdk.CoreAssemblies NuGet package supports CRM 2011?
LikeLike