MVC: Unit testing controller actions that use TempData

Part of the "big deal" about ASP.NET MVC, and of course MVC in general, is that the code you write is more easily unit tested as compared to traditional ASP.NET WebForms. However, if you've used ASP.NET MVC and tried to write a unit test for a controller action that uses TempData, you probably got some exceptions about null references and other crazy stuff. I've seen a number of solutions out there that involve private reflection (which is kind of evil) so I figured I'd show how it can be done without that trickery. (Kudos, though, to those of you who figured out how to do such trickery!)

The underlying problem is that the TempDataDictionary object tries to read from session state when it's first used. At unit test time ASP.NET is not running so there isn't any session state. The solution is to provide a mock session state object to the TempDataDictionary. We're basically telling TempDataDictionary, "Hey you want some session state??? Here's your session state!!!"

The controller we're going to test has two actions. The first action adds a value to TempData and then does a redirect. The second action checks for the existence of the value in TempData and renders a view.

public class HomeController : Controller {
    public void Index() {
        // Save UserID into TempData and redirect to greeting page
        TempData["UserID"] = "user123";
        RedirectToAction("GreetUser");
    }

    public void GreetUser() {
        // Check that the UserID is present. If it's not
        // there, redirect to error page. If it is, show
        // the greet user view.
        if (!TempData.ContainsKey("UserID")) {
            RedirectToAction("ErrorPage");
            return;
        }
        ViewData["NewUserID"] = TempData["UserID"];
        RenderView("GreetUser");
    }
}

In order to write the unit tests I created a mock HttpContext with a mock session state object:

// HttpContext for TempData that uses a custom
// session object.
public class TestTempDataHttpContext : HttpContextBase {
    private TestTempDataHttpSessionState _sessionState =
        new TestTempDataHttpSessionState();

    public override HttpSessionStateBase Session {
        get {
            return _sessionState;
        }
    }
}

// HttpSessionState for TempData that uses a custom
// session object.
public class TestTempDataHttpSessionState : HttpSessionStateBase {
    // This string is "borrowed" from the ASP.NET MVC source code
    private string TempDataSessionStateKey = "__ControllerTempData";
    private object _tempDataObject;

    public override object this[string name] {
        get {
            Assert.AreEqual<string>(
                TempDataSessionStateKey,
                name,
                "Wrong session key used");
            return _tempDataObject;
        }
        set {
            Assert.AreEqual<string>(
                TempDataSessionStateKey,
                name,
                "Wrong session key used");
            _tempDataObject = value;
        }
    }
}
Each unit test that involves an action that uses TempData needs to create a custom TestTempDataHttpContext object and use that in a new instance of TempDataDictionary:
TestTempDataHttpContext tempDataHttpContext = new TestTempDataHttpContext();
homeController.TempData = new TempDataDictionary(tempDataHttpContext);

I wrote three unit tests for HomeController:

  1. Test that the Index action sets the right TempData and does a redirect
  2. Test that the GreetUser action redirects when the TempData is missing the value
  3. Test that the GreetUser action renders the GreetUser view with the right ViewData when the TempData has the right value

And here are the unit tests:

[TestClass]
public class HomeControllerTest {
    [TestMethod]
    public void IndexSavesUserIDToTempDataAndRedirects() {
        // Setup
        TestHomeController homeController = new TestHomeController();
        TestTempDataHttpContext tempDataHttpContext = new TestTempDataHttpContext();
        homeController.TempData = new TempDataDictionary(tempDataHttpContext);

        // Execute
        homeController.Index();

        // Verify
        Assert.IsTrue(homeController.RedirectValues.ContainsKey("action"));
        Assert.AreEqual("GreetUser", homeController.RedirectValues["action"]);

        Assert.IsTrue(homeController.TempData.ContainsKey("UserID"));
        Assert.AreEqual("user123", homeController.TempData["UserID"]);
    }

