Parsing Markdown Using Custom TagHelper In ASP.NET MVC 6

30. November 2015 21:01

.NET Core ASP.NET MVC  0 Comments

Previous versions of MVC allows us to write HtmlHelpers which does a pretty good job then and they are doing it now as well. But in MVC 6, the ASP.NET team has introduced TagHelpers.

Parsing Mardown in .NET is way too simple than one can imagine. Thanks to Stackoverflow's MardownSharp and Karlis Gangis's CommonMark.NET. I use CommonMark.NET as it provides a much faster parsing than other libraries. The blogging platform I use is a custom blogging engine I wrote in MVC4. The post content is saved in HTML which makes my raw HTML way to messy when compared to simple markdown syntax. I have no plans to change the way it is right now, but for the other simple application which is quite similar to notes taking or blogging apps, I would like to save the content in markdown.

I will start with a simple implementation of this custom TagHelper and then then we can look into the other ways to enhance it. Here is how easy it is to create your custom TagHelper.

Create a new class file MarkdownTagHelper.cs. Inside the file, rename the class name to match the file name or you can change the name way you like. In my case I am keeping the class name as same as the file name.

Pay attention to the name of the custom TagHelper. By design, compiler will remove the word TagHelper from the class name and the rest of the name will become your custom TagHelper name.

The next step is to inherit our class with TagHelpers class. Every custom TagHelper will inherit this class. Just like the UserControl class when creating a custom user control. The TagHelper provide us two virtual methods, Process and a ProcessAsync method which we will be going to override to implement our custom logic for our custom markdown TagHelper. The first parameter is the TagHelperContext which holds the information about the current tag and the second parameter is TagHelperOutput object represents the output being generated by the TagHelper. As we need to parse the markdown in our razor view pages, we need to add reference of CommonMark.Net library. Use the below Nuget command to add it to your current project.

Install-Package CommonMark.Net

Till here this is how the code will look like.

So now we have our custom TagHelper that will let us parse the markdown. But to use it in our views we need to opt-in for this TagHelper in the _ViewImports.cshtml file. To enable your custom TagHelper just type in like this:

@addTagHelper "*, WebApplication1"

Your custom tag helper would have been turned purple in color on the view page. It is similar to the line above it where @addTagHelper is importing all the TagHelpers from the given namespace. If you are not interested in opting-in for all the TagHelpers in the given namespace then make use of the @removeTagHelper to disable the TagHelpers you don’t need. For this I want all the tag helpers I have created to be a part of the application and hence the * symbol.

In your view, where you want to use this just type in <markdown> and inside this tag you should have your markdown. To test it, you can view the any raw file in Github and copy the text. I am using from CommonMark.NET and it rendered perfectly.

Caution: When copy-pasting the markdown code from anywhere to your view make sure that you do not have a whitespace in the front of the line. This is only applicable when you are working with the in-line markdown. Here is the screenshot with comparison.

Hit F5 and see the markdown tag helper in action. Below is the output I get.

This is the simplest of all. Now let’s add some prefix to our custom TagHelper. To add a custom tag prefix to the TagHelper, we just need to pay a visit to _ViewImports.cshtml file again and add a new line like so:

@tagHelperPrefix "blog-"

After adding the above line in the file, go to the view page where you have used your custom TagHelper and you can notice that the <markdown> tag isn’t purple anymore. This is because we now have to add a custom tag-prefix that we just defined in the _ViewImports.cshtml file. Change it from <markdown> to <blog-markdown> and it is purple again.

By design, the TagHelper will take <markdown> as a tag to be processed. But it can be easily ignored by using the TargetElement attribute at the top of the class and allow the use of another name rather than <markdown>. This does not mean that you cannot use <markdown> but instead you can also use the custom TagHelper with the name specify in this attribute.

Now let’s add some attributes to my markdown TagHelper. Let’s try to add a url attribute which will help user to render the markdown on the view from a remote site like Github. To add an attribute, simply add a new public property of type string and call it url. When you create a public property in the TagHelper class it is automatically assumed it is an attribute. To make use of this property, my view now simply say this:

<blog-markdown url="">

