code comments edit

In my last blog post, I wrote about the proper way to check for empty enumerations and proposed an IsNullOrEmpty method for collections which sparked a lot of discussion.

This post covers a similar issue, but from a different angle. A very long time ago, I wrote about my love for the null coalescing operator. However, over time, I’ve found it to be not quite as useful as it could be when dealing with strings. For example, here’s the code I might want to write:

public static void DoSomething(string argument) {
  var theArgument = argument ?? "defaultValue";
  Console.WriteLine(theArgument);
}

But here’s the code I actually end up writing:

public static void DoSomething(string argument) {
  var theArgument = argument;
  if(String.IsNullOrWhiteSpace(theArgument)) {
    theArgument = "defaultValue";
  }
  Console.WriteLine(theArgument);
}

The issue here is that I want to treat an argument that consists only of whitespace as if the argument is null and replace the value with my default value. This is something the null coalescing operator won’t help me with.

This lead me to jokingly propose a null or empty coalescing operator on Twitter with the syntax ???. This would allow me to write something like:

var s = argument ??? "default";

Of course, that doesn’t go far enough because wouldn’t I also need a null or whitespace coalescing operator???? ;)

Perhaps a better approach than the PERLification of C# is to write an extension method that normalizes string in such a way you can use the tried and true (and existing!) null coalescing operator.

Thus I present to you the AsNullIfEmpty and AsNullIfWhiteSpace methods!

Here’s my previous example refactored to use these methods.

public static void DoSomething(string argument) {
  var theArgument = argument.AsNullIfWhiteSpace() ?? "defaultValue";

  Console.WriteLine(theArgument);
}

You can also take the same approach with collections.

public static void DoSomething(IEnumerable<string> argument) {
  var theArgument = argument.AsNullIfEmpty() ?? new string[]{"default"};

  Console.WriteLine(theArgument.Count());
}

The following is the code for these simple methods.

public static class EnumerationExtensions {
  public static string AsNullIfEmpty(this string items) {
    if (String.IsNullOrEmpty(items)) {
      return null;
    }
    return items;
  }

  public static string AsNullIfWhiteSpace(this string items) {
    if (String.IsNullOrWhiteSpace(items)) {
      return null;
    }
    return items;
  }
        
  public static IEnumerable<T> AsNullIfEmpty<T>(this IEnumerable<T> items) {
    if (items == null || !items.Any()) {
      return null;
    }
    return items;
  }
}

Another approach that some commenters to my last post recommended is to write a Coalesce method. That’s also a pretty straightforward approach which I leave as an exercise to the reader. :)

code comments edit

While spelunking in some code recently I saw a method that looked something like this:

public void Foo<T>(IEnumerable<T> items) {
  if(items == null || items.Count() == 0) {
    // Warn about emptiness
  }
}

This method accepts a generic enumeration and then proceeds to check if the enumeration is null or empty. Do you see the potential problem with this code? I’ll give you a hint, it’s this line:

items.Count() == 0

What’s the problem? Well that line right there has the potential to be vastly inefficient.

If the caller of the Foo method passes in an enumeration that doesn’t implement ICollection<T> (for example, an IQueryable as a result from an Entity Framework or Linq to SQL query) then the Count method has to iterate over the entire enumeration just to evaluate this expression.

In cases where the enumeration that’s passed in to this method does implement ICollection<T>, this code is fine. The Count method has an optimization in this case where it will simply check the Count property of the collection.

If we translated this code to English, it’s asking the question “Is the count of this enumeration equal to zero?”. But that’s not really the question we’re interested in. What we really want to know is the answer to the question “Are there any elements in this enumeration?

When you think of it that way, the solution here becomes obvious. Use the Any extension method from the System.Linq namespace!

public void Foo<T>(IEnumerable<T> items) {
  if(items == null || !items.Any()) {
    // Warn about emptiness
  }
}

The beauty of this method is that it only needs to call MoveNext on the IEnumerable interface once! You could have an infinitely large enumeration, but Any will return a result immediately.

Even better, since this pattern comes up all the time, consider writing your own simple extension method.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> items) {
    return items == null || !items.Any();
}

Now, with this extension method, our original method becomes even simpler.

public void Foo<T>(IEnumerable<T> items) {
  if(items.IsNullOrEmpty()) {
    // Warn about emptiness
  }
}

With this extension method in your toolbelt, you’ll never inefficiently check an enumeration for emptiness again.

subtext comments edit

Deploying a Subtext skin used to be one of the biggest annoyances with Subtext prior to version 2.5. The main problem was that you couldn’t simply copy a skin folder into the Skins directory and just have it work because the configuration for a given skin is centrally located in the Skins.config file.