    [TestMethod]
    public void GreetUserWithNoUserIDRedirects() {
        // Setup
        TestHomeController homeController = new TestHomeController();
        TestTempDataHttpContext tempDataHttpContext = new TestTempDataHttpContext();
        homeController.TempData = new TempDataDictionary(tempDataHttpContext);

        // Execute
        homeController.GreetUser();

        // Verify
        Assert.IsTrue(homeController.RedirectValues.ContainsKey("action"));
        Assert.AreEqual("ErrorPage", homeController.RedirectValues["action"]);

        Assert.AreEqual(0, homeController.TempData.Count);
    }

    [TestMethod]
    public void GreetUserWithUserIDCopiesToViewDataAndRenders() {
        // Setup
        TestHomeController homeController = new TestHomeController();
        TestTempDataHttpContext tempDataHttpContext = new TestTempDataHttpContext();
        homeController.TempData = new TempDataDictionary(tempDataHttpContext);
        homeController.TempData["UserID"] = "TestUserID";

        // Execute
        homeController.GreetUser();

        // Verify
        Assert.AreEqual<string>("GreetUser", homeController.RenderViewName);
        Assert.AreEqual<string>(String.Empty, homeController.RenderMasterName);
        IDictionary<string, object> viewData =
            homeController.RenderViewData as IDictionary<string, object>;
        Assert.IsNotNull(viewData);
        Assert.IsTrue(viewData.ContainsKey("NewUserID"));
        Assert.AreEqual("TestUserID", viewData["NewUserID"]);
    }

    // Test-specific subclass for HomeController. This won't be
    // needed in the next release of ASP.NET MVC.
    private sealed class TestHomeController : HomeController {
        public RouteValueDictionary RedirectValues;
        public string RenderViewName;
        public string RenderMasterName;
        public object RenderViewData;

        protected override void RedirectToAction(RouteValueDictionary values) {
            RedirectValues = values;
        }

        protected override void RenderView(string viewName, string masterName,
            object viewData) {
            RenderViewName = viewName;
            RenderMasterName = masterName;
            RenderViewData = viewData;
        }
    }
}

Some notes about the code:

  • For the unit tests I also needed to create a test-specific subclass for HomeController called TestHomeController in order to capture the values of a call to RedirectToAction and RenderView. In the upcoming preview of ASP.NET MVC this class won't be needed due to some changes we've made.
  • Making TempData easier to unit test is on our list of improvements for a later preview of ASP.NET MVC. We realize it's a bit tricky right now, and we plan to make it much, much easier.
  • Instead of creating concrete classes for the custom HttpContext and session state objects you could use a mock object framework to dynamically generate those instances. I chose not to show that since it might detract from the purpose of the post. If you're already using a mock object framework such as RhinoMocks or Moq it should be easy to modify the code to use those frameworks.

I hope you find this sample useful when you're writing your unit tests. If you have any other pain points in ASP.NET MVC please post a comment so we'll know about it.

Posted by Eilon with 7 comment(s)
Filed under: , , ,

MVC: Locking the RouteCollection

Since the advent of multithreaded programming, the responsibility of locking collections has always been a contentious issue. Who should lock the collection? When should it be locked? And for how long? The ASP.NET Routing feature that is used by the MVC framework involves a thread-safe collection that contains the list of the application's route definitions. Will your routes be safe? Continue reading to find out (on this amazing journey (into the depths of the RouteCollection)). How's that for a cheesy intro?

The problem