The url attribute value is being read by the TagHelper which in turn read the whole string of markdown from Github and render the HTML on the page. Let’s focus again on TargetElement attribute for a while. Consider a scenario where you don’t want your custom TagHelper to render or work if the attributes are not passed or missing. This is where TargetElement attribute comes into picture. If I don’t want my TagHelper to work if the url parameter is missing then you can simple write your TargetElement attribute like so:

[TargetElement("markdown", Attributes = "url")]

Notice the Attributes parameter. The Attributes parameter allows you to set the name of all the attributes which should be processed by your TagHelper or else the TagHelper will not work. For instance, if I just use the <markdown> TagHelper but did not pass the url attribute, the TagHelper will not execute and you will see the raw markdown code. My requirement is to have this TagHelper working with or without the use of url attribute. I can comment out or remove the TargetElement attribute or just remove the Attributes parameter to get going.

Here is the complete MarkdownTagHelper.cs:

using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApplication1.TagHelpers
    //[TargetElement("markdown", Attributes = "url")]
    public class MarkdownTagHelper : TagHelper
        //Attribute for our custom markdown
        public string Url { get; set; }

        private string parse_content = string.Empty;

        //Stolen from:
        private bool isValidURL(string URL)
            Uri uriResult;
            return Uri.TryCreate(URL, UriKind.Absolute, out uriResult)
                && (uriResult.Scheme.ToLowerInvariant() == "http" || uriResult.Scheme.ToLowerInvariant() == "https");

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
            if (context.AllAttributes["url"] != null)
                string url = context.AllAttributes["url"].Value.ToString();
                string webContent = string.Empty;
                if (url.Trim().Length > 0)
                    if (isValidURL(url))
                        using (HttpClient client = new HttpClient())
                            webContent = await client.GetStringAsync(new Uri(url));
                            parse_content = CommonMark.CommonMarkConverter.Convert(webContent);
                //Gets the content inside the markdown element
                var content = await context.GetChildContentAsync();

                //Read the content as a string and parse it.
                parse_content = CommonMark.CommonMarkConverter.Convert(content.GetContent());

                //Render the parsed markdown inside the tags.

I found the full TagHelper feature in MVC 6 a lot more convenient and powerful. I hope you like it as well.

 No Rating

Free E-Book: 52 Tips & Tricks to Boost .NET Performance from Redgate

26. November 2015 08:21

Musings  0 Comments

A super awesome free e-book from our friends at RedGate.

  • 52 tips from the .NET community for boosting performance in your applications.
  • Learn the secrets of your fellow developers and read advice from MVPs and other experts.
  • Covers .NET and ASP.NET, database access, memory usage, and more...

Download Now

 No Rating

Controlling 16x2 LCD With Raspberry PI 2 Using Adafruit Library

20. July 2015 12:41

Projects Raspberry Pi  0 Comments

As an enthusiast, I started working with embedded with Netduino. It was fun but at the same time Netduino was not offering that much things that I can do now. For a person like me who has no knowledge of electronics and C/C++, this was a gift. Now here I am using Raspberry PI's latest version and I have everything I ever wanted on a single piece of hardware.

To get started with Python and Raspberry PI, I looked into the "Hello World" sort of LED blinking example. Using the LCD is the second thing I would like to test and so here it is. Before you start, here are the things you will need.

1. 1 x Raspberry PI 2

2. LCD with 16x2 display - HD44780

3. 8 x Male-Female jumper wires

4. 5 x Male-Male jumper wires

Here is the simple wiring to connect LCD with your Raspberry PI 2

As you can see from the wiring diagram, the LCD will take up around 6 GPIO pins on your Raspberry PI. If you have some modules plugged in or you are planning to then there are chances that you will fall short of the GPIO pins. To save GPIO pins on your board, you can use MCP23008 or MCP23017 . To keep it simple, I am not using any port expanders for now.

Now comes the code, I have a very little knowledge of Python at the moment. So I am going to stick with what I have read and tested. For controlling the LCD, I am going to use Adafruit's LCD library which you can get it from Github here. I am going to use to control my LCD. The thing to keep in mind is that you cannot use this library out of the box. You have to make a change to set the correct GPIO pins in the __init__ function. Open the file using the below command.

$ sudo nano

If you are using the same wiring as I am, then change the __init__ function like this

def __init__init(self, pin_rs=26, pin_e=19, pins_db=[13, 6, 5, 11], GPIO=None):

Save the changes and we are good to go. To check if the wiring and the code changes are done properly, execute the below command in the same directory.

