Using Azure Functions for writing Scheduled Jobs for Dynamics CRM


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/

 

In our previous post we saw how we can invoke CRM from within the Azure Function.

https://nishantrana.me/2017/04/28/call-dynamics-crm-from-azure-functions/

Using that knowledge, let us now write an Azure Function that will run periodically.

Here we will take a simple example of creating a lead record every 2 minutes. Obviously real world scenario would involve much complex scenario like checking the status of all the open records and update them daily something of that sort.

Another way of writing a scheduled job is using Web Job I have written about it over here.

https://nishantrana.me/2017/03/21/dynamics-crm-web-job-and-azure-scheduler/

Login to Azure Portal and create a new Function App

Create a new function with Timer and CSharp template.

function.json bindings defines the schedule for the timer, it take a CRON expression for value schedule.

CRON Expression format: –

If we want it to run every 2 minute

Back to our code let us click on Run and test it.

Now let us quickly plumb the code to create Lead in CRM.

Go to App Service Editor for the Function App and add new a file named project.json which refers to the CRM Nuget Package.

Sample code that creates the lead record in CRM.


using System.Net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;

public static void Run(TimerInfo myTimer, TraceWriter log)
{
IServiceManagement orgServiceManagement = ServiceConfigurationFactory.CreateManagement(new Uri("https://nishutrial.crm.dynamics.com/XRMServices/2011/Organization.svc"));

AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = "test@test.onmicrosoft.com";
authCredentials.ClientCredentials.UserName.Password = "*******";
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
Entity lead = new Entity("lead");
lead.Attributes["subject"] = "Lead Created at" + DateTime.Now ;
organizationProxy.Create(lead);

log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
}

Inside CRM

To monitor our Azure Function please select Monitor

Click on live event stream to monitor it real-time.

To stop or disable the function, select Manage and click on function state Disabled.

Hope it helps..

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

Using Dialogs in Microsoft Bot Framework (Creating lead in CRM)


Let us continue with our previous post on Bot Framework

https://nishantrana.me/2017/04/18/getting-started-with-microsoft-bot-framework/

Here we will implement our own dialog.

Dialogs are basically a class which implements IDialog interface. Dialog sends a message to the user and is in suspended state till it waits for the response from the user. The state is saved in State Service provided by Bot Connector Service.

Here MyDialog is our dialog class which implements the IDialog Interface i.e. implement StartAsync method which would be the first method called. We also need to mark our class as Serializable.

Next we need to update our controller class to point it to our new MyDialog class.

Here we will ask the user about the product in which he is interested, then get the name and description and finally using this information we will create a Lead record inside CRM.

The lead record created in CRM.

Here we are making use of PromptDialog type for managing interactions with the user. Using PromptDialog we can easily prompt user for text, choice, attachment, confirmation etc.

The context here is the IDialogContext. In resume parameter, we can specify which dialog methods to be called next after the user has responded. The response from the user is passed to the subsequent dialog methods.