When the first preview of ASP.NET MVC was released last December, some people noted that the RouteCollection would lock itself during all read and write operations, which could cause major performance and scaling issues. Well, sort of. The RouteCollection class derives from the generic Collection<T>, which has a few virtual methods it calls when write operations are performed. Each of those methods was overridden in RouteCollection to take a full lock. The route operations of matching routes to incoming requests and generating URLs also took the same full lock. There were two problems (at least) with this approach:

  1. Taking a full lock means that if anyone is using the collection, any other operation on that collection would have to wait for the first one to be done. Even if two requests just wanted to enumerate the collection (a read-only operation), one request would have to wait. This wasn't a logic bug since it wouldn't prevent anything from working; It was just a performance issue. There was in fact a comment in the code along the lines of "TODO: Shouldn't we use a ReaderWriterLockSlim here or something?"
  2. We weren't locking enough! If someone directly enumerated the collection by calling GetEnumerator (which happens implicitly when you use C# or VB's foreach statement), no lock would be taken. Unfortunately, Collection<T> does not offer any virtual methods that get called during read operations.

The solution (or so we thought)

We knew we had to do something for ASP.NET MVC Preview 2: We had performance problems as well as bugs in our collection locking. The first thing we did was change the lock to be a multiple-reader, single-writer lock with the ReaderWriterLockSlim class. Using this class in the RouteCollection allows any number of readers to read the collection at the same time but will fully lock the collection when a write is performed and allow only that one writer to make changes until the write lock is released.

Before we knew it, though, a bug was found while running some performance tests. When there is contention for the lock, the ReaderWriterLockSlim needs to get the processor count of the server. For some reason or another, getting that count is not permitted in Medium Trust web applications and thus throws a SecurityException. We didn't notice this while we were writing unit tests and web tests because all those tests are single threaded: there is never any contention for the lock.

The final solution

We opened a work item for the owners of Environment.ProcessorCount to remove the security requirement since knowing the processor count of the host is hardly top secret information. However, since the ASP.NET Routing feature works on .NET Framework 3.5, bug fixes in a future version wouldn't be sufficient. Thus we changed RouteCollection to use ReaderWriterLock, which is slightly less performant, but works in all web trust levels.

So we solved the problem of when the collection gets locked and for how long. But what about the very first issue I mentioned: Who should lock the collection?

Our first solution was to do all the locking internally. Any time you called any member on the collection we'd take the appropriate lock. This meant implementing IList<T> directly since neither Collection<T> nor List<T> provide the necessary hooks. This proved to be a lot of work (but not for me, since I didn't have to write it smile_regular) and left some big holes of functionality. For example, how could someone atomically search for a route in the collection, remove it, and add a new route?

The solution to that problem was to expose the lock semantics publicly, though without exposing the lock object itself. Thus the RouteCollection has two new methods: GetReadLock and GetWriteLock. Developers can call those methods to get the lock that the RouteCollection uses internally and cooperate with its locking mechanism. However, you only need to get the lock if you're directly accessing the collection. If you're going through any of the typical "end-user" API calls, we do the locking automatically. For example, calling Html.ActionLink, Url.Action, and RouteCollection.GetVirtualPath will automatically lock the collection.

In case you're wondering, there were several reasons we chose not to expose the lock object itself:

  1. We wanted to be able to change the lock implementation at any time. This would let us switch back to ReaderWriterLockSlim at some point in the future.
  2. It seemed simpler for users to have a limited API surface. Less is More.
  3. It encourages users to use the dispose pattern with the lock they get, thus ensuring that the lock is released even if an exception is thrown and not caught while the lock is being held.

Why you should care

There are two takeaways I hope I provided in this article:

The first takeaway is that if you're implementing a thread-safe collection you have some food for thought. I hope the food was easy to digest!

The second takeaway is that if you're directly accessing the RouteCollection in an ASP.NET application, make sure you take the lock first! Taking the lock is easy with the dispose pattern:

RouteCollection routes = RouteTable.Routes;
using (routes.GetReadLock()) {
    foreach (RouteBase route in routes) {
        // Do something interesting here and be guaranteed that no one is modifying the collection
    }
}
// The lock is now released since we exited the "using" statement.

Who would have thought that a simple collection of routes would turn out to be so much fun? Did you ever start coding something that seemed simple and ended up writing a long blog post about it?