$ sudo ./

Let's try displaying some custom messages to the display with this simple program.

from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()
lcd.message("Raspberry PI 2\nLCD Demo")

Here is one more. The program will ask you to enter the string to display.

from Adafruit_CharLCD import Adafruit_CharLCD

lcd = Adafruit_CharLCD()

#Getting input from user
msg = raw_input("Enter message to display\n")

#Display it on the LCD

The reason I am using Adafruit library to control the display is because it has other useful functions to control LCD. Here is the list of functions that you can try.

clear() - Clears the LCD and remove text from the memory.

display()/noDisplay() - Toggle the text visibility on the LCD. Text remains in the memory.

cursor()/noCursor - Toggle cursor visibility.

blink()/noBlink() - Toggle cursor blink.

home() - Take the cursor to the 0,0 position i.e. first column of first row.

setCursor(col, row) - Set the cursor to the specific position. Use lcd.begin(col, rows) to set the number of columns and rows your display has.

I hope this will be useful to the people who are just getting started with Raspberry Pi. You can also download the complete source code from Github here.

 No Rating

.NET Projects You Should Be Follwing On Github

19. July 2015 04:51

API ASP.NET ASP.NET MVC C# Musings Web  0 Comments

Open-source has entirely change the programming and developers world. Today you can create any application, game, mobile app without spending a single penny. Thanks to open-source software and awesome community of developers and people behind them. As a .NET developer I have been developing enterprise applications for quite a long time and now I have shifted my focus towards developing products and understanding what it takes to make a successful product launch.

Back then, I used to spend most of my time in investigating the new technologies and what technology we should be using to get this thing done. I still do that today, not because it is the requirement of the project but because I have been asking a lot of questions. The list of projects I have compiled below are the projects that have helped me in learning lots of new things and insights of the programming and I hope this does the same for you as well.  Here is the list of awesome open-source project that you should be following on Github.


We all know about, it is an awesome tool and a complete replacement of Photoshop (at least for me). And yet there is another project which is almost the same and open-source and it works on Linux and Mac. It uses Gtk# (Gtk sharp) to run on both Window and Linux platforms. This project is a must have if you are a .NET guy and want to get yourself into some serious programming. You will learn about the insights of using gtk# in your projects. Though Microsoft already took the steps to have .NET FX on Linux but still this project is a great learning source.

Official site:




I take a lot of screen shots and record screen casts as well for my personal use. But I used to use two different tools to get the work done. This is one of the tools that will not just take screen shots or just let you record your screen casts easily, it will also allow you to upload them to the 40 different image storing cloud services. Dive into the source code and see the awesomeness under the hood. Here is the project description as seen on Github.

ShareX is an open source program that lets you take screenshots or screencasts of any selected area with a single key, save them in your clipboard, hard disk or instantly upload them to over 40 different file hosting services. In addition to taking screenshots, it can upload images, text files and all other different file types.

Official site:



StackExchange - Data Explorer

You got a programming question, you Google it and it redirects it to StackOverflow. StackOverflow needs no introduction among programmers. StackOverflow is one of the Q&A site dedicated to the developers to get the answers for their problems. But it is just one site. In the recent years StackExchange has grew up and not just providing support for programmers but also helping folks from other fields. Now the data StackExchange has is available for anyone out there for free under creative-commons. If you are interested in looking into the source code that powers the user to query that immense amount of data bank then head over to Github and fork this project. StackExchange is all about Microsoft stack and this tool is also written in ASP.NET MVC3.

Official App:



Mini Blog

This is the minimalistic blog engine written in ASP.NET web pages by the author of BlogEngine.NET, Mads Kristensen. I started my bog with BlogEngine.NET and I had an amazing experience with it. MiniBlog is totally different in terms of features that are offered by BlogEngine.NET. This project will tell you the power of web pages and how you can write your own simple site without wasting much time.

Demo: (with user name and password as demo).



Fluent Scheduler

If you want to run cron jobs or automated jobs in your application quietly, then this is the library you should be using. The documentation is pretty sleek and get you started in no time. But other than that you should take a look at the source code and see how nicely this has been done.




A Micro-ORM used by StackExchange sites. This is a perfect replacement for EF. This is just a single file that you can drop in your project and get started.

Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.




