Deploy Azure function from Visual Studio and connect to Dynamic 365/CRM

Posted on Posted in Azure, Azure Function, Logic Apps, Microsoft

Today we are going to create a Logic App to pass some sample JSON data, do some basic steps in it, call Azure function from Logic App, connect to Dynamics 365 in azure function, create or update records in Dynamics CRM with in azure function and then return some results back in Logic App and dome stuff in there.

First step is to create a new Visual Studio project of type Azure Functions in Cloud category

Select Http trigger as below

To keep things clean, create a new Class library project ‘LogicAppFunctionApp.Dynamics365Data’ in same solution as below

Install following Nuget Packages in class library project

Microsoft.CrmSdk.CoreAssemblies

Microsoft.CrmSdk.XrmTooling.CoreAssembly

Then add a new class ‘CallDynamics’ in LogicAppFunctionApp.Dynamics365Data project

Now, go back to your Function app project ‘LogicAppFunctionApp’ and open ‘Function1’ class, below is how basic class looks like

We are going to pass JSON data in request and will retrieve it back as below
var r = req.Content.ReadAsAsync ;

var jsonBodyResult = r.Result;

var result = CallDynamics.AddRecordToDynamics2(jsonBodyResult);

We need to create a new method ‘AddRecordToDynamics2’ in CallDynamics class

This is a method which will handle all our logic and JSON data

Let’s decide with JSON data we going to pass. In this example we passing simple JSON data as below

{
"company": "Rokhri Ltd",
"location": "Leicester, UK"
}

Now create a class with this JSON data, you can either create it yourself or use this http://json2csharp.com/ link

In our AddRecordToDynamics2 method we are going to use RootObject class to convert JSON

Our final class will look like below

Function class

To debug it, run main project and copy URL as below

Go to Postman and call this URL and pass dummy data

And you can debug your function

This will create a new account in Dynamic and return back results as below

Up to this point our Azure function is complete and ready to be deployed in Azure and use with Logic app.

Now go to azure portal and create a new Function App and call it RokhriAzureFunction

Go to Visual Studio, View, Cloud Explorer and connect to your subscription

Here you will be able to see your newly created function app

Now we can deploy this function through VS but first lets download Published Profile

next go to LogicAppFunctionApp and right click to publish

Then Import Profile

Once imported, you can publish your app

Next step is to create a Logic App

Once created, first step is to create HTTP request

Next select action of type Azure Function

and you will see RokhriAzureFunction which we created earlier

Next we want to pass Body in Request Body tag

Once saved, copy URL from Logic App and call it in Postman

Now go back to your Logic App and you will see that this has created a new record in Dynamics

Hope this helps.