Posted by Eilon with 9 comment(s)
Filed under: , ,

MVC: I'll need a little bit more context on that

ScottGu recently announced the plans for the next public preview of the ASP.NET MVC framework. For those who don't feel like clicking on links to other peoples' blog posts Scott's blog says it's being released at MIX08, which is only a couple of weeks away. And yes, I will be there!

My previous blog post talked in general about the design philosophy of the ASP.NET MVC framework. Today I'd like to talk specifically about context objects, how we use them in ASP.NET MVC, and why we like them. In the coming release of MVC there will be about seven context types throughout ASP.NET, URL routing, and MVC.

What is a Context Object?

A context object is exactly that: An object that gives another object some information about what's going on. Information such as what is the current request, what task is being performed, and sometimes even the ability the change what's going on.

Context in MVC

One context object many ASP.NET developers are already familiar with is HttpContext. HttpContext gives you everything you need to know about the current request, who's making that request, and how to respond to the request. Of course, in MVC we decoupled the MVC framework from the test-unfriendly HttpContext by introducing an IHttpContext interface (which, by the way, is now an HttpContextBase abstract base class for future-proofing purposes).

However, as the request gets processed we create and gather up additional information about what's going on. The first context we add is at the routing level: the RequestContext type. It adds just one piece of information, the RouteData, as well as including all previous context information, which is just the HttpContextBase.

Once a route is selected and we determine that it is an MVC request, we're off to the controller. This is where the ControllerContext comes in to the picture. ControllerContext derives from RequestContext and adds the controller instance to it. We then have a ViewContext type, which adds information about the selected view, its view data, and some other items.

One of the new features in the upcoming preview is action filters, and sure enough there are three filter context types as well.

Since the context types derive from one another (except for HttpContextBase), you can often pass in whatever context type you have to call some method from a lower level. For example, in the view you get a ViewContext that you can pass into the URL routing methods.

What Can Context Do For You?

By passing around context objects we have no need for global state. Global state would be something like a static property or field that everyone can get to. One of the typical requirements of a unit test is that during their execution they do not consume global state nor do they alter global state. We give you the context object and it has everything you need to know. How do I know that it's everything you need to know? Quite simply, the context object is all we know anyway, so we're just letting you know about it as well.

Since your code now makes its decisions and operates on a passed-in context object, your unit tests can produce fake contexts and pass those in to your methods to see how the code reacts to them. You no longer have to worry about your code depending on global state since there simply isn't any (at least none that we create).

Have I given you enough context on what we're doing?

Posted by Eilon with 3 comment(s)
Filed under: , , ,

ASP.NET MVC Design Philosophy

This week the first preview of the ASP.NET MVC framework was released to the web as part of the ASP.NET 3.5 Extensions CTP Preview. It's been a few months since we started coding and as the lead developer on the project I'd like to share my thoughts on the design of this framework. This isn't a post about why MVC is great. Instead, it's a post about what we did to make MVC happen in ASP.NET.

The MVC Snake

One of the design strategies we used in the MVC framework is to have a clear sequence of stages in each request. The stages are reminiscent of the ASP.NET Page and Controls lifecycle, but much, much simpler. Here's a rough diagram of the stages from the slides that Scott Hanselman and I showed at the DevConnections conference.

MVC_Snake

When a request comes in, it goes through the stages as shown in the diagram. There are a few more stages than are shown, but they were removed so the "MVC Snake" diagram wouldn't get too cluttered. An important aspect of this diagram is that each stage only depends on the previous stages. A given stage typically doesn't make any assumptions about what follows it.

For example, the IController interface doesn't assume anything about views or any particular view factory implementation. However, views can assume that an IController was involved in their creation. The implication of this is that you can stray from our path at almost any stage and still end up with success. Want to implement a controller in some new, unique way? Go ahead!

URL Routing - Not part of MVC

Part of the MVC framework is a new URL routing mechanism. This allows you to create "friendly" and "pretty" URLs such as "http://example.org/store/categories" that map to arbitrary controller actions. There's no reason that the URL should specify a physical resource. The visitors to your site surely don't care how you architected your web site or web application.

If you've downloaded the CTP you'll notice that the URL Routing types sit in the System.Web.Mvc namespace. However, the URL Routing types aren't even a part of the MVC framework. URL Routing works with arbitrary IHttpHandlers so it can serve up arbitrary requests - not just MVC requests. For the current CTP because we just couldn't find a better place so we left the types in that namespace.

New Language Features

We're technology addicts, and it shows. The latest version of the C# language includes several new features and we decided to take advantage of them in the MVC framework. We used anonymous types in place of dictionaries, extension methods for helper methods, and lambda expressions as strongly-typed URLs.

But - and there is almost always a "but" - we went a bit too far in the current CTP. We've heard from many of you already that using anonymous types as dictionaries is cool, but hard to understand. And it doesn't have Intellisense. For the next release we're still planning on keeping those features, but we want to add more familiar ways of doing the same things. For example, we're going to let you use dictionaries when we want dictionaries. It seems obvious now. :)

Extensible, Extensible, Extensible

To build a framework that was extensible, testable, and functional, we had many important design decisions to make.

Perhaps most importantly, we went with an interface-based design. We didn't use interfaces for everything, but we did for most things. Typically we used interfaces for all behavioral types, and classes for data objects. The reason is that behavior needs to be mocked, whereas data is just data. Your data objects would probably look exactly the same as our implementations anyway, so we didn't want to bother with interfaces. There are always exceptions, and in the first CTP we may have made some decisions that don't agree with this, but we already have plans to address these for the next CTP.

Traditionally in ASP.NET, a lot of extensibility is enabled by inheriting from our classes and overriding virtual members. While it is a valid approach, it requires that you inherit from our components even if you just want to tweak one small behavior. In the MVC framework we still have many instances of that, but we also allow you to extend our functionality using composition. For example, to modify the behavior of a controller you can either derive from it or you can use a filter to externally change its behavior. The same exception I mentioned in the previous paragraph applies here.

Composition often yields better separation of concerns and allows you to more easily build cross-cutting concerns. For example, if you want to apply the same "behavior modification" to several different controller classes, you don't have to override the same virtual members in each one. You can just apply an external cross-cutting concern to the controllers you want. Thus, composition is more easily used with dependency injection frameworks.

What Does All This Lead To?

Well, what does this all lead to? Several things, of course. For example, each of the components in the MVC framework is fairly small and self contained, with single responsibilities. This means that due to their small size you have building blocks that are easier to understand. It also means that you can replace or even alter the building blocks if they don't suit your needs.

Having great amounts of extensibility means you can write unit tests for your application more easily. I remember the days when I didn't write unit tests. Dark days, they were.

But who is going to use the MVC framework? Not everyone wants to write unit tests or alter so-called building blocks. Being able to drag & drop a GridView and a SqlDataSource onto a WebForm is a valid scenario and it will continue to work. We're trying to create a better fit for ASP.NET for certain types of individuals.

Anecdotes and Miscellany