A .NET library to access MediaWiki API. The library is almost 3 years old but the source code will worth the look. Excerpt from Github:

LinqToWiki is a library for accessing sites running MediaWiki (including Wikipedia) through the MediaWiki API from .Net languages like C# and VB.NET.

It can be used to do almost anything that can be done from the web interface and more, including things like editing articles, listing articles in categories, listing all kinds of links on a page and much more. Querying the various lists available can be done using LINQ queries, which then get translated into efficient API requests.


 No Rating

Getting Started With ASP.NET 5 On Ubuntu

16. June 2015 22:59

.NET Framework ASP.NET ASP.NET MVC C# Microsoft  Ubuntu Visual Studio Web  2 Comments

Ever since the .NET stack went open source last year, there is a huge excitement among the developers about the .NET stuff and developing apps using .NET which are no longer limited to Windows platform. I tried to install ASP.NET VNext on Ubuntu VM in which I terribly failed in the first go. Why? because the tutorial I used was quite old and I messed up the installation of pre-requisites. But I get everything working in the second try. So here are the steps and commands that will get you started with ASP.NET VNext on Ubuntu.

I am setting up a fresh VM for development on Ubuntu 14.04.2 LTS

Installing Mono

First thing is to install Mono. For folks who are new to Linux environment, Mono is a community driven project which allows developers to build and run .NET application on Linux platforms. Here is the set of commands that I have to execute to install Mono.

sudo apt-key adv --keyserver --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF

echo "deb wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update

Install the latest version of Mono available.

sudo apt-get install mono-complete

To check if Mono is successfully installed or to determine the version of Mono on you machine run the below command in the terminal.

mono --version

Installing LibUV

As stated on Github:

Libuv is a multi-platform asynchronous IO library that is used by the KestrelHttpServer that we will use to host our web applications.

Running the below command will install LibUV along with the dependencies require to build it.

sudo apt-get install automake libtool

Getting the source and building and installing it.

curl -sSL | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.4.2
sudo sh
sudo ./configure
sudo make 
sudo make install
sudo rm -rf /usr/local/src/libuv-1.4.2 && cd ~/
sudo ldconfig

Here is a note at Githb repo that explains what the above set of commands are doing.

NOTE: make install puts in /usr/local/lib, in the above commands ldconfig is used to update so that dlopen (see man dlopen) can load it. If you are getting libuv some other way or not running make install then you need to ensure that dlopen is capable of loading

Getting .NET Version Manager (DNVM)

DNVM is a command line tool which allows you to get new build of the DNX (.NET Execution Environment) and allows you to switch between them. To get DNVM running fire the below command in the terminal.

curl -sSL | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/

To check if the DNVM is successfully installed on your machine, type DNVM in the terminal. The output should be something like this:

At any point of time if you want to list out the installed DNX runtimes, run the below command

dnvm list

The next step after this, is to upgrade the DNVM so you can use the dnx and dnu commands. Run the following command in the terminal

dnvm upgrade

Once this is done, we are all set to run ASP.NET VNext application on Ubuntu box. Clone the aspnet/Home repository from Github. If you don't have Git installed then install it with this simple command.

sudo apt-get install git

For simplicity, I have created a new directory on Ubuntu desktop named vnext. You can name the directory as you wish. Navigate to this directory in the terminal and clone the aspnet/Home repository.

git clone

After cloning of repository is done, navigate to the 1.0.0-beta4 directory.

You can see three sample applications that you can test. For this tutorial I am going to checkout HelloMvc application. Get inside the HelloMvc directory and then, run the command 

dnu restore

This will take some time to execute. I didn't face this problem but there is a chance that someone will. When you run this command, the project.json.lock file gets created and the restore of the package will start. In the end when the restore is finalizing, it may say permission is denied. To resolve this error you can change the permission of the folder by running the following command.

sudo chmod -R 755 HelloMvc

You should always change permission to 755 for directories and 644 for files.

After the execution is completed, you can start the server by running the command.

dnx . kestrel

This command will work for both web and mvc application. If you plan to test out the console application then you can run the following command.

dnx . run

The server runs at port 5004. Fire up the browser and type in http://localhost:5004/

Hope this is helpful for the first time users of Linux.

Currently rated 5.0 by 1 person

Visit to discover Indian blogs Computers Blogs