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?!).

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

It’s that time of year again when the sakura (cherry blossoms) bloom and allergies kick into high gear. When the drive home is no longer shrouded in darkness and when the ASP.NET team releases Software!

sakuraEarlier today we released the RTM of ASP.NET MVC 2 for Visual Studio 2008 SP1. See Scott Guthrie’s announcement about it. For download and install options, visit the ASP.NET MVC Download Page.

Here are a few helpful resources to help you learn more about this release.

My team and I are excited about this release as it adds a lot of great new functionality for those building web applications with ASP.NET MVC. As with ASP.NET MVC 1.0, the community (yes, that’s you people!) were heavily involved in the making of this product via multiple preview releases. So thank you!

What about Visual Studio 2010?

Keep in mind that this release includes project templates for Visual Studio 2008. Visual Studio 2010 RTM will be released fairly soon and that will contain project templates and runtime for ASP.NET MVC 2 RTM in the box.

If you have Visual Studio 2010 RC installed, you’ll find that the installer for ASP.NET MVC 2 RTM is blocked just as it was for ASP.NET MVC 2 RC 2.

To remedy the situation, you just need to uninstall the ASP.NET MVC 2 runtime first, and then run the ASP.NET MVC 2 RTM installer.

I’ve outlined the steps in more detail in a previous blog post describing how to install MVC 2 RC 2 on a machine with Visual Studio 2010 RC. These same steps apply, but switch “RC 2” with “RTM” of course. :)

Again, sorry for the inconvenience. Once Visual Studio 2010 RTM ships, this will all just work.

Source Code! Source Code! Source Code!

As always, the source code, along with our Futures library, is available on CodePlex. For those looking for the Ms-PL package, we will be releasing the source code for System.Web.Mvc.dll very soon.

What’s Next?

I’m glad you asked. While we’ve been very busy getting this release ready, preparing for Mix 10, closing down on ASP.NET 4 and Visual Studio 2010, we’ve still found time to start preliminary planning for ASP.NET MVC 3.

It’s very early and nothing is written in stone yet (of course not, it’d be written in C#), but you can read our rough roadmap that outlines some of the ideas we have for the next version.

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

If there’s one impression that Austin left on me, besides the one that Rudy’s “extra moist” barbecue left on my gut, is that it’s a developer friendly town.

This past week I spent three days in Austin meeting with all sorts of developers and had many great conversations about technology. I met with companies and people with a passion for technology that couldn’t be suppressed.

Photo from
http://www.treehugger.com/

Meeting with Dell

The reason I was in town was to give a couple of presentations at a mini-conference for Dell employees. On my first day in Austin, the day before the conference, I met with a team working on the next generation of Dell.com. The site is undergoing a large scale rearchitecture based heavily on ASP.NET MVC 2.

I fielded some questions on ASP.NET MVC and its future and was given a presentation on their new architecture. It was clear that they spent a lot of time with ASP.NET MVC as I even received an obscure question asking why Routing uses the ReaderWriterLock rather than ReaderWriterLockSlim? (The answer, in case you’re interested in that sort of trivia, is that ReaderWriterLockSlim didn’t work in medium trust in ASP.NET 3.5 SP1, but that’s been fixed in ASP.NET 4 and Routing now uses that).

I should mention that Dell is hiring in a big way. Many of these positions will involve a lot of ASP.NET MVC development.

We’re looking for senior level folks that have extensive e-commerce experience, are experts in Microsoft technologies (MVC knowledge a big plus), and have worked on some very large sites.  We’re looking for architects, dev leads, business analysts and project managers.  We have positions open in Round Rock, Tx (just north of Austin) as well as Bangalore, India.  Visit www.dell.com and click on Careers at the bottom of the page.

Austin .NET User group

After meeting with Dell, I was whisked over to the Austin .NET User Group meeting (ADNUG) where I gave a presentation on what’s new in ASP.NET MVC 2. The room was packed and the attendees were engaged with the talk. They had to be as my demos were failing left and right and I needed the help from the audience to catch my mistakes several times. Thank you ADNUG!

Afterwards I went with several user group attendees and was treated to Rudy’s Country Store and Bar-B-Q which is a gas station, convenience store, and Bar-B-Q shack. I would soon learn that Austin is full of these multi-function restaurants. I ordered the “Extra Moist” and some cream corn which was oh so delicious!

Back at Dell

After Rudy’s I spent the evening working on digestion and my demos. The next morning I spent the day at a small conference center presenting two talks to Dell employees, the intro talk I mentioned earlier and an ASP.NET MVC 2 Tips and Tricks talk.

This time, both talks went much more smoothly and I now feel much more prepared for the upcoming Mix 10.

After my talks at Dell, Jonathan Carter and I headed over to the WhipIn to meet up with the quiet and always subdued Scott Bellware. The WhipIn is a convenience store, bar, and Indian food restaurant with a slogan of “Namaste Y’all!”” Remember that thing I said earlier about multi-function restaurants?

Visiting Headspring

My last day in Austin was spent visiting two companies full of very talented software developers doing extensive work with ASP.NET and ASP.NET MVC.

I spent the morning at Headspring which employs many well known members of the .NET community as they’re involved in blogging, C4MVC, MvcContrib, etc. Jeffrey Palermo, Eric Hexter, Jimmy Bogard, Matt Hinze, amongst others (sorry, I don’t know your URLs).

One of the first things I noticed when walking into their office was a big screen TV displaying the statuses of several different builds from their Continuous Integration (CI) server. I watched as a Watin run provided a “ghost in the machine” demonstration of their automated functional test suite.

They walked me through their current project showing how they’re using and customizing ASP.NET MVC and we discussed potential improvements to ASP.NET MVC. One thing they’ve done as they’ve gained experience building ASP.NET MVC applications is to embed many of the lessons they’ve learned into the open source CodeCampServer project.

It may be overkill for what it is, a code camp management website, but the point of the site is to demonstrate practices they use on much larger projects.

Visiting Dovetail

After meeting with Headspring, I headed over to meet the DoveTail guys for lunch. Unfortunately, we didn’t go to Torchy’s since we were short on time and didn’t want to wait. Not only that, I had a sangria margarita for lunch and was carded. Those Austin-ites are sticklers for checking IDs.

We spent lunch discussing a wide range of topics on the .NET community, technology, etc. After lunch we headed over to their office where once again I saw a monitor with the status of their continuous integration server displayed on a monitor. Seems all these Austin developers see the value in continuous integration.

We settled in and Jeremy Miller, Chad Myers, Joshua Flanagan, et all walked me through what they’ve done with FubuMVC. I really liked several of the ideas they’ve put in their framework, some of which may show up in ASP.NET MVC in the future as is typical of technical cross-pollination.

Heading Home

After the meeting at Dovetail, I took a cab to the Austin airport to catch a flight home. Looking back, I wished I had been able to spend more time in Austin. Known as the live music capital of the world, I didn’t get a chance to hit the heart of the city.

Even so, I really enjoyed my visit there. The weather was nice and the local tech community seemed to be quite involved and vibrant. It’s definitely a place I want to visit again.

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

During the MVP summit, an attendee asked me for some help with a common scenario common among those building content management systems. He wanted his site to use human friendly URLs.

  http://example.com/pages/a-page-about-nothing/

instead of

  http://example.com/pages/123/

Notice how the first URL is descriptive whereas the second is not. The first URL contains a URL “slug” while the second one contains the ID for the content, typically associated with the ID in the database.

This is easy enough to set up with routing, but there’s a slight twist. He still wanted the action method which would respond to the first URL to have the integer integer ID as the parameter, not the slug. Let’s look at one possible approach to solving this.

Here’s an example of what the route might look like:

routes.MapRoute(
  "Slug", // Route name
  "pages/{slug}", // URL with parameters
  new { controller = "Home", action = "Content" } // Parameter defaults
);

Notice that the route URL contains one parameter for “slug” and no “id” parameter whatsoever. Here’s an example of the controller action that route should map to.

public ActionResult Content(int id)
{
  // Note the argument is an id, not slug
  return View();
}

Note that the action method does not accept a parameter named “slug” but instead expects an integer “id” parameter.

Fortunately, there’s an easy way to do this. Action filters, classes which derive from ActionFilterAttribute, allow hooking into the point in time after the parameters of action method have been bound, but just before the action method has been invoked. This gives us a fine opportunity to muck around with the parameters.

The following is an example of an action filter which converts a slug to an ID (you can imagine a real one would probably look it up in the database, not in a static dictionary like the sample does).

public class SlugToIdAttribute : ActionFilterAttribute
{
  static IDictionary<string, int> Slugs = new Dictionary<string, int>
  {
    {"this-is-a-slug", 100}, 
    {"another-slug", 101}, 
    {"and-another", 102}
  };

  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    var slug = filterContext.RouteData.Values["slug"] as string;
    if(slug != null)
    {
      int id;
      Slugs.TryGetValue(slug, out id);
      filterContext.ActionParameters["id"] = id;
    }
    base.OnActionExecuting(filterContext);
  }
}

The filter overrides the OnActionExecuting method which is called just before the action method is called. The filter than grabs the slug from the route data, and looks up the corresponding id. Now all we need to do is make sure the id is passed into the action method.

