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.

Tuesday, March 28, 2017

How to change log level of Sitecore log files



On one of our Sitecore hosted server, log files sizes are growing rapidly. We are fine with few MB, but some of our search logs are growing more than 300 MB as shown below

Logs file in Data\logs folder
Logs file in Data\logs folder

Instead of logging everything, we want to log only error messages to reduce the file sizes.

How to achieve it?

Open your Sitecore web.config file.

Find “<log4net>” and locate logger section for “SearchLogFileAppender

Change its level from INFO to ERROR as

    <logger name="Sitecore.Diagnostics.Search" additivity="false">
      <level value="ERROR"/>
      <appender-ref ref="SearchLogFileAppender"/>
    </logger>

Now your search log should only record searching related errors.

In same way, you can also change log level for Crawling, WebDAV, publishing and Sitecore logs files.

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

Till that happy Sitecoring :)

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

Friday, March 24, 2017

Sitecore Habitat : what to do if 05-Sync-Unicorn is not working



I have just started to play with Sitecore Habitat project. The first problem that I encounter is Habitat setup.
 

Everything worked fine except task “05-Sync-Unicorn”. I waited for an hour to complete it but it seems to showing in progress status as 

Sync Unicorn
Sync Unicorn

I googled for the solution but didn’t find any suitable link which explained it properly. So I decided to write the article

Follow below steps if "05-Sync-Unicorn" is not working for you


  • Login to Sitecore desktop

  • Open http://yourinstance/unicorn.aspx
 
Unicorn Sync Page
Unicorn Sync Page



  • You can sync Sitecore items by clicking "Sync" button for each component one by one

  1. Syncing process updates items in Master, core, link database and in search indexes.
  2. It also sync roles, users
  3. Finally it published all synced items to web
Sync Progress
Sync Progress

  • Run "06-Deploy-Transforms" from Visual Studio

Deploy Transforms
Deploy Transforms
 
  •  Open your instance on browser and hurreyyy you will get your Habitat site

Habitat Home Page
Habitat Home Page
 

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

Till that happy Sitecoring :)

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