The Stochastic Game

Ramblings of General Geekery

Posts tagged with trick

The extension method trick

If you’ve been writing C# code lately you should be pretty familiar with extension methods: it’s a nice compiler feature added to C# 3.0 which lets you “attach” methods to an existing type.

So for instance, if you define the following extension method:

    static class ConsoleExtensions
        public static void WriteReversed(this TextWriter writer, string message)
            writer.WriteLine(new string(message.Reverse().ToArray()));

You can write:

    Console.Out.WriteReversed("hello world!");

You effectively “extended” the TextWriter type with a new WriteReversed method in which you get a pseudo-this reference. Before extension methods, these types of methods would have been in a ConsoleHelper class of some kind – a lot less discoverable for the clients of your library.

Now, the (not so-)peculiar thing about it is that the pseudo-this variable can be null. Indeed, since this whole feature is only syntactic sugar, as they say, it’s just a more elegant way to write the following, which is a plain old function call:

    ConsoleExtensions.WriteReversed(Console.Out, "hello world!");

But it means it would look like you’re calling a method on a null object without getting slapped in the face with the infamous NullReferenceException.


You just need to add some simple parameter validation code to your extension method:

    static class ConsoleExtensions
        public static void WriteReversed(this TextWriter writer, string message)
            if (writer != null)
                writer.WriteLine(new string(message.Reverse().ToArray()));
    TextWriter writer = null;             // woah, are you crazy!?
    writer.WriteReversed("hello world!"); // woah, this is crazy!!

This trick can be pretty useful if you have an API that aims to be as minimalist as possible for the user and null is a valid case for one of the objects exposed publicly. You can already handle this with various well known techniques like wrapping or the NullObject pattern, but the extension method is a nice new alternative that’s enough in some cases and requires a minimum of code.

I’ve seen that trick used only once so far, in the excellent MvcMiniProfiler:

    using (MiniProfiler.Current.Step("Getting the answer to the ultimate question"))
        var result = DeepThought.Compute();
        ViewBag.UltimateAnswer = result;

Here, it’s totally OK if you disabled profiling in your web application, which means MiniProfiler.Current would return null. That’s because the Step() method is an extension method that checks for a null value provided as “this”, and doesn’t do much in that case.

Sure, they could have abstracted the profiler behind an IProfiler interface and have the MiniProfiler.Current return a NullProfiler when profiling is disabled, or something like that, but that would have been a lot more code than just using an extension method.

Formatting mongo output

If you’re working with MongoDB‘s mongo command line tool and you often see yourself reading through this:

> db.contactInfos.find({"source":ObjectId("4e39da93058cfe28a039b546")})

