Jacob Carpenter’s Weblog

January 28, 2008

Windows Live Writer Plugin: Element tag around

Filed under: Uncategorized — Jacob @ 10:01 pm

Over the weekend, I met Joe Cheng from the Windows Live Writer team. After asking him about the ease (or potential lack thereof) of plugin authoring, he walked me through a couple of scenarios.

It turns out authoring Live Writer plugins is as easy as using the app itself. Pretty remarkable considering the app is designed to be simple enough that my mom could use it (though I did have trouble locating some simple documentation to compellingly illustrate that fact). No offense, mom.

Joe’s demonstration culminated with showing off his powerful Dynamic Template plugin. He’s even shared the source at CodePlex.

However, not being content to use what’s available (and because it was so ridiculously easy), I decided to write my own plugin:

Element tag around

In the textual discussion of code-type stuff, I’m fond of marking up keywords / class names / local variables / etc. with the html code element. See, I just did it.

I wanted a plugin to simplify adding those elements. I wanted it to be fast to use [keyboard shortcuts]. Also, I know there are all these additional HTML computer code phrase elements, but it’s too inconvenient to remember what they are.

Enter Element tag around:



The most time consuming part of creating the plugin—which took a whopping lunch break—was the layout of the elements on the dialog. Coming from a WPF mindset, dynamically laying out elements in Windows Forms sucks.

As you can see from the screenshot, the available elements are all clearly listed and are insertable via keyboard shortcut (or by simply clicking the associated LinkLabel).

And yes, that was a gratuitous use of my new plugin.



January 3, 2008

C# abuse of the day: Avoiding typecasting null

Filed under: csharp — Jacob @ 3:30 pm

With two posts in as many days, you might get the wrong idea. Let me reassure you: you cannot count on me posting regularly.

That being said, I just found another neat C# abuse and had to share.

It’s occasionally useful (or necessary, or both) to use null as a starting value or to explicitly return a null value. Aside from initializing a local variable, another (more interesting) example of the former is the Enumerable.Aggregatefold for you functional programmers—overload that takes a seed.

In certain circumstances, specifying null can cause difficulty for the compiler. With the previously referenced method, a null seed will break generic type inference and force you to either:

  1. cast null to the correct type (yuck!) or
  2. explicitly specify the two type arguments (double yuck!)

Casting null is also required when trying to use null as a result for the ternary operator (<condition> ? <true-result> : <false-result>). The compiler needs to know (and verify) the type of that expression, and gripes about “no implicit conversion” when it sees a null literal.

It turns out there’s another option, though.

When the .NET Framework 2.0 introduced generics, there was a need for a way to express the default value for a generic type (since generic types could be either value or reference types). So the default keyword (of switch fame) was overloaded with a new function.

What isn’t explicitly mentioned in that documentation is that you can use default with concrete types, too. And an expression using default is strongly typed.

So, now instead of saying:

(ComplexObject) null

You have the option of saying:


I’m not sure yet if I actually prefer this to typecasting null. It certainly looks odd, but that could just be unfamiliarity.

But I thought it had potential and wanted to share. Thoughts?

January 2, 2008

C# abuse of the day: Functional library implemented with lambdas

Filed under: csharp, extension methods, functional programming — Jacob @ 6:09 pm

With all the cool kids writing about F# and functional programming, I started thinking about a possible blog post.

One of my goals was to use lambda syntax to express the functional method implementations. To my eyes, lambdas are great at succinctly expressing higher-order functions. And using the => operator multiple times in a single line rocks! Without thinking about it too hard, I figured I could use static readonly fields to accomplish this goal.

Once I started writing the example code, though, I ran into a bit of a hitch with the generic parameters for the fields’ Func types.

Joseph Albahari (or perhaps his brother and coauthor, Ben) puts it well in C# 3.0 In a Nutshell [which, incidentally, is proving to be a great C# book] (pg. 99):

Generic parameters can be introduced in the declaration of classes, structs, interfaces, delegates […], and methods. Other constructs such as properties [or fields] cannot introduce a generic parameter, but can use one.

Meaning, if I want to declare a field that contains a generic parameter, that generic parameter has to be declared by the containing type.


public static class Functional
    public static readonly Func<Func<X, Y, Z>, Func<X, Func<Y, Z>>> Curry =
        fn => x => y => fn(x, y);

Won’t compile. Instead you’ll get a few of these:

error CS0246: The type or namespace name ‘X’ could not be found (are you missing a using directive or an assembly reference?)

You’d need to modify the class definition like so:

public static class Functional<X, Y, Z>

Now we could add the parameters to our Functional class, but then the calling code would be hideous:

Func<int, int, int> add = (x, y) => x + y;
Func<int, Func<int, int>> addCurried = Functional<int, int, int>.Curry(add);

I mean, I know this is C#, but that is just way too much type decoration. Especially since the three type arguments to Functional should all be inferable.

Ideally, the calling code should be an extension method:

Func<int, int, int> add = (x, y) => x + y;
Func<int, Func<int, int>> addCurried = add.Curry();

And then it dawned on me: we can define generic extension methods on a static FunctionalEx class and delegate the implementation to a nested generic class (with generic fields).

That is, we can hide the ugly syntax of invoking a delegate field of a generic class, while utilizing the ugly syntax of implementing our functional methods using lambdas!

public static class FunctionalEx
    public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> fn)
        return Implementation<T1, T2, TResult>.curry(fn);

    public static Func<T2, T1, TResult> Flip<T1, T2, TResult>(this Func<T1, T2, TResult> fn)
        return Implementation<T1, T2, TResult>.flip(fn);

    private static class Implementation<X, Y, Z>
        public static readonly Func<Func<X, Y, Z>, Func<X, Func<Y, Z>>> curry = 
            fn => x => y => fn(x, y);
        public static readonly Func<Func<X, Y, Z>, Func<Y, X, Z>> flip =
            fn => (y, x) => fn(x, y);

Notice how the Curry extension method is implemented by the curry field of the nested generic Implementation class. Also notice how [un-?]readable the lambda implementation is. (Seriously though, if you look at the flip lambda long enough, it should start to make sense.)

Here’s some (far from practical) sample calling code to help:

class Program
    static void Main(string[] args)
        Func<int, int, int> add = (x, y) => x + y;
        Func<int, Func<int, int>> addCurried = add.Curry();
        Func<int, int> increment = addCurried(1);

        Func<int, int, int> subtract = (x, y) => x - y;
        Func<int, Func<int, int>> subtractFlipped = subtract.Flip().Curry();
        Func<int, int> decrement = subtractFlipped(1);        

        Console.WriteLine("Expected: {0}; Actual {1}", 5, add(2, 3));
        Console.WriteLine("Expected: {0}; Actual {1}", 7, increment(6));

        Console.WriteLine("Expected: {0}; Actual {1}", 6, subtract(9, 3));
        Console.WriteLine("Expected: {0}; Actual {1}", 4, decrement(5));

The output of which is:

Expected: 5; Actual 5
Expected: 7; Actual 7
Expected: 6; Actual 6
Expected: 4; Actual 4

I never did get around to writing that post on functional programming, but I now know how I’m going to implement the library if I do.

If you want to read more on currying in C#, I’d recommend Dustin’s post. In fact I should probably skip writing any further posts on functional programming with C#, since he’s got that topic pretty thoroughly covered.

Blog at WordPress.com.