And to end with some fun facts and stories, the following is all true.

  • For the released CTP, the unit test code coverage numbers were about 93%, far more than any other major feature area. This does not include the code coverage by our QA guys, which I'm sure would bring the number up to at least 99%.
  • We had about 250 unit tests for MVC, and the ratio of unit test code to product code is about 1.9 to 1 (in terms of the size of the code files, not lines of code; I'm too lazy to do the latter!).
  • It feels good to unit test! I can't go back to the old ways.
  • Some of the code is written using true TDD, but some is code-first, but it is then quickly followed up with unit tests (prior to checking in).
  • Several weeks ago we invited several customers for a top secret sneak preview of the CTP, including the MVC framework. Jeffrey Palermo was attending and trying to build some samples with the MVC framework. Sure enough, he encountered some bugs in the product. The bits were still hot off the press and some of the bits hadn't quite settled in the right place. Millions of ones and zeros - what are the odds they'd all line up correctly on the first try? Anyway, I sat with Jeffrey for about half an hour and we managed to use many of the extensibility points in the framework to work around the bugs he encountered. The whole time I kept thinking (and probably saying aloud) that I was so glad I made those methods public or virtual or whatever! Without them Jeffrey would have been stuck.
  • The moral of the story: If you aren't sure, make it public. If we have to use a method, chances are, someone else does too.

MVC Resources

Downloads:

Documentation and discussion forums:

Blog posts and videos by team members:

Posted by Eilon with 36 comment(s)
Filed under: , , ,

How to Allow Generic Controls in ASP.NET Pages

Did you ever want to have a Repeater<Customer> control on your page? And its events were all strongly typed to recognize that each row was bound to a Customer object? Well, I came up with a way of doing it using some lesser known features of ASP.NET.

Today it's possible to use generic controls in ASP.NET, but you can't directly have a generic control in the tag markup. You'd typically have to do some trick such as deriving a concrete type from the generic type or instantiating the control from code-behind and adding it to a placeholder on the page.

My solution involves using a ControlBuilder to alter how the ASP.NET tag gets parsed. Typically ASP.NET parses a tag such as <cc:GenericControl runat="server" /> and instantiated a type called GenericControl in the mapped "cc" namespace. My ControlBuilder overrides that behavior by returning an instance of GenericControl<TDataItem> whenever that tag is encountered.

Here's an outline of my sample control:

namespace GenericControls {
    public class GenericControl<TDataItem> : Control where TDataItem : new() {
        public event EventHandler<GenericEventArgs<TDataItem>> Stuffing {
            add;
            remove;
        }
    }
}

Note that the control itself is generic over TDataItem, and that is exposes an event called "Stuffing" that uses a generic EventHandler with generic EventArgs also bound to TDataItem. So, if you have an instance of the GenericControl<Customer>, the event handler should take event arguments of type EventArgs<Customer>. Now you don't have to cast your event arguments to get to your data object!

To use the control you specify the generic argument in the form of a pseudo-property on the control tag itself called ObjectType:

        <gc:GenericControlGeneric runat="server" ID="CustomerGeneric"
            ObjectType="MyStuff.Customer, App_Code"
            OnStuffing="CustomerGeneric_Stuffing">
        </gc:GenericControlGeneric>

Yes, my naming convention is horrible. Unless you thing GenericControlGeneric sounds good. But it doesn't sound good; it's horrible! :)

And before anyone asks, the topic of generic syntax in tags has been discussed at length, so I won't repeat that here.

In summary, I encourage you to check it out and see if it helps solve any problems you've had, hopefully without creating any new problems. This was just a pet project I did to see whether it was possible to create generic controls in markup.

And finally, a caveat:

While this seems to work great at runtime, I've encountered some weird problems in Visual Studio to support this. For example, when you try to add an event handler for the Stuffing event through the property grid you might get some weird behavior.

Download the project source code here: GenericControl.zip

Posted by Eilon with 15 comment(s)
Filed under: , ,

DevConnections/ASPConnections Slides and Code

As a follow up to my previous post, here are links to Scott Hanselman's posts:

As Scott notes, you won't be able to run the demo code and you won't be able to compile it either since the ASP.NET MVC framework is not yet available.

I'd like to thank everyone who came to our talks and also those of you who stopped by afterwards to chat with us! And also those few of you who stopped by for photo opportunities :)

Posted by Eilon with 1 comment(s)
Filed under: ,

DevConnections/ASPConnections 2007 in Vegas

Next month I'll be co-speaking with Scott Hanselman at Microsoft ASP.NET Connections in Las Vegas. Completely stealing from ScottHa's post, this is the schedule for Tuesday, November 6:

(Highlighted talks are the ones Scott and I are doing.)

Time Room 1 Room 2
10:30 - 11:30 AMS307: Building a Real World Web Application with Visual Studio 2008 and the .NET Framework v3.5, Part I of 3 AMS302: Silverlight for ASP.NET Developers
11:45 - 12:45 AMS308: Building a Real World Web Application with Visual Studio 2008 and the .NET Framework v3.5, Part 2 of 3 AMS306: Developing Data Driven Applications Using ASP.NET Dynamic Data
2:30 - 3:30 AMS303: Internet Information Services 7 for ASP.NET Developers AMS304: Introduction to the new ASP.NET Model View Controller (MVC) Framework
4:14 - 5:15 AMS301: Building a Real World Web Application with Visual Studio 2008 and the .NET Framework v3.5, Part 3 of 3 AMS305: Displaying Data with the new ListView and DataPager Controls in the .NET Framework 3.5

I hope to see you in Vegas, though I'll only be there a couple of days. If you see me feel free to ask me any questions about MVC in ASP.NET!

(I really think the 4:14 start time is a mistake. But it does look nice next to the 5:15 end time!)

Posted by Eilon with 7 comment(s)
Filed under: ,

Using C# 3.0 Anonymous Types as Dictionaries

During a design meeting for a new feature in ASP.NET we had a requirement that a new method accept a dictionary of name/values pairs. An obvious solution is to have the method accept a parameter of type IDictionary (or its generic cousin):

public static string GetHtmlLink(string text, IDictionary<string, string> properties) {
...
}

While it looks nice and neat from the perspective of our function, the caller of this function has a real mess to deal with. Creating dictionaries is definitely somewhat of a pain. Since Dictionary<TKey, TValue> doesn't have an Add() method with one parameter you can't use C# 3.0's collection initializer syntax. This is some ugly code:

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
values.Add("key3", "value3");
GetHtmlLink("Click me", values);

My proposal: Have the method accept a parameter of type object. Callers could pass in a type that has properties with the appropriate names and values. They can use C#'s object initializer syntax to save some space:

MyParams myParams = new MyParams { Key1 = "value1", Key2 = "value2", Key3 = "value3" };
GetHtmlLink("Click me", myParams);

However, there was the added work of defining the MyParams type. Admittedly, it wasn't that hard with C# 3.0's automatic properties, but I hate defining types that are used in only one place. If the user can pass in an arbitrary object with properties, why not let that object be of an anonymous type? Here's the final code:

GetHtmlLink("Click me", new { Key1 = "value1", Key2 = "value2", Key3 = "value3" });

Woah! We went from five lines of code with dictionaries to two lines of code with object initializers (minus the type definition), to just one line of code with anonymous types!

So what does the GetHtmlLink method look like, anyway? Download the code from the attachment. You can now use the two helpers like so:

Sample link: <%= HtmlHelpers.GetHtmlLink("My Site", new { @class = "someStyle", href = "http://www.example.org" })%>
<br />
Sample URL: <%= HtmlHelpers.GetUrl("http://www.example.org/search", new { query = "kitten's mittens", mode = "details" })%>

And it'll render this HTML:

Sample link: <a class="someStyle" href="http://www.example.org">My Site</a>
<br />
Sample URL: http://www.example.org/search?query=kitten's+mittens&mode=details

So, what do you think?

I'm obviously ignoring certain aspects of this technique such as performance. There are certainly ways to optimize the performance with some clever caching. Performance might not be an issue anyway, depending on where this code is used.

Have you come up with a novel way to use a new language feature that you'd like to share?

Posted by Eilon with 53 comment(s)
Filed under:

ScriptManager's EnablePartialRendering and SupportsPartialRendering properties

In ASP.NET AJAX's ScriptManager control there are two properties that seem quite similar, but are in fact very different:

namespace System.Web.UI {
public class ScriptManager : Control {
public bool EnablePartialRendering { get; set; }
public bool SupportsPartialRendering { get; set; }
...
}
}

The primary difference between these two properties is who the audience is for each. EnablePartialRendering is intended for the page developer. That is, the person who is building the ASP.NET page and placing the ScriptManager on it. They get to decide whether they're interested at all in using the partial rendering feature. For example, for optimization purposes they might disable the partial rendering feature entirely to prevent any extra script from being downloaded. Or perhaps to debug an issue they want to temporarily disable UpdatePanels from doing async postbacks.

On the other hand, SupportsPartialRendering is mostly for component developers and sometimes for page developers. It's used in two ways, depending on the scenarios. The most common way is for control developers to check its value to see whether the current request is using partial rendering. The value is a combination of whether the page developer wants to use partial rendering (EnablePartialRendering) at all along with whether the current request supports partial rendering. To determine whether the request supports partial rendering the ScriptManager looks at the request's browser capabilities.

The other way that SupportsPartialRendering is used is for page developers who want to override the ScriptManager's default browser detection logic. When we release ASP.NET AJAX 1.0 we came up with a set of checks that worked great for the browsers we knew we supported at the time (IE6, IE7, Firefox, Safari, and maybe some others). Inevitably, the market of browsers has changed since then with newer browsers appearing, and our logic isn't always right. There's your chance to override it!

Another case people want to override our default browser detection is when proxies alter the browser headers. For example, I've heard from a number of customers that they are using web proxies that replace the HTTP User Agent header with the proxy's name and version. While I think that's a ridiculous thing for a proxy to do, that's how some of them do it. When ScriptManager sees "FooProxy v1.23" as the agent, it decides that it's not a known browser and won't let you use partial rendering. The customer's workaround was to set SupportsPartialRendering to true when EnablePartialRendering was true and the user agent was the FooProxy.

Posted by Eilon with no comments
Filed under: , , ,

How ASP.NET databinding deals with Eval() and Bind() statements

A recent question on one of our internal mailing lists asked where the definition for the Bind() method is located in ASP.NET. The asker had located the definition of the Eval() method on the TemplateControl class, but the Bind() method was nowhere to be found, even using Reflector.

If you're familiar with databinding in ASP.NET 2.0, you probably know that for read-only values such as Labels you can use the Eval() statement, and for read-write values such as TextBoxes (also known as "two-way databinding") you can use the Bind() statement. Where does that Bind() statement come from?

To the surprise of many readers, there isn’t a bind method in ASP.NET! When ASP.NET parses your file and sees you're using a databinding expression (in the angle-bracket-percent-pound format, "<%# %>") it has special-case code to parse for the Bind syntax and generates some special code for it. When you use <%# Bind("Name") %> it's not a real function call. If ASP.NET parses the code and detects a Bind() statement, it splits the statement into two parts. The first part is the one-way databinding portion, which ends up being just a regular Eval() call. The second part is the reverse portion, which is typically some code along the lines of "string name = TextBox1.Text" that grabs the value back out from where it was bound.

Non-Bind() databinding statements are literal code (we use CodeSnippetExpressions in CodeDom), so arbitrary code in the language of your choice is allowed. However, because ASP.NET has to parse Bind() statements, two-way databinding doesn’t support anything other than Bind(). For example, the following syntax is invalid because it tries to invoke arbitrary code and use Bind() at the same time:
                <%# FormatNameHelper(Bind("Name")) %>
The only formats supported in two-way databinding are Bind("field") and Bind("field", "format string {0}"). There are some very minor variations of these syntax examples, such as allowing use of single quotes and not just double quotes. Since some languages supported by ASP.NET favor one format over the other, we have to support both formats, even though the language you're using may support only one.

The moral of the story is: There are some things that Reflector won't tell you. smile_teeth

Posted by Eilon with 16 comment(s)
More Posts Next page »