elephant-skinIn other words, a skin wasn’t self contained in a single folder. With Subtext 2.5, this has changed. Skins are fully self contained and there is no longer a need for a central configuration file for skins.

What this means for you is that it is now way easier to share skins. When you get a skin folder, you just drop it into the /skins directory and you’re done!

In most cases, there’s no need for any configuration file whatsoever. If your skin contains a CSS stylesheet named style.css, that stylesheet is automatically picked up. Also, with Subtext 2.5, you can provide a thumbnail for your skin by adding a file named SkinIcon.png into your skin folder. That’ll show up in the improved Skin picker.

When To Use A Skin.config File

Each skin can have its own manifest file named Skin.config.This file is useful when you have multiple CSS and JavaScript files you’d like to include other than style.css (though even in this case it’s not absolutely necessary as you can reference the stylesheets in PageTemplate.ascx directly).

The other benefit of using the skin.config file to reference your stylesheets and script files is you can take advantage of our ability to merge these files together at runtime using the StyleMergeMode and ScriptMergeMode attributes.

Also, in some cases, a skin can have multiple themes differentiated by stylesheet as described in this blog post. A skin.config file can be used to specify these skin themes and their associated CSS file.

Creating a Skin.config file

Creating a skin.config file shouldn’t be too difficult. If you already have a Skins.User.config file, it’s a matter of copying the section of that file that pertains to your skin into a skin.config file within your skin folder and removing some extraneous nodes.

Here’s an example of a new skin.config file for my personal skin.

<?xml version="1.0" encoding="utf-8" ?>
<SkinTemplates>
    <SkinTemplate Name="Haacked-3.0">
        <Scripts>
            <Script Src="~/scripts/lightbox.js" />
            <Script Src="~/scripts/XFNHighlighter.js" />
        </Scripts>
        <Styles>
            <Style href="~/css/lightbox.css" />
            <Style href="~/skins/_System/csharp.css" />
            <Style href="~/skins/_System/commonstyle.css" />
            <Style href="~/skins/_System/commonlayout.css" />
            <Style href="~/scripts/XFNHighlighter.css" />
            <Style href="IEPatches.css" conditional="if IE" />
        </Styles>
    </SkinTemplate>
</SkinTemplates>

If you compare it to the old format, you’ll notice the <Skins> element is gone and there’s no need to specify the TemplateFolder since it’s assumed the folder containing this file is the template folder.

Hopefully soon, we’ll provide more comprehensive documentation on our wiki so you don’t have to go hunting around my blog for information on how to skin your blog. My advice is to copy an existing skin and just tweak it.

comments edit

Wow, has it already been over a year since the last major version of Subtext? Apparently so.

Today I’m excited to announce the release of Subtext 2.5. Most of the focus on this release has been under the hood, but there are some great new features you’ll enjoy outside of the hood.

Major new features

  • New Admin Dashboard: When you login to the admin section of your blog after upgrading, you’ll notice a fancy schmancy new dashboard that summarizes the information you care about in a single page.subtext-dashboardThe other thing you’ll notice in the screenshot is the admin section received a face lift with a new more polished look and feel and many usability improvements.
  • Improved Search:We’ve implemented a set of great search improvements. The biggest change is the work that Simone Chiaretta did integrating Lucene.NET, a .NET search engine, as our built-in search engine. Be sure to check out his tutorial on Lucene.NET. Also, when clicking through to Subtext from a search engine result, we’ll show related blog posts. Subtext also implements the OpenSearch API.

Core Changes

We’ve put in huge amounts of effort into code refactoring, bulking up our unit test coverage, bug fixes, and performance improvements. Here’s a sampling of some of the larger changes.

  • Routing: We’ve replaced the custom regex based URL handling with ASP.NET Routing using custom routes based on the page routing work in ASP.NET 4. This took a lot of work, but will lead to better control over URLs in the long run.
  • Dependency Injection:Subtext now uses Ninject, an open source Dependency Injection container, for its Inversion of Control (IoC) needs. This improves the extensibility of Subtext.
  • Code Reorganization and Reduced Assemblies: A lot of work went into better organizing the code into a more sane and understandable structure. We also reduced the overall number of assemblies in an attempt to improve application startup times.
  • Performance Optimizations:We made a boat load of code focused performance improvements as well as caching improvements to reduce the number of SQL queries per request.
  • Skinning Improvements:This topic deserves its own blog post, but to summarize, skins are now fully self contained within a folder. Prior to this version, adding a new skin required adding a skin folder to the /Skins directory and then modifying a central configuration file. We’ve removed that second step by having each skin contain its own manifest, if needed. Most skins don’t need the manifest if they follow a set of skin conventions. For a list of Breaking changes, check out our wiki.

Upgrading

Because of all the changes and restructuring of files and directories, upgrading is not as straightforward as it has been in the past.

To help with all the necessary changes, we’ve written a tool that will attempt to upgrade your existing Subtext blog.

I’ve recorded a screencast that walks through how to upgrade a blog to Subtext 2.5 using this new tool.

Installation

Installation should be as easy and straightforward as always, especially if you install it using the Web Platform Installer (Note, it may take up to a week for the new version to show up in Web PI). If you’re deploying to a host that supports SQLExpress, we’ve included a freshly installed database in the App_Data folder.

To install, download the zip file here and follow the usual Subtext installation instructions.

More information

We’ll be updating our project website with more information about this release in the next few weeks and I’ll probably post a blog post here and there.

I’d like to thank the entire Subtext team for all their contributions. This release probably contains the most diversity of patches and commits of all our releases with lots of new people pitching in to help.

personal comments edit

I saw a recent Twitter thread discussing the arrogance of Steve Jobs. One person (ok, it was my buddy Rob) postulated that it was this very arrogance that led Apple to their successes.

I suppose it’s quite possible that it had a factor, but I tend to think Steve Job’s vision and drive were much bigger factors.

This idea is a reflection of a pervasive belief out there that arrogance is excusable, perhaps even acceptable and admirable in successful people and institutions. In contrast, I think we’d all agree that that arrogance is universally detestable in unsuccessful people.

But is arrogance necessary for success? I certainly don’t think so. I think there’s an alternative characteristic that can lead to just as much success.

Joy.

pele
pic

My example here is the most successful national soccer team ever, Brazil. They’ve won the most world cups of any team and yet the one word you’d be hard pressed to find anyone using to describe them is “Arrogant.” (Yes, I know that many from Argentina would disagree, but this is the perception out there) ;)

Instead, the word often associated with them is “Joy.” When Brazil plays, their joy for the beautiful game is so infectious you can’t help but share in the joy when they win. Heck, even as you’re grumbling about your own team losing to them, it’s hard not to join in the Samba spirit (again, unless you’re from Argentina).

This is a team that has been incredibly successful over the years and arrogance was unnecessary.

I think there are probably many examples in the technology and business world we could point to where incredible success and visionary leadership came from a joy in the work they do rather than arrogance. Have any examples for me? Leave them in the comments.

The World Cup starts in 6 days! I’ll try not to make all my posts soccer themed if I can help it. :)

asp.net mvc, personal, open source comments edit

The June issue (also in pdf) of the online PragPub magazine, published by the Pragmatic Bookshelf has two articles on ASP.NET MVC.

The first is called Agile Microsoft and is an introduction to ASP.NET MVC geared towards those who’ve never seen it. It’s nice seeing ASP.NET MVC featured in this magazine which in its own words tends to cater to a non-Microsoft crowd.

To some developers, Microsoft’s technologies are a given, the river they swim in. To others, not using Microsoft’s tools is the default. PragPub being an open source- and Agile-friendly kind of magazine, we tend to connect with the latter group.

So when we get an article titled “Agile Microsoft,” we are naturally intrigued. And we think you’ll also be intrigued by Jonathan McCracken’s introduction toASP.NET MVC, a framework that some have called “Rails for .NET.”

The second article is an interview with me entitled “Why ASP.NET MVC?” where I ramble on about how if wandering the halls of Microsoft doesn’t get you tossed out by security, it might land you a great job, as well as ASP.NET MVC, TDD, and Open Source Software.

Something I found interesting was that the person who interviewed me was Michael Swaine who co-wrote the book, Fire in the Valley, that the movie Pirates of Silicon Valley (no Jonny Depp in this one) was based on. The movie (and book) covers the rise of the computer industry and Steve Jobs, Bill Gates, among others.

code comments edit

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.

personal comments edit

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.

IMG_0346

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.

IMG_0359Nearly 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.

IMG_0360

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.

IMG_0372 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.

IMG_0376We 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. IMG_0386But who are we to blame them, the view was beautiful despite the clouds and rain rolling in right as we got there.

IMG_0392If 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.

tech comments edit

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.

Remote Desktop Dialog

Then expand the dialog by clicking on Options, then check the Local**Resources tab.

Remote Desktop Local Resources Options

Make sure Clipboard is checked, and then hit the More… button.

Remote Desktop Drives

Now you can select a local disk to be shared with the remote machine. For example, in this case I selected my C: drive.

Local Drive shared on Remote DesktopAs 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.

Remote Desktop

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.

stuff

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, code comments edit

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

asp.net, asp.net mvc, code comments edit

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.

valid-range

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.

invalid-range

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.

invalid-range-es-ES

