Configure Dynamics 365 and Azure Service Bus Integration


As we know, we can connect Dynamics 365 with Azure platform by coupling Dynamics 365 event execution pipeline to the Microsoft Azure Service Bus. Once configured, this connection allows data that’s been processed as current Dynamics 365 operation to be posted to the service. Microsoft Azure Service Bus solutions that are “Dynamics-365 aware” can listen for and read the Dynamics 365 data from the service bus.There are many ways to establish a contract between Dynamics 365 and an Azure solution as below.

  • Queue
  • One-way
  • Two-way
  • Rest
  • Topic
  • Event Hub

In this post, I will use “Queue” contract where a listener doesn’t have to be actively listening for messages on the endpoint.
Let’s implement a basic scenario – When a record is created in CRM then pass the execution context to queue and then prepare a application to read and display the entity information.

Lets first configure Azure to create a Queue listener using Azure Portal(https://portal.azure.com).

  1. Create a Service Bus by click on “Add” button.

    2. Enter mandatory fields as below.

3. Create a Queue in newly created Service Bus(mcstaging in my case)

4. Create SAS Policy for Authorization and copy the Primary Connection String which is required during end point registration in CRM

Now let’s create service endpoint in CRM using plugin registration tool.
Login into plugin registration tool and click on Register ->Register New Service End Point as below


Copy the primary connection string form  step 4 and click on “Next”

All information will be populated automatically and then click on “Save”.
Now, need to register a step for this endpoint(In my case, custom entity Enquiry(mc_feedback)  on create message).


Now create a enquiry record in CRM, once you create a record in CRM a system job will be created and message will be passed to azure queue created earlier.

You can see one message in queue as below


Now, how to read the message from Queue. Lets create a console application to read the message from Queue.
Here the connection string will be the same which we had specified in the plugin registration tool. The message body is of type RemoteExecutionContext.


Output

 

Retrieve data from N-N relationship in CRM


Sharing a sample code to retrieve data from N-N relationship in CRM. We have a trainer profile which have N-N relationship with Centre that means one trainer can visit to multiple centre and one centre can be assigned to multiple trainers. Here we are trying to retrieve list of centres associated with particular trainer.

List<Centre> centreList = new List<Centre>();
QueryExpression query = new QueryExpression(“mc_centre”);
query.ColumnSet = new ColumnSet(new string[] { “mc_centreid”, “mc_name” });

LinkEntity linkEntity1 = new LinkEntity(“mc_centre”, “mc_mc_trainer_mc_centre”, “mc_centreid”, “mc_centreid”, JoinOperator.Inner);
LinkEntity linkEntity2 = new LinkEntity(“mc_mc_trainer_mc_centre”, “mc_trainer”, “mc_trainerid”, “mc_trainerid”, JoinOperator.Inner);

linkEntity1.LinkEntities.Add(linkEntity2);
query.LinkEntities.Add(linkEntity1);

linkEntity2.LinkCriteria = new FilterExpression();
linkEntity2.LinkCriteria.AddCondition(new ConditionExpression(“mc_trainerid”, ConditionOperator.Equal, new Guid(trainerId)));

EntityCollection centreCollection = service.RetrieveMultiple(query);
if (centreCollection.Entities.Count > 0)
{
foreach (var centre in centreCollection.Entities)
{
Centre cr = new Centre();
cr.centreId = centre.Attributes[“mc_centreid”].ToString();
cr.centreName = centre.Attributes[“mc_name”].ToString();
centreList.Add(cr);
}
}

return centreList

Execute Workflow using Web API in Dynamics 365


Sharing sample code to call workflow using Web API from JavaScript.
First, we will create a normal workflow which works on demand and a create task with predefined subject and description and activate the workflow.Workflow

Copy the workflow Id and save it to use in JavaScript function.Call below JavaScript function from ribbon button from Lead entity.

function CallWorkflow() {
var workflowId = “71A6BC35-16D8-4447-8ADE-F040CDAE9524″;
var clientURL = Xrm.Page.context.getClientUrl();
var leadId = Xrm.Page.data.entity.getId().replace(‘{‘, ”).replace(‘}’, ”);
var data = {
“EntityId”: leadId
};
var req = new XMLHttpRequest();
req.open(“POST”, clientURL + “/api/data/v8.2/workflows(“+workflowId+”)/Microsoft.Dynamics.CRM.ExecuteWorkflow”, true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(JSON.stringify(data));
}
For more details, please refer below URL
http://www.inogic.com/blog/2016/11/execute-workflow-using-web-api-in-dynamics-365-2/
hope this helps.

 

Execute Action using Web API in Dynamics 365


Sharing simple scenario to call custom action from JavaScript (from ribbon button).
First of all, create an Action for Sales Order entity and a step to change status to Active(New) as shown below.
Action

Call below function form ribbon button to change the status of Sales Order to New.

function ChangeAgreementStatus() {
var Id = Xrm.Page.data.entity.getId().replace(‘{‘, ”).replace(‘}’, ”);
var clientURL = Xrm.Page.context.getClientUrl();

// pass the id as inpurt parameter
var data = {
“agreementid”: Id
};

var req = new XMLHttpRequest();

// specify name of the entity, record id and name of the action in the Wen API Url
req.open(“POST”, clientURL + “/api/data/v8.2/salesorders(” + Id + “)/Microsoft.Dynamics.CRM.new_ActivateAgreement”, true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var data = JSON.parse(this.response);
alert(data);
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};

// send the request with the data for the input parameter
req.send(window.JSON.stringify(data));

//Refresh form
Xrm.Page.data.refresh();
}

For details, please refer below URL.

https://community.dynamics.com/crm/b/nishantranaweblog/archive/2017/05/27/sample-code-to-call-action-using-web-api-in-crm

hope this help you

Debug WCF Restful service (POST/GET) – Part 2


There are many way to debug WCF/Cloud service hosted in Azure and you can refer the below tutorial but I prefer to debug the service old and easy way by deploying the service in local IIS then publish to Azure.

https://docs.microsoft.com/en-us/azure/vs-azure-tools-debug-cloud-services-virtual-machines

https://docs.microsoft.com/en-us/azure/vs-azure-tools-debugging-cloud-services-overview

In Part 1, I explain how to create and deploy WCF Restful service in Azure.

https://arvindcsit.blog/crm-and-azure-integration/

I will use the same existing code and will add another POST method to explain debugging.

I am going to create one POST method which takes User Name and Password as request body and return predefined token.

So I added below code in Part 1 source code.

Contract: ICRMService.cs

Under ServiceContract

[OperationContract]
[WebInvoke(Method = “POST”,
UriTemplate = “/getauth”,
ResponseFormat = WebMessageFormat.Json)]
CRMTokenResponse GetCRMToken(CRMTokenRequest tokenReqeust);

DataContract
[DataContract]
public class CRMTokenResponse
{
public CRMTokenResponse()
{
this.Token = “”;
this.Error = “”;
}
[DataMember(IsRequired = false)]
public string Token { get; set; }
[DataMember(IsRequired = false)]
public string Error { get; set; }
}
[DataContract]
public class CRMTokenRequest
{
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
CRMService.svc.cs
public CRMTokenResponse GetCRMToken(CRMTokenRequest tokenRequest)
{
CRMTokenResponse resp = new CRMTokenResponse();
if (tokenRequest != null)
{
string userName = WebConfigurationManager.AppSettings[“CRM.Username”];
string password = WebConfigurationManager.AppSettings[“CRM.Password”];
string tokenId = WebConfigurationManager.AppSettings[“CRM.Token”];
if (tokenRequest.Username == null || tokenRequest.Password == null)
{
resp.Error = “Enter UserName and Password”;
return resp;
}
if (tokenRequest.Username.Equals(userName) && tokenRequest.Password.Equals(password))
{
resp.Token = tokenId;
}
else
{
resp.Error = “Invalid Username & Password”;
}
}
else
{
resp.Error = “Request is Null”;
}
return resp;
} 

Web.config

Add these three lines under <appSettings></appSettings> tag.
<add key=”CRM.Username” value=”Arvind” />
<add key=”CRM.Password” value=”Singh” />
<add key=”CRM.Token” value=”8178746c24b9f5544d259f2a38d7c1a785bc70a2″ />

We are done with code changes, make sure you build the project in Debug mode and deploy in local IIS.

Browse the service and make sure the service is running without any error. I will use PostMan to hit and debug the service.

Set the breakpoint and attached to W3WP process. Select the Content Type and Request Body as below.

Then Click “Send” and cursor will stop at breakpoint as shown below.

you can see the token value while debugging as below

Finally, you get output in output window of PostMan as below.

Similarly, you can debug it for GET method. Once your service is working fine, you can publish your service to Azure using steps mentioned in PART 1 (https://arvindcsit.blog/crm-and-azure-integration/)

Hope this helps you.

 

 

 

 

Check open activity related case using oData query


Sharing below code which returns some value using oData query. This function will check if there is any open activity related to Incident entity.

function CheckOpenActivity() {

var Id = parent.Xrm.Page.data.entity.getId();

var IncidentId = Id.substring(1, 37);

//Retrieve dynamically the organization’s server url

var serverUrl = document.location.protocol + “//” + document.location.host + “/” + Xrm.Page.context.getOrgUniqueName();

var ODATA_ENDPOINT = “/xrmservices/2011/OrganizationData.svc”;

var ODATA_EntityCollection = “/IncidentSet?$select=IncidentId,Incident_ActivityPointers/ActivityId,Incident_ActivityPointers/StateCode&$expand=Incident_ActivityPointers”;

var ODATA_Filter1 = “&$filter=IncidentId eq guid'” + IncidentId + “‘”;

var oDataRequestUrl = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Filter1;

var result = syncODataCall(oDataRequestUrl);

var isOpenActivity = ProcessReturnedEntities(result);

if (isOpenActivity)
alert(‘The Case has open Activity’);
else
alert(‘The Case has not any open Activity’);

}

// function to make synchronous oData call

function syncODataCall(odataSelect) {

var request = new XMLHttpRequest();

request.open(“GET”, odataSelect, false);

request.setRequestHeader(“Accept”, “application/json”);

request.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

request.send();

var objJQuery = jQuery.parseJSON(request.responseText);

return objJQuery.d

}

function ProcessReturnedEntities(d) {

var hasRelated = false;

if (d.results[0] != null) {

var activities = d.results[0].Incident_ActivityPointers;

if (activities != null) {

if (activities.results.length > 0) {

$.each(activities.results, function (index) {

if (activities.results[index].StateCode.Value == ‘0’) {

hasRelated = true;
return hasRelated;

}
});

} else {
hasRelated = false;
return hasRelated;
}

} else {
hasRelated = false;
return hasRelated;
}
}
return hasRelated;
}

 

Hope this help you.