New to Azure Function?
Function is serverless offering form Azure. Serverless computing is a way to write code without need to manage infrastructure, application dependencies and other required resources. Even for scaling Azure will take care of them. Once we know the environment using Function is easy, login to Azure portal write or deploy code and start using it.
An Azure function is simply a function written in C#, Java, JavaScript, F#, Python or PHP. A function can be executed manually or scheduled to run automatically. The third way to execute a function is through triggers. A trigger can be another Azure service or something which has no link with Azure. Some Azure services which can trigger a function are Cosmos DB, Event Hubs, App Service, Storage queues, blobs, Service Bus queues or topics. Functions are also available for Logic Apps, Power Apps, Microsoft Flow and outside Azure over HTTP.
About Demo
This function will be scheduled to run once in 24 hours. From ftp server it will read a CSV file (data for lead entity) and pass it to CRM. Functions can be coded and published from Visual Studio or directly in Azure portal, for this demo I will use later approach.
Create Function App and Function
To create a function we need to create a function app. If you don’t want to use existing resource group and storage feel free to create new.
Open function app and add a function in it:
In Schedule add 0 0 12 * * *. This cron expression will trigger this function in midnight at 12 O’clock. See this for more details about cron expression.
App Settings
Let’s add CRM connection string, FTP URL and credentials as application settings to avoid hard coding.
Sample of application settings:
Key Value Comments FtpId UserId Ftp account user id FtpPassword P@ssword Ftp account password FtpAddress ftp://ftp.domain.com/full.csv Ftp address with file name Connectionstring AuthType = Office365; Url = https://crminstace.crm6.dynamics.com/; UserName=crmuser@domain.com;
Password=crmP@ssword
This is example with Dynamics 365, no need to surround with single or double quote.
Code
using System;using System.Configuration;using System.IO;using System.Net;using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Host;using Microsoft.Xrm.Sdk;using Microsoft.Xrm.Tooling.Connector;public static void Run(TimerInfo myTimer, TraceWriter log){log.Info($”Execution Started. : {DateTime.Now} “);Stream fileStream = null;string[] fileContentToWriteToCRM;IOrganizationService org;string ftpId = ConfigurationManager.AppSettings[“Ftpid”].ToString();string ftpAddress = ConfigurationManager.AppSettings[“ftpAddress”].ToString();string ftpPassword = ConfigurationManager.AppSettings[“ftpPassword”].ToString();#region Read Ftp File(s)FtpWebRequest ftpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpAddress);ftpReq.Credentials = new NetworkCredential(ftpId, ftpPassword);ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;ftpReq.EnableSsl = false;WebResponse tmpRes = ftpReq.GetResponse();fileStream = tmpRes.GetResponseStream();#endregion#region ProcessDataTextReader tmpReader = new StreamReader(fileStream);var txtData = tmpReader.ReadToEnd();fileContentToWriteToCRM = txtData.Split(new string[] { “\r\n” }, StringSplitOptions.RemoveEmptyEntries);#endregion#region CRM Data Postingstring connectionstring = ConfigurationManager.AppSettings[“connectionstring”];CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionstring);org = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;log.Info($”CRM connection established”);log.Info($”Looping to move data to CRM”);foreach (var row in fileContentToWriteToCRM){var rowvalues = row.Split(‘,’);Entity lead = new Entity(“lead”);lead.Attributes[“subject”] = rowvalues[0].ToString();lead.Attributes[“firstname”] = rowvalues[1].ToString();lead.Attributes[“lastname”] = rowvalues[2].ToString();var id = org.Create(lead);log.Info($”Lead created in CRM with GUID : {id} “);}log.Info($”Loop Ended moved all data to CRM “);#endregion}
Adding Dependencies
Since code use assemblies from CRM SDK, we will add these to our code. With Azure Function it is achieved using project.json file. Add project.json file if it is not already there and then add NuGet packages in it.
{“frameworks”: {“net46”:{“dependencies”: {“Microsoft.CrmSdk.CoreAssemblies”: “9.0.0.0”,“Microsoft.CrmSdk.XrmTooling.CoreAssembly”:”9.0.0.7″}}}}
Result
Hope this help, enjoy your 365 day 🙂
Cheers
About Me 🙂
I m an IT consultant working in Melbourne Australia. I solve business problems using Microsoft technologies (Dynamics 365, Office 365, Azure, Flow, Power Apps, Power BI). I m involved in community activities and I blog at http://www.crmtechie.com/
I love to get connected with people working in IT, providing solutions or who just like Microsoft technologies. To get in touch please follow my blog, and connect through Linkedin, Twitter or Facebook
Blog: http://www.crmtechie.com/
Twitter: @YawerIqbal
Linkedin: YawerIqbal
Facebook: Yawer.Iqbal
neat idea!
Thank you, glad you like it 🙂