Wednesday, February 24, 2016

Most Essential Sitecore Blog posts

Start Glass Mapper 4 , Unit test

For Beginner- All about Renderings

Autofac and Ninject. with Sitecore

Custom Item Bucket

Relative datasources in Sitecore templates using queries

Context Datasource

Must Look For
Coffee=> Coder =>Code
Alan Coates

All about Architecting

John West

Tuesday, February 23, 2016

GlassCast In Glass mapper

Recently I was revieiwing one of the sitecore repository and I got to see the extensive use of GlassCast in the codebase . I quickly checked in glass mapper site and I happened to see this blogpost.

Sometimes we overlooked such abstract implementation and just use them in our solution. It depends whether this is coded for high critical enterprise application then ofcourse such use of library will haunt you when it is tested against high user volume. It is sometimes mandatory to hook up your system to undergo performance soak test and load test to give comfort and confidence.

This is what it states in the blog

var item = Sitecore.Context.Item;
var model = item.GlassCast<MyModel>();
From some basic performance tests we can see that for 10000 item requests that using one SitecoreService to get an item takes around 94ms vs 164ms when using GlassCast! That is a big difference.


Wednesday, February 10, 2016

Consume Google My Business API Using Service Account.

If it comes to google my business API setup one has to go through developer console request api access , create project and enabled OAuth2.0.

Very important things to note: This solution is applicable only if you're looking at creating a console or batch job that is going to run in server or in azure cloud.

What it tackles?

  1. There is no clear cut direction or documentation as such in terms of service account.
  2. There is no nuget pkg available at the moment.
  3. Sometimes you may face problem with Key.p12 file that is mentioned in documentation.
  4. If key.p12 path results into error look at Byte[] options to load it.

Here is the few tweak in terms of google my business c# implementation. Feel free to comment.

