Saturday, June 26, 2010

Formatting Source Code for Blogger.com (and other blog sites)

When you search the net for a solution to formatting source code for your blog there won’t be a shortage of hits. I’ve tried quite a large number of them only to be disappointed.

The best option I’ve found so far is this syntax highlighting tutorial. It uses a hosted version of Alex Gorbatchev’s SyntaxHighlighter, which has gained a lot of popularity (e.g. ASP.NET forums).

Here is an example for how your source code looks like once you’ve set everything up:

using System.Net.Mail;

public class EmailHelper {
   private static void SendEmail(string from, string to, string subject, string body) {
      var message = new MailMessage(from, to, subject, body);
      using (var smtpClient = new SmtpClient()) {
         smtpClient.Send(message);
      }
   }
}

And your XML code would look as follows (note the error in the multi-line comment, at time of publishing this post):

<system.net>
   <mailSettings>
      <!-- Setting for release (need to update account settings): -->
      <!--<smtp deliveryMethod="Network">
         <network host="mail.mydomain.com" port="25" />
      </smtp>-->
      
      <!-- Setting for development (uses ssfd.codeplex.com): -->
      <smtp deliveryMethod="SpecifiedPickupDirectory">
         <specifiedPickupDirectory pickupDirectoryLocation="C:\data\Temp" />
      </smtp>
   </mailSettings>
</system.net>

image After some more searching I then found PreCode, yet another plug-in for Windows Live Writer (WLW). PreCode also supports SyntaxHighlighter.

When you use PreCode, it will also take care of the angle brackets as they need to be substituted so they are not interpreted as HTML.

Finally I seem to have found a solution that allows me to work seamlessly.

Here are the bits for this solution:

  • SyntaxHighlighter: See Alex Gorbetchev’s web site for more details, and check the syntax highlighting tutorial for how to set up your blog / web site.
  • PreCode: Download Precode from codeplex and install. Restart WLW.

The only thing missing – but I can live with that for the moment: The code is displayed in Edit and Preview mode in WLW but not highlighted. PreCode’s web site explains why.

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!