Formatting Source Code in your Blog

Posted by: Clarity Blogs: ASP.NET, on 27 Oct 2008 | View original | Bookmarked: 0 time(s)

I really like it when blogs authors take the time to properly format source code in their posts. I work in Visual Studio every day, and immediately make a visual connection to well-indented and color-coded source code.

If you own the book WPF Unleashed, you know that one of the best things about it is that all the XAML looks exactly like it does in Visual Studio (or Blend). So purrty!  I heard an interview with Adam Nathan in which he talked about how he had to manually format each snippet of code for the publisher.

Thankfully, there are easier ways to do this for blogs. I often include code snippets in my blog posts, but I'm guilty of relying too much on the Windows Snipping Tool to just "snip" code out of Visual Studio.

That's a cop out, so what are some better ways? Here are some freely available tools that I've tried out:

http://formatmysourcecode.blogspot.com/

This is a pretty simple tool - you paste your source code into a textbox, specify some options, and click a button to generate HTML which you can paste into your post.

 /> </p><pre style= /// <summary> /// Ensures the correct content types are added to the /// Pages library associated with the Publishing Portal. /// </summary> private void EnsureContentTypes (SPWeb site, string pagesList) { SPContentTypeCollection pageCTs = site.Lists[pagesList].ContentTypes; foreach (SPContentType contentType in site.Site.RootWeb.AvailableContentTypes) { if (IsCustomContentType(contentType) && pageCTs[contentType.Name] == null) pageCTs.Add(contentType); } }

Looks decent, but the output isn't specifically color-coded to the language that the code is in.

c# code format

The tool at http://www.manoli.net/csharpformat/  is one of my favorites. It can format c#, vb, html/xml/xaml/aspx, t-sql, and others. You can also choose to show line numbers and alternate line backgrounds.

When using this, you specify whether or not to embed the necessary styles in the generated output. You can upload the style sheet it uses to your blog, and configure your blog engine to make the style sheet visible to all your posts.

 /> </p>
<p>Here's some nicely formatted xml: 

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}

.csharpcode .lnum { color: #606060; }


<pre class= 1: <ElementManifests>

   2:      <ElementManifest Location="masterPages.xml" />
   3:      <ElementManifest Location="pageLayouts.xml" />
   4:   
   5:      <ElementFile Location="MasterPages\PublishingMinimalTmp.master" />
   6:      <ElementFile Location="MasterPages\PublishingMinimalPreviewTmp.png" />
   7:      <ElementFile Location="PageLayouts\MinimalTmp.aspx" />
   8:      <ElementFile Location="PageLayouts\MinimalPreviewTmp.png" />
   9:      <ElementFile Location="PageLayouts\MinimalTOCTmp.aspx" />
  10:      <ElementFile Location="PageLayouts\MinimalTOCPreviewTmp.png" />
  11:    </ElementManifests>

and some c#:

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }
   1:  List<Person> peeps = new List<Person>()
   2:  {
   3:      new Person{FirstName="George", LastName="Durzi", Age=32},
   4:      new Person{FirstName="Mark", LastName="Durzi", Age=29},
   5:      new Person{FirstName="Amy", LastName="Shafer", Age=33}
   6:  };
   7:   
   8:  IEnumerable<Person> results = peeps.Where(p => p.LastName == "Durzi");
   9:  double averageAge = peeps.Average(p => p.Age);

Note how the formatting missed some c# keywords like List and IEnumerable - that's my only complaint with the tool.

c# code format Plugin for Windows Live Writer

Mike Ormond took this to the next level and made it into a plugin for Windows Live Writer which you can download here. The plugin gives you a new option called Formatted Code under the Insert menu item.

  /> </p>
