MSDN Style Syntax Highlighting In ASP.NET

There are many syntax highlighting plugins available on the web right now. Majority of the sites are using javascript based Syntax Highlighter from Alex Gorbatchev. I am using it for my current blog and BlogEngine.NET has it as a default syntax highlighter. It is good because it has a lot of themes to offer and you can also customize according to the look and feel of your blog or site. Moreover it has support for multiple languages which makes it acceptable among most of the bloggers and developers.

I also like the way MSDN and Codeplex style their code. Although it has some flaws like moving the code to the next line if it exceeds the length of the pre or div tags. The library MSDN and Codeplex are using for syntax highlighting is ColorCode. ColorCode is open-source and supports every language specific to Microsoft. The way ColorCode works is totally different than that of any other syntax highlighting library. Javascript based syntax highlighter use CSS for different styles whereas ColorCode uses in-line CSS to set styling for the code.

To install ColorCode you can use NuGet command or add ColorCode reference as a library downloadable from Codeplex. NuGet command:

PM> Install-Package ColorCode

Only Microsoft stack languages are supported by ColorCode. Here is the complete list:

  • XML
  • Java
  • JavaScript
  • SQL
  • C#
  • VB.NET
  • ASPX (C#)
  • ASPX (VB.NET)
  • C++
  • PHP
  • PowerShell
  • Typescript
  • FSharp

As I mentioned earlier that this library uses in-line CSS and therefore you cannot use it in the windows forms application. You can use the webbrowser control in windows forms application if you want code to render correctly.

This is a sample basic usage of ColorCode.

string code = File.ReadAllText(Server.MapPath("~/Test.txt"));
string finalCode = new CodeColorizer().Colorize(code, Languages.CSharp);
codediv.InnerHtml = finalCode;

First line of the code will read all the text from a file. The second line will initialize a new CodeColorizer class Colorize method which will take 2 parameters, first is the code for which we want the syntax highlighting for and the second parameter is language. I now have the finalCode string which has the code with syntax highlighting. This is the output I have in my browser window.

MSDN Style Syntax Highlighting

It looks pretty good from the front but behind the scenes it’s not that pretty.

MSDN Style Syntax Highlighting Code Behind

ColorCode is an open-source library and is hosted on Codeplex.

Reference:

comments powered by Disqus