Meanwhile, 1.000 is within the valid range as that’s equivalent to 1,000.

valid-range-es-ES

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.

asp.net mvc, asp.net, code comments edit

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.

zoolander

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.

Add View
Dialog

When you click Add, you should see the new template in the DisplayTemplates folder like so.

solution
explorer

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 {.clear}

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.

asp.net mvc, asp.net, code comments edit

Like the well disciplined secure developer that you are, when you built your ASP.NET MVC 1.0 application, you remembered to call Html.Encode every time you output a value that came from user input. Didn’t you?

Well, in ASP.NET MVC 2 running on ASP.NET 4, those calls can be replaced with the new HTML encoding syntax (aka code nugget). I’ve written a three part series on the topic.

But dang, going through all your source files cleaning up these calls is a pretty big pain. Don’t worry, I have your back. Just bring up the Find an Replace dialog (CTRL + SHIFT + H) and expand the Find options section and check the checkbox labeled Use and make sure Regular expressionsis selected.

Then enter the following in the Find what textbox.

\<\%:b*=:b*Html.Encode\({[^%]*}\):b*\%\>

And enter the following in the Replace with textbox.

<%: \1 %>

Here’s a screenshot of what the dialog should look like (though yours won’t have the red box :P).

find-and-replaceNote that this regular expression I’m giving you is not foolproof. There are some very rare edge cases where it might not work, but for the vast majority of cases, it should work fine. At least, it works on my machine!

works-on-my-machine

Now that I’m finally done with updates to Professional ASP.NET MVC 2, I hope to get back to my regular blogging schedule. This will be only my third blog post this month, a new record low! And I love to blog! It’s been a busy past few months.

asp.net, asp.net mvc, code comments edit

One annoyance that some developers have run into with ASP.NET MVC is that certain reserved filenames are not allowed in URLs. Often, this is manifested as a Bad Request error or a File Not Found (404) error.

The specifics of this restriction are accounted for in an interesting blog post entitled Zombie Operating Systems and ASP.NET MVC. This actually wasn’t a restriction on ASP.NET MVC but was built into the core of ASP.NET itself.

Fortunately, ASP.NET 4 fixes this issue with a new setting. In web.config, simply add <httpRuntime relaxedUrlToFileSystemMapping="true"/> to the system.web node. Here’s a snippet from my web.config.

<configuration>
  <system.web>
    <httpRuntime relaxedUrlToFileSystemMapping="true"/>

    <!-- ... your other settings ... -->
  </system.web>
</configuration>

Here is a screenshot of it working on my machine.

con-in-my-url

Now you are free to use COM1-9, LPT1-9, AUX, PRT, NUL, CON in your URLs. I know you were dying to do so. :)

What about web.config?

So the question comes up from time to time, “what if I want to have web.config in my URL?” Why would you want that? Well if you are StackOverflow.com, this makes sense because of the tagging system which places a tag (such as the “web.config” tag, into the URL. I’m not sure why anyone else would want it. ;)

The answer is yes, it works.

web.config-in-my-url

Please note, that you still can’t request /web.config because that would try to request web.config in the root of your web application and ASP.NET won’t allow that for good reason!

In fact, any request for a *.config file that doesn’t match a route will fail.

While I think the vast majority of developers really won’t encounter this issue, it’s a really improvement included in ASP.NET 4 for those that do care.

Keep in mind that this isn’t restricted to just these special names. For example, a URL segment ending with a dot such as the following URL http://example.com/version/1.0./something will not work unless you set the this web.config value.

asp.net mvc, asp.net, code comments edit

UPDATE: The JsonValueProviderFactory is now registered by default in ASP.NET MVC 3. So if you’re using ASP.NET MVC 3, you can ignore that part of this blog post.

Javier “G Money” Lozano, one of the good folks involved with C4MVC, recently wrote a blog post on posting JSON (JavaScript Object Notation) encoded data to an MVC controller action. In his post, he describes an interesting approach of using a custom model binder to bind sent JSON data to an argument of an action method. Unfortunately, his sample left out the custom model binder and only demonstrates how to retrieveJSON data sent from a controller action, not how to send the JSON to the action method. Honest mistake. :)

His post reminds me of how remiss I’ve been in blogging recently because a while back, we added something to our ASP.NET MVC 2 Futures library that handles sending JSON to an action method but I just never found time to blog about it.

There’s one key problem with using a model binder to accept JSON. By writing a custom model binder, you miss out on validation. Using his example, if you type “abc” for the Age field, you will get a serialization failure when attempting to serialize the JSON into the PersonInputModel object because Age is an Int32 and the serialization will fail.

Value Providers to the rescue!