<p>I like this tool because I use Windows Live Writer to write my posts, but check out how it got thrown off by the < and > characters - rendering them as < and &ht;. </p>
<pre>   1:  </span></span>L</span>i</span>s</span>t</span>&</span>l</span>t</span>;</span>P</span>e</span>r</span>s</span>o</span>n</span>&</span>g</span>t</span>;</span> </span>p</span>e</span>e</span>p</span>s</span> </span>=</span> new</span></span> </span>L</span>i</span>s</span>t</span>&</span>l</span>t</span>;</span>P</span>e</span>r</span>s</span>o</span>n</span>&</span>g</span>t</span>;</span>(</span>)</span></pre><pre>   2:  </span></span></pre><pre>   3:  </span></span>{</span></pre><pre>   4:  </span></span></pre><pre>   5:  </span></span> </span> </span> </span> new</span></span> </span>P</span>e</span>r</span>s</span>o</span>n</span>{</span>F</span>i</span>r</span>s</span>t</span>N</span>a</span>m</span>e</span>="George"</span></span>,</span> </span>L</span>a</span>s</span>t</span>N</span>a</span>m</span>e</span>="Durzi"</span></span>,</span> </span>A</span>g</span>e</span>=</span>3</span>2</span>}</span>,</span></pre><pre>   6:  </span></span></pre><pre>   7:  </span></span> </span> </span> </span> new</span></span> </span>P</span>e</span>r</span>s</span>o</span>n</span>{</span>F</span>i</span>r</span>s</span>t</span>N</span>a</span>m</span>e</span>="Mark"</span></span>,</span> </span>L</span>a</span>s</span>t</span>N</span>a</span>m</span>e</span>="Durzi"</span></span>,</span> </span>A</span>g</span>e</span>=</span>2</span>9</span>}</span>,</span></pre><pre>   8:  </span></span></pre><pre>   9:  </span></span> </span> </span> </span> new</span></span> </span>P</span>e</span>r</span>s</span>o</span>n</span>{</span>F</span>i</span>r</span>s</span>t</span>N</span>a</span>m</span>e</span>="Amy"</span></span>,</span> </span>L</span>a</span>s</span>t</span>N</span>a</span>m</span>e</span>="Shafer"</span></span>,</span> </span>A</span>g</span>e</span>=</span>3</span>3</span>}</span></pre><pre>  10:  </span></span></pre><pre>  11:  </span></span>}</span>;</span></pre><pre>  12:  </span></span></pre><pre>  13:  </span></span></pre><pre>  14:  </span></span></pre><pre>  15:  </span></span>I</span>E</span>n</span>u</span>m</span>e</span>r</span>a</span>b</span>l</span>e</span>&</span>l</span>t</span>;</span>P</span>e</span>r</span>s</span>o</span>n</span>&</span>g</span>t</span>;</span> </span>r</span>e</span>s</span>u</span>l</span>t</span>s</span> </span>=</span> </span>p</span>e</span>e</span>p</span>s</span>.</span>W</span>h</span>e</span>r</span>e</span>(</span>p</span> </span>=</span>&</span>g</span>t</span>;</span> </span>p</span>.</span>L</span>a</span>s</span>t</span>N</span>a</span>m</span>e</span> </span>=</span>=</span> "Durzi"</span></span>)</span>;</span></pre><pre>  16:  </span></span></pre><pre>  17:  </span>double</span></span> </span>a</span>v</span>e</span>r</span>a</span>g</span>e</span>A</span>g</span>e</span> </span>=</span> </span>p</span>e</span>e</span>p</span>s</span>.</span>A</span>v</span>e</span>r</span>a</span>g</span>e</span>(</span>p</span> </span>=</span>&</span>g</span>t</span>;</span> </span>p</span>.</span>A</span>g</span>e</span>)</span>;</pre>
<p>I also get pretty annoyed with extra carriage returns, somehow they sneak into the HTML when using this plugin. And since it's based on the same code as the <strong>c# code format </strong>tool, it's also going to miss the List and IEnumerable keywords. </p>
<h3>syntaxhighlighter</h3>
<p>You can download this from Google Code at <a title=http://code.google.com/p/syntaxhighlighter/.

To use this tool, you have to upload some JavaScript and CSS files to your Blog and reference them from your post. This is explained in the Usage page for syntaxhighlighter which you can find at http://code.google.com/p/syntaxhighlighter/wiki/Usage.

You can style code snippets by daisy-chaining css attributes to the style applied to a <pre> tag that the code lives in, e.g. class="c-sharp:nocontrols" to denote that the snippet is in c#, and that I don't want any of the syntaxhighlighter controls to be displayed.

This was the toughest one to get working, and since it's JavaScript based can get pretty slow if you're applying it to a large amount of code. You won't come across this limitation for normal code snippets in your post. syntaxhighlighter also has support for the most number of languages.

Unless I'm doing something wrong, the way this works is through a script in the window.onload event. This caused some issues during authoring in Windows Live Writer - the onload script would recreate the code snippet every time I switched between web preview mode and HTML mode.

I can't get this to work property, so I'm pasting a snip of what it looks like when it's working.

 /> </p>
<p>The most solid and feature-rich of all the tools, but I couldn't get it to work properly...</p>
<h3>Verdict</h3>
<p>Based on ease of use and the consistency of results, I recommend the <strong>c# code format</strong> tool at <a title=http://www.manoli.net/csharpformat/.

I don't event want to look at the View - Source of this post!

Links

Advertisement
Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.
Category: C# | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 1104 | Hits: 13

Similar Posts

  • November's Toolbox Column Now Online more
  • All typed up and nowhere to post more
  • Important releases from Microsoft you may have missed more
  • Migrated from Community Server to DasBlog more
  • Experimenting with MongoDB from C# more
  • Sergejus is running Oxite on Azure and thinking in .NET more
  • RIA Svcs Data Source Control more
  • Tip/Trick: Increase your VS screen real estate by disabling HTML Navigation Bar more
  • True RSS Feed Bankrupcy more
  • The Downside of Transparency more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD