Running Concourse locally using Docker

Hi, this is a short post on running concourse locally using docker.


Install Docker locally.

Once you have docker running locally, we can pull the Concourse image and set up concourse to run locally.

The following is docker compose file that you can use to set up postgres database and concourse running in Docker.

version: ‘2’
image: postgres
POSTGRES_DB: concourse
PGDATA: /database
image: concourse/concourse
command: quickstart
privileged: true
depends_on: [postgres-db]
ports: [“8080:8080”]
CONCOURSE_EXTERNAL_URL: http://localhost:8080
Save the above as a yml file. This file has instructions to pull the postgres and concourse images and start concourse on port 8080.
Run the above file using the command,
docker-compose up
Once it is done, in your browser navigate to the URL,


Great, now download the CLI tool as per your operating system and install it.

We will look at using fly to create and run pipelines in a future post! Thanks for reading!


Debug ASP.NET Core 3 Source Code


In this article, we will debug a simple ASP.NET Core MVC application In Windows.

I am using the master in this example.

I did the following steps to get ASP.NET Core source code debugging in my local.


  1. Visual Studio Preview version
  2. Git tools.
  3. Node version 10 or higher


  1. Download the source code from the Repo,

Note : clone the repo recursively using,

git clone --recursive
  1. You can use master branch or check out to the tag version that you wish to debug.
  2. navigate to the aspnetcore folder and run the restore command to restore the dependencies for the project.
  3. Before opening the solution, to ensure we have not missed any softwares we need to debug, use powershell to execute the file, aspnetcore\eng\InstallVisualStudio.ps1


Run the script with the parameters, -edition community -channel preview

It will open a installer. Install any missing dependencies.

  1. go to the MVC folder and copy path of mvc.sln file
  2. open the solution using the startvs srcipt since this will open the solution with the required environment variables as well.

startvs “[path to your solution]\dotnetsource\aspnetcore\src\Mvc

Once your solution opens, build it. It may take a couple of minutes. 

Once build completes, you are good to go! It may look bit intimidating with so many projects in the solution, but dont worry, there will be a sample folder in it which references the source code in the other projects. Set it as the startup project and run the solution. Once you see the home page loading, you are good to debug any project in the source code! 

have fun!





Installing Sitecore 9.3 using SIA

With the launch of Sitecore 9.2 and 9.3, installation has become relatively easy again! When Sitecore 9 was launched, it was slightly hard to install local sitecore developer setup. A lot of prerequisites had to be done ourselves before we could run the powershell scripts. With Sitecore 9.2 and 9.3, there is setup.exe which helps set up the sitecore 9.3 really easily.

The following are the steps I followed,

  1. Requested free sitecore trial from sitecore. Yes, sitecore offers a free 60 day sitecore trial license. You can request it from the link, 

It will take roughly 2-3 days to get your license. Follow the steps in the mail you receive from sitecore when you request it.

2. Once you get the license, you account will be activated and you can download the sitecore 9.3 software. You can download it from the location,

You can only download it from the account you would have created once you requested the license. I downloaded, Graphical setup package for XP Single from the installables. Unzip the downloaded file. It should have 23 files in it.

3. Before starting the installation, I also installed Microsoft SQL Server 2017 Express and the management studio. You can install SQL Server 2017 from the link,

I installed using the default mode. After installing, it gives you an option to install SQL Server management studio as well. Install it as well.

4. In the management stdio, connect to the SQL Server you installed in previous step and enable SQL login. Also you can create new user or activate sa user and update the password for the sa user as well. Keep these details separately. They will be used while installing Sitecore 9.3

5. Now, you are ready to install sitecore 9.3. From the download, run setup.exe as administrator.

The tool takes you through the steps and is pretty straight forward and self guided. Following are some of the screenshots form steps in my local,

welcome sitecore install

I installed prerequisites as well in the next step,



Install Solr if not already installed


Give a admin password


Provide SQL Server connection details


Provide the Solr settings from the initial step






Now just click through the next two steps and your local new shiny Sitecore 9.3 is up and ready to use!

Thanks for reading!


Multisites in Sitecore

A Collection of articles on web development by Nataraj Gandhi Arunachalam

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…

View original post 583 more words

Implementing Simple Identity Provider (IDP) in ASP.NET Core

We will set up a simple Identity Provider (IDP) in this demo for securing our client application which will be a web application in this demo.

For setting up a simple IDP, we can use the IdentityServer 4 package. Create a new ASP.NET Core web application (I have used version 2.2 for my demo). Add a nuget reference for IdentityServer 4 package.

Nuget IDP

Now, In add a static class add add the following static methods to it,

public static class Config
public static List GetUser()
return new List
new TestUser
SubjectId = "1dfsfsf342dffd",
Username = "natarajgandhi",
Password = "helloworld",
Claims = new List
new Claim("given_name","Nataraj Gandhi"),
new Claim("family_name", "Arunachalam")

public static IEnumerable GetIdentityResources()
return new List
new IdentityResources.OpenId(),
new IdentityResources.Profile()

public static IEnumerable GetClients()
return new List
new Client()
ClientId = “natwebclient”,
ClientName = “Nataraj Web Application”,
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List()
AllowedScopes = new List()
ClientSecrets =
new Secret(“abcd”.Sha256())

In the above code, we are setting up a single user natarajgandhi. Note that this is just a demo where the username and password are stored in code. It should not be done in real production applications. The user has a set of claims that are accessed through the scope property in OpenID connect. The scope for this IDP is set through the GetIdentityResources method. Then we have the GetClients method where we register a client application named natwebclient in this case. We will discuss the webclient in the upcoming sections.

Now, in the startup.cs file, configure the following services,



Also configure the following middlewares,


Great, now we have set up the IDP!

You can run the application and access the following URL to see the meta data.



Great! For adding UI, you can use the startup template from the below URL,

From the releases, you can download the release 2.2 which is compatible with the package version we are using. Copy the Views and controllers and WWW folders into the IDP project in your local and you should be good! Compile the solution and run it again, you should now get a good UI!


Your IDP is now running!

Now, you can create a simple web application that you are trying to set up authentication use the above created IDP. You can follow the following steps to use the IDP created above in your client web app.

In the startup.cs, configure services method, add the following

services.AddAuthentication(options =>
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
.AddOpenIdConnect("oidc", options =>
options.SignInScheme = "Cookies";
options.Authority = "https://localhost:44380/";
options.ClientId = "natwebclient";
options.ClientSecret = "abcd";
options.ResponseType = "code id_token";
options.SaveTokens = true;

This instructs your web app to use cookie to store the authentication cookie and talk to your new IDP. You are also setting up the various options that you have set up in the IDP previously.

Also set up the middleware to use the authentication,


And decorate the controllers that you want protected with [Authorize] attribute.

Thats it! Your web app should now be able to talk to your IDP and get itself authenticated!

Thank you for reading!


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! 🙂