This is where value providers, a new feature of ASP.NET MVC 2, enters to save the day. Whereas model binders are used to bind incoming data to an object model, value providers provide an abstraction for the incoming data itself.

When the ASP.NET MVC feature team first implemented value providers, Jonathan Carter and I were working on a client templating sample which sent JSON to an action method. Rather than write a custom model binder which was the approach I took, Jonathan had the unique insight to write a custom value provider which received JSON data and serialized it to a dictionary rather than the target object. The beauty of his approach is that this dictionary data is then passed to the default model binder which binds it to the final object with validation!

I took is his prototype and added the JsonValueProviderFactory to our ASP.NET MVC 2 Futures library and then totally didn’t write about it. Yes, I suck.

Setting it up

To get started, download the ASP.NET MVC 2 Futures Library and reference the Microsoft.Web.Mvc.dll assembly. Then, in your Global.asax.cs file, add the following call to register the JsonValueProviderFactory.

protected void Application_Start() 
{
  RegisterRoutes(RouteTable.Routes);
  ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

That’s it! You’re done!

This value provider will handle requests that are encoded as application/json. There’s no need to specify a model binder on classes that accept JSON input.

See it in action

I took the liberty of updating Javier’s sample to use this new value provider and to actually post JSON to the action method.

It turns out, sending JSON encoded data to an action method with jQuery was not as straightforward as I hoped. If you know of a more straightforward way, let me know. I ended up using a JSON plug-in for jQuery I found on the Internets. This provides a $.toJSON method I could use to serialize an object into a JSON encoded string. Here’s the updated client script code.

UPDATE: Per Dave Ward’s comment here I should be using json2.js and its JSON.stringify(...) method instead because it matches an API that some browsers implement and will use the native implementation if it exists. Nice! I’ll update this blog post later when I have a moment.

$(function () {
    $("#personCreate").click(function () {
        var person = getPerson();

        // poor man's validation
        if (person == null) {
            alert("Specify a name please!");
            return;
        }

        var json = $.toJSON(person);

        $.ajax({
            url: '/home/save',
            type: 'POST',
            dataType: 'json',
            data: json,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // get the result and do some magic with it
                var message = data.Message;
                $("#resultMessage").html(message);
            }
        });
    });
});

function getPerson() {
    var name = $("#Name").val();
    var age = $("#Age").val();

    // poor man's validation
    return (name == "") ? null : { Name: name, Age: age };
}

Notice that we use the $.ajax method to specify both the JSON data and the JSON content type for the request.

A quick check in Fiddler confirms that the data in the POST request is properly JSON encoded.

json-request-fiddler

Now, within my action method, I can actually check to see if the model state is valid and if not, return an error message.

[HttpPost]
public ActionResult Save(PersonInputModel inputModel) {
  if (ModelState.IsValid)
  {
    string message = string.Format("Created user '{0}' aged '{1}' in the system."
      , inputModel.Name, inputModel.Age);
    return Json(new PersonViewModel { Message = message });
  }
  else {
    string errorMessage = "<div class=\"validation-summary-errors\">" 
      + "The following errors occurred:<ul>";
    foreach (var key in ModelState.Keys) {
      var error = ModelState[key].Errors.FirstOrDefault();
      if (error != null) {
        errorMessage += "<li class=\"field-validation-error\">" 
         + error.ErrorMessage + "</li>";
      }
    }
    errorMessage += "</ul>";
    return Json(new PersonViewModel { Message = errorMessage });
  }
}

And as you can see in the Fiddler screenshot, I sent an invalid Age to the server and yet, it all still works.

validation-with-json

Whew! I can finally cross this off of my immense blog backlog. :) Hopefully soon, I’ll blog a more detailed write-up of value providers.

We have plans to add the JsonValueProviderFactory to ASP.NET MVC 3 so that it’s a built-in feature. I hope you find this useful and as always, let me know if there are ways we can improve it!

Oh, and here’s Javier’s updated sample with the value provider.

asp.net mvc, asp.net, code comments edit

This is the third in a three part series related to HTML encoding blocks, aka the <%: ... %> syntax.

Scott Guthrie recently wrote about the new <%: %> syntax for HTML encoding output in ASP.NET 4. I also covered the topic of HTML encoding code nuggets in the past as well providing some insight into our design choices for the approach we took.

A commenter to Scott’s blog post asked,

Will it be possible to extend this so that is uses libraries like AntiXSS instead? See: http://antixss.codeplex.com/

The answer is yes!

ASP.NET 4 includes a new extensibility point which allows you to replace the default encoding logic with your own anywhere ASP.NET does encoding.

All it requires is to write a class which derives from System.Web.Util.HttpEncoder and register that class in Web.config via the encoderType attribute of the httpRuntime element.

Walkthrough

