December 2010 Blog Posts

End Of Year 2010 Extravaganza

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 smileMe-and-the-kids

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.
  • September I 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.). StackOverflow.com had a strong showing coming in third with 85,002 visits referred.

Podcasts/Videos

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.

ASP.NET MVC 3 Extensionless URLs on IIS 6

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:

iis6-allowing-extensions

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

iis6-allow-web-service

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

iis6-home-directory-tab

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

iis6-isapi

iis6-extension-mapping

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!

See Me in Brazil and Argentina in March

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

argentina_flagBrazil_flag

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.

Not Really Interested In Lean

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?

leaning

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.

How Would You Maximize Profit From A Time Machine?

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.

ASP.NET MVC 3 Release Candidate 2

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):

extension-manager

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 Roundup December 2010 Edition

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.

089

I also tend to post links from my twitter account http://twitter.com/haacked.

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

ASP.NET MVC Diagnostics Using NuGet

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.

pebkac-comic

Thankfully, in the interest of saving my hair, Brad Wilson (recently featured 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”.

add-package-dialog

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.

mvcdiagnostics-viewinbrowser

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

mvc-diagnostics

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.

Grouping Routes Part 1

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.

Implementation

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.