mhinze.com

Matt Hinze, learning in public

The following is an excerpt from ASP.NET MVC 2 in Action, a book from Manning appearing in bookstores in May.  The early access (MEAP) edition is available now on http://manning.com/palermo2.  Authors include Jeffrey Palermo, Ben Scheirman, Jimmy Bogard, Eric Hexter and Matt Hinze.  Technically edited by Jeremy Skinner.

This selection is from chapter 19, Lightweight controllers.  All hyperlinks were added for this post.


A quick way to lighten the controller’s load is to simply remove responsibilities from it. Consider the burdened action, shown below:

A heavyweight controller
public RedirectToRouteResult Ship(int orderId)
{
   User user = _userSession.GetCurrentUser();
   Order order = _repository.GetById(orderId);

   if (order.IsAuthorized)
   {
      ShippingStatus status = _shippingService.Ship(order);

      if (!string.IsNullOrEmpty(user.EmailAddress))
      {
         Message message = _messageBuilder
            .BuildShippedMessage(order, user);

         _emailSender.Send(message);
      }

      if (status.Successful)
      {
         return RedirectToAction("Shipped", "Order", new {orderId});
      }
   }
   return RedirectToAction("NotShipped", "Order", new {orderId});
}

This action is doing a lot of work-it’s incomprehensible at first glance. You can almost count its jobs by the number of if statements. Beyond its appropriate role as director of the storyboard flow of the user interface, this action is deciding if the Order is appropriate for shipping and determining whether or not to send the User a notification email. Not only is it doing those things, but it’s deciding how to do them-it’s determining what it means for an Order to be appropriate for shipping and how the notification email should be sent.

Logic like this-domain logic, business logic-should generally not be in a user interface class like a controller. It violates the single responsibility principle, obfuscating both the true intention of the domain and the actual duties of the controller, which is redirecting to the proper action. Testing and maintaining an application written like this is difficult.

Cyclomatic complexity: source code viscosity

Cyclomatic complexity is a metric we can use to analyze the complexity of code. The more logical paths a method or function presents, the higher its cyclomatic complexity. In order to fully understand the implication of a particular procedure, each logical path must be evaluated. For example, each simple if statement presents two paths-one when the condition is true, and another when it’s false. Functions with high cyclomatic complexity are more difficult to test and to understand and have been correlated with increased defect rates.

A simple refactoring that can ease this is called Refactor Architecture by Tiers. It directs the software designer to move processing logic out of the presentation tier into the business tier.

After we move the logic for shipping an order to an OrderShippingService, our action is much simpler.

A simpler action after refactoring architecture by tiers
public RedirectToRouteResult Ship(int orderId)
{
   var status = _orderShippingService.Ship(orderId);
   if (status.Successful)
   {
      return RedirectToAction("Shipped", "Order", new {orderId});
   }
   return RedirectToAction("NotShipped", "Order", new {orderId});
}

Everything having to do with shipping the order and sending the notification has been moved out of the controller into a new class. The controller is left with the single responsibility of deciding where to redirect the client. The new class can fetch the Order, get the User, and do all the rest.

But the result of the refactoring is more than just a move. It’s a semantic break that puts the onus of managing these tasks in the right place. This change has resulted in a clean abstraction that our controller can use to represent what it was doing before. Other logical endpoints can reuse the OrderShippingService, such as other controllers or services that participate in the order shipping process. This new abstraction is clear, and it can change internally without affecting the presentation duties of the controller.

Refactoring doesn’t get much simpler than this, but a simple change can result in significantly lower cyclomatic complexity and can ease the testing effort and maintenance burden associated with a complex controller.

JSON Hijacking in ASP.NET MVC 2

The following is an excerpt from ASP.NET MVC 2 in Action, a book from Manning appearing in bookstores in May.  The early access (MEAP) edition is available now on http://manning.com/palermo2.  Authors include Jeffrey Palermo, Ben Scheirman, Jimmy Bogard, Eric Hexter and Matt Hinze.  Technically edited by Jeremy Skinner.