using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Bot_Application1.Dialogs
{

public enum InterestOptions
{
Product1,
Product2,
Product3
}

// Decorate the class with Serializable attribute
[Serializable]
// Implement IDialog Interface
public class MyDialog : IDialog
{
InterestOptions interestOptions;
string name;
string description;

// Start Sysnc is the first method which is called
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("Hi how may i help you?");
// wait for the user's response
context.Wait(MessageRecieveAsync);
}

public virtual async Task MessageRecieveAsync(IDialogContext context, IAwaitable argument)
{
// get the message
var message = await argument;

if (message.Text.Contains("interested"))
{
PromptDialog.Choice(
context: context,
resume: ResumeGetInterest,
options: (IEnumerable<InterestOptions>)Enum.GetValues(typeof(InterestOptions)),
prompt: "Which product are your interested in :",
retry: "I didn't understand. Please try again.");
}

}

public async Task ResumeGetInterest(IDialogContext context, IAwaitable result)
{
interestOptions = await result;

PromptDialog.Text(
context: context,
resume: ResumeGetName,
prompt: "Please provide your name",
retry: "I didn't understand. Please try again.");
}

public async Task ResumeGetName(IDialogContext context, IAwaitable result)
{
name = await result;

PromptDialog.Text(
context: context,
resume: ResumeGetDescription,
prompt: "Please provide a detailed description",
retry: "I didn't understand. Please try again.");
}

public async Task ResumeGetDescription(IDialogContext context, IAwaitable result)
{
description = await result;
PromptDialog.Confirm(
context: context,
resume: ResumeAndConfirm,
prompt: $"You entered Product :- '{interestOptions}', Your Name - '{name}', and Description - '{description}'. Is that correct?",
retry: "I didn't understand. Please try again.");
}

public async Task ResumeAndConfirm(IDialogContext context, IAwaitable result)
{
bool confirm = await result;

if (confirm)
await context.PostAsync("Thanks for showing your interest we will contact you shortly.");

// Create a lead record in CRM
CreateLeadinCRM();

}

private void CreateLeadinCRM()
{
Microsoft.Xrm.Sdk.Entity lead = new Microsoft.Xrm.Sdk.Entity("lead");
lead.Attributes["subject"] = "Interested in product " + interestOptions;
lead.Attributes["lastname"] = name;
lead.Attributes["description"] = description;
GetOrganizationService().Create(lead);
}

public static OrganizationServiceProxy GetOrganizationService()
{
IServiceManagement<IOrganizationService> orgServiceManagement =
ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("https://nishantcrm365.crm.dynamics.com/XRMServices/2011/Organization.svc"));

AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = "nishant@nishantcrm365.onmicrosoft.com";
authCredentials.ClientCredentials.UserName.Password = "*****";
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);
return new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
}
}

}

The next posts in this series

Hope it helps..

List of all blog posts on CRM and Azure Integration


 

Advertisements

Configure Automatically suggest knowledge articles using Cognitive Services Text Analytics (Preview) in Dynamics 365 (online)


As a first step, we need to set up Text Analytics Service and connect it to our CRM Online. Follow the below post for that

https://nishantrana.me/2017/03/24/configure-case-topic-analysis-using-cognitive-services-text-analytics-preview-in-dynamics-365-online/

Next, we need to set up Knowledge Search field settings

For this go to Settings – Service Management and click on Knowledge Search field Settings

There click on New to create a new Search Model record.

Below we have specified case as our source entity. Click on Save.

Next, we need to define Keyword fields for our model, click on + to create a new text analytics entity mapping record.

To keep things simple, we have selected entity as Case and Field as Case Title based on which suggestions will be made. Save the record.

Click on Activate to activate the model.

Next, we need to modify the Case form to include knowledge base suggestions

Open the Conversation Tabs, go to Knowledge Base Search and select Text Analytics for Give Knowledge base suggestions as described below and publish the form

Open any of the case record, go to KB Records. Here based on the Case Title, the text analytics picks up the keyword “Delay” and shows/suggests the corresponding KB Articles matching that keyword.

Get all the details here

https://technet.microsoft.com/en-us/library/mt703319.aspx

Hope it helps..

Configure Document Suggestions using Cognitive Services Text Analytics (Preview) in Dynamics 365 (online)


Let us take a simple example to understand how to configure Document Suggestion preview feature.

To do so first we need to enable Text Analytics Service, Connect it to our CRM Online and configure similar record suggestions. Please follow the below post for all the details.

https://nishantrana.me/2017/03/27/configure-similar-record-suggestion-using-cognitive-services-text-analytics-preview-in-dynamics-365-online/

Go to Settings – Document Management – Manage Document Suggetions

Select the entity for which we want to enable it, as we had our similar record suggestions enabled for Case we select the Case entity here.

Click on Apply.

Now as we already have Similar Record Suggestions configured for Case entity, for a case record with Delay keyword in its title we get the below suggestions

So, for Delay in Dispatch record we are getting Delay in service, delivery and shipment as suggestions as similar cases.

Now what we have done over here next is that we have attached document(s) to each of these case records.

For Delay in Dispatch case record –

For Delay in Service case record –

For Delay in Shipment record we have 2 document attached.

For Dispatch in Delivery case record we do not have any document attached yet.

Now let us open case with title “Dispatch in Delivery” and go to its Documents related records and click on Show Suggestions button

A dialog opens which list all the documents that are associated to the case records similar to the Delay in Delivery record i.e. all the remaining case records having delay keyword in its title.

Select documents and click on Copy.

Documents Copied to the Delay in Delivery record.

Hope it helps..