In the following section, I’ll walk you through setting this up. First, you’re going to need to download the AntiXSS library which is at version 3.1 at the time of this writing. On my machine, that dropped the AntiXSSLibrary.dll file at the following location: C:\Program Files (x86)\Microsoft Information Security\Microsoft Anti-Cross Site Scripting Library v3.1\Library

Create a new ASP.NET MVC application (note, this works for *any* ASP.NET application). Copy the assembly into the project directory somewhere where you’ll be able to find it. I typically have a “lib” folder or a “Dependencies” folder for this purpose. Right clicke on the References node of the project to add a reference to the assembly.

add-reference Add-Reference-dialogThe next step is to write a class that derives from HttpEncoder. Note that in the following listing, some methods were excluded which are included in the project.

using System;
using System.IO;
using System.Web.Util;
using Microsoft.Security.Application;

/// <summary>
/// Summary description for AntiXss
/// </summary>
public class AntiXssEncoder : HttpEncoder
{
  public AntiXssEncoder() { }

  protected override void HtmlEncode(string value, TextWriter output)
  {
    output.Write(AntiXss.HtmlEncode(value));
  }

  protected override void HtmlAttributeEncode(string value, TextWriter output)
  {
    output.Write(AntiXss.HtmlAttributeEncode(value));
  }

  protected override void HtmlDecode(string value, TextWriter output)
  {
      base.HtmlDecode(value, output);
  }

  // Some code omitted but included in the sample
}

Finally, register the type in web.config.

...
  <system.web>
    <httpRuntime encoderType="AntiXssEncoder, AssemblyName"/>
...

Note that you’ll need to replace AssemblyName with the actual name of your assembly. Also, in the sample included with this blog post, AntiXssEncoder is not in any namespace. If you put your encoder in a namespace, you’ll need to make sure to provide the fully qualified type name.

To prove that this is working, run the project in the debugger and set a breakpoint in the encoding method.

debugger-breakpoint

With that, you are all set to take full control over how strings are encoded in your application.

Note that Scott Hanselman and I gave a live demonstration of setting this up at Mix 10 this year as part of our security talk if you’re interested in watching it.

As usual, I’ve provided a sample ASP.NET MVC 2 project for Visual Studio 2010 which you can look at to see this in action.

humor, code comments edit

The “copyleft” provisions of the GPL (GNU General Public License) require that any changes or additions to a GPL licensed work must itself be licensed under terms that adhere to the GPL.

Critics of these “copyleft” provisions have derogatively labeled the GPL as a “viral” license. Such criticism points out that any code that seeks to incorporate GPL licensed code must itself adhere to the terms of the GPL, thus potentially “infecting” other code with its restrictions.

This has caused many developers of proprietary systems to be concerned about any usage of GPL code within their products for fear of turning their closed source codebase into a GPL licensed open source codebase.

But now there’s a new viral license to be feared. This new license us the product of a legal thought experiment that was assumed to be purely theoretical in nature, but impossible to actually realize. The experiment proposed the following question:

Just as there is a license which virally turns closed source code into open source code, is it possible to craft a viral license that does the opposite, turning open source into closed source?

locked-computer

Jim, I’m afraid it is.

The possibility of this specter has been a grave concern for many open source experts for years, but now has been realized by the new antithesis to the GPL called the CSPL, which stands for Closed Source Proprietary License.

Under the terms of the CSPL (pronounced Sess-Puhl), any codebase operating within the same user memory space of the CSPL licensed code is itself licensed under the CSPL which removes all rights to view or change the source code.

Famed Linux developer Linus Torvald, when presented with this news, could only muster the following comment.

Are you fucking kidding me?!

Which coincidentally was the same response uttered by notable Ruby on Rails creator David Heinemeier Hansson (aka DHH), apart from the fact that DHH omitted the words “Are”, “you”, “ing”, “kidding”, and “me”.

Noted open source developer Miguel De Icaza railed against this library in his twitter feed 140 characters at a time noting:

The CSPL is a travesty and a cancer and it must be stopped. OTOH, as long as http://trollcats.com/ is unaffected it can’t all be bad. BRB…

Miguel could not be reached for further comment as he was ostensibly engaged in finding the proper TrollCats image to express his complete outrage.

TekPub co-owner Rob Conery glumly noted that sales of his developer focused educational videos have declined precipitously ever since he was forced to redact the source code from his screen casts.

redacted-code

Well regarded speaker and .NET luminary Scott Hanselman had this to say…

This reminds me of the panic that ensued when it was discovered that the last GUID had been used up. By the way, have you seen the Hamster on a Piano?