JSON (pronounced like the English name, Jason) hijacking is a rare hack similar to XSRF, except it’s targeted to request secure JSON from vulnerable applications. The JSON hijacking process involves several steps:

1. A conspiring site, via JavaScript, instructs the victim’s browser to request some secure JSON data from another site.

2. The evil JavaScript receives the JSON data.

3. If the JSON is formatted as an array, the evil script can exploit browser JavaScript processing code to read the JSON data and transmit it back to the attacking site.

Allow JSON via POST only

The solution to this exploit offered by ASP.NET MVC 2 is to only accept requests for JSON data by HTTP POST requests, rather than by GETs. This is baked into and enforced by the standard JsonResult action result that ships with the framework. If we were to request data to be returned by JsonResult with a GET request, we wouldn’t receive the JSON data.

Listing 11.12 shows how we must issue a POST from JavaScript code requesting JSON data.

Listing 11.12 Requesting JSON data via POST
<script type="text/javascript">
    $.postJSON = function(url, data, callback) {
        $.post(url, data, callback, "json");
    };                                                         

    $(function() {
    $.postJSON('/post/getsecurejsonpost',
        function(data) {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options += '<option value="' +  #|2
                data[i].Id + '">' + data[i].Title +
                '</option>';
            }
            $('#securepost').html(options);                    

        });
    });
</script>

 <h2>Secure Json (Post)</h2>
  <div>
    <select id="securepost"/>
 </div>

Listing 11.12 uses the jQuery JavaScript library to craft a special POST request for our JSON data.  When the results are returned, the function populates the select list with them.

Override defaults for GET access

The problem with this approach isn’t technical-this works and it prevents JSON hijacking. But it’s a workaround that’s sometimes unnecessary and can interfere with systems developed using the REST architectural style.

If this approach causes problems, we have additional options. First, we can explicitly enable JSON requests from GETs with the code shown in listing 11.13.

Listing 11.13 Directing JsonResult to accept GETs
[HttpGet]
public JsonResult GetInsecureJson()
{
    object data = GetData();

    return Json(data, JsonRequestBehavior.AllowGet);
}

This will allow our action to respond to normal JSON GET requests. Finally, we can scrap JsonResult itself, instead using an action result to return only non-vulnerable, non-array formatted, JSON.

Modifying the JSON response

The code in listing 11.14 shows a special action result that wraps vulnerable JSON data in a variable, d.

Listing 11.14 Creating a SecureJsonResult encapsulates serialization logic
public class SecureJsonResult : ActionResult
{
    public string ContentType { get; set; }
    public Encoding ContentEncoding { get; set; }
    public object Data { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
         if (context == null)
         {
              throw new ArgumentNullException("context");
         }
         HttpResponseBase response = context.HttpContext.Response;
         if (!string.IsNullOrEmpty(ContentType))
         {
              response.ContentType = ContentType;
         }
         else
         {
              response.ContentType = "application/json";
         }
         if (ContentEncoding != null)
         {
              response.ContentEncoding = ContentEncoding;
         }
         if (Data != null)
         {
              var enumerable = Data as IEnumerable;
              if (enumerable != null)
              {
                    Data = new {d = enumerable};
              }
              var serializer = new JavaScriptSerializer();
              response.Write(serializer.Serialize(Data));
         }
    }
}

This action result encapsulates the tricky code to output the proper JSON, and it works well. The downside to this approach is that we must use this d variable in our JavaScript code. Listing 11.15 shows consuming the serialized data using jQuery.

Listing 11.15 Consuming SecureJsonResult with jQuery
$(function() {
$.getJSON('/post/getsecurejson',
    function(data) {
        var options = '';
        for (var i = 0; i < data.d.length; i++) {
            options += '<option value="' +
            data.d[i].Id + '">' + data.d[i].Title +
            '</option>';
        }
        $('#secure').html(options);
    });
});

Using this technique, we can still use GETs to retrieve our JSON data, but the JSON is secure because it’s never just an array-any arrays are wrapped in a d variable. We just must be sure to access values through the d variable.

This unconventional code can be confusing. We recommend using the default behavior of using HTTP POST requests to retrieve JSON data. If that becomes a problem, you can switch to this technique.

(tl;dr : The bits, serializing to IDictionary<string, object> for RouteValueDictionary)

We have several spots in our ASP.NET MVC 2 app that need to serialize an object into a RouteValueDictionary so that, in a subsequent request, it can be inflated, resurrected by the model binding infrastructure.

We wrote extension method called ToHttpDictionary and we used it like this:

<%= Url.Action("index", "something", new RouteValueDictionary(Model.ToHttpDictionary())) %>

or like this:

RedirectToAction("index", new RouteValueDictionary(form.ToHttpDictionary()))

(and no, we do not use those raw helper method, we wrap them with a strong-typed, smarter one  = ) )

The goal is to transfer this example object, that we might accept as an action parameter:

var spec = new SearchSpecification
{
    FirstName = "John",
    LastName = "Doe"
};

Into the arguments for another request:

http://example.com/search?FirstName=John&LastName=Doe

That’s a lot easier than creating a form and a bunch of hidden fields just to store parameters for a GET request, or using that kludge anonymous type business.  It also makes working with RedirectResult extremely easy, skipping all the nasty TempData stuff you might be tempted to use.

At first we just needed some small, flat objects to be “un bound”, but then once we needed prefixes, the ability to skip properties, support for custom unbinders, and to handle arrays we decided to pull it into its own library and put it on CodePlex.

public static IDictionary<string, object> ToHttpDictionary<T>
    (this T model, params Expression<Func<T, object>>[] propertiesToSkip)
{
    SpecificValueUnbinderFactory.CustomUnbinders =
        () => new ISpecificValueUnbinder[]
        {
            new EnumerationValueUnbinder(),
            new PersistentObjectValueUnbinder()
        };

    return new Unbinder().Unbind(x => x.Source(model).SkipProperties(propertiesToSkip));
}

Custom value unbinders are the analog to custom model binders.  For example, I’ve seen model binders that take the Id of an Entity from the request and hydrate a full Entity object from persistence.  In that case we need an unbinder (sorry, I really can’t think of a better name for the concept) to serialize the Entity as the Id property.  That would look something like this:

public class PersistentObjectValueUnbinder : ISpecificValueUnbinder
{
    public string UnbindValue(object value)
    {
        return ((PersistentObject)value).Id.ToString();
    }

    public bool AppropriatelyUnbinds(object value)
    {
        return value is PersistentObject;
    }
}

And you’d plug it in to the factory function like in the above example.

It’s just a simple helper function, but the technique has been useful.

January Events

Got a couple training events to plug.

First, a fast paced and code-heavy journey towards understanding IOC.  This free event features about 20 minutes of slides and another hour of live coding.  We talk basics but quickly dive into advanced techniques.  We had a packed house last time, so please register early.

Free Inversion of Control Workshop
Tuesday, January 19 2:00 pm to 4:30 pm
at the Microsoft offices in Austin, Texas

Also, I’m working another Headspring Agile Bootcamp class this month.  It’s three intense days of TDD and object oriented design.  If you have any specific questions about this course, check the info page on the Headspring site, leave a comment or shoot me an email.

Headspring Agile Bootcamp
January 20 to January 22
Austin, Texas

Call Headspring to Enroll: (877) 459-2260

Breaking up with the ternary operator

I love the ternary operator.  It’s so terse and clever.  It’s been my bread and butter for years.  It does things no other operator can do, and on three operands!  It’s really a shining example of programming language designer genius

But lately we’ve been having problems.  Things between us just aren’t working out.

I generally catch it sneaking around, hiding complexity in a quick line of seemingly meaningless symbols.  I won’t stand for it any longer. 

I hardly ever actually type it out, anyway.  I always use Resharper to craft it from an existing if statement.

It’s not that I don’t understand the ternary operator.  I do.  But as it increases the time-to-comprehension while reading and maintaining source code by even one tick, its unholy presence can accumulate an untenable viscosity in my workflow.

Reading code I’ve previously written, I find myself using Resharper to decode those same ternary operators back into if statements.

Source code should be easy to write and easy to read.  There are very few contexts in which I’ll tolerate greater terseness over comprehensibility.

Ternary operator, pack your bags.  It’s not you it’s me.

Aggregated specifications

An example from my inversion of control talk involves a message formatter.  It applies formatting rules to a string.

public interface IMessageFomatter
{
    string Format(string message);
}

Instead of doing all the work in the implementation of this interface, the message formatter will aggregate several distinct rules.  An inversion of control tool is configured to compose these rules and provide them to the formatter.

public class MessageFomatter : IMessageFomatter
{
    private readonly IFormatRule[] _rules;

    public MessageFomatter(IFormatRule[] rules)
    {
        _rules = rules;
    }

    public string Format(string message)
    {
        foreach (var action in _rules)
        {
            message = action.ApplyRule(message);
        }
        return message;
    }
}

In this way each rule can be small, testable, and have only one job.  I can add functionality to the formatting process without changing the formatter or any existing rule. 

public interface IFormatRule
{
    string ApplyRule(string text);
}

public class DisclaimerRule : IFormatRule
{
    public string ApplyRule(string text)
    {
        return text + "\nDisclaimer: This message will self-destruct";
    }
}

public class UppercaseRule : IFormatRule
{
    public string ApplyRule(string text)
    {
        return text.ToUpper();
    }
}

This technique is extremely powerful and we use it all over the place in our projects.

Recently we were building a search screen.  It has several text input boxes and select lists and radio button groups, you know, the standard enterprisey UI mess.  Anyway, that’s what it was and it’s a common feature in the apps I work on. I’ve seen the scenario over and over. But armed with the above technique and LINQ to NHibernate, we were able to craft a much more elegant solution than we had previously created.

First we have a type that represents the search query.  It could be implemented by the class that represents the user interface form or be built by the user interface layer.  It’s sent to a service that will perform the query.

public interface IProductSearchQuery
{
    decimal? Price { get; set; }
    int? PriceRange { get; set; }
    string Name { get; set; }
    ProductCategory Category { get; set; }
    // ...
}

public interface IProductRepository
{
    Product[] Search(IProductSearchQuery query);
    // ...
}

What we don’t want is a huge method that checks to see if a search criteria exists and then conditionally appends predicates to a database query.  That’s the old school way, and it’s a beast to test and to change.  Adding a user interface element, like a new text input field, would require us to change that big method by introducing repetitive and dangerous new code.

What we do want are small, isolated specifications that we can aggregate like the message formatter.

public interface IProductSearchFilter
{
    bool ShouldApply(IProductSearchQuery query);
    IQueryable<Product> Filter(IQueryable<Product> candidates, IProductSearchQuery query);
}

An example filter:

public class PriceRangeFilter : IProductSearchFilter
{
    public bool ShouldApply(IProductSearchQuery query)
    {
        return query.Price.HasValue && query.PriceRange.HasValue;
    }

    public IQueryable<Product> Filter(IQueryable<Product> candidates, IProductSearchQuery query)
    {
        return from product in candidates
               where product.Price <= (query.Price + query.PriceRange)
               && product.Price >= (query.Price - query.PriceRange)
               select product;
    }
}

You can test drive this thing.  It’s small and distinct.  And using LINQ to NHibernate you can combine several of them in a way that produces one select.

public class ProductRepository : IProductRepository
{
    private readonly ISession _session;
    private readonly IProductSearchFilter[] _filters;

    public ProductRepository(ISession session, IProductSearchFilter[] filters)
    {
        _session = session;
        _filters = filters;
    }

    public Product[] Search(IProductSearchQuery query)
    {
        var products = _session.Linq<Product>();
        return _filters
            .Where(x => x.ShouldApply(query))
            .Aggregate(products, (candidates, filter) =>
                filter.Filter(candidates, query)).ToArray();
    }

    // ...
}

One tricky spot for a lot of people is that Aggregate call.  It does the exact same thing as the foreach in the message formatter: passes the seed (products, in this case) through the filters aggregating the result.  The lambda parameter variable candidates is the result of the previous filter (or the seed for the first filter).  In other ecosystems besides .NET, Aggregate is called reduce.  You can see why – each filter reduces the candidates according to its specification.

When you think about it, an entire architecture could be a reduce. That would be really interesting.

Microsoft MVP

I received word today that I’m a Microsoft MVP for C#.  Cool.

This next bit is going to read like some phony sales pitch or something but it’s legitimate:

I got the award because I work at a great company that nurtures community involvement, encourages open source contribution and gives me the opportunity to develop and deliver high quality courseware for programmers.  I also work every day in the IDE and whiteboard trenches with an incredibly talented team of developers who foster a real culture of continuous improvement.

AutoMapper in NerdDinner

Speaking of NerdDinner, Scott asked me to use it to create an AutoMapper example. logo

AutoMapper, the brainchild of Jimmy Bogard, is an object-to-object mapper.  What that means is up to you – but we’ll use it here to map from the domain model to a view model.  The view model is an object heirarchy that represents the screen.  It’s as dumb as possible, just like the view.

We get a lot of nice things out of it and it helps us go faster.  You can read more about it AutoMapper from Jimmy or at the website on Codeplex.

For starters, NerdDinner isn’t the best scenario in which to apply AutoMapper.  NerdDinner is very small so there’s not much reuse to harvest. For example, if you format dates the same way a million times you can use AutoMapper to only write that formatting code once.  In a small application you may format dates two ways and only use the resulting text in two views.  It doesn’t make a lot of sense to extract a class just for that – it will seem like a lot of overhead. 

Also NerdDinner doesn’t have a rich domain model – there’s just not that much to do.  So the AutoMapper feature of flattening complex hierarchies can’t be appreciated.

I posted the result of this quick and dirty spike as a sample project – hopefully this will help you get started looking at it.

First, I copypasted a class to bootstrap AutoMapper:

namespace NerdDinner.Helpers.AutoMapper
{
    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x => x.AddProfile<ViewModelProfile>());
        }
    }
}

.. which will be called when the application starts:

void Application_Start()
{
    AutoMapperConfiguration.Configure();

    RegisterRoutes(RouteTable.Routes);

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine());
}

I copypasted another class that will check the mapping configuration for errors, providing fast feedback should I make a mistake.

[TestClass]
public class AutoMapperConfigurationTester
{
    [TestMethod]
    public void Should_map_dtos()
    {
        AutoMapperConfiguration.Configure();
        Mapper.AssertConfigurationIsValid();
    }
}

Now I’m ready to begin creating the view model and configuring AutoMapper.

To design a view model, start with the screen.  What’s displayed will be represented in the model.  Again: the view model is an object hierarchy that represents the user interface.  I picked the Dinner Details screen, by the way.

The current model being used by the view was the Dinner entity itself.  There was a lot of formatting in the view and a lot of duplication.

Almost every property was surrounded by code that would HtmlEncode it (it will be nice to have AutoMapper do this for us):

<%= Html.Encode(Model.Title) %>

And there is a lot of formatting to do:

<abbr class="dtstart" title="<%= Model.EventDate.ToString("s") %>">
    <%= Model.EventDate.ToString("MMM dd, yyyy") %>
    <strong>@</strong>
    <%= Model.EventDate.ToShortTimeString() %>
</abbr>

Imagine a project with 300 screens and a team of analysts and you can imagine that specifying this formatting over and over again in requirements documents and planning would become tedious.  Not to mention coding it.  It’d be easier to just say: “Format this date in the standard way.” You can also imagine the security implications of forgetting to encode even one value.

In converting these screens to use a view model instead of the domain model I didn’t want to change existing functionality.  So I took this:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>"

and changed it to this:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DinnerDetailsViewModel>"

See what I did there?  I just changed the type of the Model property to a new DinnerDetailsViewModel type.

The view will receive a view model mapped from the domain model when I apply a special action filter to the controller action:

[AutoMap(typeof(Dinner), typeof(DinnerDetailsViewModel))]

The code’s in the sample, straight from Jimmy’s post.

I started out with DinnerDetailsViewModel being an empty class definition and used Resharper to generate each property as I encountered it.  I removed the formatting and the ubiquitous encoding from the parameters, turning this:

<div id="dinnerDiv" class="vevent">

    <h2 class="summary"><%= Html.Encode(Model.Title) %></h2>

    <p>
        <a href="http://feeds.technorati.com/events/<%= Url.AbsoluteAction("Details", new { id = Model.DinnerID }) %>">
            Add event to your calendar (iCal)
        </a>
    </p>

    <p>
        <strong>When:</strong>
<abbr class="dtstart" title="<%= Model.EventDate.ToString("s") %>">
<%= Model.EventDate.ToString("MMM dd, yyyy") %>
<strong>@</strong>
<%= Model.EventDate.ToShortTimeString() %>
</abbr>

into this:

<h2 class="summary"><%= Model.Title %></h2>

<p>
    <a href="http://feeds.technorati.com/events/<%= Url.AbsoluteAction("Details", new { id = Model.DinnerID }) %>">
        Add event to your calendar (iCal)
    </a>
</p>

<p>
    <strong>When:</strong>
    <%= Model.EventDate %>
</p>

I had to write a formatter to replace the custom formatting performed by the view.

public class AttendeeNameFormatter : BaseFormatter<string>
{
    protected override string FormatValueCore(string value)
    {
        return value.Replace("@", " at ");
    }
}

See how testable that is; small and reusable?

I also moved some methods that were previously being called from the view directly into the domain model which AutoMapper will evaluate at runtime.

Before:

<p id="whoscoming">
    <strong>Who's Coming:</strong>
    <%if (Model.RSVPs.Count == 0){%>
          No one has registered.
    <% } %>
</p>

After:

<p id="whoscoming">
    <strong>Who's Coming:</strong>
    <%if (Model.IsNobodyRegistered){%>
          No one has registered.
    <% } %>
</p>

The view model for this screen ends up looking like this:

public class DinnerDetailsViewModel
{
    public string Address { get; set; }
    public string Title { get; set; }
    public string DinnerID { get; set; }
    public string EventDate { get; set; }
    public string Country { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string Description { get; set; }
    public string HostedBy { get; set; }
    public string ContactPhone { get; set; }
    public bool IsAnyoneRegistered { get; set; }
    public bool IsNobodyRegistered { get; set; }
    public bool IsCurrentUserRegistered { get; set; }
    public bool IsCurrentUserHosting { get; set; }

    public List<RsvpViewModel> RSVPs { get; set; }

    public class RsvpViewModel
    {
        public string AttendeeName { get; set; }
    }
}

The really key part is the AutoMapper configuration profile.  You can group configurations with profiles.  Maybe in one profile you format dates in one way, in another profile you format dates in another way.  I’m just using one profile here.

public class ViewModelProfile : Profile
{
    protected override string ProfileName
    {
        get { return "ViewModel"; }
    }

