May 2010 Blog Posts
A while ago I was talking with my manager at the time about traits that we value in a Program Manager. He related an anecdote about an interview he gave where it became clear that the candidate did not deal well with ambiguity.
This is an important trait for nearly every job, but especially for PMs as projects can often change on a dime and it’s important understand how to make progress amidst ambiguity and eventually drive towards resolving ambiguity.
Lately, I’ve been asking myself the question, doesn’t this apply just as much to software?
One of the most frustrating aspects of software today is that it doesn’t deal well with ambiguity. You could take the most well crafted robust pieces of software, and a cosmic ray could flip one bit in memory and potentially take the whole thing down.
The most common case of this fragility that we experience is in the form of breaking changes. Pretty much all applications have dependencies on other libraries or frameworks. One little breaking change in such a library or framework and upgrading that dependency will quickly take down your application.
Someday, I’d love to see software that really did deal well with ambiguity.
For example, lets take imagine a situation where a call to a method which has changed its signature wouldn’t result in a failure but would be resolved automatically.
In the .NET world, we have something close with the concept of assembly binding redirection, which allow you to redirect calls compiled against one version of an assembly to another. This is great if none of the signatures of existing methods have changed. I can imagine taking this further and allowing application developers to apply redirection to method calls account for such changes. In many cases, the method itself that changed could indicate how to perform this redirection. In the simplest case, you simply keep the old method and have it call the new method.
More challenging is the case where the semantics of the call itself have changed. Perhaps the signature hasn’t changed, but the behavior has changed in subtle ways that could break existing applications.
In the near future, I think it would be interesting to look at ways that software that introduce such breaks could also provide hints at how to resolve the breaks. Perhaps code contracts or other pre conditions could look at how the method is called and in cases where it would be broken, attempt to resolve it.
Perhaps in the further future, a promising approach would move away from programming with objects and functions and look at building software using autonomous software agents that communicate with each other via messages as the primary building block of programs.
In theory, autonomous agents are aware of their environment and flexible enough to deal with fuzzy situations and make decisions without human interaction. In other words, they know how to deal with some level of ambiguity.
I imagine that even in those cases, situations would arise that the software couldn’t handle without human involvement, but hey, that happens today even with humans. I occasionally run into situations I’m not sure how to resolve and I enlist the help of my manager and co-workers to get to a resolution. Over time, agents should be able to employ similar techniques of enlisting other agents in making such decisions.
Thus when an agent is upgraded, ideally the entire system continues to function without coming to a screeching halt. Perhaps there’s a brief period where the system’s performance is slightly degraded as all the agents learn about the newly upgraded agent and verify their assumptions, etc. But overall, the system deals with the changes and moves on.
A boy can dream, eh? In the meanwhile, if reducing the tax of backwards compatibility is the goal, there are other avenues to look at. For example, by you could apply isolation using virtualization so that an application always runs in the environment it was designed for, thus removing any need for dealing with ambiguity (apart from killer cosmic rays).
In any case, I’m excited to see what new approaches will appear over the next few decades in this area that I can’t even begin to anticipate.
The last time I wrote about one of my hiking adventures, it started off great, but really didn’t end well. But I survived, so on that scale, yes it did end well! It’s a matter of perspective.
On Saturday, I went on my first hike of the spring to Lake Serene and Bridal Veil Falls. This hike is really two hikes in one. The main destination is Lake Serene, but there’s an absolutely wonderful half mile (1 mile round trip) side trip to the Bridal Veil Falls on the way to Lake Serene.
The trail starts in the small town of Index in the county of HomeController (sorry, I couldn’t resist). The entire trail is lush with greenery as you would expect in the pacific northwest. All along the trail are many little waterfalls and river crossings like the one seen here.

