Inkey Solution Logo
banner

Blogs

Integrate external web resource with Microsoft Dynamics 365 using Azure Service Bus & Logic App

, September 5, 2018 4821 Views

Today in this blog, I will explain how we can communicate with the Microsoft dynamics 365 from an external website using Azure Service Bus & Logic App.

Using Logic App we can create, update, return list of records etc from the CRM. Below is an example of how we can create the record in the CRM on trigger from an external resource such as website, mobile app etc.

For this, I have created a web API(c#) and added a class (Model), with the required parameters:-

Model class

public class RecordDetails
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
}

And, below is the controller class performing the logic that connects to the Azure Logic App using Service Bus.

Note:- You will require below namespaces in the controller. You can download it from NuGet gallary:-

using System;
using System.Web.Http;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.Configuration;
using Microsoft.Azure;
using Microsoft.ServiceBus;

Controller Class

[RoutePrefix("api")]
 public class CreateRecordController : ApiController
 {
    [HttpPost]
    [Route("CreateRecordDetails")]
    public IHttpActionResult CreateRecordDetails([FromBody] RecordDetails parameters)
    {
     try
     {
        #region Check the state of the Model

        //If the Model State is invalid, then, return Error response
        if (!ModelState.IsValid)
        {
          return BadRequest(ModelState);
        }

        #endregion

   	  #region Send parameters send to the controller to Azure servicebus
   	
        //Create the MessageSender object
   	  MessageSender sender = CreateSender();
   	  if (sender != null)
   	  {
         //Serialize Object
     	   string recordDetailsAttributeValues = JsonConvert.SerializeObject(parameters, 
             new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

    	    //Send Message to the Azure ServiceBus
    	    byte[] bytes = Encoding.UTF8.GetBytes(recordDetailsAttributeValues);
    	    MemoryStream stream = new MemoryStream(bytes, writable: false);
    	    sender.Send(new BrokeredMessage(stream));
    	    result = Ok("The data has been submitted successfully.");
  	  }
      else
 	  {
    		result = BadRequest("Could not connect the Azure Service Bus.");
 	  }
 	
  #endregion
   }
   catch (Exception ex)
   {
     throw new Exception(ex.Message);
    }
    return result;
  }

 #region CreateSender
 /// <summary>
 /// Create the Message sender object to access Service Bus of Azure portal
 /// </summary>
 /// <returns>MessageSender Object</returns>
 private static MessageSender CreateSender()
 {
    #region Variable declarations

    string keyName = string.Empty;
    string accessKey = string.Empty;
    string baseAddress = string.Empty;
    string topicName = string.Empty;
    MessageSender sender = null;

    #endregion

    try
    {
      //Get Service Bus details from local app settings
      keyName = ConfigurationManager.AppSettings["SvcBusSharedAccessKey"];
      accessKey = ConfigurationManager.AppSettings["SvcBusAccessKey"];
      baseAddress = ConfigurationManager.AppSettings["SvcBusBaseAddress"];
      topicName = ConfigurationManager.AppSettings["SvcBusTopicName"];

      //Create the Message sender object
      TokenProvider tokenProvider =
             TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, accessKey);
      MessagingFactory messagingFactory = 
             MessagingFactory.Create(baseAddress,  tokenProvider);
      sender = messagingFactory.CreateMessageSender(topicName);
    }
    catch (Exception ex)
    {
      throw new Exception(ex.Message);
    }
    return sender;
    }
#endregion
}

In the above web API, we are sending all the data received from the external resource / website to the Azure Logic App. The External website will call this web API and pass the fields as parameter with values to create in CRM.

You need to set the Service Bus details in Web.config file as follows:-

<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="SvcBusSharedAccessKey" value="SharedAccessKeyName from the Primary Connection String of the Service Bus goes here" />
    <add key="SvcBusAccessKey" value="SharedAccessKey from the Primary Connection String of the Service Bus goes here" />
    <add key="SvcBusBaseAddress" value="Endpoint from the Primary Connection String of the Service Bus goes here" />
    <add key="SvcBusTopicName" value="Topic name goes here" />
  </appSettings>
</configuration>

To get the Service Bus details, navigate as follows in Azure portal:-

Home → Resource groups → Click on your resource group link → Click on your Service Bus namespace link → Go to the (SETTINGS→ Shared Access Policies) → Click on the Policy → Copy the Primary Connection String

From the ‘Primary Connection String’ of the Service Bus, you will get the SvcBusSharedAccessKey, SvcBusAccessKey & SvcBusBaseAddress.

You can get the Topic name from Service Bus namespace by navigating from Home → Resource groups → Click on your resource group link → Click on your Service Bus namespace link → Go to the (ENTITIES→ Topics) → Copy the name

Now, let us see how the Logic App will consume the data that we send and how the record will be created in the CRM.

The flow of the Logic App will be as follows:-

Here, the first step is to create the Service Bus, that receives the data that we send from the web API.

Please refer the below link to know, how to create Service Bus in Logic App:-
https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-create-namespace-portal

The second step is to parse the JSON message received from the Service Bus to user friendly tokens for Logic App consumption.

The Parse JSON Component of the Logic App is having two parts:-

1. Content

This will have the function as below to convert the message received from the Service Bus to user friendly tokens:

substring(base64ToString(triggerBody()?['ContentData']), indexof(base64ToString(triggerBody()?['ContentData']), '{'), sub(lastindexof(base64ToString(triggerBody()?['ContentData']), '}'),indexof(base64ToString(triggerBody()?['ContentData']), '{')))

2. Schema
Here, we need to declare all the fields send from the controller and send it as an object:-

{
  "properties": {
    "FirstName": {
       "type": "string"
     },
    "LastName": {
       "type": "string"
     },
    "Address": {
       "type": "string"
     }
   },
   "type": "object"
}

After the JSON object is parsed, the next step is to create the record in dynamic CRM.

Please refer the below link to know how to create record in CRM from Logic App:-
https://docs.microsoft.com/en-us/azure/connectors/connectors-create-api-crmonline

Now, we need to just call our web API from the external resource such as website, mobile app etc. And the record will then be created in the CRM.

Please refer the below link to know in detail how to call the web API that we have created above, from an external resource to create record in CRM using Azure Service Bus & Logic App.

Access the Azure Logic App using Service Bus to connect Microsoft Dynamics 365 from an external website

 

I hope this helps you!!

Happy CRMing.


 

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/drag-and-drop-listbox

Create a personal / system view in Dynamics CRM with all the fields on the form/s which you select for a particular entity using the View Creator.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/view-creator

mm

Inkey

INKEY is your solution partner.
Our focus is to deliver you in-time intelligent innovative solutions ("key") for the problems in hand. Maintaining a quality standard right from the inception of a project is our top most priority.

Our team of talented professionals will execute your projects with dedication and excellence. We take ownership and accountability for the effort that goes into meeting our client’s needs.

Years of experience and proven success of delivering innovative custom solutions.

More posts by

One response to “Integrate external web resource with Microsoft Dynamics 365 using Azure Service Bus & Logic App”

  1. […] Integrate external web resource with Microsoft Dynamics 365 using Azure Service Bus & Logic App […]

Leave a Reply

Your email address will not be published. Required fields are marked *

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Drop file here

Would you like to digitize your business and put it on the cloud?
Do you need clear, concise reports for your organization?