Fortunately the filter context passed into this method allows us to peek into the parameters that will get passed into the action method via the ActionParameters property. Not only that, it allows us to change them!

In this case, I’m grabbing the slug from the route data, and looking up the associated id, and adding a parameter named “id” to the action parameters with the correct id value.

All I need to do now is apply this filter to the action method and when the action method is called, this id will be passed into the method.

This works whether the argument to the action method is a simple primitive type as in this example or whether it’s a complex type. I’ve included a sample project that demonstrates changing parameters to action methods via an action filter.

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

If you have a model object with a property named Id, you may have run into an issue where your model state is invalid when binding to that model even though you don’t have an “Id” field in your form.

The following scenario should clear up what I mean. Suppose you have the following simple model with two properties.

public class Product {
    public int Id { get; set; }
    public string Name { get; set; }
}

And you are creating a view to create a new Product. In such a view, you obviously don’t want the user to specify the Id.

<% using (Html.BeginForm()) {%>

  <fieldset>
    <legend>Fields</legend>
        
        
    <div class="editor-label">
      <%= Html.LabelFor(model => model.Name) %>
    </div>
    <div class="editor-field">
      <%= Html.TextBoxFor(model => model.Name) %>
      <%= Html.ValidationMessageFor(model => model.Name) %>
    </div>
       
    <p>
      <input type="submit" value="Create" />
    </p>
  </fieldset>

<% } %>

However, when you post it to an action method like so:

[HttpPost]
public ActionResult Index(Product p)
{
    if (!ModelState.IsValid) {
        throw new InvalidOperationException("Modelstate not valid");
    }
    return View();
}

You’ll find that the model state is not valid. What gives!?

Well the issue here is that the Id property of Product is being set to an empty string. Why is that happening when there is no “Id” field in your form? The answer to that, my friend, is routing.

When you crack open a freshly created ASP.NET MVC 1.0 application, you’ll notice the following default route defined.

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

To refresh your memory, that’s a route with three URL parameters (controller, action, id), each with a default value (“home”, “index”, “”).

What this means is if you post a form to the URL /Home/Index, without specifying an “ID” in the URL, you’ll still have an empty string route value for the key “id”. And as it turns out, we use route values to bind to action method parameters.

In the scenario above, it just so happens that your model object happens to have a property with the same name, “Id”, as that route value, so the model binder attempts to set the value of the Id property to empty string, and since Id is a non-nullable int, we get a type conversion error.

This wouldn’t be so bad if “Id” wasn’t such a common name for properties. ;)

In ASP.NET MVC 2 RC 2, we added an MVC specific means to work around this issue via the new UrlParameter.Optional value. If you set the default value for a URL parameter to this special value, MVC makes sure to remove that key from the route value dictionary so that it doesn’t exist.

Thus the fix to the above scenario is to change the default route to:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

With this in place, if there’s no ID in the URL, there won’t be a value for ID in the route values and thus we’ll never try to set a property named “Id” unless you have a form field named “Id”.

Note that this should be the default in the project templates for ASP.NET MVC 2 RTM.

comments edit

As many of you have probably heard, the release candidate for Visual Studio 2010 was recently released containing immense performance improvements and tons of bug fixes.

Another thing that release contains is the release candidate for ASP.NET MVC 2. However, that release is not the latest release of ASP.NET MVC 2 as we recently released a second release candidate for ASP.NET MVC 2 in response to customer feedback.

I apologize for the confusion this may have caused, but we really felt it was important to have another release candidate for ASP.NET MVC to help verify that we were responding to feedback in the correct manner.

If you wish to have Visual Studio 2010 RC and ASP.NET MVC 2 RC 2 installed at the same time, it’s not a problem.

If you installed ASP.NET MVC 2 RC 2 Before installing VS 2010 RC

Believe it or not, you’re all set if you install them in this order.

When installing VS 2010 RC, the installation will detect that a newer version of the ASP.NET MVC runtime (aka the System.Web.Mvc assembly) is already installed and will not overwrite it with the older version included with VS 2010 RC.

Keep in mind that the project templates for VS 2010 will still be the slightly older ASP.NET MVC 2 RC project templates and not the RC 2 templates. Fortunately those templates haven’t changed too much between release candidates.

In this configuration, when you create a project using VS 2010 RC, even though the templates may be slightly older, the project will reference the newer System.Web.Mvc assembly.

If you are installing ASP.NET MVC 2 RC 2 After installing VS 2010 RC

In this case, there’s a tiny bit of work to do. The installer for ASP.NET MVC 2 RC 2 will block if an older version of the ASP.NET MVC 2 runtime is installed.

To remedy the situation, all you need to do is uninstall the ASP.NET MVC 2 runtime. In Add/Remove Programs dialog(also known as the Program and features dialog), this would be the entry named “Microsoft ASP.NET MVC 2”.