    protected override void Configure()
    {
        AddFormatter<HtmlEncoderFormatter>();
        ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();

        CreateMap<Dinner, DinnerDetailsViewModel>()
            .ForMember(x => x.IsCurrentUserRegistered, o => o.ResolveUsing<CurrentUserRegisteredResolver>())
            .ForMember(x => x.IsCurrentUserHosting, o => o.ResolveUsing<CurrentUserHostingResolver>())
            .ForMember(x => x.EventDate, o => o.SkipFormatter<HtmlEncoderFormatter>());

        CreateMap<RSVP, DinnerDetailsViewModel.RsvpViewModel>()
            .ForMember(x => x.AttendeeName, o => o.AddFormatter<AttendeeNameFormatter>());
    }
}

Most properties of the view model are mapped conventionally.  The property names match up so AutoMapper knows exactly what do do with them.  AutoMapper will do a lot more for you if you’d like it to.  This is actually a pretty hefty configuration.  In a different scenario it’d be likely that almost everything is mapped conventionally.

Note the first AddFormatter call.  That’s instructing AutoMapper to html encode everything.  I skip it for a property later.  The possibilities here are endless.  One cool thing we do in another project is wrap each property in a span that’s given a conventionally named CSS class.  In automated UI tests, we can use that class to find the proper element and ensure that the screen is displaying the right thing.

image

Let me know if you have any questions.

Jeffrey and Eric will be delivering a free afternoon of ASP.NET MVC in Austin on Tuesday, June 16th.  If you haven’t yet had a run-in with the new framework or if you’re ready to see what we’ve learned using ASP.NET MVC in the field, this afternoon will be an excellent opportunity to compress learning and maximize your time… 

Simple Nested Closure

Nested closure is one of those fancy patterns Martin Fowler first coined (as far as I know) and published on his DSL WIP site. His formal definition:

Express statement sub-elements of a function call by putting them into a closure in an argument.

You pass a delegate as a method parameter. The receiving method executes the function represented by that delegate against an object it controls.  Nested closure in C# is easy to spot because the delegate is usually typed as Action<T>, where T is the type of the object that the called method will provide as a parameter to our argument function.

The most obvious example is a common extension method:

public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
    foreach (T item in items)
    {
        action(item);
    }
}

Nested closure is like template method, but instead of deriving from a base class to affect behavior, the additional behavior is provided as an argument.  In the same way that template method is great when you want to communicate behavior from derivations to base classes, nested closure works when you want to communicate behavior as you call a method.

Consider working with a common series of steps when writing repository methods against NHibernate:

public Order[] GetAllOpenOrders(Customer customer)
{
    ISession session = GetSession();
    IQuery query = session.CreateQuery("from Order o where o.Resolution is null and o.Customer = ?");
    query.SetEntity(0, customer);
    var results = query.List<Order>().ToArray();
    return results;
}

Code like this – where you have the same basic structure in several methods – can be made more terse by using a nested closure.

public Order[] GetShippedOrders(Customer customer)
{
    const string hql = "select distinct s.Order from Shipment s where s.Order.Customer = ?";

    return Hql(hql, x => x.SetEntity(0, customer));
}

The second parameter is an Action<IQuery>.

protected T[] Hql(string query, Action<IQuery> additionalWork)
{
    IQuery iquery = GetSession().CreateQuery(query);

    if (additionalWork != null)
        additionalWork(iquery);

    return iquery.List<T>().ToArray();
}

Nested closures are also good for adding fluency to APIs.  This is the context of Fowler’s writing, and you can see it clearly in Rhino Mocks:

repository.AssertWasCalled(x => x.Save(null), o =>
    {
        o.IgnoreArguments();
        o.Constraints(Property.AllPropertiesMatch(visitToSave));
    });

In this scenario we’re passing a delegate that, when invoked later, helps Rhino Mocks configure options for its expectations.