{ "_id" : ObjectId("4e6e9a9f058cfe01dc1bcded"), "source" :ObjectId("4e39da93
058cfe28a039b546"), "sourceId" : "754731", "sourceUserName" : "loudej", "ful
lName" : "Louis DeJardin", "description" : "A software guy on the ASP.NET te
am and author of Spark", "avatarUrl" : "
161371928/DSC01367_normal.jpg", "websiteUrl" : "",
"location" : "Kenmore, WA", "friendCount" : 97, "followerCount" : 1428 }
{ "_id" : ObjectId("4e6e9a9f058cfe01dc1bcdf3"), "source" : ObjectId("4e39da9
3058cfe28a039b546"), "sourceId" : "16925866", "sourceUserName" : "sebastienr
os", "fullName" : "Sébastien Ros", "description" : "", "avatarUrl" : "http:/
normal.jpeg", "websiteUrl" : "", "location" : "S
eattle", "friendCount" : 18, "followerCount" : 142 }
{ "_id" : ObjectId("4e6e9a9f058cfe01dc1bcdf4"), "source" : ObjectId("4e39da9
3058cfe28a039b546"), "sourceId" : "768197", "sourceUserName" : "haacked", "f
ullName" : "Phil Haack", "description" : "This bio is not true.", "avatarUrl
" : "", "websi
teUrl" : "", "location" : "Bellevue", "friendCount" : 225
, "followerCount" : 15947 }

…then you may want to add toArray() at the end of your line:

> db.contactInfos.find({"source":ObjectId("4e39da93058cfe28a039b546")}).toArray()

        "_id" : ObjectId("4e6e9a9f058cfe01dc1bcded"),
        "source" : ObjectId("4e39da93058cfe28a039b546"),
        "sourceId" : "754731",
        "sourceUserName" : "loudej",
        "fullName" : "Louis DeJardin",
        "description" : "A software guy on the ASP.NET team and author of Spark",
        "avatarUrl" : "",
        "websiteUrl" : "",
        "location" : "Kenmore, WA",
        "friendCount" : 97,
        "followerCount" : 1428

        "_id" : ObjectId("4e6e9a9f058cfe01dc1bcdf3"),
        "source" : ObjectId("4e39da93058cfe28a039b546"),
        "sourceId" : "16925866",
        "sourceUserName" : "sebastienros",
        "fullName" : "Sébastien Ros",
        "description" : "",
        "avatarUrl" : "",
        "websiteUrl" : "",
        "location" : "Seattle",
        "friendCount" : 18,
        "followerCount" : 142
        "_id" : ObjectId("4e6e9a9f058cfe01dc1bcdf4"),
        "source" : ObjectId("4e39da93058cfe28a039b546"),
        "sourceId" : "768197",
        "sourceUserName" : "haacked",
        "fullName" : "Phil Haack",
        "description" : "This bio is not true.",
        "avatarUrl" : "",
        "websiteUrl" : "",
        "location" : "Bellevue",
        "friendCount" : 225,
        "followerCount" : 15947

Much more readable, isn’t it? The only problem is that mongo will, by default, return only the first 20 hits of a query (it will write “has more” at the bottom to indicate that, well, there’s more). The toArray() method, however, will get everything and print it out. This could mean printing a lot of stuff, so you may want to stick a limit(20) in between if you’re not sure:

> db.contactInfos.find({"source":ObjectId("4e39da93058cfe28a039b546")}).limit(20).toArray()

Spam your friends with Yahoo! Pipes

You know how it goes: you’re an internet hipster with blogs and Twitter feeds and all that kind of new age stuff, but only other internet hipsters read them. Your friends (at least the ones that are not internet hipsters) only stick to Facebook. So how can you bring your stuff to them?

At first, it seems easy: Facebook can pull “stories” from various websites and services. Go to your profile, and under the status update box, click “Options” and then “Settings”. You get the following interface:


That’s cool for most people. You bring in your Flickr photos, and your blog articles, and maybe a few other things… but what happens if you’ve got more than one blog? The “Blog/RSS” site can be only chosen once. Also, notice how you can choose Google Reader as a story source. Sure, this works, but the way your shared items appear on your wall is not optimal: they appear as “secondary activities”, presented like your comments or likes, sometimes merging several ones together which adds extra clicks to get to the actual article (e.g: “Ludovic shared 2 new items on Google Reader”, with only a link to your shared items page, which means you don’t know which 2 items were shared, as they may not be the last 2 ones if there have been other, newer ones since then). At least it was like that a few months ago (maybe they fixed it in the meantime, you tell me). That’s not proper spamming, so let’s do it the power user way.

A few years ago, Yahoo launched Yahoo! Pipes, a website that lets you build feed mashups. I decided to use that to aggregate all my stuff and post it on my Facebook wall.

It’s pretty simple, at first. You just go to the Yahoo! Pipes website, log-in, click “Create a pipe”, and add one source node for each site you want to pull data from. You’ll most probably use “Fetch Feed” nodes with the direct URL to your blogs and shared items RSS or Atom feeds, but you can also use some “Fetch Site Feed” nodes, too (they will find the actual feed URLs like any feed reader would do). Now pick the “Union” node from the “Operators” category, and plug all your sources into it. Plug the “Union” output into the “Pipe Output” node that should have been created by default for you. Voilà, you have an aggregated feed that you can import on your wall on Facebook!


Or do you?

One problem you’ll notice right away is that all the items from the first feed are displayed, and then all the items from the second feed, and so on… The “Union” node only built a, well, union of those feeds. You need to re-order them by date so that all the items from all the sources are correctly mixed together. For this, add a “Sort” node, as shown above, that will sort items by “item.pubDate”.

There. Fixed? Nope… not yet.

Now you have a user experience problem. All those items appear as “notes” on your Facebook wall, with their contents directly readable. If you’re pulling feeds from your own websites and feeds from elsewhere at the same time (e.g. your Google Reader’s shared items feed), it becomes difficult for your friends to figure out which stuff was written by you, and which stuff is just cool shit you found on the web and wanted to share. You need to create a differentiator, like for example prepend “Shared on Google Reader:” in front of each of your shared items’ titles.

I’m still evaluating different options but at the moment I’m using something a bit less user-friendly, although definitely more friendly to the websites from which I share stuff from: I completely replace the contents of the item with a link to the actual article on its original website. This means that people can’t read the item right there (they need to click on the link), but it also means the people who posted the cool shit in the first place get a visitor that will potentially start clicking around on links and ads if he linked whatever I shared.

For this I created a different pipe, although I could have hard-coded it in the first one.


This pipe basically gets my Google Reader shared items feed and processes it in a loop: for each item, I replace the contents with a link whose text is just the title of the item. Inject this new pipe into the first one (you can reference a pipe inside another pipe) and, at last, you’re done!

The only problem I’ve had so far is that, after adding my aggregated feed to Facebook for the first time, the mobile version of the website did something funky. Instead of weaving all those notes into my friends’ timelines, moving the older items behind the more recent updates from other people and applications, it put everything it could at the top. So basically, I really spammed all my friends with dozens and dozens of items that were several weeks or even several months old. This bug didn’t affect the normal website, neither did it affect the iPhone application, as far as I could tell, so I only got a couple complaints. And hopefully they fixed the bug since then.

That’s pretty much it. You can find the 2 pipes I showed here and here.

Visual Studio Tips & Tricks

Stephen Walther recently blogged about tricks that every developer should know about Visual Studio. Most of those he mentioned I use on a daily basis, so I highly recommend them. It actually surprises me how many other programmers don’t know about those features. Somehow, most programmers know Visual Studio as much as they know Microsoft Word: there’s a big space in the middle to type your text, and then maybe they know a couple of menus and shortcuts and that’s it.

Anyway, here are a few other features I use frequently:

Tip #1 – Use CTRL-I for incremental search

I’m a big fan of incremental search. It’s actually the reason I originally switch from Internet Explorer to Firefox, back when Firefox was in beta (I already had tabs with Netcaptor). By the way, I’m happy to see IE8 now also features incremental search but, well, I’m hooked on FF now… anyway…

In Visual Studio, the incremental search mode is entered with CTRL-I. Then you can start typing right away what you want to find. You can also use backspace and all, as expected. The only problem is that it uses the last search mode defined in the “Find” dialog, so if the “Match case” option is currently checked, it will only perform incremental search on what you type in a case sensitive way. This may be a bit confusing at first, but using incremental search really makes navigating code faster.

Tip #2 – Use navigate backward and forward

Like the first tip, this tip make it faster to navigate code (because we’re spending more time reading code than writing code).

CTRL– (minus sign) and CTRL-SHIFT– allow you to respectively navigate backward and forward. The first one is the one I use almost all the time: I’m looking at some code, see a call to a function, go to the definition of that function, search for something, and then I want to go back to where I was at first. Well, without having to worry about anything, I can navigate backward twice and I end up where I want. No need to find the correct tab, figure out if I stayed in the same file or not while jumping through the code, etc. Wicked!

Tip #3 – Define some external tools

You can define “external tools” with, surprisingly, the Tools > External Tools menu item. A common thing for me is to define revision control related stuff there because most of the time I don’t like how buggy and slow source control plugins are. I also do this in Visual Studio Express where there is no support for plugins at all in the first place.

For example, say you’re using Perforce. You can create a new external tool like this:


It will checkout the current file (the one you’re editing if the focus is in the text editor, or the one selected in the Solution Explorer if that’s where the focus is). Now you just need to bind “Tools.ExternalCommand2” (because it’s the second external tool) to the keyboard shortcut of you choice (mine is CTRL-K, CTRL-E for “open for edit”). Shazam! Just use your keyboard shortcut and you can checkout a file without leaving the text editor.

You can setup other commands, like show the history of the file or make a diff with the previous version. You can also easily adapt this to other systems, like SubVersion (except in this case you won’t need the “open for edit” command because SVN doesn’t lock files by default).

XAML markup is for real men

The Visual Studio designer for WPF is quite lame as it stands now, and although it will get a lot better when Visual Studio 2008 SP1 is released, if you're a WPF developer, you really need to know how to read and write XAML by hand, much like web developers and designers know how to read and write HTML and CSS by hand.

Since you're not a wussy, what you actually want is for Visual Studio to always show a full view of the XAML markup when you open a XAML document. It's also a good thing because you won't have to wait for a few seconds for the designer to load the first time.

To do this in Visual Studio 2008 Express, go to the Options dialog, check "Show all settings", and go to "Text Editor", "XAML", "Miscellaneous". There, check the "Always open documents in full XAML view".