Structuring JavaScript Code using Design Patterns

One of the most battle tested and long standing language is JavaScript. Almost any front end framework you touch today is created mostly based on JavaScript. Still, even today, we see a lot of JavaScript in many websites that seems like Spaghetti code. We see so many JavaScript methods hastily put together in large files without any concern for global namespace pollution, reuse etc.
In this article, we will see some techniques on how we can convert a set of loosely written JavaScript methods to a more modular design that we are more accustomed to seeing in an object oriented language such as C#.
Issues with loose JavaScript methods
Before we discuss on some of the design patterns, let us first understand some of the basic issues that occurs when we do not go for a modular design.
Please refer the below code listing,

 var add = function(a,b) { alert(a+b); };

In the above listing, add(1,2) alerts the value 3. Now, what happens if we declare “add” again as shown below,

var add = 55;

Fiddle reference:
This throws an error. Since the variable add has been overwritten. Though the problem is obvious here, it may not be always obvious when your overriding takes place in a different file and the method call happens in another file.
Basically, the problem here is that we are polluting the global namespace. Any variable we create here is added to the global scope. Our code should be written in such a manner that we do not add any variable to the global namespace unless absolutely necessary to do so for solving a business case.
Ok, now that we are warmed up to the issues, let us see how we can solve this problem using some common JavaScript design patterns!

Module Pattern

Module pattern is a favourite pattern for many due to it close resemblance to class and object declaration in a OOPs language such as C#.
Closure in JavaScript is the driving principle behind making of the modular pattern. In case you have not heard of closures in JavaScript, it is a good idea to read up on this as this is one of the principal foundation in JavaScript. Basically, closure in JavaScript enables private (local) variables of a JavaScript function to be kept alive even after the function has returned. This is enabled when the private (local) variable is referred inside a public variable that is returned by the function. Well, closure is a complex topic which is outside the scope of this discussion, but I would strongly suggest reading and understanding closures in JavaScript to really grow into a seasoned JavaScript developer.
Ok, now let us look at an example of a module pattern implementation and then discuss its anatomy and learn about it.
Let us say we have the following listing which is basically just a set of loosely defined methods to implement addition and subtraction. We convert it to use a modular pattern as shown below.
JSFiddle reference:

