
What is Azure Function?
We all grew up learning Functions in C#. A Function allows you to encapsulate a piece of code and call it from other parts of your code. You may very soon run into a situation where you need to repeat a piece of code, from multiple places, and this is where functions come in.
In the same way, Azure Function is a function (can be written either directly in Azure or through Visual Studio), which allows you to encapsulate a piece of code on cloud and can call it from any platform.
Technically, Azure Functions is the on-demand execution of functions or small fragments of code based on events. it is a serverless compute service that enables you to run code-on-demand without having to explicitly provision or manage infrastructure. Use Azure Functions to run a script or piece of code in response to a variety of events.
Let\’s understand it through an example:
Since we are dynamics people and talking in the context of Dynamics CRM, Therefore we understand the Azure Function through one Dynamics CRM requirement.
Let suppose, you have a requirement, where you have to call a web service (given by your client) in order to pass the CRM information to the third party application/system. To implement that, I can only go with the following options in Dynamics CRM
- Plugins
- Custom Workflow
- Custom Action
- JavaScript or WEB API.
Being a dynamics developer, you would like to keep the web service calling logic/code at one place instead of writing it repeatedly in Plugin, Custom Workflow, Custom Action and WEB API.
Azure Function is the best way to keep your logic/code at one place on cloud and can call it from anywhere, not only from the CRM but also from outside CRM either using C# Console, Web Applications, Window Applications, JAVA Applications or through other languages like Python, Javascript, PHP, F# Powershell etc. (Supported Languages)
Hence, Azure Function is a piece of code which we can keep it on the cloud and can call it from anywhere (inside and outside CRM) on a particular event to fulfil our requirement.
Why Azure Function?
Someone might have a query that, why I need Azure Function just to keep my logic/code on the cloud? I might also go with CRM Custom Actions as well. Because Custom Action is also provided by Microsoft to reuse the code/logic in CRM. We can keep the logic/code in our Custom Acton and can call it either through Plugin/Custom Workflow or WEB API. Then why Azure Function?
Answer is:
- Custom Actions needs to be created in Visual Studio and in CRM both in order to configure its scope(entity or global) and parameters, then only you can call it through either plugin, workflow or javascript.
- As per my personal experience, In case of any error or issue, debugging of custom action is very complex and not have proper troubleshooting mechanism provided by Microsoft.
- Tracing of an error log is not possible in Custom Action using ITracingService.
- Custom Action is only limited to CRM, can\’t use it through other platforms and languages.
- Need Visual Studio to write the code.
- Plugins
- Custom Workflows
- Custom Actions
- C# External Applications (Web, Console, Window etc).
- Monitoring and Tracking- We have access to execution log and if we want the result of previous executions, in the options of the function we can find the monitor.
- Scheduled the Logic – Azure function provide the provision to schedule the logic/code at a defined time interval. For example, in Dynamics CRM, the scheduled workflow has always been a problem? It’s been bugging us since the early days of Dynamics, and there has never been a good solution. There is still no standard/simple solution in Dynamics but stop thinking Dynamics.. think Azure Function.
- Retry the Logic – Azure function can be retried automatically in case of any error.
- Reusability – Code/logic can be called through various places (inside and outside CRM).
- Support various Languages – Check this for more info.
How to call Azure Function in Dynamics CRM?
Let\’s take a very simple requirement to understand, how Azure Functions can be called through CRM Plugin:
Create a Task which will store the Azure Function response on create of Contact record.
1. Log in to Azure
Sign in to the Azure portal at https://portal.azure.com with your Azure account.
2. Create a function app
You must have a function app to host the execution of your functions. A function app lets you group functions as a logic unit for easier management, deployment, and sharing of resources.
Select the New button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.
3. Use the function app settings as specified in the table below the image.
4, Select Create to provision and deploy the function app.
5. Select the Notification icon in the upper-right corner of the portal and watch for the Deployment succeeded message.
6. Select \’Go to resource\’ to view your new function app.
7. Click on + New function
8. Create an HTTP triggered function
9. Provide function information as shown below
10. Update the code and set first name, last name, email parameter
A function is created using a language-specific template for an HTTP triggered function.
Now, you can run the new function by sending an HTTP request.
Update Request body Parameter as below
11. Test the function
In your new function, click Get function URL at the top right, select default (Function key), and then click Copy. You\’ll get the url in below format:https://.azurewebsites.net/api/?code=
You can use Postman also in order to test your Azure Function.
Also, you can directly test the response from Azure itself.
12. Trace log of Azure Function
When your function runs, trace information is written to the logs. To see the trace output from the previous execution, return to your function in the portal and click the arrow at the bottom of the screen to expand the Logs.
13. Write Plugin to call Azure Function
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace DemoPluginToCallAzureFunction
{
public class Contact
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
}
public class AzureFunctionCaller : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains(\”Target\”) && context.InputParameters[\”Target\”] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters[\”Target\”];
using (WebClient client = new WebClient())
{
var myContact = new Contact();
myContact.firstname = entity.Attributes[\”firstname\”].ToString();
myContact.lastname = entity.Attributes[\”lastname\”].ToString();
myContact.email = entity.Attributes[\”emailaddress1\”].ToString();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Contact));
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, myContact);
var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = \”application/json\”;
// our function key
var code = \”123W1gzjHaQkJ7Xid19fRPaLCBSxbS0/107645AscDbJ5STVvrz3mjh4A==\”;
// the url for our Azure Function
var serviceUrl = \”https://mycrmtestfunapp.azurewebsites.net/api/CRM_Contact_Information?code=\” + code;
// upload the data using Post mehtod
string response = webClient.UploadString(serviceUrl, jsonObject);
// Create Task with response from Azure function
Entity taskObj = new Entity(\”task\”);
taskObj[\”subject\”] = \”Azure Function Called Successfully..\”;
taskObj[\”description\”] = \”Azure Response: \”+ response;
taskObj[\”regardingobjectid\”] = new EntityReference(\”contact\”, entity.Id);
service.Create(taskObj);
}
}
} // try end
catch (Exception ex) {
throw new InvalidPluginExecutionException(ex.Message);
}
}
}
}
How to Monitor Azure Function?
How Azure Functions Pricing Works?
Supported languages in Azure Functions?
Caching in Azure Function?
Best Practices of Azure Functions?
Thanks a lot for your time reading this article. Your feedback and suggestions are always welcome. In my next article, I\’ll explain, how Azure Functions can be written through Visual Studio. Till then,
Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well.CRM Software in indiaCRM Software in Chennai
LikeLike
This comment has been removed by a blog administrator.
LikeLike
This comment has been removed by a blog administrator.
LikeLike
Well written post! Really glad that I found your post. Thanks for sharing.Microsoft Dynamics AX Online Training
LikeLike
Hi, can you use early bound in an Azure function?
LikeLike
Your post is really awesome. Your blog is really helpful for me to develop my skills in a right way. Thanks for sharing this unique information with us.You can also check Suite/SugarCRM Product or plugin.Outright Store
LikeLike
This comment has been removed by a blog administrator.
LikeLike
Nice Blog,Keep updatesI think it’s awesome,someone share these kind of knowledge.Keep it upYou can also check here Global Hide Manager for SuiteCRM for more related information.
LikeLike
THANK YOU FOR THE INFORMATION .HI GUYS IF SEARCHING FOR CRM Solutions PLEASE VISIT USCMR Solutions
LikeLike
Wow, Great information and this is very useful for us. pomalex 4mg
LikeLike
Wow, Great information and it is very useful for us. Crm software development company in chennai
LikeLike
Hey, very nice site. I came across this on Google, and I am stoked that I did. I will definitely be coming back here more often. Wish I could add to the conversation and bring a bit more to the table, but am just taking in as much info as I can at the moment. Thanks . DedicatedHosting4u.com
LikeLike
It’s interesting to read content. nice post.Microsoft Dynamics Online Training
LikeLike
what is fantastic post? this is so chock full of useful information I cannot wait to dig deep and start utilizing the resource give me.your exuberance is refreshing.Software Development Travel portal development Travel white label Travel Portal Solution B2C Travel Portal B2B Travel Portal Flight Booking API System Flight api integration
LikeLike
Great. It is good to constantly coming up with creative ideas. Provides much needed knowledge. goal oriented blog posts and always tried to find creative ways to meet goals.ThanksOnline affiliates
LikeLike
The points you have mentioned are interesting to use in the practical process. This is very beneficial for everyone … thank you for providing us with such useful information. DedicatedHosting4u.com
LikeLike
This way is not working in function app. If you want to perform Crud Operation with dynamics then you need to follow few steps i have publish a blog on this. Please give your valuable feedback on that-https://www.linkedin.com/pulse/dynamics-365-web-api-authentication-example-azure-govind-chouksey?articleId=6577866233704734720#comments-6577866233704734720&trk=public_profile_article_view
LikeLike
Great post.It seems to be interesting and gave me lot of information,Thank for sharing it.I am looking forward for new articles.keep it up.Website Development Company in Bangalore | Website Design Company in Bangalore | Mobile App Development Companies in Bangalore | Game Development Companies in Bangalore
LikeLike
Great post with unique information.This blog will really helpful for me to develop my skills in a right way.Thanks for sharing,keep update with your blogs. Website Design Company in Bangalore | Mobile App Development Companies in Bangalore | Website Development Company in Bangalore
LikeLike
This article is so great! Thank you for sharing this awesome information. Microsoft Azure DevOps TrainingAzure DevOps Online Training in Hyderabad
LikeLike
This is a nice article you shared great information I have read it thanks for giving such a wonderful Blog for the reader.SQL Azure Online TrainingAzure SQL Training SQL Azure Training
LikeLike
Great article …Thanks for your great information, the contents are quiet interesting.MS Azure Training in HyderabadMS Azure Training in AmeerpetMicrosoft Azure Training in HyderabadAzure TrainingAzure Online TrainingMS Azure Online Training
LikeLike
HI,This is an awesome article but 99% complete. I don't know why you left 1% which is showing Registration of the Plugin using Plugin Registration Tool and finally show the Azure Function Response. I really appreciate to complete this article.
LikeLike
Very good article but it does´t working for me. In my case, I have as response the error : 502 Bad gateway. Any clue why I have this error? I'm in a dead end.
LikeLike
nice and needed information which i wantgrandwebstoresThankyou 🙂
LikeLike
Very useful information, the post shared was very nice.Microsoft Azure DevOps Online Training
LikeLike
Very significant Information for us, I have think the representation of this Information is actually superb one. This is my first visit to your site. Travel Portal Development
LikeLike
I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.Best CRM System
LikeLike
ecommerce website development company in chennai, crm software development company in chennai, software development company in chennai, web hosting service provider in chennai
LikeLike
abinitio trainingspark trainingscala trainingazure devops training
LikeLike