nuget comments edit

Last night I got a little treat in the mail from the kind folks at StickerMule. I really appreciate how they support open source projects with such great stickers.

NuGet-Stickers-550x365 Look at all those little NuGets!

Just in time as I have a few events I’ll be going to where I can hand some out such as Web Camps Argentina/Brazil, the MVP Summit, and if I’m selected, Mix 2011.

After that, I need to figure out the best way to give the rest out since I won’t be travelling a whole lot this year. We’ll need to have a Nerd Dinner or something. I’ll give some to Scott Hanselman since he travels a lot too. mvc, open source, nuget comments edit

For those of you who enjoy learning about a technology via screencast, I’ve recorded a video to accompany and complement this blog post. The screencast shows you what this package does, and the blog post covers more of the implementation details.

A key feature of any package manager is the ability to let you know when there’s an update available for a package and let you easily install that update.

For example, when we deployed the release candidate for NuGet, the Visual Studio Extension Manager displayed the release in the Updates section.

Extension Manager Displaying NuGet as an Available

Likewise, NuGet lets you easily see updates for installed packages. You can either run the List-Package –Updates command:


Or you can click on the Updates node of the Add Package dialog:


This feature is very handy when using Visual Studio to develop software such as Subtext, an open source blog engine I run in my spare time. But I started thinking about the users of Subtext and the hoops they jump through to upgrade Subtext itself.

Wouldn’t it be nice if Subtext could notify users when a new version is available and let them install it directly from the admin section of the running website completely outside of Visual Studio? Why yes, that would be nice.

NuGet to the Rescue!

Well my friends, that’s where NuGet comes into play. While most people know NuGet as a Visual Studio extension for pulling in and referencing libraries in your project, there’s a core API that’s completely agnostic of the hosting environment whether it be Visual Studio, PowerShell, or other. That core API is implemented in the assemly, NuGet.Core.dll.

This assembly allows us to take advantage of many of the features of NuGet outside of Visual Studio such as within a running web site!

The basic concept is this:

  1. Package up the first version of a website as a NuGet package.
  2. Install this package in the website itself. I know, crazy talk, right?
  3. Add a custom NuGet client that runs inside the website and checks for updates to the one package that’s installed.
  4. When the next version of the website is ready, package it up and deploy it to the package feed for the website. Now, the users of the website can be notified that an update is available.s

I should point out a brief note about step #2, because this is going to be confusing. When I say install the package in the website, I mean to contrast that with installing a package into your Web Application Project for the website.

When you install a package into your Web Application Project, you use the standard NuGet client within Visual Studio. But when you deploy your website, the custom NuGet client within the live website will install the website package into a different location. In the example I’ll show you, that location is within the App_Data\packages folder.

The AutoUpdate Package

Earlier this week, I gave an online presentation to the Community For MVC (C4MVC) user’s group on NuGet. During that talk I demonstrated a prototype package I wrote called AutoUpdate. This package adds a new area to the target website named “Installation”. It also adds a nuspec file to the root of the application to make it easy to package up the website as a NuGet Package.

The steps to use the package are very easy.

  1. Install-Package AutoUpdate.
  2. In Web.config, modify the appSetting PackageSource to point to your package source. In my demo, I just pointed it to a folder on my machine for demonstration purposes. But this source is where you would publish updates for your package.
  3. In the Package Console, run the New-Package script (This creates packages up the website in a NuPkg file).
  4. Copy the package into the App_Data\Packages folder of the site.
  5. When you are ready to publish the next version as an update, increment the version number in the nuspec file and run the New-Package script again.
  6. Deploy the updated package to the package source.
  7. Now, when your users visit /installation/updates/check within the web site, they’ll be notified that an update is available and will be able to install the update.

The Results

Lets see the results of installing the AutoUpdate package and I’ll highlight some of the code that makes the package work. The following screenshot shows a very basic sample application I wrote.


The homepage here has a link to check for updates which links to an action within the area installed by the AutoUpdate package. That action contains the logic to check for updates for this application’s package.

Clicking on that link requires me to login first and then I get to this page:


As I mentioned in the steps before, I packaged up the first version of the application as a package and “installed” it into the App_Data folder.

That yellow bar above is the result of an asynchronous JSON request to see if an update is available. It’s a little redundant on this page, but I could have it show up on every page within the admin as a notification.

Under the Hood

Let’s take a look at the controller that responds to that asynchronous request.