The early part of the hike is dominated by moss covered trees and bushes. Higher up there’s less moss, but just as many trees.
Nearly two miles in, there’s a juncture with a sign pointing to the right towards Bridal Veil Falls. There’s a juncture before this one without the sign, don’t take that one, take this one.
The roar of the falls served as our guide through the series of switchbacks leading us to a grand view.
There are two viewing platforms, both with great views of the falls.
The trail is well marked and easy to follow, though it wasn’t without its occasional obstacle. Nothing a strong man like myself can’t handle though.
As we got closer to the lake, we captured glimpses of snow capped mountains jutting into the sky. Near the end of the trail, we rounded a bend and were greeted with the sight of a calm lake nestled in a snow covered valley surrounded by jagged peaks. The lake lives up to its name.
We followed a little trail along the lake to a large rock face where we were able to get a better view of the trail. There just happened to be a large group of friends already there, breaking the sense of solitude.
But who are we to blame them, the view was beautiful despite the clouds and rain rolling in right as we got there.
If you live in the Seattle or Bellevue area, I highly recommend this hike. One member of the large group told us that he did the same hike a month ago and the lake was still frozen over and they sat back and enjoyed the dramatic site of constant avalanches on the other side of the lake. We didn’t get the opportunity to witness any.
Here’s a handy tip I just recently learned from the new intern on our team (see, you can learn something from anyone on any given day). I’ve long known you could access your local drives from a remote machine.
For example, start up a remote desktop dialog.
Then expand the dialog by clicking on Options, then check the Local Resources tab.
Make sure Clipboard is checked, and then hit the More… button.
Now you can select a local disk to be shared with the remote machine. For example, in this case I selected my C: drive.
As you can see in the screenshot, the file explorer has another drive named “C on HAACKBOOK” which can be used to copy files back and forth from my local machine to the remote machine.
But here’s the part I didn’t know. Let’s take a look at the desktop of my remote machine, which has a text file named info.txt.
One way I can get that file to my local machine is to copy it to the mapped drive we saw in the previous screenshot.
Or, I can simply drag and drop the info.txt from my remote desktop machine to a folder on my local machine.
So all this time, I had no idea cut and paste operations for files work across remote desktop. This may be obvious for many of you, but it wasn’t to me. :)
ASP.NET 4 introduces a few new extensibility APIs that live the hermit lifestyle away from the public eye. They’re not exactly hidden - they are well documented on MSDN - but they aren’t well publicized. It’s about time we shine a spotlight on them.
PreApplicationStartMethodAttribute
This new attribute allows you to have code run way early in the ASP.NET pipeline as an application starts up. I mean way early, even before Application_Start.
This happens to also be before code in your App_code folder (assuming you have any code in there) has been compiled.
To use this attribute, create a class library and add this attribute as an assembly level attribute. A common place to add this would be in the AssemblyInfo.cs class within the Properties folder.
Here’s an example:
[assembly: PreApplicationStartMethod(
typeof(SomeClassLib.Initializer), "Initialize")]
Note that I specified a type and a method. That method needs to be a public static void method with no arguments. Now, any ASP.NET website that references this assembly will call the Initialize method when the application is about to start, giving this method a chance to do perform some early initialization.
public static class Initializer
{
public static void Initialize() {
// Whatever can we do here?
}
}
The primary use of this feature is to enable tasks that can’t be done within Application_Start because it’s too late. For example, registering build providers and adding assembly references.
Which leads us to…
BuildProvider.RegisterBuildProvider
As you might guess, if one of the key scenarios for the previously mentioned feature is to allow registering build providers, well ASP.NET better darn well allow you to register them programmatically.
Prior to ASP.NET 4, the only way to register a custom build provider was via the <buildproviders> node within web.config. But now, you can register them programmatically via a call to the new BuildProvider.RegisterBuildProvider method.
BuildProvider.RegisterBuildProvider(".foo", typeof(MyBuildProvider));
Combining the PreApplicationStartMethodAttribute with this method call means that installing a build provider can be done in one step -simply reference the assembly with the build provider and the assembly can register it for you. Whereas before, you would have to reference the assembly and then muck around with web.config.
I think I speak for us all when I say “Yay! Less junk in my web.config trunk!”
BuildManager.AddReferencedAssembly
Another new method added in ASP.NET 4 allows adding an assembly to the application’s list of referenced assemblies. This is equivalent to adding an assembly to the <assemblies> section of web.config.
As you might guess, this comes in handy when registering a custom build provider. It allows you to programmatically add references to assemblies that may be needed by your build provider.
Oh, and it’s yet another way to reduce the size of your web.config file. Who doesn’t love that? :)
One of my favorite features of ASP.NET MVC 2 is the support for client validation. I’ve covered a bit about validation in the following two posts:
However, one topic I haven’t covered is how validation works with globalization. A common example of this is when validating a number, the client validation should understand that users in the US enter periods as a decimal point, while users in Spain will use a comma.
For example, let’s assume I have a type with the RangeAttribute applied. In this case, I’m applying a range from 100 to 1000.
public class Product
{
[Range(100, 1000)]
public int QuantityInStock { get; set; }
public decimal Cost { get; set; }
}
And in a strongly typed view, we have the following snippet.
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%: Html.LabelFor(model => model.QuantityInStock) %>
<%: Html.TextBoxFor(model => model.QuantityInStock)%>
<%: Html.ValidationMessageFor(model => model.QuantityInStock)%>
<% } %>
Don’t forget to reference the necessary ASP.NET MVC scripts. I’ve done it in the master page.
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript">
</script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript">
</script>
<script src="/Scripts/MicrosoftMvcValidation.debug.js"
type="text/javascript"></script>
Now, when I visit the form, type in 1,000 into the text field, and hit the TAB key, I get the following behavior.
Note that there is no validation message because in the US, 1,000 == 1000 and is within the range. Now let’s see what happens when I type 1.000.
As we can see, that’s not within the range and we get an error message.
Fantastic! That’s exactly what I would expect, unless I was a Spaniard living in Spain (¡Hola mis amigos!).
In that case, I’d expect the opposite behavior. I’d expect 1,000 to be equivalent to 1 and thus not in the range, and I’d expect 1.000 to be 1000 and thus in the range, because in Spain (as in many European countries), the comma is the decimal separator.
Setting up Globalization for ASP.NET MVC 2
Well it turns out, we can make ASP.NET MVC support this. To demonstrate this, I’ll need to change my culture to es-ES. There are many blog posts that cover how to do this automatically based on the request culture. I’ll just set it in my Global.asax.cs file for demonstration purposes.
protected void Application_BeginRequest() {
Thread.CurrentThread.CurrentCulture
= CultureInfo.CreateSpecificCulture("es-ES");
}
The next step is to add a call to the Ajax.GlobalizationScript helper method in my Site.master.
<head runat="server">
<%: Ajax.GlobalizationScript() %>
<script src="/Scripts/MicrosoftAjax.debug.js" type="text/javascript">
</script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript">
</script>
<script src="/Scripts/MicrosoftMvcValidation.debug.js" type="text/javascript">
</script>
</head>
What this will do is render a script tag pointing to a globalization script named according to the current locale and placed in scripts/globalization directory by convention. The idea is that you would place all the globalization scripts for each locale that you support in that directory. Here’s the output of that call.
<script type="text/javascript" src="~/Scripts/Globalization/es-ES.js">
</script>
As you can see, the script name is es-ES.js which matches the current locale that we set in Global.asax.cs. However, there’s something odd with that output. Do you see it? Notice that tilde in the src attribute? Uh oh! That there is a bona fide bug in ASP.NET MVC.
Not to worry though, there’s an easy workaround. Knowing how discriminating our ASP.NET MVC developers are, we knew that people would want to place these scripts in whatever directory they want. Thus we added a global override via the AjaxHelper.GlobalizationScriptPath property.
Even better, these scripts are now available on the CDN as of this morning (thanks to Stephen and his team for getting this done!), so you can specify the CDN as the default location. Here’s what I have in my Global.asax.cs.
protected void Application_Start()
{
AjaxHelper.GlobalizationScriptPath =
"http://ajax.microsoft.com/ajax/4.0/1/globalization/";
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
With that in place, everything now just works. Let’s try filling out the form again.
This time, 1,000 is not within the valid range because that’s equivalent to 1 in the es-ES locale.
Meanwhile, 1.000 is within the valid range as that’s equivalent to 1,000.

So what are these scripts?
They are simply a JavaScript serialization of all the info within a CultureInfo object. So the information you can get on the server, you can now get on the client with these scripts.
In Web Forms, these scripts are emitted automatically by serializing the culture at runtime. However this approach doesn’t work for ASP.NET MVC.
One reason is that the scripts themselves changed from ASP.NET 3.5 to ASP.NET 4. ASP.NET MVC is built against the ASP.NET 4 version of these scripts. But since MVC 2 runs on both ASP.NET 3.5 and ASP.NET 4, we couldn’t rely on the script manager to emit the scripts for us as that would break when running on ASP.NET 3.5 which would emit the older version of these scripts.
As usual, I have very simple sample you can download to see the feature in action.
The ASP.NET MVC2 templates feature is a pretty nice way to quickly scaffold objects at runtime. Be sure to read Brad Wilson’s fantastic series on this topic starting at ASP.NET MVC 2 Templates, Part 1: Introduction.
As great as this feature is, there is one template that’s conspicuously missing. ASP.NET MVC does not include a template for displaying a list of objects in a tabular format. Earlier today, ScottGu forwarded an email from Daniel Manes (what?! no blog! ;) with a question on how to accomplish this. Daniel had much of it implemented, but was trying to get over the last hurdle.
With Brad’s help, I was able to give him a boost over that hurdle. Let’s walk through the scenario.
First, we need a model.
No, not that kind of model. Something more along the lines of a C# variety.
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
[DisplayName("Date Published")]
public DateTime PublishDate { get; set; }
}
Great, now lets add a controller action to the default HomeController which will create a few books and pass them to a view.
public ActionResult Index()
{
var books = new List<Book>
{
new Book {
Id = 1,
Title = "1984",
Author = "George Orwell",
PublishDate = DateTime.Now
},
new Book {
Id = 2,
Title = "Fellowship of the Ring",
Author = "J.R.R. Tolkien",
PublishDate = DateTime.Now
},
//...
};
return View(books);
}
Now we’ll create a strongly typed view we’ll use to display a list of such books.
<% @Page MasterPageFile="~/Views/Shared/Site.Master"
Language="C#"
Inherits="ViewPage<IEnumerable<TableTemplateWeb.Models.Book>>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h2>All Books</h2>
<p>
<%: Html.DisplayForModel("Table") %>
</p>
</asp:Content>
If you run the code right now, you won’t get a very useful display. Also, notice that we pass in the string “Table” to the DisplayForModel method. That’s a hint to the template method which tells it, “Hey! If you see a template named ‘Table’, tell him he owes me money! Oh, and use it to render the model. Otherwise, if he’s not around fallback to your normal behavior.”
Since we don’t have a Table template yet, this code is effectively the same as if we didn’t pass anything to DisplayForModel.
What we need to do now is create the Table template. To do so, create a DisplayTemplates folder within the Views/Shared directory. Then right click on that folder and select Add | View.
This brings up the Add View dialog. Enter Table as the view name and make sure check Create a partial view. Also, check Create a strongly-typed view and type in IList as the View Data Class.
When you click Add, you should see the new template in the DisplayTemplates folder like so.
Here’s the code for the template. Note that there’s some code in here that I could refactor into a helper class in order to clean up the template a bit, but I wanted to show the full template code here in one shot.
<% @Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList>" %>
<script runat="server">
public static bool ShouldShow(ModelMetadata metadata,
ViewDataDictionary viewData) {
return metadata.ShowForDisplay
&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !viewData.TemplateInfo.Visited(metadata);
}
</script>
<%
var properties = ModelMetadata.FromLambdaExpression(m => m[0], ViewData)
.Properties
.Where(pm => ShouldShow(pm, ViewData));
%>
<table>
<tr>
<% foreach(var property in properties) { %>
<th>
<%= property.GetDisplayName() %>
</th>
<% } %>
</tr>
<% for(int i = 0; i < Model.Count; i++) {
var itemMD = ModelMetadata.FromLambdaExpression(m => m[i], ViewData); %>
<tr>
<% foreach(var property in properties) { %>
<td>
<% var propertyMetadata = itemMD.Properties
.Single(m => m.PropertyName == property.PropertyName); %>
<%= Html.DisplayFor(m => propertyMetadata.Model) %>
</td>
<% } %>
</tr>
<% } %>
</table>
Explanation
There’s a lot going on in here, but I’ll try to walk through it bit by bit. If you’d rather skip this part and just take the code and run, I won’t hold it against you.
In the first section, we define a ShouldShow method which is pulled right out of the logic for our default Object template. You’ll notice there’s mention of System.Data.EntityState (defined in the System.Data.Entity.dll) which is used to filter out certain Entity Framework properties. If you aren’t using Entity Framework you can safely delete that line. You’ll know you don’t need that line if you aren’t referencing System.Data.Entity.dll which will cause this code to blow up like aluminum foil in a microwave.
In the next code block, we grab all the property ModelMetadata for the first item in the list. Remember, the current model in this template is a list, but we need the metadata for an item in this list, not the list itself. That’s why we have this odd bit of code here. Once we grab this metadata, we can iterate over it and display the column headers.
In the final block of code, we iterate over every item in the list and use this handy dandy FromLambdaExpression method to grab the ModelMetadata for an individual item.
Then we grab the property metadata for that item and iterate over that so that we can display each property in its own column. Notice that we call DisplayFor on each property rather than simply spitting out propertyMetadata.Model.
Usage
Now that you’ve created this Table.ascx template and placed it in the Shared/DisplayTemplates folder, it is available any time you’re using a display template to render a list. Simply supply a hint to use the table template. For example:
<%: Html.DisplayForModel("Table") %>
or
<%: Html.DisplayFor(m => m.SomeList, "Table") %>
Download the sample
As I typically do, I’ve written up a sample project you can try out in case you run into problems getting this to work. Note this sample was built for Visual Studio 2010 targetting ASP.NET 4. If you are running ASP.NET MVC 2 on Visual Studio 2008 SP1, just copy the Table.ascx into your own project but replace the Html encoding code nuggets <%: … %> to <%= Html.Encode(…) %>.
Here’s the link to the sample.