I wrote a little extension for BlogEngine.NET 1.2 that parses BBCode for use in the comments. BBCode allows you to write square bracket syntax to format your text. It’s smart because it gives more power to the people commenting and it gives you total control over the HTML output because BBCode is not HTML – the parsing takes place server side when the comment is served and not when it is saved.

So, when you write a comment you can now use these few BBCode tags. More will come when I find out which ones make most sense.

Bold [b]some text[/b]

Italic [i]some text[/i]

Cite [cite]some text[/cite]

You can easily add new tags your self by adding a single line in the extension. Also, if you want to be able to write BBCode syntax in your posts, you can easily do that by adding a single line to the constructor of the extension. Just type in this line:

Safety first

A BBCode parser is not as straight forward to write as you might expect. It’s not just a matter of replacing [b] with <strong> since that can lead to trouble. Let’s say someone writes this comment:

It’s a [b]lovely weather today.

If we just replace [b] with <strong> then the entire page will become bold since the tag is never closed. That means a wrong formatted comment can turn your entire website into something very ugly.

Instead we need to make sure that all BBCode tags are closed before we parse them. This extension will parse all the correctly closed BBCode tags even though there is a malformed tag in the same comment. It simply ignores the malformed tag and moves on and thereby doesn’t screw with the design of the site.

Implementation

Download the BBCode.cs file below and paste it into the /App_Code/Extensions/ folder of your BlogEngine.NET 1.2 installation.