If you have an older version of MVC tooling/project templates for Visual Studio 2008 installed (named “Microsoft ASP.NET MVC 2 – Visual Studio 2008 Tools”), you’ll also need to uninstall that, but do not uninstall the MVC tooling for VS 2010.

add-remove-dialog 

At this point, you should only have Microsoft ASP.NET MVC 2 – Visual Studio Tools for VS 2010 installed. You may now run the installer for ASP.NET MVC 2 RC 2, which will put the runtime on your machine as well as tooling/project templates for VS 2008.

Hopefully this clears up some of the confusion and gets you going with VS 2010 RC and ASP.NET MVC 2 RC 2.

personal, code comments edit

UPDATE: We moved the date to February 24th.

The stars at night, are big and bright – clap clap clap clap – deep in the heart of Texas!

Hold onto your ten gallon hats, I’m visiting Texas for the first time! I’m very excited to visit the second largest state in the union. ;)

austin The purpose of my trip is to meet with some developers at Dell doing interesting things and to give a talk there as well.

But since I’ve heard such good things about the vibrant tech community in Austin, I am trying to make the most of my short trip. On Wednesday, February 24, I’ll be speaking at Austin .NET User Group meeting at 7:00 PM CSTat the Microsoft offices in Austin.So be sure to come by and say hello.

We moved it to the 24th so if you were planning on attending Martin Fowler’s talk on February 25th, you can see both! Unfortunately for me, I was hoping to see Martin speak, but I saw that they’ve closed registration.

I’m also going to visit my good friends at Headspring as well as Dovetail Software to jabber about technology and see what cool things they’re doing with ASP.NET and ASP.NET MVC.

And of course, a trip to Austin wouldn’t be complete without a night out on the town with Bellware. I expect chaos. ;)

Tags: austin, texas, .net user group

asp.net comments edit

The ASP.NET Team is still looking for that QA person out there who shares our passion for technology and improving the means by which software is made.

Keep in mind that the QA position on our team is not someone who mindlessly follows a script hoping by sheer random luck to find bugs. Oh no no no my friends.

This is considered a software development position in which you will be responsible for improving the processes and tools we have in place for ensuring quality software. You’d be involved in improving the quality of all phases of product development as a valued member of a feature crew. Think broadly about the idea of software quality. Your role is to question whether we’re building the right product as much as it is to test the product once it is built.

Matt Osborn, a member of the ASP.NET MVC feature crew has a description of the position.

That’s right you read the title right the ASP.NET QA team is once again hosting ninja try outs. We are looking for someone who is able to help evolve the team processes, improve our tooling, and join us in the trenches as we test one of the best technologies out there. Overall the team is responsible for ASP.NET WebForms, ASP.NET MVC, Microsoft AJAX, and a whole slew of other technologies. Our technologies can be found in numerous large scale web sites such as MySpace.com, Dell.com andDeals.Woot.com.

Once again we would like to find someone that shares our passion for our technology and our trade and someone that has spent sometime in the trenches. So if this sounds like something you’re interested in polish your nun chucks, practice your disappearing skills, and slice your way through our job posting. In the meantime while your sword is out for sharpening send Mark Berryman (one of our managers) an email.

PS: If you listen to the Coding QA podcast you can get a good feel for what it is like being the frontline testing ninjas for ASP.NET. We had a great turn out last time and please feel free submit your resume again it can’t hurt.

Keep in mind we’re not looking for “test” ninjas as in “sample” ninjas. We’re looking for the real deal, brimming with throwing stars of bug finding. Ok, the analogy breaks down a bit there. But you get the picture.

And before I forget, here’s the direct link to the job description on the Microsoft careers site.

subtext, code comments edit

This blog is experiencing technical difficulties. Do not adjust your browser.

Hi there. If you’ve tried to visit this blog recently you might have noticed it’s been down a lot in the last two days. My apologies for that, but hopefully you found what you needed via various online web caches.

I’ve been dogfooding the latest version of Subtext and as CodingHorror points out, dogfood tastes bad.

I’ve done a lot of testing on my local box, but there are a class of bugs that I’m only going to find on a high traffic real site, and boy have I found them!

Some of them might be peculiar to my specific data or environment, but others were due to assumptions I made that were wrong. For example, if you use ThreadPool.QueueUserWorkItem to launch a task, and that task throws an unhandled exception, that can bring your entire App Domain down. Keep that in mind if you think to use that method for a fire-and-forget style task.

In any case, the point of this post is to say that we’re not going to release the next version of Subtext until it’s rock solid. My blog going down occasionally is the cost I’m incurring in order to make sure the next version of Subtext is a beast that won’t quit.