Sunday, February 21, 2010

Add C# Code Formatter Widget To Your Blog

This widget formats all the C# code in your blog so it looks exactly like in Visual Studio.
It supports all the cases of string literals, comments, keywords and preprocessors. It has a huge list of all commonly used types, and it has some capability of learning new types (classes, enums, interfaces, structs) from your code.
Try it now online! - OR - Add it to your blog:
Note: the widget is for lazy people like me, if you want you can add the formatting script to your HTML Layout manually.

Here is a simple example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace exp1
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello, world!");
        }
    }
}

This is what the author sees when writing the post:
<pre formatcs="1">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace exp1
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello, world!");
        }
    }
}</pre>

So how does it work?
The script scans the page looking for <pre> elements with the attribute formatcs=1. Each element is then formatted as C# code.
The <pre> tag was chosen for a reason - if the user doesn't have JavaScript supported, then the <pre> tag is the best way to show code in a blog.

Here is a more advanced example:
[XmlRoot("Node")]
class MyNode<T> : MyBaseClass<T>
    where T : Dictionary<List<T>, int>, ISerializable
{
    MyNode MyNode = new SuperNode();
    
    /// <summary>   *
    /// comment2... *
    /// </summary>  *
    MyType1 foo(out MyType2 x)
    {
        x = MyType1.StaticFunction(@"c:\");
        Console.WriteLine(" aaaa \" \\\" \\\\");
        return new T();
    }
}
Note that these classes are being deduced by reading the code: MyNode, MyBaseClass, SuperNode, MyType1, MyType2.
Note that "T" is not styled as a type, exactly as in Visual Studio.

OK OK! I'm convinced! How do I add this widget to my blog?
Simply by clicking here:
- Or - You can use the online version here:
formatmycsharpcode.blogspot.com

For more information refer to this wiki page.

2 comments:

  1. Do you know how I can remove the
    tags? Everything is on one line.

    ReplyDelete