Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, March 29, 2017

Integrating Microsoft Azure Service Bus with Sitecore 8.2



Azure service bus is super useful when you want to integrate external system with Sitecore.
Let’s say you have external system which release some data on periodic basis. We want to process this data and perform create/update/delete item operation in Sitecore.

 
Azure Service Bus
Azure Service Bus

How to do that?

Sender

External system send the data in the form of JSON format and drop in Azure service bus messaging queue.

We are using below code for reading data from file and pushing JSON data message to Azure service bus as

using Microsoft.ServiceBus.Messaging;
using System;
using System.Configuration;
using System.IO;
using System.Web.Http;
public string PushData()
{
    string result = "success";

    try
    {
        string content = File.ReadAllText(ConfigurationManager.AppSettings["JSONFilePath"]);

        var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
        var queueName = ConfigurationManager.AppSettings["QueueName"];

        var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

        var message = new BrokeredMessage(content);
        client.Send(message);
    }
    catch (Exception ex)
    {
        result = ex.Message;
    }

    return result;
}


Receiver

We will create scheduler in Sitecore which polling this service bus after regular interval. These intervals are scheduled as per business needs.

In below code, we will get all the messages from Azure service Bus and if we are able to create Sitecore item successfully then we will mark that service bus message to be deleted from queue otherwise we will reprocess that message in next cycle of scheduler.

/// <summary>
/// Execute method is called by Sitecore scheduler
/// </summary>
/// <param name="items"></param>
/// <param name="command"></param>
/// <param name="schedule"></param>
public void Execute(Item[] items, Sitecore.Tasks.CommandItem command, Sitecore.Tasks.ScheduleItem schedule)
{
    try
    {
        var connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];
        var queueName = ConfigurationManager.AppSettings["QueueName"];

        var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

        int counter = 1;

        var destinationTemplateId = "{7DA49B50-B1C3-4410-9C4C-9FBC4945935F}";
        string destinationPath = "{ED84594E-47E2-4FA1-9689-6BCF874DC04F}";

        OnMessageOptions omp = new OnMessageOptions();
        omp.AutoComplete = false;
        omp.AutoRenewTimeout = new TimeSpan(0, 1, 0);

        client.OnMessage((message) =>
            {
                try
                {
                    var myContent = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(message.GetBody<string>());

                    //Code to Store it in Sitecore
                    var item = CreateSitecoreItem(destinationPath, myContent.Title, destinationTemplateId, myContent.FirstName, myContent.LastName);

                    if (item != null)
                    {
                        //This is important step as if we able to create item in sitecore then we will mark delete the message from service bus queue
                        message.Complete();
                    }

                }
                catch (Exception ex)
                {
                    //This is important step as if we unable to process this message, we will process it again in next cycle
                    message.Abandon();
                    File.AppendAllText("d:\\error.txt", ex.Message + Environment.NewLine);
                }
            }, omp);
    }
    catch (Exception ex)
    {
        var result = ex.Message;
    }
}

private Item CreateSitecoreItem(string destinationPath, string itemName, string targetTemplateId, string firstName, string lastName)
{
    Item sitecoreItem = null;
    try
    {
        // The SecurityDisabler overrides the current security model, allowing you
        // to access the item without any security. It's like the user being an administrator
        using (new Sitecore.SecurityModel.SecurityDisabler())
        {
            // Get the master database
            Database master = Database.GetDatabase("master");
            // Get the place in the site tree where the new item must be inserted
            Item parentItem = master.GetItem(destinationPath);
            if (parentItem != null)
            {
                // Get the template to base the new item
                TemplateItem template = master.GetItem(targetTemplateId);
                // Add the item to the site tree
                sitecoreItem = parentItem.Add(itemName, template);
            }
            if (sitecoreItem != null)
            {
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    sitecoreItem.Editing.BeginEdit();

                    if (sitecoreItem.Fields["First Name"] != null)
                    {
                        sitecoreItem.Fields["First Name"].Value = firstName;
                    }

                    if (sitecoreItem.Fields["Last Name"] != null)
                    {
                        sitecoreItem.Fields["Last Name"].Value = lastName;
                    }

                    sitecoreItem.Editing.EndEdit();

                    File.AppendAllText(HLConstants.LogPath, Environment.NewLine + "Created new item " + firstName + " " + lastName + Environment.NewLine);
                }
            }
        }
    }
    catch (Exception ex)
    {
        File.AppendAllText(HLConstants.LogPath, "add New Item " + itemName + " Error Message " + ex.Message + " ---- " + "trace " + ex.StackTrace + Environment.NewLine);
    }

    return sitecoreItem;
}

You can learn about Service Bus Messaging at https://docs.microsoft.com/en-us/azure/service-bus-messaging/

I hope you like this Sitecore article. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this article if it’s useful for you.