Tuesday, September 27, 2011

How to format code in your blog - the easy way

I've spend numerous hours trawling the internet looking for ways to make the code that I use in my blog easy to read and nicely formatted. Unfortunately I've never managed to find anything that cuts the mustard and I had resigned myself to having to use numerous hacks. That is until I saw a colleague cut and paste some code that he was working on into a Wiki and it came out perfectly formatted straight from Visual Studio!

"How the %$#@ did you do that?" I shouted
"Don't know - I just cut and pasted" was the reply
"Can't be. Visual Studio doesn't use HTML for it's code editor"

Sure enough when we cut and pasted the code into a text editor you could see that it was perfectly styled using CSS. Afer a bit of digging we discovered that he had Power Productivity Tools installed which has the capacity to enable HTML cut and paste - Eureka!

You can get this add on using NuGet (Tools -> Extension Manager -> Online Gallery and then search for Power Productivity Tools).

Now I can cust and paste code like this straight from Visual Studio:
<h2>Log On</h2>
    Please enter your pin and password. 
@Html.ValidationSummary(true"Login was unsuccessful. Please correct the errors 
and try again.")
@using (Html.BeginForm()) {
            <legend>Account Information</legend>



  1. Thanks for sharing this useful coding. It is very useful for me.

  2. Hey thanks for sharing this post. Its really helpful.

  3. This comment has been removed by a blog administrator.

  4. I've just always had trouble with my blog's styles messing with the spacing of the lines and lots of other problems, so I created http://www.blogtrog.com as a personal solution, but anyone else is welcome to use it. It uses a pretty iframe where possible (like on your web page), and basic syntax highlighted code elsewhere (like inside Google Reader).