public ActionResult Check(string packageId) {
  var projectManager = GetProjectManager();
  var installed = GetInstalledPackage(projectManager, packageId);
  var update = projectManager.GetUpdate(installed);

  var installationState = new InstallationState {
    Installed = installed,
    Update = update

  if (Request.IsAjaxRequest()) {
    var result = new { 
      Version = (update != null ? update.Version.ToString() : null), 
      UpdateAvailable = (update != null)
    return Json(result, JsonRequestBehavior.AllowGet);

  return View(installationState);

The logic here is pretty straightforward. We grab a project manager. We then grab a reference to the current installed package representing this application. And then we check to see if there’s an update available. If there isn’t an update, the GetUpdate method returns false. There’s a couple of methods here that I wrote we need to look at.

The first method very simply retrieves a project manager. I encapsulated it into a method since I call it in a couple different places.

private WebProjectManager GetProjectManager() {
  string feedUrl = @"D:\dev\hg\AutoUpdateDemo\test-package-source";
  string siteRoot = Request.MapPath("~/");

  return new WebProjectManager(feedUrl, siteRoot);

There’s a couple things to note here. I hard coded the feedUrl for demonstration purposes to point to a directory on my machine. This is a nice demonstrations that NuGet can simply treat a directory containing packages as a package source.

For your auto-updating web application, that should point to a custom feed you host specifically for your website. Or, point it to the official NuGet feed and put your website up there. It’s up to you.

This method returns an instance of WebProjectManager. This is a class that I had to copy from the System.Web.WebPages.Administration.dll assembly because it’s marked internal. I don’t know why it’s internal, so I’ll see if we can fix that. It’s not my fault so please direct your hate mail elsewhere. Smile

What is the web project manager? Well the WebMatrix product which includes the ASP.NET Web Pages framework includes a web-based NuGet client for simple web sites. This allows packages to be installed into a running website. I’m just stealing that code and re-purposing it for my own needs.

Now, we just need to use the project manager to query the package source to see if there’s an update available. This is really easy.

private IPackage GetInstalledPackage(WebProjectManager projectManager,     string packageId) {
  var installed = projectManager.GetInstalledPackages("AutoUpdate.Web")    .Where(p => p.Id == packageId);

  var installedPackages = installed.ToList();
  return installedPackages.First();

What’s really cool is that we can just send a LINQ query to the server because we’re running OData on the server, it’ll run that query on the server and send us back the packages that fulfill the query.

That’s all the code necessary to check for updates. The next step is to write an action method to handle the upgrade. That’s pretty easy too.

public ActionResult Upgrade(string packageId) {
  var projectManager = GetProjectManager();
  var installed = GetInstalledPackage(projectManager, packageId);
  var update = projectManager.GetUpdate(installed);

  if (Request.IsAjaxRequest()) {
    return Json(new { 
      Success = true, 
      Version = update.Version.ToString()
    }, JsonRequestBehavior.AllowGet);
  return View(update);

This code starts off the same way that our code to check for the update does, but instead of simply returning the update, we call projectManager.UpdatePackage on the update. That method call updates the website to the latest version.

The rest of the method is simply concerned with returning the result of the upgrade.

Try it Yourself

If you would like to try it yourself, please keep a one big caveat in mind. This is rough proof of concept quality code. I hope to shape it into something more robust over time and publish it in the main package feed. Until then, I’ll post it here for people to try out. If there’s a lot of interest, I’ll post the source on

So with that in mind, give the AutoUpdate package a try

install-package AutoUpdate

and give me some feedback!

UPDATE: I upgraded the project to target ASP.NET MVC 4 and posted the source on GitHub. I have no idea if it still works, so please do submit pull requests if you find bugs you would like to have fixed., mvc, code, open source, nuget comments edit

The changing of the year is a time of celebration as people reflect thoughtfully on the past year and grow excited with anticipation for what’s to come in the year ahead.

Today, there’s one less thing to anticipate as we announce the final release of ASP.NET MVC 3 and NuGet 1.0!

double-rainbow \ Oh yeah, this never gets old.

Install it via Web Platform Installer or download the installer directly to run it yourself.

Here are a few helpful resources for learning more about this release:

Those links will provide more details about what’s new in ASP.NET MVC 3, but I’ll give a quick bullet list of some of the deliciousness you have to look forward to. Again, visit the links above for full details.

  • Razor view engine which provides a very streamlined syntax for writing clean and concise views.
  • Improved support for Dependency Injection
  • Global Action Filters
  • jQuery based Unobtrusive Ajax and Client Validation.
  • ViewBag property for dynamic access to ViewData.
  • Support for view engine selection in the New Project and Add View dialog
  • And much more!

For those of you wishing to upgrade an ASP.NET MVC 2 application to ASP.NET MVC 3, check out Marcin Dobosz’s post about our ASP.NET MVC 3 Projct upgrader tool. The tool itself can be found on our CodePlex website.

NuGet 1.0 RTM

Also included in this release is the 1.0 release of NuGet. I’ll let you in on a little secret though, if you upgraded NuGet via the Visual Studio Extension Gallery, then you’ve been running the 1.0 release for a little while now.

If you already have an older version of NuGet installed, the ASP.NET MVC 3 installer cannot upgrade it. Instead launch the VS Extension manager (within Visual Studio go to the Tools menu and select Extension Manager) and click on the Updates tab.

Just recently we announced the Beta release of our NuGet Gallery. Opening the door to the gallery will make it very easy to publish packages, so what are you waiting for!?

At this point I’m obligated to point out that everything about NuGet is open source and we’re always looking for contributors. If you’re interested in contributing, but are finding impediments to it, let us know what we can improve to make it easier to get involved. Here’s the full list of OSS projects that make up the NuGet client and the server piece:

Show Me The Open Source Code!

As we did with ASP.NET MVC 1.0 and ASP.NET MVC 2, the source for the ASP.NET MVC 3 assembly is being released under the OSI certified Ms-PL license. The Ms-PL licensed source code is available as a zip file at the download center.

If you’d like to see the source code for ASP.NET Web Pages and our MVC Futures project, we posted that on too.

What’s Next?

So what’s next? Well you can probably count as well as I can, so it’s time to start getting planning for ASP.NET MVC 4 and NuGet 2.0 in full gear. Though this time around, with NuGet now available, we have the means to easily distribute a lot of smaller releases throughout the year as packages, with the idea that many of these may make their way back into the core product. I’m sure you’ll see a lot of experimentation in that regard.

nuget, open source comments edit

As David Ebbo blogged today, the NuGet Gallery is now open to the public. The goal of the NuGet Gallery is to be the hub for NuGet users and package authors alike. Users should be able to search and discover packages with detailed information on each one and eventually rate them. Package authors can register for an API key and upload packages.

We’re not quite where we want to be with the gallery, but we’re moving in the right direction. If you want to see us get there more quickly, feel free to lend a hand. The gallery is running on fully open source code!

In this blog post, I wanted to cover step by step what it takes to create and upload a package.

Create Your Package

Well the first step is to create a package so you have something to upload. If you’re well acquainted with creating packages, feel free to skip this section, but you may learn a few tips if you stick with it.

I’ll start with a simple example that I did recently. The XML-RPC.NET library by Charles Cook is very useful for implementing XML-RPC Services and clients. It powers the MetaWeblog API support in Subtext. As a courtesy, I recently asked Charles if he would mind if I created a NuGet package for his library for him, to which he said yes!

So on my machine, I created a folder named after the latest 2.5 release, xmlrpcnet.2.5.0. Here’s the directory structure I ended up with.


By convention, the lib folder is where you place assemblies that will get added as referenced assemblies to the target project when installing this package. Since this assembly only supports .NET 2.0 and above, I put it in the net20 subfolder of the lib folder.

The other required file is the .nuspec file, which contains the metadata used to build the package. Let’s take a look at the contents of that file.

<?xml version="1.0" encoding="utf-8"?> 
    <authors>Charles Cook</authors> 
    <owners>Phil Haack</owners>
    <description>A client and server XML-RPC library for .Net.</description> 
    <tags>xml-rpc xml rpc .net20 .net35 .net40</tags>

There’s a couple of things I want to call out here. Notice that I specified Charles Cook in the authors element, but put my own name in the owners element. Authors represent the authors of the library within the package, while the owner typically represents the person who created the package itself. This allows people to know who to contact if there’s a problem with the package vs a problem with the library within the package.

In general, we hope that most of the time, the authors and the owners are one and the same. For example, someday I’d love to help Charles take ownership of his packages. Until that day, I’m happy to create and upload them myself.

If somebody creates a package for a library that you authored and uploads it to NuGet, assume it’s a favor they did to get your library out there. If you wish to take ownership, feel free to contact them and they can assign the packages over to you. This is the type of thing we’d like to see resolved by the community and not via some policy rules on the gallery site. This is a case where the gallery could do a lot to make this sort of interaction easier, but does not have such features in place yet.

With this in place, it’s time to create the package. To do that, we’ll need the NuGet.exe console application. Copy it to a utility directory and add it to your path, or copy it to the parent folder of the package folder.


Now, open a command prompt and navigate to the directory and run the nuget pack command.

nuget pack path-to-nuspec-file

Here’s a screenshot of what I did:


Pro tip: What I really did was add a batch file I call build.cmd in the same directory that I put the NuGet.exe file. The contents of the batch file is a single line:

for /r %%x in (*.nuspec) do nuget pack "%%x" -o d:\packages\

What that does is run the nuget pack command on every subdirectory of the current directory. I have a folder that contains multiple packages that I’m working on and I can easily rebuild them all with this batch file.

Ok, so now we have the package, let’s publish it! But first, we have to create an account on the NuGet Gallery website.

Register and Upload

The first step is to register for an account at Once you have an account, click on the Contribute tab. This page gives you several options for managing packages (click to enlarge).


To upload your package, click on the Add New Package link.


Notice there’s two options. At this point, you can simply browse for the package you created and upload it and you’re done. In a matter of a few minutes, it should appear in the public feed.

The second option allows you to host your package file in a location other than the NuGet gallery such as, Google Code, etc. Simply enter the the direct URL to the package and when someone tries to install your package, the NuGet client will redirect the download request to the external package URL.

Submit From The Command Line

Ok, that’s pretty easy. But you’re a command line junky, right? Or perhaps you’re automating package submission.

Well you’re in luck, it’s pretty easy to submit your package directly from the command line. But first, you’re going to need an API key.

Visit the My Account page ( and make a note of your API key (click image below to enlarge it).


Be sure to keep that API key secret! Don’t give it out like I just did. If you do happen to accidentally leak your API key, you can click the Generate New Key button, again like I just did. You didn’t really think I’d let you know my API key, did you?

Now, using the same NuGet.exe command line tool we downloaded earlier, we can push the package to the gallery using the nuget push command.

nuget push path-to-nupkg api-key –source

Here’s a screenshot of the exact command I ran.


Shoot! There I go showing off my secret API key again! I better regenerate that.

As you can see, this command uploaded my package and published it to the feed. I can login and visit the Manage My Contributions page to see this package and even make changes to it if necessary.

Moving Forward

We’re still working out the kinks in the site and hopefully, by the time you read this blog post, this particular issue will be fixed. Also, we’re planning to update the NuGet.exe client and make the NuGet gallery be the default source so that the –source flag is not required.

As David mentioned, the site was primarily developed as a project by the Nimble Pros in a very short amount of time. There’s two major components to the site. There’s the front-end Orchard Gallery built as an Orchard module. This powers the gallery website that you see when you visit There’s also the back-end gallery server which hosts the OData feed used to browse and search for packages as well as the WCF service endpoint for publishing packages.

Each of these components are open source projects which means if you really wanted to, you could take the code and host your own gallery website. Orchard will be using the same code to host its own gallery of Orchard modules.

Also, these projects accept contributions! I personally haven’t spent much time in the code, but I hope to find some free time to chip in myself. mvc,, code comments edit

In part 1 of this series, we looked at the scenario for grouping routes and how we can implement matching incoming requests with a grouped set of routes.

In this blog post, I’ll flesh out the implementation of URL Generation.

Url Generation Implementation

URL generation for a group route is tricky, especially when using named routes because the individual routes that make up the group aren’t in the main route collection.

As I noted before, the only route that’s actually added to the route table is the GroupRoute. Thus if you supply a route name for one of the child routes (such as “r1”) during URL generation, you’ll get a null URL.

Interestingly enough, in this case, if you don’t use named routes when using URL generation, everything works just fine. However, since I heartily recommend using named routes all the time, I should cover that situation.

So what we need to do here is supply two route names during URL generation. One for the group route, and one for the child route. How do we supply the child route name? We’re going to have to supply it in the route values. Here’s an example of generating an URL in this manner:

@Html.RouteLink("Hello World Child", "group", new { __RouteName = "hello-world3" }) 

Note that the second parameter, “group”, refers to the route name for the GroupRoute that we registered. The route value __RouteName is passed into the GroupRoute so that it can look in its own collection of routes for the matching child route.

In the following code sample, I’ve highlighted the essential part of the URL generation logic within the GroupRoute class.

public override VirtualPathData GetVirtualPath(RequestContext 
    requestContext, RouteValueDictionary values) {
  string routeName = values.GetRouteName();
  var virtualPath = ChildRoutes.GetVirtualPath(requestContext, 
    routeName as string, values.WithoutRouteName());
  if (virtualPath != null) {
    string rewrittenVirtualPath = 
    string directoryPath = VirtualPath.WithoutTildePrefix(); // remove tilde
    rewrittenVirtualPath = rewrittenVirtualPath.Insert(0, 
    virtualPath.VirtualPath = rewrittenVirtualPath.Remove(0, 1);

  return virtualPath;

The code grabs the route name for the child route from the supplied route values. Notice that I’m using an extension method I wrote in my last blog post.

The block of code after the highlighted portion rewrites the virtual path back to the full virtual path for the parent GroupRoute. This ensures that the virtual path that’s eventually returned to the caller will actually work, since the individual routes within the group don’t have a clue that they’re within a group.

In a follow-up blog post, I’ll wrap up this series and provide access to the full source code. mvc,, code comments edit

I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax.

It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax.

So I thought it might be handy to write up a a really concise quick reference about the Razor syntax.

Syntax/Sample Razor Web Forms Equivalent (or remarks)
Code Block
  int x = 123; 
  string y = "because.";
  int x = 123; 
  string y = "because."; 
Expression (Html Encoded)
<span><%: model.Message %></span>
Expression (Unencoded)
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
<% if (foo) { %> 
  Plain Text 
<% } %>
Using block
@using (Html.BeginForm()) {
  <input type="text" value="input here">
<% using (Html.BeginForm()) { %>
  <input type="text" value="input here">
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
Same as above
Email Addresses
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
This is a server side 
multiline comment 
This is a server side 
multiline comment
Calling generic method
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
  Func<dynamic, object> b = 
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.
Conditional attributes
<div class="@className"></div>
When className = null
When className = ""
<div class=""></div>
When className = "my-class"
<div class="my-class"></div>
Conditional attributes with other literal values
<div class="@className foo bar">
When className = null
<div class="foo bar"></div>
Notice the leading space in front of foo is removed.
When className = "my-class"
<div class="my-class foo bar">
Conditional data-* attributes.

data-* attributes are always rendered.
<div data-x="@xpos"></div>
When xpos = null or ""
<div data-x=""></div>
When xpos = "42"
<div data-x="42"></div>
Boolean attributes
<input type="checkbox"
  checked="@isChecked" />
When isChecked = true
<input type="checkbox"
  checked="checked" />
When isChecked = false
<input type="checkbox" />
URL Resolution with tilde
<script src="~/myscript.js">
When the app is at /
<script src="/myscript.js">
When running in a virtual application named MyApp
<script src="/MyApp/myscript.js">

Notice in the “mixing expressions and text” example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.

Let me know if there are other examples you think should be placed in this guide. I hope you find this helpful.

UPDATE 12/30/2012: I’ve added a few new examples to the table of new additions to Razor v2/ASP.NET MVC 4 syntax. Razor got a lot better in that release!

Also, if you want to know more, consider buying the Programming ASP.NET MVC 4 book. Full disclosure, I’m one of the authors, but the other three authors are way better.

humor, blogging comments edit

Dear Reader, I apologize for not blogging much lately. I know, total #fail, but I’ve been so f***ing busy lately. I thought I would start off this new year right with a top ten list FTW!

Without further ado, I present my list of the top 10 blogging clichés of

  1. These are things yours truly would never ever do, right?stones-on-a-beach

  2. The random photo: Starting off the list is a very common one that even gets the very best bloggers, including a random photo in the blog post completely irrelevant to the topic at hand as if trying to meet a stock photography quota for the month. Perhaps you own stock in the stock xchng (or perhaps I should!). At least try to make the photo slightly relevant so it adds something to the post.
  3. “Dear Reader”:Is there a more patronizingly boorish phrase to use to refer to those reading your blog than “Dear Reader”. Do you know if the person reading your blog is dear? Seriously, he or she could be a total prick who’s only redeeming quality is that he or she clicks on your AdSense link so you can buy a cup of coffee in two years. Do you realize that the person reading the blog might be me? I’m a total jerk and I don’t click on your ad links, but you just complimented me. Ha! When I read a blog post that uses the phrase “Dear Reader” what I see in my head is “Dear random person that I hope clicks on my ads”. I’ve used it at least five times. Don’t be like me.
  4. Apologizing for not posting regularly: I have a dirty little secret, nobody gives a flying f*** whether or not you’re posting regularly (unless you’re Randall Munroe, then we absolutely do care), so stop apologizing for it. They’re all using some sort of RSS aggregator in the first place so they didn’t even have a clue to how lame you are up until the point that just reminded them. Great job Sport!
  5. Using f*** when you really meant to say “fuck”: It’s just a fucking word! If you really mean to use it for emphasis, just fucking use it! Nobody, in the history of humanity, ever lost his sight, hearing, or sanity from reading the word fuck. Not to mention that you’re not fooling anyone when you type f***. Do you really have such a low opinion of your readers that you think they’re sitting there thinking “Gee, I wonder wonder what word that could be? Good thing he asterisked the fuck out of that word because I might go blind if he had spelled it out.”
  6. Overusing the word “fuck”: Whoa nelly! Just because it’s ok to unmask those asterisks from time to time doesn’t mean we should go overboard here. Slowly back away from the “F” key. The word is meant to be very lightly sprinkled to pack a powerful punch when you need it. It’s not meant to be poured liberally like salt in a futile attempt to salvage taste from your awful cooking.
  7. “Wah wah, I’m so busy.”:You know what, we’re all fucking busy, so shut your pie hole about it already.
  8. “Hinting at a super secret project you can’t reveal just yet.”: Yeah yeah, we get it. You know something we don’t know so you’re going to rub our faces in it like a bad little doggy who just did a no-no. Bad doggy! This may even be the reason you’re “so busy”. Well I have news for you…wait for it. Wait for it. Nobody cares! Maybe your project really is the next big thing since that little plastic triangle thingy that holds the pizza box up away from the cheese. Really, that thing is awesome! Maybe your project is better than that, but if you can’t talk about it yet, you’re just wasting bandwidth. Once again, shut your pie hole until you can talk about it.
  9. Top ten lists, for all values of “ten”:Top ten (or eight, or eleven, or any number) lists are a cop out. You know it, I know it, and your readers know it. Top ten lists are what happens when a blogger is in the middle of writing a blog post apologizing for not posting regularly and thinks, “What the f*** am I apologizing for?! I know, I’ll write a top ten list of the varieties of lint I found in my belly button.” Yeah, you’ll make the front page of Reddit, but at what cost of your soul, dear reader? What cost?
  10. Name Dropping:So just last year I was chatting with my friends Jeff Atwood (aka CodingHorror), George Clooney, and Miguel De Icaza (aka Mr. Mono) about how lame it is to name drop. There’s nothing lamer than that except for name dropping about fictitious events that never happened. Seriously, nobody is going to change their opinion of how lame you are just because you happened to have seen the neighbor of the third cousin of Bruce Schneier from across the conference hall floor (but if you did, high five right atcha!).
  11. “FTW!” Yes, we all know you’re so hard core and like to express your enthusiasm while simultaneously tweaking your nose at the powers that be, but seriously now. You’re all growed up and it’s time to lay this one to rest, in the same way you no longer play with your GI Joes except when the wife has the kids at her mother’s. One exception to this rule, it’s perfectly fine to use it on Twitter, but only because of its brevity and only until we come up with something better.

Yes, some of these clichés were also noted back in 2007 as reported in CodingHorror, but apparently nobody got the memo as they were still going strong in

  1. Now it is 2011 and I’ve made a new years resolution to avoid such blogging clichés. How am I doing so far?

Probably about as well as my resolution to stop procrastinating, which I made after the new year, so I’m not off to a good start on that one either. Winking

Before you flame me about this blog post, this was all in good fun. I love top 10 lists for binary values of 10!

personal comments edit

It’s the end of the year and it’s time for the annual year in review blog post. I know what you’re thinking, but don’t worry, you remembered to turn off the stove before leaving.

You’re also probably thinking, “do we really need an end of year blog post from everyone?”. I asked on Quora, and the answer is a definitive no, we don’t. This is my absolutely unnecessary self indulgent end of year blog post. I wouldn’t have it any other way, would you?

I didn’t want to settle with an ordinary “Ho hum bore you to tears 2010 Year in Review Blog Post”. Mainly because I hate to see you cry. Really. Please stop. What I wanted was nothing short of nuclear supernova fireworks, dancing panda bears, and double rainbow fish that shoot sparks out their butts. In short, a blow your monocle off spectacular end of year review blog post!

Unfortunately, I waited too long and everybody was booked. So all I could get was this dancing panda.

This has been a great but somewhat crazy year for me. It’s kind of insane to think that in the same year we released the RTM for ASP.NET MVC 2, we also released not one, but count ‘em, two release candidates for ASP.NET MVC 3!

Also in this year, we started a new open source package manager, NuGet, which accepts external contributions. My how the pendulum swings over here.

What I Liked In 2010

2010 presented me with a lot of things to like.

  • Podcast: In general, I feel the same way Scott Hanselman feels about Podcasts when he said “Sorry folks, PodCasting = Verbal Incontinence.  I’m just not feeling it.” This makes for delicious irony that he’s involved in my favorite podcast of 2010, This Developer’s Life. Started by friend Rob Conery, I describe it as focusing on the more human side of software and it’s pretty much the only podcast I subscribe to.
  • Video: RSA Animate – Drive: The surprising truth about what motivates us. I absolutely love how this video uses a unique animation style to present on the topic of motivation.
  • Book: I didn’t read a lot of books in 2010, but one that stood out was Rocket Surgery Made Easy: The Do-It-Yourself Guide to Finding and Fixing Usability Problems, which is Steve Krug’s worthy follow-up to Don’t Make Me Think. You owe it to the users of your software to read and absorb these books.
  • Blog: Nothing really did it for me this year. As always, I enjoyed CodingHorror, but I found a read a much wider variety of blog posts due to Twitter and unfortunately didn’t remember to bookmark my favorite of the year. I’ll try better next year. Smile
  • Gadgets: This is a tie between my iPhone 4 and my Kinect. I am on my phone all the time. Perhaps too much. Ok, definitely too much. I now have a WP7 Samsung Focus at home, but I haven’t had any time to play with it yet. We recently got a Kinect and I am totally hooked on Dance Central. The part that really hooked me is that they show where your score ranks among the scores of your friends on X-Box live after each dance. I’m determined to destroy my friends with my fresh moves.
  • My Kids:Seriously, they’re cool! (I like my wife too, but she doesn’t like her picture plastered on the web. My kids get no choice.) Winking

Memorable Moments/Trips of 2010

Here are some memorable moments from 2010 that I happened to blog about. I’m sure there are many others memorable moments I forgot to blog about.

  • February I visited Austin Texas for the first time. I spoke at the Austin .NET User Group as well as at Dell and enjoyed the fine taste of Rudy’s BBQ. I spent every moment reminding Texans that if Alaska were split in half to make two states, Texas would be the third largest state in the union.
  • March We released ASP.NET MVC 2 which was shortly followed with the source code release of System.Web.Mvc.dll under the Ms-PL license. I was allowed exactly two breaths of relief before getting started on ASP.NET MVC 3. In the same month, I attended the Mix 10 conference in Las Vegas and met John Resig and Douglas Crockford for the first time. I gave two talks, one of them co-presented with Scott Hanselman which is always a good time.
  • April I attempted an April Fool’s joke. I’ve been told many times I should leave comedy to the experts, but I don’t see the fun in that.
  • June The Subtext team and I released version 2.5 of Subtext. The pace of work on Subtext has really slowed down as work has kept me busier and busier, but we’re still improving it and getting closer to another release. Also in June, I took my son to Alaska to visit his grandparents as a little vacation. While there, I spoke at the Alaska .NET User Group. No moose were in attendance.
  • July We released the first preview of ASP.NET MVC 3. This was the first public disclosure of the new streamlined Razor syntax for views. Nobody was cut in the process.
  • August After a five year absence, I returned to Black Rock City for the Burning Man festival. As best as I can tell, I did not die while there.
  • SeptemberI presented at Web Camp L.A. In the evening, I visited my old friends and we went curling. Yeah, seriously.
  • October We publicly announced the NuGet package manager project (it was initially called NuPack). This was a project I had been working on at the same time as ASP.NET MVC 3. To me, this project was very significant as it’s an open source project that accepts external contributions! But don’t worry, we also reject some too.
  • December We released the second release candidate for ASP.NET MVC 3.

My Top 3 Posts (Using the Ayende Formula)

With Subtext 2.5, the Ayende Formula, as we call it, is now integrated into the Subtext admin dashboard which makes compiling this list very easy!

Interestingly enough, this list doesn’t correspond to the posts that I think are most interesting. But that’s typically the case. I have bad taste.

  • ASP.NET MVC 2 Optional URL Parameters Covers using UrlParameter.Optional for optional Routing paramreters in ASP.NET MVC 2 (36 comments, 40,542 Web views, 23,818 aggregator views).
  • Sending JSON to an ASP.NET MVC Action Method Argument This post covers posting JSON to an action method in ASP.NET MVC 2. Some of the code presented in this post is now built-in with ASP.NET MVC 3. (39 comments, 37,668 web views, 21,899 aggregator views)
  • Razor View Syntax This post gave a little bit of the backstory about the new Razor syntax our team built for ASP.NET MVC as well as a new product, ASP.NET Web Pages. (43 comments, 27640 web views, 23234 aggregator views)

My Top 3 Posts (Using the Haack Formula)

The Haack Formula just involves me arbitrarily picking my personal favorites.

Enough About Me, What about You?

Yes, I get self absorbed. But let’s set that aside a moment and talk about you (insomuch as it pertains to me Me ME!). How you doin’?

According to Google Analytics:

  • Hello Visitors! 1,308,414 of you (absolute unique visitors) made 1,972,239 visits to my blog came from 219 countries/territories. Most of you came from the United States (676,050) followed by the United Kingdom (170,814) with India (140,732) in third place.
  • Browser of choice:40.94% of you use Firefox, 29.2% use IE, and 23.07% of you use Chrome. Probably not even worth mentioning, but 3.43% of you use Safari and  2.32% of you use Opera. Opera?!
  • Operating System: Not surprisingly, 90.64% of you are on Windows. 5.11% on a Mac and 2.62% on Linux. The mobile devices are a tiny percentage, but I would imagine that’ll pick up a lot next year.
  • What you read: The blog post most visited in 2010 was written in 2009, Using jQuery Grid with ASP.NET MVC with 93,715 page views.
  • How’d you get here: As usual, most of you came here via Google search results (1,120,983), which probably means most of you aren’t reading this. Winking
smile In second place, many of you came here directly (254,533) via typing the URL to this blog in an address bar (or clicking on a bookmark, etc.). had a strong showing coming in third with 85,002 visits referred.


This next list is more for me than for you as I was curious about the various interviews and talks I gave online. It’s the kind of list I wouldn’t expect anyone but myself and my mother to be interested in. In fact, I’m pretty sure my mother doesn’t care.

Suffice to say, there were plenty of opportunities for me to be aghast at the sound of my own voice.

Well if you’ve read this far, wow! you must really be bored on your holiday break. But seriously, if you’re a regular reader of my blog, thanks for sticking around! I think 2011 is going to be an interesting year as well and I’m looking forward to it.

Let me know if you have suggestions on how I can make my blog suck less., mvc, code comments edit

A lot has been written about how to get ASP.NET MVC running on IIS 6 with extensionless URLs. Up until now, the story hasn’t been very pretty. When running ASP.NET MVC on ASP.NET 4, it gets a lot easier.

To be fair, the part that makes it easier has nothing to do with ASP.NET MVC 3 and everything to do with a little known new feature of ASP.NET 4 creatively called the ASP.NET 4 Extensionless URL feature. ASP.NET MVC 3 requires ASP.NET 4 so it naturally benefits from this new feature.

If you have a server running IIS 6, ASP.NET 4, and ASP.NET MVC 3 (or even ASP.NET MVC 2. I haven’t tried ASP.NET MVC 1.0), your website should just work with the default extensionless URLs generated by ASP.NET MVC applications. No need to configure wildcard mappings nor *.mvc mappings. In fact, you don’t even need to set RAMMFAR to true. RAMMFAR is our pet name for the runAllManagedModulesForAllRequests setting within the system.webserver setting in web.config. You can feel free to set this to false.

<modules runAllManagedModulesForAllRequests="false"/>

When installing ASP.NET 4, this is enabled by default. So if you have a hosting provider still using IIS 6, but does have ASP.NET 4 installed, then this should work for you, unless…

How does this work?

To be honest, it’s a bit of voodoo magic as far as I can tell and there’s a lot of caveats when it comes to using this feature with IIS 6. There are edge cases where it can cause problems. This is why Thomas Marquardt, the implementor of the feature, wrote a blog post on how to disable ASP.NET 4.0 Extensionless URLs just in case.

In that blog post, he describes the bit of magic that makes this work.

Here’s how the v4.0 ASP.NET extensionless URL features works on IIS 6.  We have an ISAPI Filter named aspnet_filter.dll that appends “/eurl.axd/GUID” to extensionless URLs.  This happens early on in the request processing.  We also have a script mapping so that “*.axd” requests are handled by our ISAPI, aspnet_isapi.dll.  When we append “/eurl.axd/GUID” to extensionless URLs, it causes them to be mapped to our aspnet_isapi.dll, as long as the script map exists as expected.  These requests then enter ASP.NET where we remove “/eurl.axd/GUID” from the URL, that is, we restore the original URL.  The restoration of the original URL happens very early.  Now the URL is extensionless again, and if no further changes are made

He also has a list of conditions that must be true for this feature to work. If any one of them is false, then you’re back to the old extensionfull URLs with IIS 6.

I’m Getting a 403 Forbidden

This is not technically related, but when I tried to test this out to confirm the behavior, I ran into a case where every request was giving me a 403 Forbidden error message. Here’s how I fixed it.

In IIS Manager, I right clicked on the Web Services Extension node and selected the menu option labeled Allow all Web Service extensions for a specific application:


In the resulting dialog, I chose the ASP.NET v4.0.30319 option.


To double check that everything was configured correctly, I looked at the properties for my website and ensured that Scripts were enabled.


I also clicked on the Configuration… button and made sure that *.axd was mapped to the proper ASP.NET Isapi dll (aspnet_isapi.dll).



With all that in place, I was able to run standard ASP.NET MVC web application and make requests for /, /home/about/, etc. without any problems!

personal, mvc, comments edit

Along with James Senior, I’ll be speaking at a couple of free Web Camps events in South America in March 2011.


Buenos Aires, Argentina –March 14-15, 2011

São Paulo, Brazil –March 18-19, 2011

The registration links are not yet available, but I’ll update this blog post once they are.Registration is open! Register for Argentina. Register for Brazil. For a list of all upcoming Web Camps events, see the events list.

If you’re not familiar with Web Camps, the website provides the following description, emphasis mine:

Microsoft’s 2 day Web Camps are events that allow you to learn and build websites using ASP.NET MVC, WebMatrix, OData and more. Register today at a location near you! These events will cover all 3 topics and will have presentations on day 1 with hands on development on day 2. They will be available at 7 countries worldwide with dates and locations confirming soon.

Did I mention that these events are free? The description neglects to mention NuGet, but you can bet I’ll talk about that as well. Smile 

I’m really excited to visit South America (this will be my first time) and I hope that schedules align in a way that I can catch a Fútbol/Futebol game or two. I also need to brush up on my Spanish for Argentina and learn a bit of Portugese for Brazil.

One interesting thing I’m learning is that visiting Brazil requires a Visa (Argentina does not) which is a heavyweight process. According to the instructions I received, it takes a minimum of 40 business days to receive the Visa! Wow. I’m sure the churrascaria will be worth it though.

Good thing I’m getting started on this early. Hey Brazil, I promise not to trash your country. So feel free to make my application go through more quickly.

Tags: webcamps, aspnetmvc,, brazil, argentina

code, nuget comments edit

We could have done better. That’s the thought that goes through my mind when looking back on this past year and reflecting on NuGet.

Overall, I think we did pretty well with the product. Nobody died from using it, we received a lot of positive feedback, and users seem genuinely happy to use the product. So why start off with a negative review?

It’s just my way. If you can’t look back on every project you do and say to yourself “I could have done better”, then you weren’t paying attention and you weren’t learning. For example, why stop at double rainbows when we could have gone for triple?


When starting out on NuGet, we hoped to accomplish even more in our first full release. Like many projects, we have iteration milestones which each culminate in a public release. Ours tended to be around two months in duration, though our last one was one month.

Because we were a bit short staffed in the QA department, at the end of each milestone our one lone QA person, Drew Miller, would work like, well, a mad Ninja on fire trying to verify all the fixed bugs and test implemented features. Keep in mind that the developers do test out their own code and write unit tests before checking the code in, but it’s still important to manually test code with an eye towards thinking like a user of the software.

This my friends, does not scale.

When we look back on this past year, we came to the conclusion that our current model was not working out as well as it could. We weren’t achieving the level of quality that we would have liked and continuing in this fashion would burn out Drew.

I came to the realization that we need to assume we’ll never be fully staffed on the QA side. Given this, it became obvious that we need a new approach.

This was apparent to the developers too. David Fowler noted to me that we needed to have features tested closer to when they were implemented. As we discussed this, I remember a radical notion that Drew told me about when he first joined our QA team. He told me that he wants to eliminate dedicated testers. Not actually kill them mind you, just get rid of the position.

An odd stance for someone who is joining the QA profession. But as he explained it to me in more detail over time, it started to make more sense. In the most effective place he worked, every developer was responsible for testing. After implementing a feature and unit testing it (both manually and via automated tests), the developer would call over another developer and fully test the feature end-to-end as a pair. So it wasn’t that there was no QA there, it was that QA was merely a role that every developer would pitch in to help out with. In other words, everyone on the team is responsible for QA.

So as we were discussing these concepts recently, something clicked in my thick skull. They echoed some of the concepts I learned attending a fantastic presentation back in 2009 at the Norwegian Developer’s Conference by Mary Poppendieck. Her set of talks focused on the concept of a problem solving organization and the principles of Lean. She gave a fascinating account of how the Empire State Building finished in around a year and under budget by employing principles that became known as Lean. I remember thinking to myself that I would love to learn more about this and how to apply it at work.

Well fast forward a year and I think the time is right. Earlier in the year, I had discussed much more conservative changes we could make. But in many ways, by being an external open source project with a team open to trying new ideas out, the NuGet team is well positioned to try out something different than we’ve done before as an experiment. We gave ourselves around two months starting in January with this new approach and we’ll evaluate it at the end of those two months to see how it’s working for us.

We decided to go with an approach where each feature was itself a micro-iteration. In other words, a feature was not considered “done” until it was fully done and able to be shipped.

So if I am a developer working on a feature, I don’t get to write a few tests, implement the feature, try it out a bit, check it in, and move on to the next feature. Instead, developers need to call over Drew or another available developer and pair test the feature end-to-end. Once the feature is fully tested, only then does it get checked into the main branch of our main fork.

Note that under this model, every developer also wears the QA hat throughout the development cycle. This allows us to scale out testing whether we have two dedicated QA, one dedicated QA, or even zero. You’ll notice we’re still planning to keep Drew as a dedicated QA person while we experiment with this new approach so that he can help guide the overall QA process and look at system level testing that might slip by the pair testing. Over time, we really want to get to a point where most of our QA effort is spent in preventing defects in the first place, not just finding them.

Once a feature has been pair tested, that feature should be in a state that it can be shipped publicly, if we so choose.

We’re also planning to have a team iteration meeting every two weeks where we demonstrate the features that we implemented in the past two weeks. This serves both to review the overall user experience of the features as well as to ensure that everyone on the team is aware of what we implemented.

You’ll note that I’m careful not to call what we’re doing “Lean” with a capital “L”. Drew cautioned me to user lower-case “lean” as opposed to capital “Lean” because he wasn’t familiar with Lean when he worked this model at his previous company. We wouldn’t want to tarnish the good name of Lean with our own misconceptions about what it is.

This is where I have to confess something to you. Honestly, I’m not really that interested in Lean. What I’m really interested in is getting better results. It just seems to me that the principles of Lean are a very good approach to achieving those results in our situation.

I’m not one to believe in one true method of software development that works for all situations. What works for the start-up doesn’t work for the Space Shuttle and vice versa. But from what I understand, NuGet seems to be a great candidate for gaining benefits from applying lean principles.

So when I said I’m not interested in Lean, yeah, that was a bit of a fib. I definitely am interested in learning more about Lean (and I imagine I’ll learn a lot from many of you). But I am so much more interested on the better results we hope to achieve by applying lean principles.

personal comments edit

At some point, everybody and every team makes a mistake they regret and wish they could take back. During our regular status meetings, I sometimes make the mistake of saying something like “if I could go back in time, I’d tell myself not to make that decision.”

flux-capacitor \ Image from the greenhead.

That tees it up for our lead developer who’s so smart even his ass is smart. You might say he’s a smart ass. His response is usually “Really? I can think of a lot better things I would do with a time machine.”

Which got me thinking. Hypothetically speaking of course, if I did have a time machine, how exactly would I maximize my profit?

Often, time travel questions fixate on boring topics such as if you could meet anyone in history, who would it be?

Lincoln? Snore. Jesus? Yah, maybe he can do something about that chronic rash you got going down there.

I think the question of how you’d become rich is much more interesting and potentially creative. Let’s put some constraints on the question to make it more interesting.

  1. The time machine room size and located in your house. Thus you can’t travel with the time machine.
  2. The time machine can only transport you back in time and back. It can’t transport you through space to another location. So if you live in Seattle Washington, you can travel back in time to any year, say 1951, but you’ll still be in Seattle.
  3. You have one trip and one trip only and you can only bring yourself and the clothes on your back. I’d recommend a backpack.
  4. You have the resources available to you today. You can’t go back in time and buy a million shares of some stock unless you could actually afford to buy that stock.

Keep in mind the consequences of your action. It might seem like it’d be easy to go back in time around ten years, go to a public library and login to your old E-Trade account and buy a bunch of stock. But you, ten years ago, would probably notice and assume you’ve been hacked and perhaps sell immediately.

Also, if you travel to a time before you were born, consider that you probably won’t have proper identification and papers, unless you forge them. Could you buy stocks without identification?

So my friends, I ask you. Given these constraints, how would you maximize profit with a single trip back in time?

Again, this is purely hypothetical. I don’t have a time machine in the garage. Let’s just say, I like to be prepared just in case., mvc, nuget, code comments edit

Almost exactly one month ago, we released the Release Candidate for ASP.NET MVC 3. And today we learn why we use the term “Candidate”.

As Scott writes, Visual Studio 2010 SP1 Beta was released just this week and as we were testing it we found a few incompatibilities with it and the ASP.NET MVC 3 RC that we had just released.

newdotnetlogo_2That’s when we, in the parlance of the military, scrambled the jets to get another release candidate prepared.

You can install it directly using the Web Platform Installer (Web PI) download the installer yourself from from here.

Be sure to read the release notes for known issues and breaking changes in this release. I’m not saying I put an Easter egg in there or not, but you’ll have to read all the notes to find out.

In particular, there are two issues I want to call out.

Breaking Change Alert!

The first is a breaking change. Remember way back when I wrote about Dynamic Methods in ViewData? Near the end of that post I wrote an Addendum about the property name mismatch between ViewModel and View.

Well we finally resolved that mismatch. The new property name, both in the controller and in the view is ViewBag. This may break many of your existing ASP.NET MVC 3 pre-release applications.

NuGet Upgrade Alert

The other issue I want to call out is that if you already have NuGet installed, running the ASP.NET MVC 3 RC 2 installer will not upgrade it. Instead, you need to go to the Visual Studio Extension Manager dialog (via the Tools | Extensions menu option) and click on the Updates tab. You should see NuGet listed there (click on image for larger image):


The NuGet.exe command line tool for creating packages is available on CodePlex.

Overall, this release consists mostly of bug fixes along with some fit and finish work for ASP.NET MVC 3. We’ve updated the version of jQuery and jQuery Validation that we include in the project templates and now also include jQuery UI, a library that builds on top of jQuery to provide animation, advanced effects, as well as themeable widgets.

In terms of NuGet, this release contains a significant amount of work. I’ll try and follow up soon with more details on the NuGet release along with release notes.

nuget, code comments edit

I don’t normally post lists of links as it’s really not my style. But there’s a lot of great NuGet blog posts I want to call out so I thought I’d try my hand at it.

Hey! Here’s a random picture of a goat.


I also tend to post links from my twitter account

Well that’s it for now. If you found this helpful, let me know and I’ll try to do it once in a while. Either once a quarter or once a month depending on interest. Smile, mvc, nuget, code comments edit

Sometimes, despite your best efforts, you encounter a problem with your ASP.NET MVC application that seems impossible to figure out and makes you want to pull out your hair. Or worse, it makes you want to pull out my hair. In some of those situations, it ends up being a PEBKAC issue, but in the interest of avoiding physical harm, I try not to point that out.


Thankfully, in the interest of saving my hair, Brad Wilson (recentlyfeatured on This Developer’s Life!) wrote a simple diagnostics web page for ASP.NET MVC that you can drop into any ASP.NET MVC application. When you visit the page in your browser, it provides diagnostics information that can help discover potential problems with your ASP.NET application.

To make it as easy as possible to use it, I created a NuGet package named “MvcDiagnostics”. If you’re not familiar with NuGet, check out my announcement of NuGet as well as our Getting Started guide written by Tim Teebken.

With NuGet, you can use the Add Package Library Dialog to install MvcDiagnostics. Simply type in “MVC” in the search dialog to filter the online entries. Then locate the MvcDiagnostics entry and click “Install”.


Or you can use the Package Manager Gonsole and simply type:

install-package MvcDiagnostics

Either way, this will add the MvcDiagnostics.aspx page to the root of your web application.


You can then visit the page with your browser to get diagnostics information.


With NuGet, it’s much easier to make use of this diagnostics page. Hopefully you’ll rarely need to use it, but it’s nice to know it’s there. Let us know if you have ways to improve the diagnostics page., mvc, code comments edit

UPDATE: 2011/02/13: This code is now included in the RouteMagic NuGet package! To use this code, simply run Install-Package RouteMagic within the NuGet Package Manager Console.

One thing ASP.NET Routing doesn’t support is washing and detailing my car. I really pushed for that feature, but my coworkers felt it was out of scope. Kill joys.

Another thing Routing doesn’t support out of the box is a way to group a set of routes within another route. For example, suppose I want a set of routes to all live under the same URL path. Today, I’d need to make sure all the routes started with the same URL segment. For example, here’s a set of routes that all live under the “/blog” URL path.

RouteTable.Routes.MapRoute("r1", "blog/posts");
RouteTable.Routes.MapRoute("r2", "blog/posts/{id}");
RouteTable.Routes.MapRoute("r3", "blog/archives");

If I decide I want all these routes to live under something other than “blog” such as in the root or under a completely different name such as “archives”, I have to change each route. Not such a big deal with only three routes, but with a large system with multiple groupings, this can be a hassle.

I suppose one easy way to solve this is to do the following:

string baseUrl = "blog/";
RouteTable.Routes.MapRoute("r1", baseUrl + "posts");
RouteTable.Routes.MapRoute("r2", baseUrl + "posts/{id}");
RouteTable.Routes.MapRoute("r3", baseUrl + "archives");

Bam! Done! Call it a night Frank.

This is actually a very simple and great solution to the problem I stated. In fact, it probably works better than the alternative I’m about to show you. If this works so well, why am I showing you the alternative?

Well, there’s something unsatisfying about that answer. Suppose a request comes in for /not-blog. Every one of those routes is going to be evaluated even though we already know none of them will match. If we could group them, we could reduce the check to just one check. Also, it’s just not as much fun as what I’m about to show you.

What I would like to be able to do is the following.

var blogRoutes = new RouteCollection();
blogRoutes.MapRoute("r1", "posts");
blogRoutes.MapRoute("r2", "posts/{id}");
blogRoutes.MapRoute("r3", "archives");

RouteTable.Routes.Add("blog-routes", new GroupRoute("~/blog", blogRoutes));

In this code snippet, I’ve declared a set of routes and added them to a proposed GroupRoute instance. That group route is then added to the route table. Note that the child routes are not themselves added to the route table and they have no idea what parent path they’ll end up responding to.

With this proposed route, I these child routes would then handle requests to /blog/posts and /blog/archives. But if I decide to place them under a different path, I can simply change a single route, the group route, and I don’t need to change each child route.


In this section, I’ll describe the implementation of such a group route in broad brush strokes. The goal here is to provide an under the hood look at how routing works and how it can be extended.

Implementing such a grouping route is not trivial. Routes in general work directly off of the current http request in order to determine if they match a request or not.

By themselves, those child routes I defined earlier would not match a request for /blog/posts. Note that the URL for the child routes don’t start with “blog”. Fortunately though, the request that is supplied to each route is an instance of HttpRequestBase, an abstract base class.

What this means is we can muck around with the request and even change it so that the child routes don’t even know the actual requests starts with /blog. That way, when a request comes in for /blog/posts, the group route matches it, but then rewrites the request only for its child routes so that they think they’re trying to match /posts.

Please note that what I’m about to show you here is based on internal knowledge of routing and is unsupported and may cause you to lose hair, get a rash, and suffer much grief if you depend on it. Use this approach at your own risk.

The first thing I did was implement my own wrapper classes for the http context class.

public class ChildHttpContextWrapper : HttpContextBase {
  private HttpContextBase _httpContext;
  private HttpRequestBase _request;

  public ChildHttpContextWrapper(HttpContextBase httpContext, 
      string parentVirtualPath, string parentPath) {
    _httpContext = httpContext;
    _request = new ChildHttpRequestWrapper(httpContext.Request, 
      parentVirtualPath, parentPath);

  public override HttpRequestBase Request {
    get {
      return _request;

  // ... All other properties/methods delegate to _httpContext

Note that all this does is delegate every method and property to the supplied HttpContextBase instance that it wraps except for the Request property, which returns an instance of my next wrapper class.

public class ChildHttpRequestWrapper : HttpRequestBase {
  HttpRequestBase _httpRequest;
  string _path;
  string _appRelativeCurrentExecutionFilePath;

  public ChildHttpRequestWrapper(HttpRequestBase httpRequest, 
    string parentVirtualPath, string parentPath) {
    if (!parentVirtualPath.StartsWith("~/")) {
      throw new InvalidOperationException("parentVirtualPath 
        must start with ~/");

    if (!httpRequest.AppRelativeCurrentExecutionFilePath
        .StartsWith(parentVirtualPath, StringComparison.OrdinalIgnoreCase)) {
      throw new InvalidOperationException("This request is not valid 
        for the current path.");

    _path = httpRequest.Path.Remove(0, parentPath.Length);
    _appRelativeCurrentExecutionFilePath = httpRequest.
      AppRelativeCurrentExecutionFilePath.Remove(1,       parentVirtualPath.Length - 1);
    _httpRequest = httpRequest;

  public override string Path { get { return _path; } }

  public override string AppRelativeCurrentExecutionFilePath {
    get { return _appRelativeCurrentExecutionFilePath; }

  // all other properties/method delegate to_httpRequest

What this child request does is strip off the portion of the request path that corresponds to its parent’s virtual path. That’s the “~/blog” part supplied by the group route.

It then makes sure that the Path and the AppRelativeCurrentExecutionFilePath properties return this updated URL. Current implementations of routing look at these two properties when matching an incoming request. However, that’s an internal implementation detail of routing that could change, hence my admonition earlier that this is voodoo magic.

The implementation of request matching for GroupRoute is fairly straightforward then.

public override RouteData GetRouteData(HttpContextBase httpContext) {
  if (!httpContext.Request.AppRelativeCurrentExecutionFilePath.
      StartsWith(VirtualPath, StringComparison.OrdinalIgnoreCase)) {
    return null;

  HttpContextBase childHttpContext = VirtualPath != ApplicationRootPath ? 
    new ChildHttpContextWrapper(httpContext, VirtualPath, _path) : null;

  return ChildRoutes.GetRouteData(childHttpContext ?? httpContext);

All we did here is to make sure that the group route matches the current request. If so, we then created a child http context which as we saw earlier, looks just like the current http context, only the /blog portion of the request is stripped off. We then pass that to our internal route collection to see if any child route matches. If so, we return the route data from that match and we’re done.

In Part 2 of this series, we’ll look at implementing URL generation. That’s where things get really tricky., mvc, code comments edit

A question I often receive via my blog and email goes like this:

Hi, I just got an email from a Nigerian prince asking me to hold some money in a bank account for him after which I’ll get a cut. Is this a scam?

The answer is yes. But that’s not the question I wanted to write about. Rather, a question that I often see on StackOverflow and our ASP.NET MVC forums is more interesting to me and it goes something like this:

How do I get the route name for the current route?

My answer is “You can’t”. Bam! End of blog post, short and sweet.

Joking aside, I admit that’s not a satisfying answer and ending it there wouldn’t make for much of a blog post. Not that continuing to expound on this question necessarily will make a good blog post, but expound I will.

It’s not possible to get the route name of the route because the name is not a property of the Route. When adding a route to a RouteCollection, the name is used as an internal unique index for the route so that lookup for the route is extremely fast. This index is never exposed.

The reason why the route name can’t be a property becomes more apparent when you consider that it’s possible to add a route to multiple route collections.

var routeCollection1 = new RouteCollection();
var routeCollection2 = new RouteCollection();

var route = new Route("{controller}/{action}", new MvcRouteHandler());

routeCollection1.Add("route-name1", route);
routeCollection2.Add("route-name2", route);

So in this example, we add the same route to two different route collections using two different route names when we added the route. So we can’t really talk about the name of the route here because what would it be? Would it be “route-name1” or “route-name2”? I call this the “Route Name Uncertainty Principle” but trust me, I’m alone in this.

Some of you might be thinking that ASP.NET Routing didn’t have to be designed this way. I address that at the end of this blog post. For now, this is the world we live in, so let’s deal with it.

Let’s do it anyways

I’m not one to let logic and an irrefutable mathematical proof stand in the way of me and getting what I want. I want a route’s name, and golly gee wilickers, I’m damn well going to get it.

After all, while in theory I can add a route to multiple route collections, I rarely do that in real life. If I promise to behave and not do that, maybe I can have my route name with my route. How do we accomplish this?

It’s simple really. When we add a route to the route collection, we need to tell the route what the route name is so it can store it in its DataTokens dictionary property. That’s exactly what that property of Route was designed for. Well not for storing the name of the route, but for storing additional metadata about the route that doesn’t affect route matching or URL generation. Any time you need some information stored with a route so that you can retrieve it later, DataTokens is the way to do it.

I wrote some simple extension methods for setting and retrieving the name of a route.

public static string GetRouteName(this Route route) {
    if (route == null) {
        return null;
    return route.DataTokens.GetRouteName();

public static string GetRouteName(this RouteData routeData) {
    if (routeData == null) {
        return null;
    return routeData.DataTokens.GetRouteName();

public static string GetRouteName(this RouteValueDictionary routeValues) {
    if (routeValues == null) {
        return null;
    object routeName = null;
    routeValues.TryGetValue("__RouteName", out routeName);
    return routeName as string;

public static Route SetRouteName(this Route route, string routeName) {
    if (route == null) {
        throw new ArgumentNullException("route");
    if (route.DataTokens == null) {
        route.DataTokens = new RouteValueDictionary();
    route.DataTokens["__RouteName"] = routeName;
    return route;

Yeah, besides changing diapers, this is what I do on the weekends. Pretty sad isn’t it?

So now, when I register routes, I just need to remember to call SetRouteName.

routes.MapRoute("rName", "{controller}/{action}").SetRouteName("rName");

BTW, did you know that MapRoute returns a Route? Well now you do. I think we made that change in v2 after I begged for it like a little toddler. But I digress.

Like eating a Turducken, that code doesn’t sit well with me. We’re repeating the route name twice here which is prone to error. Ideally, MapRoute would do it for us, but it doesn’t. So we need some new and improved extension methods for mapping routes.

public static Route Map(this RouteCollection routes, string name, 
    string url) {
  return routes.Map(name, url, null, null, null);

public static Route Map(this RouteCollection routes, string name, 
    string url, object defaults) {
  return routes.Map(name, url, defaults, null, null);

public static Route Map(this RouteCollection routes, string name, 
    string url, object defaults, object constraints) {
  return routes.Map(name, url, defaults, constraints, null);

public static Route Map(this RouteCollection routes, string name, 
    string url, object defaults, object constraints, string[] namespaces) {
  return routes.MapRoute(name, url, defaults, constraints, namespaces)

These methods correspond to some (but not all, because I’m lazy) of the MapRoute extension methods in the System.Web.Mvc namespace. I called them Map simply because I didn’t want to conflict with the existing MapRoute extension methods.

With these set of methods, I can easily create routes for which I can retrieve the route name.

var route = routes.Map("rName", "url");

// within a controller
string routeName = RouteData.GetRouteName();

With these methods, you can now grab the route name from the route should you need it.

Of course, one question to ask yourself is why do you need to know the route name in the first place? Many times, when people ask this question, what they really are doing is making the route name do double duty. They want it to act as an index for route lookup as well as be a label applied to the route so they can take some custom action based on the name.

In this second case though, the “label” doesn’t have to be the route name. It could be anything stored in data tokens. In a future blog post, I’ll show you an example of a situation where I really do need to know the route name.

Alternate Design Aside

As an aside, why is routing designed this way? I wasn’t there when this particular decision was made, but I believe it has to do with performance and safety. With the current API, once a route name has been added to a route collection with a name, internally, the route collection can safely use the route name as a dictionary key for the route knowing full well that the route name cannot change.

But imagine instead that RouteBase (the base class for all routes) had a Name property and the RouteCollection.Add method used that as the key for route lookup. Well it’s quite possible that the value of the route’s name could change for some reason due to a poor implementation. In that case, the index would be out of sync with the route’s name.

While I agree that the current design is safer, in retrospect I doubt many will screw up  a read-only name property which should never change. We could have documented that the contract for the Name property of Route is that it should never change during the lifetime of the route. But then again, who reads the documentation? After all, I offered $1,000 to the first person who emailed me a hidden message embedded in our ASP.NET MVC 3 release notes and haven’t received one email yet. Also, you’d be surprised how many people screw up GetHashCode(), which effectively would have the same purpose as a route’s Name property.

And by the way, there are no hidden messages in the release notes. Did I make you look?

tdd, code comments edit

A while back I wrote about mocking successive calls to the same method which returns a sequence of objects. Read that post for more context.

In that post, I had written up an implementation, but quickly was won over by a better extension method implementation from Fredrik Kalseth.

public static class MoqExtensions
  public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup, 
    params TResult[] results) where T : class  {
    setup.Returns(new Queue<TResult>(results).Dequeue);

As good as this extension method is, I was able to improve on it today during a coding session. I was writing some code where I needed the second call to the same method to throw an exception and realized this extension wouldn’t allow for that.

However, it wasn’t hard to write an overload that allows for that.

public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup,
    params object[] results) where T : class {
  var queue = new Queue(results);
    setup.Returns(() => {
        var result = queue.Dequeue();
        if (result is Exception) {
            throw result as Exception;
        return (TResult)result;

So rather than taking a parameter array of TResult, this overload accepts an array of object instances.

Within the method, we create a non generic Queue and then create a lambda that captures that queue in a closure. The lambda is passed to the Returns method so that it’s called every time the mocked method is called, returning the next item in the queue.

Here’s an example of the method in action:

var mock = new Mock<ISomeInterface>();
mock.Setup(r => r.GetNext())
    .ReturnsInOrder(1, 2, new InvalidOperationException());

Console.WriteLine(mock.Object.GetNext()); // Throws InvalidOperationException

In this sample code, I mock an interface so that when its GetNext method is called a third time, it will throw an InvalidOperationException.

I’ve found this to be a helpful and useful extension to Moq and hope you find some use for it if you’re using Moq.

NOTE: As Richard Reeves pointed out to me in an email, do be careful if you mock a property using this approach. If you evaluate the property while within a debugger, you will dequeue the element potentially causing maddening debugging difficulty., mvc, code comments edit

The beginning of wisdom is to call things by their right names – Chinese Proverb

Routing in ASP.NET doesn’t require that you name your routes, and in many cases it works out great. When you want to generate an URL, you grab this bag of values you have lying around, hand it to the routing engine, and let it sort it all out.


For example, suppose an application has the following two routes defined

    name: "Test",
    url: "code/p/{action}/{id}",
    defaults: new { controller = "Section", action = "Index", id = "" }

    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = "" }

To generate a hyperlink to each route, you’d write the following code.

@Html.RouteLink("Test", new {controller="section", action="Index", id=123})

@Html.RouteLink("Default", new {controller="Home", action="Index", id=123})

Notice that these two method calls don’t specify which route to use to generate the links. They simply supply some route values and let ASP.NET Routing figure it out.

In this example, The first one generates a link to the URL /code/p/Index/123 and the second to /Home/Index/123which should match your expectations.

This is fine for these simple cases, but there are situations where this can bite you. ASP.NET 4 introduced the ability to use routing to route to a Web Form page.  Let’s suppose I add the following page route at the beginning of my list of routes so that the URL /static/url is handled by the page /aspx/SomePage.aspx.

routes.MapPageRoute("new", "static/url", "~/aspx/SomePage.aspx"); 

Note that I can’t put this route at the end of my list of routes because it would never match incoming requests since /static/url would match the default route. Adding it to the beginning of the list seems like the right thing to do here.

If you’re not using Web Forms, you still might run into a case like this if you use routing with a custom route handler, such as the one I blogged about a while ago (with source code). In that blog post, I showed how to use routing to route to standard IHttpHandler instances.

Seems like an innocent enough change, right? For incoming requests, this route will only match requests that exactly matches /static/url but no others, which is great. But if I look at my page, I’ll find that the two URLs I generated earlier are broken.

Now, the two URLs are/url?controller=section&action=Index&id=123and /static/url?controller=Home&action=Index&id=123.


This is running into a subtle behavior of routing which is admittedly somewhat of an edge case, but is something that people run into from time to time. In fact, I had to help Scott Hanselman with such an issue when he was preparing his Metaweblog example for his fantastic PDC talk (HD quality MP4).

Typically, when you generate a URL using routing, the route values you supply are used to “fill in” the URL parameters. In case you don’t remember, URL parameters are those placeholders within a route’s URL with the curly braces such as {controller} and {action}.

So when you have a route with the URL {controller}/{action}/{Id}, you’re expected to supply values for controller, action, and Id when generating a URL. During URL generation, you need to supply a route value for each URL parameter so that an URL can be generated. If every route parameter is supplied with a value, that route is considered a match for the purposes of URL generation. If you supply extra parameters above and beyond the URL parameters for the route, those extra values are appended to the generated URL as query string parameters.

In this case, since the new route I mapped doesn’t have any URL parameters, that route matches every URL generation attempt since technically, “a route value is supplied for each URL parameter.” It just so happens in this case there are no URL parameters. That’s why all my existing URLs are broken because every attempt to generate a URL now matches this new route.

There’s even more details I’ve glossed over having to do with how a route’s default values figure into URL generation. That’s a topic for another time, but it explains why you don’t run into this problem with routes to controller actions which have an URL without parameters.

This might seem like a big problem, but the fix is actually very simple. Use names for all your routes and always use the route name when generating URLs. Most of the time, letting routing sort out which route you want to use to generate an URL is really leaving it to chance. When generating an URL, you generally know exactly which route you want to link to, so you might as well specify it by name.

Also, by specifying the name of the route, you avoid ambiguities and may even get a bit of a performance improvement since the routing engine can go directly to the named route and attempt to use it for URL generation.

So in the sample above where I have code to generate the two links, the following change fixes the issue (I changed the code to use named parameters to make it clear what the change was).

    linkText: "route: Test", 
    routeName: "test", 
    routeValues: new {controller="section", action="Index", id=123}

    linkText: "route: Default", 
    routeName: "default", 
    routeValues: new {controller="Home", action="Index", id=123}

People’s fates are simplified by their names.  ~Elias Canetti

And the same goes for routing. Smile

code, nuget, open source comments edit

Note, this blog post applies to v1.0 of NuGet and the details are subject to change in a future version.

In general, when you create a NuGet package, the files that you include in the package are not modified in any way but simply placed in the appropriate location within your solution.

However, there are cases where you may want a file to be modified or transformed in some way during installation. NuGet supports two types of transformations during installation of a package:

  • Config transformations
  • Source transformations

Config Transformations

Config transformations provide a simple way for a package to modify a web.config or app.config when the package is installed. Ideally, this type of transformation would be rare, but it’s very useful when needed.

One example of this is ELMAH (Error Logging Modules and Handlers for ASP.NET). ELMAH requires that its http modules and http handlers be registered in the web.config file.

In order to apply a config transform, add a file to your packages content with the name of the file you want to transform followed by a .transform extension. For example, in the ELMAH package, there’s a file named web.config.transform.


The contents of that file looks like a web.config (or app.config) file, but it only contains the sections that need to be merged into the config file.

            <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
            <add verb="POST,GET,HEAD" path="elmah.axd"              type="Elmah.ErrorLogPageFactory, Elmah" />
        <validation validateIntegratedModeConfiguration="false" />
            <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
            <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd"              type="Elmah.ErrorLogPageFactory, Elmah" />

When NuGet sees this transformation file, it attempts to merge in the various sections into your existing web.config file. Let’s look at a simple example.

Suppose this is my existing web.config file.

Existing web.config File

            <add name="MyCoolModule" type="Haack.MyCoolModule" />

Now suppose I want my NuGet package to add an entry into the modules section of config. I’d simply add a file named web.config.transform to my package with the following contents.

web.config.transform File

            <add name="MyNuModule" type="Haack.MyNuModule" />

After I install the package, the web.config file will look like

Existing web.config File

            <add name="MyCoolModule" type="Haack.MyCoolModule" />
            <add name="MyNuModule" type="Haack.MyNuModule" />

Notice that we didn’t replace the modules section, we merged our entry into the modules section.

I’m currently working on documenting the full set of rules for config transformations which I will post to our NuGet documentation page once I’m done.I just wanted to give you a taste for what you can do today.

Also, in v1 of NuGet we only support these simple transformations. If we hear a lot of customer feedback that more powerful transformations are needed for their packages, we may consider supporting the more powerful web.config transformation language as an alternative to our simple approach.

Source Transformations

NuGet also supports source code transformations in a manner very similar to Visual Studio project templates. These are useful in cases where your NuGet package includes source code to be added to the developer’s project. For example, you may want to include some source code used to initialize your package library, but you want that code to exist in the target project’s namespace. Source transformations help in this case.

To enable source transformations, simply append the .pp file extension to your source file within your package.

Here’s a screenshot of a package I’m currently authoring.


When installed, this package will add four files to the target project’s ~/Models directory. These files will be transformed and the .pp extension will be removed. Let’s take a look at one of these files.

namespace $rootnamespace$.Models {
    public struct CategoryInfo {
        public string categoryid;
        public string description;
        public string htmlUrl;
        public string rssUrl;
        public string title;

Notice the highlighted section that has the token $rootnamespace$. That’s a Visual Studio project property which gets replaced with the current project’s root namespace during installation.

We expect that $rootnamespace$ will be the most commonly used project property, though we support any project property such as $FileName$. The available properties may be specific to the current project type, but this MSDN documentation on project properties is a good starting point for what might be possible.