November 2010 Blog Posts
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)
.SetRouteName(name);
}
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");
route.GetRouteName();
// 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?
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());
Console.WriteLine(mock.Object.GetNext());
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.
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
routes.MapRoute(
name: "Test",
url: "code/p/{action}/{id}",
defaults: new { controller = "Section", action = "Index", id = "" }
);
routes.MapRoute(
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/123 which 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=123 and /static/url?controller=Home&action=Index&id=123.
WTF?!
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).
@Html.RouteLink(
linkText: "route: Test",
routeName: "test",
routeValues: new {controller="section", action="Index", id=123}
)
@Html.RouteLink(
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. 
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.
<configuration>
<system.web>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
</httpModules>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
</modules>
<handlers>
<add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah" />
</handlers>
</system.webServer>
</configuration>
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
<configuration>
<system.webServer>
<modules>
<add name="MyCoolModule" type="Haack.MyCoolModule" />
</modules>
<system.webServer>
</configuration>
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
<configuration>
<system.webServer>
<modules>
<add name="MyNuModule" type="Haack.MyNuModule" />
</modules>
<system.webServer>
</configuration>
After I install the package, the web.config file will look like
Existing web.config File
<configuration>
<system.webServer>
<modules>
<add name="MyCoolModule" type="Haack.MyCoolModule" />
<add name="MyNuModule" type="Haack.MyNuModule" />
</modules>
<system.webServer>
</configuration>
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.
Today we’re releasing the release candidate for ASP.NET MVC 3. We’re in the home stretch now so it’ll mostly be bug fixes and small tweaks from here on out.
There are two ways to install ASP.NET MVC 3:
Also, be sure to check out the ASP.NET MVC 3 web page for information and content about ASP.NET MVC 3 as well as the release notes for this release.
Also, don’t miss Scott Guthrie’s blog post on ASP.NET MVC 3 which provides the usual level of detail on the release.
Razor Intellisense. Ah Yeah!
Probably the most frequently asked question I received when we released the Beta of ASP.NET MVC 3 was “When are we going to get Intellisense for Razor?” Well I’m happy to say the answer to that question is right now!
Not only Intellisense, but syntax highlighting and colorization also works for Razor views. ScottGu’s blog post I mentioned earlier has some screenshots of the Intellisense in action as well as details on some of the other improvements included in ASP.NET MVC 3 RC.
NuGet
As I wrote earlier, this release of ASP.NET MVC includes an updated version of NuGet, a free and open source Package Manager that integrates nicely into Visual Studio.
What’s Next?
Well if all goes well, we’ll land this plane nicely with an RTM release, and then it’s time to start thinking about ASP.NET MVC 4. There, I said it. Well, actually, I should probably already be thinking about 4, but seriously, can’t a guy catch a break once in a while to breathe for a moment?
Well, since I’m lazy, I’ll probably be asking you very soon for your thoughts on what you’d like to see us focus on for the next version of ASP.NET MVC. Then I can present your best ideas as my own in the next executive review. You don’t mind that at all, do you? 
Seriously though, please do provide feedback and I’ll keep you posted on our planning.
Now that we have Nuget in place, one thing we’ll be focusing on is looking at building packages for features that we would have liked to include in ASP.NET MVC, but maybe didn’t have the time to implement them. Or perhaps simply for experimental features that we’d like feedback on. I think building NuGet packages will be a great way to try out new feature ideas and for the ones we think belong in the product, we can always roll them into ASP.NET MVC core.
My team has been hard at work the past few weeks cranking out code and today we are releasing the second preview of NuGet (which you may have heard referred to as NuPack in the past, but was renamed for CTP 2 by the community). If you’re not familiar with what NuGet is, please read my introductory blog post on the topic.
For a detailed list of what changed, check out the NuGet Release Notes.
To see NuGet in action, watch the talk that Scott Hanselman’s gave at the Professional Developer’s Conference which was the highest rated talk. You can watch it online or download it in HD.
How do I get it?
There are three ways to get NuGet CTP 2.
Via MVC 3
NuGet CTP 2 is included as part of the ASP.NET MVC 3 Release Candidate installation (install via Web PI or download the standalone installer) . So when you install ASP.NET MVC 3 RC, you’ll have NuGet installed.
Via the Visual Studio Extension Gallery
If you want to try out NuGet without installing ASP.NET MVC 3 RC, feel free to install it via the Visual Studio Extension Gallery.
Via CodePlex.com
As with all of our releases, we also make the download available on our CodePlex website.
What’s new?
As the release notes point out, we’ve made a lot of improvements. Some of the big ones are changes to the NuSpec package format, so if you have any old .nupkg files laying around, you’ll need to build them with the new CTP 2 NuGet.exe command line tool.
But to be nice, we already updated all the packages in the temporary feed which is at a new location now, so you won’t need to do that. But if you’re building new packages, be sure to update your copy of Nuget.exe.
The NuSpec format now includes two new fields you should take advantage of if you are creating packages:
- The
iconUrl field specifies the URL for a 32x32 png icon that shows up next to your package entry within the Add Package Dialog. Be sure to set that to distinguish your package. - The
projectUrl field points to a web page that provides more information about your package.
Another big change we made is that the package feed is now an Open Data Protocol (OData) Service Endpoint. This makes it easy for clients to write arbitrary queries using LINQ against an IQueryable interface which is automatically translated to the proper query URL. For example, to see the first 10 packages that start with “N”:
http://feed.nuget.org/current/odata/v1/Packages?$filter=startswith(Id,'N') eq true&$top=10
Also, when using the Powershell based Package Manager Console, be sure to note that we renamed the Add-Package command to Install-Package and the Remove-Package command to Uninstall-Package. We felt the new names conveyed the right semantics.
How’s things?
So far, the project has been a lot of fun to work on, in large part due to the enthusiasm and excitement that we’ve seen from the community. As I mentioned in the past, this is truly an Open Source project and we’ve had quite a few community code contributions.
Of course, we still have plenty of items up for grabs if you’re looking for something to work on.
ReviewBoard
One cool thing we’ve done is integrated the use of ReviewBoard for doing code reviews into our process. For information on that, check out our code review instructions. Our review board is currently hosted at http://reviewboard.nupack.com/ but that domain name will change soon.
Continuous Integration
For those of you who like life in the fast lane, we do have a Team City based Continuous Integration (CI) server hosted at http://ci.nuget.org:8080/. You can get daily builds compiled directly from our source tree. So for those of you who knew about the build server, you would have been playing with the CTP 2 for a while now. 
What’s next?
Well our next release is going to be NuGet version 1.0 RTM. A lot of our focus for this iteration will be on applying some spit and polish as well as integration work on our sister project, Gallery Server.
The Gallery Server project is building what will become the official gallery for NuGet (as well as for Orchard modules and other types of galleries). It’s being developed as an Open Source project as well so that anyone can take the source and host their own galleries.
Once the gallery server is completed and hosted, we’ll start to transition from our current temporary feed over to the gallery server. We’ll leave the temporary feed up for a while to allow people time to transition over to whatever the final official gallery location ends up at.
At this point, if you haven’t tried NuGet, give it a try. If you have tried it, let us know what you think. I hope you enjoy using it, I know I do. 
This month’s Scientific American has an interesting commentary by Scott Lilienfield entitled Fudge Factor that discusses the fine line between academic misconduct and errors caused by confirmation bias.
For a great description of confirmation bias, read the YouAreNotSoSmart.com’s post on the topic.
The Misconception: Your opinions are the result of years of rational, objective analysis.
The Truth: Your opinions are the result of years of paying attention to information which confirmed what you believed while ignoring information which challenged your preconceived notions.
The fudge factor article talks about some of the circumstances that contribute to confirmation bias in the sciences.
Two factors make combating confirmation bias an uphill battle. For one, data show that eminent scientists tend to be more arrogant and confident than other scientists. As a consequence, they may be especially vulnerable to confirmation bias and to wrong-headed conclusions, unless they are perpetually vigilant. Second, the mounting pressure on scholars to conduct single-hypothesis-driven research programs supported by huge federal grants is a recipe for trouble. Many scientists are highly motivated to disregard or selectively reinterpret negative results that could doom their careers.
Obviously this doesn’t just apply to scientists. I’m sure we all know developers who are equally prone to confirmation bias, present company excluded of course.
Pretty much everybody is succeptbile. We all probably witnessed an impressive (in magnitude) display of confirmation bias in the recent elections.
However, there’s another contributing factor that the article doesn’t touch upon that I think is worth calling out, our education system. I remember when I was in high school and college, I had a lot of “lab” classes for the various sciences. We’d conduct experiments, take measurements, and plot the measurements on a graph. However, we already knew what the results were supposed to look like. So if a measurement was way off the expected graph, there was a tendency to retake the measurement.
“Whoops, I must’ve nudged the apparatus when I took that measurement, let’s try it again.”
As the article points out (emphasis mine)…
The best antidote to fooling ourselves is adhering closely to scientific methods. Indeed, history teaches us that science is not a monolithic truth-gathering method but rather a motley assortment of tools designed to safeguard us against bias.
So how can schools do a better job of teaching scientific methods? I think one interesting thing a teacher can do is have students conduct an experiment where the students think they know what the expected results should be beforehand, but where the actual results will not match up.
I think this would be interesting as an experiment in its own right. I’d be curious to see how many students turn in results which match their expectations rather than what matched their actual observations. That could provide a powerful teaching opportunity about scientific methods and confirmation bias.
It was a dark and stormy coding session; the rain fell in torrents as my eyes were locked to two LCD screens in a furious display of coding …

…sorry sorry, I just can’t continue. It’s all a lie.
This actually a cautionary tale describing one subtle way that you can run afoul Code Access Security (CAS) when attempting to run an application in partial trust. But who wants to read about that? Right? Right?
Well this isn’t a sordid tale, but if you bear with me, you may just find it interesting. Either that, or you may just take pity on me that I find this type of thing interesting.
I was hacking on NuGet the other day and all I wanted to do was write some code that accessed the version number of the current assembly. This is something we do in Subtext, for example. If you scroll to the very bottom of the admin section, you’ll see the following.

As you can imagine, the code for to get the version number is very straightforward:
System.Reflection.Assembly.ExecutingAssembly().GetName().Version
Or is it!? (cue scary organ music)
What the code does here (besides appearing to smack the Law of Demeter in the mouth) is get the currently executing assembly. From that it gets the Assembly name and extracts the version from the name. What could go wrong? I tested this in medium trust and it received the “works on my machine” seal of approval!

But does it work all the time? Well if it did, I wouldn’t be writing this blog post would I?
Fortunately, my colleague David Fowler caught this latent bug during a code review. Levi (no blog) Broderick was brought in to help explain the whole issue so a dunce like me could understand it. These two co-workers are scary smart and must never be allowed to fall into a life of crime as they would decimate the countryside. Just letting you know.
As it turns out, code exactly like this was the source of a medium trust bug in ASP.NET MVC 2 (that we fortunately caught and fixed before RTM). So what gives?
Well there’s very subtle latent bug with this code. To illustrate, I’ll put the code in context. The following snippet is a class library that makes use of the code I just wrote.
using System.Reflection;
using System.Security;
[assembly: SecurityTransparent]
namespace ClassLibrary1 {
public static class Class1 {
public static string GetExecutingAssemblyVersion() {
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
}
We need an application to reference that code. The following is code for an ASP.NET MVC controller with an action method that calls the method in the class library and returns it as a string. It may seem odd that the action method returns a string rather than an ActionResult, but that’s allowed. ASP.NET MVC simply wraps it in a ContentResult.
using System.Web.Mvc;
namespace MvcApplication1.Controllers {
public class HomeController : Controller {
public string ClassLibAssemblyVersion() {
return ClassLibrary1.Class1.GetExecutingAssemblyVersion();
}
}
}
Still with me?
When I run this application and visit /Home/ClassLibAssemblyVersion everything works fine and we see the version number.

Now’s where the party gets a bit wild (but still safe for work). At this point, I’ll put the class library assembly in the GAC and then recompile the application. I’m going to assume you know how to do that. Note that I’ll need to remove the local copy of the class library from the bin directory of my ASP.NET MVC application and also remove the project reference and replace it with a GAC reference.
When I do that and run the application again, I get.

Oh noes!
So what happened here? Reflector to the rescue! Looking at the stack trace, let’s dig into RuntimeAssembly.GetName(Boolean copiedName) method.
[SecuritySafeCritical]
public override AssemblyName GetName(bool copiedName) {
AssemblyName name = new AssemblyName();
string codeBase = this.GetCodeBase(copiedName);
this.VerifyCodeBaseDiscovery(codeBase);
// ... snipped for brevity ...
return name;
}
I’ve snipped out some code so we can focus on the interesting part. This method wants to return a fully populated AssemblyName instance. One of the properties of AssemblyName is CodeBase, which is a path to the assembly.
Once it has this path, it attempts to verify the path by calling VerifyCodeBaseDiscovery. Let’s take a look.
[SecurityCritical]
private void VerifyCodeBaseDiscovery(string codeBase)
{
if ((codeBase != null) &&
(string.Compare(codeBase, 0, "file:", 0, 5
, StringComparison.OrdinalIgnoreCase) == 0))
{
URLString str = new URLString(codeBase, true);
new FileIOPermission(FileIOPermissionAccess.PathDiscovery
, str.GetFileName()).Demand();
}
}
Notice that last line of code? It’s making a security demand to check if you have path discovery permissions on the specified path. That’s what’s failing. Why?
Well before you put the assembly in the GAC, the assembly was being loaded from your bin directory. Naturally, even in medium trust, you have rights to discover that path. But now that the class library is in the GAC, it’s being loaded from a subdirectory of c:\Windows\Assembly and guess what. Your medium trust application doesn’t have path discovery permissions to that directory.
As an aside, I think it’s too bad that this particular property doesn’t check its security demand lazily. That would be my kind of property access. My gut feeling is that people don’t often ask for an assembly’s Codebase as much as they ask for the other “safe” properties, like Version!
So how do we fix this? Well the answer is to construct our own AssemblyName instance.
new AssemblyName(typeof(Class1).Assembly.FullName).Version.ToString();
This implementation avoids the security issue I mentioned earlier because we’re generating the AssemblyName instance ourselves and it never has a reference to the disallowed path.
If you want to see this in action, I put together a little demo showing the bad approach and the fixed approach.
You’ll need to GAC the ClassLibrary1 assembly to see the exception occurred. I have another action that has the safe implementation. Try it out.
As a tangent, the astute reader may have noticed that I used the assembly level SecurityTransparentAttribute in my class library. Is that a case of my assembly attempting to deal with self esteem issues and shying away from a clamoring public? Why did I put that attribute there? The answer to that, my friends, is a story for another time. 