Prolific blogger and open source developer, Oren Eini (also known as Ayende) noted with dismay that he was finding it very difficult to continue working on his projects formerly known as open source while averting his eyes from the screen in order to comply with the license. His blogging and open source contributions took a noticeable hit as he only managed 256 blog posts in the past week while contributing 297,051 lines of new code to NHibernate, Rhino Mocks, and Log4Net.

Richard Stallman could not be reached for comment on this matter, but it can be safely assumed a legal challenge is brewing.

code comments edit

UPDATE: After an email exchange with Eric Meijer, I learned that I was a bit imprecise in this treatment. Or, as the colloquial term goes, “wrong”. :) I’ve changed the title to reflect more accurately what Reactive extensions provide.

Iterating over a collection of items seems like a pretty straightforward mundane concept. I don’t know about you, but I don’t spend the typical day thinking about the mechanics of iteration, much like I don’t spend a lot of time thinking about how a roll of toilet paper is made. At least I didn’t until watching Elmo Potty Time with my son. Now I think about it all the time, but I digress.

the-futureHistorically, I’ve always thought of iteration as an action over a static set of items. You have this collection of elements, perhaps a snapshot of data, and you then proceed to grab a reference to each one in order and do something with that reference. What you do with it is your business. I’m not going to pry.

It wasn’t till the yield operator was introduced into C# that I realized this was a very limited view of iteration. For example, using the yield operator makes it easy to enumerate over computed sets, as demonstrated by iterating over the Fibonacci sequence. In this case, the set of elements being iterated is not a static set.

Reactive Extensions

Recently, Matt “is his middle name really not F#” Podwysocki swung by my office to show me yet another way of thinking about iterations via the Reactive Extensions to JavaScript. These extensions are based on the same concept applied in the Reactive Extensions for .NET which I’ve sadly ignored until now.

There’s a channel9 video where Eric Meijer describes these extensions as push collections, as contrasted with normal collections where you pull each item from the collection.

Unfortunately, when I first heard this analogy, it didn’t click in my head. That’s not terribly unusual as it often takes a few bat swings at my head for something to stick. It wasn’t till I understood the pattern of code that reactive extensions are a replacement for, did it click. By inverting the analogy that Eric used, these extensions made a lot more sense to me.

Typically, when you write code to handle user interactions, you write events and methods (event handlers) which handle the events. In my mind, this is a very “push” way to handle it. For example, as soon as a user moves the mouse over an element you’re interested in, a mouseover event gets pushed to your mouseover event handler method.

Reactive extensions inverts this model by taking what I would call a “pull” model of events. Using these extensions, you can treat the sequence of user events (such as the sequence of mouse over events) as if it were a normal collection (well actually, as an enumeration). Thus you can write LINQ queries over the collection which do things like filtering, grouping, composing, etc.

Your code really looks like it’s dealing with a fully “populated” collection, even though elements of that collection may not have occurred yet.

Effectively, you’re enumerating querying over the future.

The mental shift for me is to realize that we’re actually working with sequences being “pushed” into our query in this case and not queries running over already populated collections.

Speaking of keyboard presses, Matt Podwysocki took my Live Preview jQuery Plugin and ported it to use the Reactive Extensions for JavaScript. You can see a demo of it in action here (view source for the code).

The snippet that’s pretty cool to me is the following:

textarea
  .ToObservable("keyup")
  .Take(1)
  .SelectMany(function() {
  return Rx.Observable.Start(function() {
    return textarea.reloadPreview(); });
  }).Repeat()
.Subscribe(function() {});

As Matt told me, if you squint hard enough, it looks like you’re writing a LINQ query in JavaScript. :)

Tags: reactive extensions,javascript

personal, code comments edit

Last week I spent a few days in Las Vegas attending the Mix 10 conference. Mix is billed as …

A 3 day conference for web designers and developers building the world’s most innovative web sites.

Which certainly reflects its origins as a conference focused on the web and web standards. But this year, it seemed that the scope for Mix was expanded to be about, well, a Mix of technologies as the Windows Phone 7 series figured prominently at the conference.

shanselman-haacked-jeresig Scott Hanselman and I are seen here attempting to tutor this young man about a language called “JavaScript”

Mix of communities

One aspect I love about Mix is it’s also a Mix of communities. Sure, it’s heavily Microsoft dominated, since it is, well, Microsoft that puts it on, but this conference has never been shy about bringing in people outside of the Microsoft community to speak.

One of the speakers I was excited to finally meet in person was John Resig, the creator of the very popular jQuery JavaScript library seen in the above photograph to the right. Yes, for those of you amongst the humor impaired, the caption is a joke (thanks to Peter Kellner who took the photo).

Also speaking was Douglas Crockford (inventor of JSON) who had the best slide of the show with the words…

IE 6 Must Die!

