Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

Code Formatter for HTML

by Ioannis Panagopoulos

I have been searching for some time for a neat html code generator from C# code that supports syntaxt highlighting, in order to use it in BlogEngine.Net. The previous posts in this article have been written by applying the usual _[_code:cs]...[_/code] tags. Unfortunately this approach does not always work correctly especially when somebody wants to copy-paste code directly from Visual Studio. Moreover it would be nice if the converter was univeral, that is it could be used independently of BlogEngine.

What I want to do is copy-paste code from a program I have written in Visual Studio, convert the code to html with tags defining what each word is (keyword, comment, string etc), copy-paste this code to my HTML page or the BlogeEninge's javascript editor (in HTML mode) and finally apply some styles in the css file to define the colors of the words.

I am putting in this post a small program I have written that can help towards this direction. You can copy-paste any code from a Visual Studio window and get its simple html version in the form described above. You only have to copy-paste this code to your post as plain html and add to your .css file, the formatting directives as you will see in the accompanying zip file. Here are some results acquired using this tool:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ConverVSCodeToHTML
{
    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormConverter());
        }
    }
}

Or the following:

if (level == 1)
{
    if (CharRead[0] == ' ')
        convertedString += "hello";
    else
        convertedString += CharRead[0].ToString();
   
}
BytesRead = rdr.Read(CharRead, 0, 1);
break;


The program works as follows: The code is initially in RTF format. The software looks for the color directives of the RTF code and based on the coloring defines the word as keyword, comment, string etc. This means that If you have changed the default syntax coloring of VS 2008 this program will not work. Note also that this syntax highlighter can be used independently of BlogEngine.NET if you want to easily copy-paste code to your HTML page.

Finally I stress that this is a beta version of the software and therefore any bug reports/comments are more than welcome. Note also that there is a minor bug in the code generated. Specifically, exactly at the start of the generated code the text "lang 1024" is displayed. You must manually erase that.

CSToHTMLConverter.zip (14,22 kb)

blog comments powered by Disqus
hire me