var add = function(a, b) {
 alert(a + b);
 var subtract = function(a, b) {
 alert(a - b);
 add(1, 2);
 subtract(4, 2);

In the above listing we are declaring two variables add and subtract. Thus, we are polluting the global namespace and also we are opening ourselves to the situation where another file can overwrite these variables add and subtract with a different implementation or worse, convert it to a simple variable holding just a integer or string!

//Convert to Module Pattern
 var Calculator = function() { //note the Pascal casing we have used. More explanation provided below
 //declare the private (local) variables
 var addition = function(a, b) {
 alert(a + b);
 var subtraction = function(a, b) {
 alert(a - b);
 return { //define the public API
 add: addition,
 subtract: subtraction,
 multiple: function(a, b) {
 alert(a * b);
 //create an instance of your class (class referes to the function basically in this case)
 var calculator = new Calculator();
 calculator.add(1, 2);
 calculator.subtract(5, 1);
 calculator.multiple(2, 4);

Please note the above listing. See how we have taken the addition and subtraction method and converted it as private variables (you can test it, by trying to execute calculator.addition(1,2), it will throw an error).
In the public API for this function, we only return three variables, add, subtract and multiply, which can be called by an instance of Calculator.
Another good practice to follow is whenever you are declaring a class (a function) which will need to be initialized using a new operator to create objects, it is a standard practice to use Pascal casing (as we follow in C#). This is because, in JavaScript, the standard practice of variable naming is to use camel casing.
Also note, how we have only created one global variable in this case. You can reduce it still further by reusing an existing namespace. You can do something as follows,
var ns = ns || {}
The above lines mean, if the namespace variable ns exists, then use it, else create an empty object. Thus no danger of overwriting existing namespace/variable with your definition.
The only major disadvantage with modular pattern is that for each instance you create, you get the functions loaded in memory. Well, unless you are creating hundreds of objects, this may not actually prove to be an issue.
The above is an example of modular pattern. Let us now look at some other patterns.

The Prototype Pattern (“this” pattern)

The prototype pattern is another popular pattern that you can use for structuring your JavaScript code. The prototype pattern only creates one copy of the functions in memory even if you have hundreds of instances, all the instances share the same functions in memory.
The prototype pattern works on the basis of the native prototypical inheritance support in JavaScript. Basically, what we need to understand is that for any function that we create and assign to a variable, a “prototype” object is created to which you can add further methods (your API methods), that will be inherited to any object you create based on the original class (the variable which points to the function).
This pattern is also called as “this pattern” due to the heavy usage of the “this” keyword. This is the only major “disadvantage” of this pattern since the “this” keyword in JavaScript is slightly more complicated than that of other languages such as C# that we are accustomed to. The “this” keyword in JavaScript refers to the context of the caller rather than the context in which the “this” keyword is used.
Well, that was some pretty heavy stuff, let us now see some code in action. Please refer to the following listing, which is basically the same Calculator example that we used in the prototype pattern, but converted to use the Prototype pattern,
JSFiddle location:

//Prototype pattern for the Calculator sample

//1. Create the constructor function and set the private properties for the object
 var Calculator = function(a, b) {
 this.operand1 = a;
 this.operand2 = b;
 //2. Create the prototype object and assign all the public properties (API)
 Calculator.prototype = {
 add: function() {
 alert(this.operand1 + this.operand2);
 subtract: function(){
 alert(this.operand1 - this.operand2);
 var calci = new Calculator(5,2); //Create an object for Calculator and use it as shown below
 //override add method
 Calculator.prototype.add = function(){
 alert(this.operand1 + this.operand2 + 55);

If you observe the output of the last line, the overridden method is called, this gives us a tremendous advantage if we want to override methods that are provided by a library. So, when you are writing a library for others to use, it is a good option to use Prototype pattern as it gives developers an easy way to override your methods without having to update your code that was downloaded as part of the library and risk having it changed when you release a new version of the library.

Have fun coding! Two more patterns coming up soon……..


Multisites in Sitecore

One of the features I love most in sitecore is the ability to create multisites. I just love the way you can create beautiful websites in a matter of hours using existing renderings. Of course you do have to do the hard work of creating these beautiful renderings initially. But once it is done and set up, you can create any number of sites using these renderings. That is the magic of multisites!

So, what are multisites?

A default sitecore installation defines only a single published site. But, you do have the feature to add any number of sites to an installed sitecore version through the user of the <sites> section in the sitecore’s web.config file.

So, basically multisites are sub sites which are running based off the same code base. As far your IIS is concerned, these act as independent sites receiving traffic of its own. But internally, it is mapped to the same code base with the same configuration file.

How multisites help us (developers and organizations alike!)

The keyword here is really “rendering reuse”! Since all the websites are now sharing the same code base, the renderings you create for the first website can be used by any other website that is configured as a multisite for that particular sitecore installation.

And the only changes you will have to do is to just update you root configuration file to include the new site name and some changes to your IIS to create the new website and all the other related network updates! As far as code updates, code deployment is concerned, there is absolutely no changes!

How to set up multisites

Some basics before looking at the steps:

When you request for a website hosted in IIS and powered by sitecore, once ASP.NET pipeline picks up the request and after determining that it needs to be handled by sitecore, it transfers it to the sitecore pipleline. The Sitecore HttpBeginrequest pipeline picks up the request. There is a processer by name SiteResolver, which is a part of the HttpBeginRequest pipeline.

This processer determines the sitecore item that needs to be processed (the sitecore home page/child page that user requests which contains the presentation details) based on the request. It resolves this using one of the following information from the request,

  1. If the query string contains, sc_site querystring. That particular key is used to fetch the proper <site> node from the <sites> secton.
  2. The virtualFolder key of the <sites> section for each website can be used in the request URL to help sitecore resolve to the proper site.
  3. The most common way and which should be used by an organization is through using the hostname attribute. The hostname attribute in the <site> node of the <sites> section points to the domain to which the multisite is mapped to. So based on the domain in the request, the proper <site> node is mapped and the corresponding sitecore item is fetched and rendered.

The following is an example entry for the default “website” <site> node in the <sites> section,

< site name = “website” hostname=”” virtualFolder=”/” physicalFolder=”/” rootPath=”/sitecore/content” startItem=”/home” database=”web” domain=”extranet” allowDebug=”true” cacheHtml=”true” htmlCacheSize=”10MB” registryCacheSize=”0″ viewStateCacheSize=”0″ xslCacheSize=”5MB” filteredItemsCacheSize=”2MB” enablePreview=”true” enableWebEdit=”true” enableDebugger=”true” enableAnalytics=”true” disableClientData=”false” />

Note the hostname section and how it points to the item, “/Sitecore/Content/home”. So, any request to will be mapped to /sitecore/content/home item.

Now, if you want to create multiple sites pointing to the same code base, just create a couple of more sections which different host names and pointing to different sitecore items!

< site name = “website1″ hostname=”” virtualFolder=”/” physicalFolder=”/” rootPath=”/sitecore/content” startItem=”/home1″

< site name = “website2″ hostname=”” virtualFolder=”/” physicalFolder=”/” rootPath=”/sitecore/content” startItem=”/home2″

< site name = “website3″ hostname=”” virtualFolder=”/” physicalFolder=”/” rootPath=”/sitecore/home3″ startItem=”/home”

So, now a request to will get mapped to /sitecore/content/home1

This the basic underlying concept of setting up a multisite. For more detailed instructions, please follow the links I have provided at the end of this blog.


So, multisites are a great way of creating websites based off existing code base in a very efficient and quick manner. Whatever hard work you have done for creating a web site can be reused very easily through the user of multisites. You get to set up websites very quickly without any code changes and deployments. That sounds really cool to me and I hope you feel the same way!

Some references

Dependency Injection in ASP.NET Core

This article explains the dependency injection feature available out of the box in ASP.NET core (ASP.NET 5). It will also cover some of the basics of dependency injection so that everyone can get the best out this article.

What is dependency Injection?

Dependency Injection is the process of “injecting” the “dependency” whenever the dependency is requested by a client, where the dependency may be another service which the client (requester) may have no means of knowing how to create.

As an analogy, imagine a person (client) going to office carrying his lunch cooked by himself. In this scenario, the person has a “dependency” on food. But he had to know how to cook his food. But honestly, not everyone (client) knows to cook, but people do need food (dependency). This is where restaurants play the role of dependency Injection. They can supply food (“inject dependency”) to the people (client) without the person needing to know how to cook.

This is also called as Inversion of control. Since the control for creation of the service has been passed from the requester to another entity which takes care of creating the dependencies needed by a class to perform its tasks. The entity which takes care of creating these requested dependencies and injecting them automatically to the client is known as the DI (dependency Injection) container.

Dependency Injection in ASP.NET 5

Ok, enough said about what is dependency injection. I am sure most of you knew it. If not, this is a great feature to know and a great tool to add to your tool belt! Let us now look at how to implement dependency injection out of the box in ASP.NET 5.

ASP.NET core applications can leverage built in framework support for implementing dependency injection. It has support for the following types of lifetimes for configured services (injected dependencies).

1. Transient – A new instance of the service is created each time it is requested. It can be used for stateless and light weight services.
2. Scoped – A single instance is created once per request.
3. Singleton – Created only once the first time they are requested.

Now for some code!

Use case:

Implement a UniqueKeyProvider service. For demonstrating the lifetimes, we will create three differently named interfaces (one for each type of lifetime) for UniqueKeyprovider, all inheriting from the same parent interface having a single property, UniqueKey.

Also, to further illustrate the scoped and singleton lifetime, we will create another service, SomeService, which will have a dependency on all the three different UniqueKeyProvider services (the three different lifetime services).

1. Service Interface definition

Please note the three differently named interfaces, one for demonstrating each type of lifetime.

namespace DependencyInjectionASPNetCore.Services
public interface IUniqueKeyProvider
Guid UniqueKey { get; set; }

public interface ITransientUniqueKeyProvider : IUniqueKeyProvider

public interface IScopedUniqueKeyProvider : IUniqueKeyProvider

public interface ISingletonUniqueKeyProvider : IUniqueKeyProvider

2. Service Class definition

namespace DependencyInjectionASPNetCore.Services
public class UniqueKeyProvider : ITransientUniqueKeyProvider, ISingletonUniqueKeyProvider, IScopedUniqueKeyProvider
public Guid UniqueKey { get; set; }

public UniqueKeyProvider(Guid uniqueKey)
UniqueKey = uniqueKey;

3. Registering the services in the startup.cs

Now register your services in the startup.cs file. This is the step where you are actually configuring your dependency injection container. You are basically instructing your dependency injection container that if the user requests for the service, ITransientUniqueKeyProvider, then please provide with a transient scoped instance of UniqueKeyProvider class and similarly for the other services.
You need to register your services in the ConfigureServices method in the startup.cs file. Please refer to the code below for registration,

            services.AddTransient&amp;amp;amp;lt;ITransientUniqueKeyProvider&amp;amp;amp;gt;(provider =&amp;amp;amp;gt; new UniqueKeyProvider(Guid.NewGuid()));
            services.AddScoped&amp;amp;amp;lt;IScopedUniqueKeyProvider&amp;amp;amp;gt;(provider =&amp;amp;amp;gt; new UniqueKeyProvider(Guid.NewGuid()));
            services.AddSingleton&amp;amp;amp;lt;ISingletonUniqueKeyProvider&amp;amp;amp;gt;(provider =&amp;amp;amp;gt; new UniqueKeyProvider(Guid.NewGuid()));
            services.AddTransient&amp;amp;amp;lt;ISomeService, SomeService&amp;amp;amp;gt;();

Note that I am also registering another service, ISomeService which I am just using for demo purposes for showing the nature of transient and singleton lifetime. Also note that SomeService implementation requires dependency on the three Unique Key providers, which will be injected through dependency injection. Implementation of ISomeservice provided below,

4. IsomeService and Someservice Implementation

public class ISomeService
ITransientUniqueKeyProvider TransientUniquekeyProvider { get; set; }
IScopedUniqueKeyProvider ScopedUniquekeyProvider { get; set; }
ISingletonUniqueKeyProvider SingletonUniquekeyProvider { get; set; }
public class SomeService : ISomeService
public ITransientUniqueKeyProvider TransientUniquekeyProvider { get; set; }
public IScopedUniqueKeyProvider ScopedUniquekeyProvider { get; set; }
public ISingletonUniqueKeyProvider SingletonUniquekeyProvider { get; set; }

public SomeService(ITransientUniqueKeyProvider transientprovider,
IScopedUniqueKeyProvider scopedprovider,
ISingletonUniqueKeyProvider singletonprovider)
TransientUniquekeyProvider = transientprovider;
ScopedUniquekeyProvider = scopedprovider;
SingletonUniquekeyProvider = singletonprovider;

Now it is time to wrap it all up and test it through a controller. I am using the Home controller’s Index action. Please refer to the below code from the controller and view.

5. Home Controller

public class HomeController : Controller
private ITransientUniqueKeyProvider _transientUniquekeyProvider;
private IScopedUniqueKeyProvider _scopedUniquekeyProvider;
private ISingletonUniqueKeyProvider _singletonUniquekeyProvider;
private ISomeService _someserviceProvider;

public HomeController(ITransientUniqueKeyProvider transientprovider,
IScopedUniqueKeyProvider scopedprovider,
ISingletonUniqueKeyProvider singletonprovider, ISomeService someserviceprovider)
_transientUniquekeyProvider = transientprovider;
_scopedUniquekeyProvider = scopedprovider;
_singletonUniquekeyProvider = singletonprovider;
_someserviceProvider = someserviceprovider;
public IActionResult Index()
ViewBag.transientID = _transientUniquekeyProvider.UniqueKey;
ViewBag.scopedID = _scopedUniquekeyProvider.UniqueKey;
ViewBag.singletonID = _singletonUniquekeyProvider.UniqueKey;
ViewBag.someServiceProvider = _someserviceProvider;
return View();

Note the constructor which takes in the dependencies. So when the request comes to this page, the framework notes that it needs an implementation for these services. It checks the DI container and finds the registration, and based on that the valid instance is passed to the constructor. The same happens in case of the ISomeService dependency which the controller’s constructor needs.

6. Index View

In the view file, we are just displaying the values that we set in the view bag. Results provided in the next section.

&amp;amp;lt;div style=&amp;amp;quot;margin-top:35px&amp;amp;quot;&amp;amp;gt;
&amp;amp;lt;p style=&amp;amp;quot;font-weight:bold;text-decoration:underline&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/p&amp;amp;gt;
        These are the values that were injected into the home controller



Transient value of Guid: @ViewBag.transientID



Scoped value of Guid: @ViewBag.scopedID



Singleton value of Guid: @ViewBag.singletonID


&amp;amp;lt;p style=&amp;amp;quot;font-weight:bold;text-decoration:underline&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/p&amp;amp;gt;

These are the values that were injected into Someservice Implementation



Transient value of Guid: @ViewBag.someServiceProvider.TransientUniquekeyProvider.UniqueKey



Scoped value of Guid: @ViewBag.someServiceProvider.ScopedUniquekeyProvider.UniqueKey



Singleton value of Guid: @ViewBag.someServiceProvider.SingletonUniquekeyProvider.UniqueKey



That’s it! Results given below

Output in screen
Page load first time

DI - First page load

Page load second time

DI - Second page load

I really hope it was useful and fun. Happy coding!

Tag Helpers in MVC6

This article explains in a simple manner what is tag helpers in MVC6, why do we need tag helpers over the HTML helpers provided by the previous versions of MVC and a simple implementation of a use case using tag helpers.


Tag helpers is a new feature introduced in MVC6 to improve readability of razor code. Tag helpers function similarly to HTML helpers, by translating the custom tags (defined in our tag helper) into HTML code.

Why do we need tag helpers?

Well, the first question that comes to our mind is, why do we even need tag helpers? Or for that reason, why do we need a HTML helper.  The main reason we need them is to avoid repeating the same snippets of HTML again and again in our project. It enables consistency of code in a project with a large number of developers. Also, it has uses in generating input fields, generating anchor links taking advantage of routing etc.

Tag helpers over HTML helpers

The next question that pops up is if HTML helpers can do the same job, what role does tag helpers play? That is true, we can achieve almost everything that tag helpers can provide us with HTML helpers. But, if you look at a view file created largely using HTML helpers, it will start appearing more like a C# code page than like a HTML page.

For many who love HTML, this doesn’t seem right. People want a HTML page (a view in our case) to look like a HTML page. So enter tag helpers! Tag helpers can help you achieve you do this.

Of course, please note there is nothing stopping you from using HTML helpers to create your view. It is just a choice provided to you by MVC6 to make your view look much cleaner.

Ok, enough said, let us now look into an example of how to use tag helpers.

Use case: Create a <section> with a <h2> and a <p>

  1. Create a new Visual Studio 2015 ASP.NET 5 MVC project (you can download Visual Studio 2015 community edition for free,,
  2. Create a class file where you will implement your custom tag helper.
using Microsoft.AspNet.Razor.TagHelpers;
using TagHelpersDemo.Models;

namespace TagHelpersDemo.TagHelpers
    public class CustomSectionTagHelper : TagHelper
        public SectionInfo Info { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
            output.TagName = &quot;section&quot;;

                $@&quot;&lt;h2&gt; {Info.Heading} &lt;/h2&gt; 
                &lt;p&gt; {Info.Content} &lt;/p&gt;&quot;

            output.TagMode = TagMode.StartTagAndEndTag;

SectionInfo Class

namespace TagHelpersDemo.Models
    public class SectionInfo
        public string Heading { get; set; }
        public string Content { get; set; }

In the above code, the name of the custom tag helper will be custom-section. Basically, the content of the class minus the TagHelper part, converted to lower-kebab-case.

You write your logic on how you want your HTML markup rendered in the Process method. The output parameter needs to be set with the way the rendered HTML needs to look like.

In our case, we want our custom tag to be translated into a heading and a paragraph inside a section tag.

For passing the values of the heading and the paragraph, we are using a custom class named, SectionInfo. The Info property in the tag helper class will get the value of the SectionInfo that we pass from our view file.

  1. Register your tag helper assembly and tag helpers in your _ViewImports file

@using TagHelpersDemo

@using TagHelpersDemo.Models

@using TagHelpersDemo.ViewModels.Account

@using TagHelpersDemo.ViewModels.Manage

@using Microsoft.AspNet.Identity

@inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration TelemetryConfiguration

@addTagHelper “*, Microsoft.AspNet.Mvc.TagHelpers”

@addTagHelper “*, TagHelpersDemo”

The * indicates that you are registering all your custom tag helpers in your assembly, TagHelpersDemo

  1. Use the tag helper in your view file
    ViewData[&quot;Title&quot;] = &quot;About&quot;;

&lt;custom-section info=&quot;new SectionInfo
                            Heading = Model.Heading,
                            Content = Model.Content
                        }&quot; /&gt;



Well, that is an example of creating and using a tag helper!

Enjoy and have fun coding! 🙂

First blog post

Hi friends,

Finally I have been attracted and drawn in to the wonderful world of blogging!

I have always felt that sometimes the best company you can have is your own. Everyone should spend some quality time with themselves, reflecting on everything from family, friends, work, life and not but the least on themselves.

Well, but I felt most of the times, I just forget my resolutions and life just goes on as usual without all the grand changes you think you should be doing. So enter blogging! I think it is a great idea to pen your thoughts before they are lost in oblivion for forever! I hope to blog regularly penning down my thoughts into blogs which will range from my random musings to technical topics.

Well, it really feels great writing down my very own blog! I hope to keep writing!

p.s. : I know I said it is good to have your own company sometimes, but it does help every now and then to spend quality time with your friends and family 🙂