Preach it brother Crockford! Since I was able to chat with him in person, I confirmed it was really Douglas who left this comment on my JSON post suggesting that requiring POST was a good change to the JsonResult in ASP.NET MVC 2. I really enjoyed having the opportunity to chat with him about security and JSON.

Sessions

If you’re interested in watching the keynotes, check out Day 1 (Silverlight, Windows Phone 7 series) and Day 2 (IE9, Web Development, OData).

I presented two sessions (click on the title for the video).

What’s new in ASP.NET MVC 2 

Come see and hear about the latest innovations in ASP.NET MVC 2 and the tooling support in Microsoft Visual Studio 2008 and 2010. We introduce you to a range of productivity (and extensibility) enhancements such as template helpers, model validation, and the new “Areas” feature, which enhances the team development of large websites. With template helpers you can get your website up and running for any data entity type without having to create UI. With improved server side validation and brand new client side validation support, your business data model can define the behavior of your application automatically. All this and more!

The HaaHa Show: Microsoft ASP.NET MVC Security with Haack and Hanselman

The HaaHa brothers take turns implementing features on an ASP.NET MVC website. Scott writes a feature, and Phil exploits it and hacks into the system. We analyze and discuss the exploits live on stage and then close them one by one. Learn about XSS, CSRF, JSON Hijacking and more. Is *your* site safe from the Haack?

For those interested in seeing the decks, trying out the code, and perhaps reading the checklist I use for my demos (the checklist is there to help in case I freeze from stage fright), I’ve made them all available for these two talks in a single zip file.

For the most part, I thought the talks went well, despite some technical difficulties. During my first talk, despite my preparation, I had a demo go wrong due to what I later realized was a comedic chain of errors.

I had a pre-baked attribute I just needed to add to my project containing my entities. However, I accidentally added it to my web project instead, which references the entities project. I then proceeded to import the namespace for the attribute on a class in the entities project. At least that’s what I thought I was doing, but since my entities project didn’t reference the web project (where I dragged said attribute), I accidentally ran the Generate from Usage command adding a new blank attribute class to the project.

You can probably see the surprise and then concern on my face as my big TADA moment where I show the feature working fails to materialize. ;) At least I was able to recover from this demo failure with the help of the audience. Scott and I had a demo failure where I had the wrong version of an app in our machines so we had to tap dance around that failure.

jQuery and Microsoft

If you missed it, one of the big announcements (at least big to me as an open source guy) was that Microsoft is going to focus on investing in jQuery as our primary technology for client browser scripting. Part of this includes contributing back to jQuery, though any contributions we supply will go through the same approval process as any contribution from any other contributor would. No special treatment as far as I know.

I’m very excited about this as it’s been a long time coming. Stephen Walther has more details on his blog post, Microsoft, jQuery, and Templating.

The Attendee Party

The attendee party this year was held at LAX in the Luxor. It was a nice venue except it didn’t have any sort of outdoor patio you could escape to get a breath of fresh air like there was at TAO.

Even so, we had a great time there and you can see many of the pics from the Mix10 flickr set. Afterwards, several of us went to Pure at Ceasars. When we got there, there was a huge line of beautiful people. However, we were able to go up to the rope, show the stamps from the attendee party, and the bouncers waved us right in. It was the total rockstar treatment, which was a lot of fun. I can only imagine the thoughts going through the heads of all those people waiting in line wondering who the heck are these nerds and why are they getting the VIP treatment? :)

Summary

All in all, it was a great conference. I always manage to have a good time in Las Vegas, even when losing a bit of money at Poker. I met countless people, many with interesting questions on ASP.NET MVC. If I forget your name the next time I see you, I apologize in advance. Don’t be shy in reminding me. :)

asp.net, asp.net mvc, open source, code comments edit

Hot on the heels of the release of ASP.NET MVC 2 yesterday, I’m happy to announce that we are releasing the source code to ASP.NET MVC 2 under theMs-PL license, an OSI approved Open Source license.

This continues the trend from nearly a year ago when we released ASP.NET MVC 1.0 under the Ms-PL. You can read my blog post there to learn more about the hard work that goes into such releases.

While I’m one who loves lawyer jokes, I do appreciate the work that they do (one of my best friends is a lawyer) and am grateful for the hard work our legal team put in to make this happen again.

Get the source!

To grab the source code, visit the ASP.NET MVC 2 RTM Download Details page and look for the file named mvc2-ms-pl.zip.

What’s next?

This time around, we’re not planning to stop with just the source code for System.Web.Mvc.dll. There’s a bit more source I would like to release under the Ms-PL which should hopefully be coming soon if I can get the ducks to line in a row (who knew releasing code required working with ducks?!).