using System;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System.IO;
using Google.Apis.Mybusiness.v2;
using Google.Apis.Mybusiness.v2.Data;
namespace ConsoleApplication1
    /// This sample demonstrates the simplest use case for a Service Account service.
    /// The certificate needs to be downloaded from the Google Developers Console
    ///   "Create another client ID..." -> "Service Account" -> Download the certificate,
    ///   rename it as "key.p12" and add it to the project. Don't forget to change the Build action
    ///   to "Content" and the Copy to Output Directory to "Copy if newer".
    public class Program

        public static void Main(string[] args)
            Console.WriteLine("Google My Business API - Service Account");
            //byte[] scriot=ReadFile("key.p12");
            String serviceAccountEmail = "";

            var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
            //var certificate = new X509Certificate2(scriot);
            string[] scopes = new string[] { "" };

            ServiceAccountCredential credential = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(serviceAccountEmail) {

               Scopes =scopes,
               User = ""

            MybusinessService service = new MybusinessService(new BaseClientService.Initializer()
                HttpClientInitializer = credential,
                ApplicationName = "ABC-GMB",

            string loc = "accounts/1900345345435435345";
            AccountsResource.LocationsResource.ListRequest locRequest = service.Accounts.Locations.List(loc);
            ListLocationsResponse locationsResponse =locRequest.Execute();
        internal static byte[] ReadFile(string fileName)
            FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            int size = (int)f.Length;
            byte[] data = new byte[size];
            size = f.Read(data, 0, size);
            return data;

Monday, February 8, 2016

Sitecore Pipeline : Add controls to sitecore at runtime through renderContentEditor

If you are looking at customizing page editor and incorporate more settings the way content editor got we can make use of following approaches. The reference links are quite helpful to look more internals of core database and how to built experience editor.

Approach 1- restricted to URL

using System.Web;
using System.Web.UI;
using Sitecore.Pipelines;

namespace Demo.SC.Practical
    public class InjectScript
        public void Process(PipelineArgs args)
            var url = HttpContext.Current.Request.Url.AbsolutePath;

          if (url.Contains("field%20editor") || url.Contains("field editor"))
                AddControl("some script tags");
          AddControl("some script tags");
          AddControl("some script tags");         

        private static void AddScript(string headerScript)
            Sitecore.Context.Page.Page.Header.Controls.Add(new LiteralControl(headerScript));
Approach 2 - referred from blog reference below. Restricted to configuration.

Custom Control

Custom Text Field - Limit

Editing Meta Data in Sitecore for SEO- page Editor Mode.

Adam Conn- Custom Field Editor

Page Editor Blogs


Thursday, February 4, 2016

Azure Data Centre Migration and Publish profile online download

While we are about to do lift and shift we realize this going to be very tedious task of migration. Still we are half way and looking for more productive and effective solution to migration azure cloud service from US data centre to Australia data centre.

When we look at this option given in this article, we felt this is what we want to go for however this got lot of caveat and problems based on infrastructure and the way it is done for public azure cloud.

Few things to consider while you try to hook into this solution.

Problem with Download Publish Profile .

Publish profile download link is old and its refer to old reference
Try this

Instead of this

This will act as wiki for me as I progress I will keep adding the problem statement and solution around so that it help others in similar issue.

1. Login to So that session will ensure you got publish profile established properly.
2.Download Publish profile as per above link. Ensure right subscription and environment is selected.
3. Download code from GitHub
4. *** Enable Nuget package- Tools- Extensions and Updates
5. *** Ensure all unwanted service is deleted where there is no deployment package .

We struggle to migrate database instance and databases from US to AUS. The only reason we looking at more automated approach which was not covered in the above migration checklist.

V12 Azure SQL database is not supporting manage db online . We can connect using sql server management studio for the same. The only important thing is your client system should have port and firewall enabled for the access to cloud database. Else you may have tough time connecting to outside network to enable the same.


Wednesday, February 3, 2016

Wild Wild West -The only @sitecorejohn

It took me back when I first time heard about sitecore John bid farewell. Every morning I used to read one of his blog and start my to-do’s and work. When I first started my sitecore assignment the very first result in google gave me @SitecoreJohn blog since then it was only John whose blog I book marked and referred to as my sitecore bible however I don't say SDN network resource was not enough but at least John blogs used to give all direction to start with. He is Sitecore Evangelist for me. He is Guru! When I think of .net first name comes to me is Scott Hanselman, when I think of Azure cloud its Scott Guthrie when I think of CLR Maoni Stephen comes to my mind and of course when I think of c# I look upon Anders Hejlsberg likewise when its sitecore it is the only John West.

Nothing change but when someone like John keep contributing it makes big impact to this world. It enables people. They help generate ideas, create synergies and trust me very, very few people capable of doing this.

My standing ovation and salute to this gentleman who is remarkable in his journey of Sitecore.

I know it’s not end though, John will be seen again in different style with lot of conviction.

 All the best John and thanks for giving your best shot till date.

Tuesday, February 2, 2016

Production Support: sitecore Admin Cheat Sheat

Here is the bunch of admin tools that can come handy for any sitecore production incidents and operation management. Any devops lead or team will surely use these tools to make their troubleshooting or house clean up easy.


You may have to configure them or make be disable security access on your instance or box. Be careful when using them.

Rebuild Key Behavior Cache

Install Language

Redeploy Marketing Data

Path Analyzer

Rebuild Reporting Database

Media Hash

Remove Broken Links

Pipeline Profiler

LINQ Scratchpad

Fill Database

Set Application Center Endpoint

Update Installation Wizard

Unlock Admin


Show Config





Database browser

Size Status


Add, update and delete Sitecore Items Programmatically

Cheat Sheat

Before we start below are the cheat sheat that can serve as starting point to understand sitecore item at ease

Sitecore.Data Library
  • Context
  • Configuration
  • Factory
  • Database
  • SecurityModel
  • Template
  • TemplateId
  • Items
  • Item
  • Field
  • Sitecore.SecurityModel
  • Sitecore.Configuration.Factory
  • Sitecore.Data.Managers.LanguageManager
  • Sitecore.Context.Language
  • Sitecore.Data.Items.Item
  • Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline

***Each item exists in a database, and you can either use use the context database:

Sitecore.Data.Database context = Sitecore.Context.Database;
  • Item item= context.GetItem("/sitecore/content");
  • Sitecore.Data.Items.Item item = context.GetItem(Sitecore.ItemIDs.ContentRoot);

***Or you can explicitly reference a named database, such as the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
  • master.GetItem("/sitecore/content");
  • master.Items["/sitecore/content"];
  • master.GetTemplate();

***If needed, you can access a specific version of a specific language:
Sitecore.Data.Items.Item version = context.GetItem(item.ID,
  new Sitecore.Data.Version(1));

***You can also retrieve items by URI:
Sitecore.Data.ItemUri homeUri = new Sitecore.Data.ItemUri(
Sitecore.Data.Items.Item home = Sitecore.Data.Database.GetItem(uri); 

***To retrieve a child with a specific key:
Sitecore.Data.Items.Item home = item.Children["home"];

1. Create Item Using Tempate
public void CreateItem()
  //Again we need to handle security
  //In this example we just disable it
  using (new Sitecore.SecurityModel.SecurityDisabler())
    //First get the parent item from the master database
     Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
//Get Parent Node.
     Item parentItem = masterDb.Items["/sitecore/content/home"];

    //Now we need to get the template from which the item is created
    TemplateItem template = masterDb.GetTemplate("sample/sample item");
    //Now we can add the new item as a child to the parent
    parentItem.Add("NewItemName", template);


2. Update Item Field Value
public void UpdateItem()
  //Use a security disabler to allow changes
  using (new Sitecore.SecurityModel.SecurityDisabler())
    //You want to alter the item in the master database, so get the item from there
    Database db = Sitecore.Configuration.Factory.GetDatabase("master");
    Item item = db.Items["/sitecore/content/home"];
    //Begin editing
      //perform the editing
      item.Fields["Title"].Value = "This value will be stored";
    catch (Exception ex)
       Sitecore.Diagnostics.Log.Error("Could not update item " + item.Paths.FullPath + ": " + ex.Message, this);
       //Close the editing state

3. Publish Item
public void PublishItem(Item item)
 //We need the target database
        Database webDb = Sitecore.Configuration.Factory.GetDatabase("web");

       //We need to know the language to publish. Here we use the context language
        Language language = Sitecore.Context.Language;

       //We set the publish date to now
        DateTime publishTime = DateTime.Now;
       //Now we can create the publish options
        Sitecore.Publishing.PublishOptions options = new PublishOptions(masterDb, webDb, PublishMode.SingleItem, language, publishTime);
       //Activate the publishpipeline
        Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(item.ID, options);


If cache is a concern above pipeline option is required.
4. Publish with Options
 private void PublishItem(Sitecore.Data.Items.Item item)
  // The publishOptions determine the source and target database,
  // the publish mode and language, and the publish date
  Sitecore.Publishing.PublishOptions publishOptions =
    new Sitecore.Publishing.PublishOptions(item.Database,
                                           System.DateTime.Now);  // Create a publisher with the publishoptions
  Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);
  // Choose where to publish from
  publisher.Options.RootItem = item;
  // Publish children as well?
  publisher.Options.Deep = true;
  // Do the publish!
Key Notes:
  • Droplink vs Droplist-> Droplink store GUID whereas Droplist stores just name
Sitecore 8.0 higher- Multiple version in web database
Content testing Enabled.
By default the publishVersion pipeline contains two processors in order:
  • Sitecore.ContentTesting.Pipelines.PublishVersion.PublishTestingVersions, Sitecore.ContentTesting
  • Sitecore.Publishing.Pipelines.PublishVersion.Processors.RemoveOtherVersions, Sitecore.Kernel