<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Forloop Blog</title><link>http://forloop.co.uk:80/blog</link><description>Forloop Blog</description><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/forloop" /><feedburner:info uri="forloop" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item><title>Managing Scripts for Razor Partial Views and Templates in ASP.NET MVC</title><link>http://forloop.co.uk:80/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc</link><description>&lt;blockquote&gt;&lt;strong&gt;UPDATE 13-03-2013:&lt;/strong&gt; I've created a &lt;a href="http://nuget.org/packages/Forloop.HtmlHelpers/"&gt;nuget package for the helpers.&lt;/a&gt; The original ScriptContext scope had to be brought back in for MVC 4 as the TemplateStack approach no longer worked.&lt;/blockquote&gt;
&lt;blockquote&gt;&lt;strong&gt;UPDATE 21-11-2011:&lt;/strong&gt; After some digging through the MVC framework code, I've come up with a slightly cleaner solution that doesn't require ScriptContext to implement IDisposable and therefore removes the need to create a "scope" for the scripts. &lt;a href="#updated-article"&gt;Skip to the end to see the update&lt;/a&gt;.&lt;/blockquote&gt;
&lt;p&gt;The view engine in ASP.NET MVC is flexible, &lt;em&gt;very flexible&lt;/em&gt;. With great flexibility comes great responsibility however, and managing JavaScript files and code blocks can be particularly cumbersome in conjunction with partial views and templates.&lt;/p&gt;
&lt;h2&gt;&amp;ldquo;It&amp;rsquo;s my script!,&amp;rdquo; &amp;ldquo;No, it&amp;rsquo;s my script!&amp;rdquo;&lt;/h2&gt;
&lt;p&gt;It&amp;rsquo;s a good idea to split discrete sections of page markup into their own partial views and templates, not only to support reuse but also to support the creation of richer interactive applications that take advantage of AJAX, fetching only the markup that is required from the server at any particular time.&lt;/p&gt;
&lt;p&gt;If discrete sections of markup require JavaScript for client-side functionality, in my opinion, it&amp;rsquo;s good to keep the script near to where it&amp;rsquo;s needed i.e. declared in the partial view or template. Herein lies a problem; putting JavaScript in the middle of page markup will block subsequent rendering of the page until that script has been executed. To avoid this, &lt;a title="Yahoo's web site performance recommendations" href="http://developer.yahoo.com/yslow/" target="_blank"&gt;YSlow&lt;/a&gt; recommends putting scripts near the end of the document, just before the closing &lt;code&gt;&amp;lt;/body&amp;gt;&lt;/code&gt; tag. Doing this however may cause another problem; the partial view script may be reliant on other script to have been executed before it runs, for example, if it is dependent on a JavaScript library. The question is then, how do we render scripts from partials and templates near the end of the document and control the order of rendering?&lt;/p&gt;
&lt;h2&gt;I get by with a little help from my friends&lt;/h2&gt;
&lt;p&gt;I&amp;rsquo;ve put together some &lt;a title="MSDN documentation for the HtmlHelper class" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx" target="_blank"&gt;HtmlHelper&lt;/a&gt; extension methods and a small class that aid in managing scripts and rendering them at the correct time. Note that I have only tried this with the Razor View Engine; the order of execution of the view hierarchies is different between Razor and WebForms views, so I wouldn&amp;rsquo;t expect this to work with the latter.&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:d6a9b7a0-24a5-4e08-a7bf-f0029d9a633d" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;public static class HtmlHelperExtensions
{
    public static ScriptContext BeginScriptContext(this HtmlHelper htmlHelper)
    {
        var scriptContext = new ScriptContext(htmlHelper.ViewContext.HttpContext);
        htmlHelper.ViewContext.HttpContext.Items[ScriptContext.ScriptContextItem] = scriptContext;
        return scriptContext;
    }

    public static void EndScriptContext(this HtmlHelper htmlHelper)
    {
        var items = htmlHelper.ViewContext.HttpContext.Items;
        var scriptContext = items[ScriptContext.ScriptContextItem] as ScriptContext;

        if (scriptContext != null)
        {
            scriptContext.Dispose();
        }
    }

    public static void AddScriptBlock(this HtmlHelper htmlHelper, string script)
    {
        var scriptGroup = htmlHelper.ViewContext.HttpContext.Items[ScriptContext.ScriptContextItem] as ScriptContext;

        if (scriptGroup == null)
            throw new InvalidOperationException("cannot add a script block without a script context. Call Html.BeginScriptContext() beforehand.");

        scriptGroup.ScriptBlocks.Add(script);
    }

    public static void AddScriptFile(this HtmlHelper htmlHelper, string path)
    {
        var scriptGroup = htmlHelper.ViewContext.HttpContext.Items[ScriptContext.ScriptContextItem] as ScriptContext;

        if (scriptGroup == null)
            throw new InvalidOperationException("cannot add a script file without a script context. Call Html.BeginScriptContext() beforehand.");

        scriptGroup.ScriptFiles.Add(path);
    }

    public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
    {
        var scriptContexts = htmlHelper.ViewContext.HttpContext.Items[ScriptContext.ScriptContextItems] as Stack&amp;lt;ScriptContext&amp;gt;;

        if (scriptContexts != null)
        {
            var count = scriptContexts.Count;
            var builder = new StringBuilder();
            var script = new List&amp;lt;string&amp;gt;();
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            for (int i = 0; i &amp;lt; count; i++)
            {
                var scriptContext = scriptContexts.Pop();

                foreach (var scriptFile in scriptContext.ScriptFiles)
                {
                    builder.AppendLine("&amp;lt;script type='text/javascript' src='" + urlHelper.Content(scriptFile) + "'&amp;gt;&amp;lt;/script&amp;gt;");
                }

                script.AddRange(scriptContext.ScriptBlocks);

                // render out all the scripts in one block on the last loop iteration
                if (i == count - 1)
                {
                    builder.AppendLine("&amp;lt;script type='text/javascript'&amp;gt;");
                    foreach (var s in script)
                    {
                        builder.AppendLine(s);
                    }
                    builder.AppendLine("&amp;lt;/script&amp;gt;");
                }
            }

            return new MvcHtmlString(builder.ToString());
        }

        return MvcHtmlString.Empty;
    }
}

public class ScriptContext : IDisposable
{
    internal const string ScriptContextItems = "ScriptContexts";
    internal const string ScriptContextItem = "ScriptContext";

    private readonly HttpContextBase _httpContext;
    private readonly IList&amp;lt;string&amp;gt; _scriptBlocks = new List&amp;lt;string&amp;gt;();
    private readonly HashSet&amp;lt;string&amp;gt; _scriptFiles = new HashSet&amp;lt;string&amp;gt;();

    public ScriptContext(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        _httpContext = httpContext;
    }

    public IList&amp;lt;string&amp;gt; ScriptBlocks { get { return _scriptBlocks; } }

    public HashSet&amp;lt;string&amp;gt; ScriptFiles { get { return _scriptFiles; } }

    public void Dispose()
    {
        var items = _httpContext.Items;
        var scriptContexts = items[ScriptContextItems] as Stack&amp;lt;ScriptContext&amp;gt; ?? new Stack&amp;lt;ScriptContext&amp;gt;();

        // remove any script files already the same as the ones we're about to add
        foreach (var scriptContext in scriptContexts)
        {
            scriptContext.ScriptFiles.ExceptWith(ScriptFiles);
        }

        scriptContexts.Push(this);

        items[ScriptContextItems] = scriptContexts;
    }
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;These can be used in your layout, view or partial view in one of three ways (all with the same outcome):&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:08a8666e-8956-4583-bb2c-4ab148bcb9bc" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;@{
    Html.BeginScriptContext();
    Html.AddScriptBlock(@"$(function() { if (console) { console.log('rendered from the view'); } });");
    Html.AddScriptFile("~/Scripts/jquery-ui-1.8.11.js");
    Html.EndScriptContext(); 
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:8ffae33f-3fe5-4181-b194-5bb27f33b102" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;@{ 
  using (Html.BeginScriptContext())
  {
    Html.AddScriptFile("~/Scripts/jquery.validate.js");
    Html.AddScriptFile("~/Scripts/jquery-ui-1.8.11.js");
    Html.AddScriptBlock(@"$(function() { 
        $('#someField').datepicker();
    });");
  }
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;or using the ScriptContext directly&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:2b60237f-8272-4554-8edd-5adbe30b50fc" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;@{
  using (var context = Html.BeginScriptContext())
  {
    context.ScriptFiles.Add("~/Scripts/jquery-1.5.1.min.js");
    context.ScriptFiles.Add("~/Scripts/modernizr-1.7.min.js");
  }   
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;If you reference a script more than once, the helpers will ensure that it is rendered only once and in the ordinal position that matches the &lt;em&gt;expected&lt;/em&gt; rendering order of views i.e.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Layout&lt;/li&gt;
&lt;li&gt;View&lt;/li&gt;
&lt;li&gt;Partial View / Template&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;All that remains is to call &lt;code&gt;@Html.RenderScripts()&lt;/code&gt; in your base layout, before the closing &lt;code&gt;&amp;lt;/body&amp;gt;&lt;/code&gt; tag.&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:974763d1-09f3-4e63-aaff-61869b69a35d" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: html;"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;title&amp;gt;@ViewBag.Title&amp;lt;/title&amp;gt;
    &amp;lt;link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /&amp;gt;
    &amp;lt;link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" /&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    @RenderBody()
    @Html.RenderScripts()
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;I&amp;rsquo;ve put up &lt;a title="an example of how to use the ScriptContext Html Helpers on Bitbucket" href="https://bitbucket.org/forloop/forloop-htmlhelpers" target="_blank"&gt;an example up on Bitbucket&lt;/a&gt; &amp;ndash; let me know what you think &lt;img style="border-style: none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="/Media/Default/Windows-Live-Writer/Managing-Scripts-for_799E/wlEmoticon-smile_2.png" /&gt;&lt;/p&gt;
&lt;h2 id="updated-article"&gt;An Updated Solution&lt;/h2&gt;
&lt;p&gt;After digging through the MVC 3 framework code looking for a way to determine when the razor template currently being rendered changes, I came across &lt;a target="_blank" title="MSDN documentation for TemplateStack" href="http://msdn.microsoft.com/en-us/library/system.web.webpages.templatestack%28v=vs.99%29.aspx"&gt;&lt;code&gt;TemplateStack&lt;/code&gt;&lt;/a&gt; and the static method &lt;a target="_blank" title="MSDN documentation for GetCurrentTemplate" href="http://msdn.microsoft.com/en-us/library/system.web.webpages.templatestack.getcurrenttemplate%28v=vs.99%29.aspx"&gt;&lt;code&gt;GetCurrentTemplate(HttpContext)&lt;/code&gt;&lt;/a&gt;. Using this method, we can do away with creating a scope for a &lt;code&gt;ScriptContext&lt;/code&gt; and simply use&lt;/p&gt;
&lt;pre class="brush: c#;"&gt;@{
    Html.ScriptFile("~/Scripts/jquery-ui-1.8.11.js");
    Html.ScriptBlock(@"$(function() { if (console) { console.log('rendered from the view'); } });");
}&lt;/pre&gt;
&lt;p&gt;inside of any view, partial view or template. As a more elaborate example, take the following &lt;strong&gt;view&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="brush: html;"&gt;@model HomeModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

&amp;lt;h2&amp;gt;ScriptContext Example&amp;lt;/h2&amp;gt;

&amp;lt;p&amp;gt;4 datepickers rendered from an editor template. The jQuery UI script that contains the datepicker plugin is 
    added inside of the editor template using the script context Html Helpers and rendered out at the end of the page.&amp;lt;/p&amp;gt;

@{ Html.RenderPartial("Partial", "partial 1"); }

@Html.EditorFor(m =&amp;gt; m.Date1, "DatePicker")
@Html.EditorFor(m =&amp;gt; m.Date2, "DatePicker")
@Html.EditorFor(m =&amp;gt; m.Date3, "DatePicker")
@Html.EditorFor(m =&amp;gt; m.Date4, "DatePicker")

@Html.Partial("Partial", "partial 2")

@{
    Html.ScriptFile("~/Scripts/jquery-ui-1.8.11.js");
    Html.ScriptBlock(@"$(function() { if (console) { console.log('rendered from the view'); } });");
}
&lt;/pre&gt;
&lt;p&gt;This view is using the following &lt;strong&gt;Layout &lt;/strong&gt;(_Layout.cshtml in the shared folder)&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="brush: html;"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;meta charset="utf-8" /&amp;gt;
        &amp;lt;title&amp;gt;@ViewBag.Title&amp;lt;/title&amp;gt;
        &amp;lt;link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /&amp;gt;
        &amp;lt;link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" /&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        @RenderBody()
        @{
            Html.ScriptFile("~/Scripts/jquery-1.5.1.min.js");
            Html.ScriptFile("~/Scripts/modernizr-1.7.min.js");
        }
        @Html.RenderScripts()
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;
&lt;p&gt;With the following &lt;strong&gt;editor template &lt;/strong&gt;(DatePicker.cshtml in the shared folder)&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="brush: html;"&gt;@model DateTime
@Html.TextBox("", ViewContext.ViewData.TemplateInfo.FormattedModelValue)
@{
    Html.ScriptFile("~/Scripts/jquery-ui-1.8.11.js");
    Html.ScriptBlock(
        @"$(function() { 
    $('#" + ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("") + @"').datepicker();
    if (console) { console.log('rendered from the editor template'); }
});");
}
&lt;/pre&gt;
&lt;p&gt;and finally, the following &lt;strong&gt;partial &lt;/strong&gt;(Partial.cshtml in the shared folder)&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;pre class="brush: html;"&gt;@model string
@{
    Html.ScriptBlock(@"$(function() { if (console) { console.log('rendered from " + Model + "'); } });");
}
&lt;/pre&gt;
&lt;p&gt;Looking at the output with Firebug, we see the following&lt;/p&gt;
&lt;p&gt;&lt;img src="/Media/Default/BlogPost/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc/managing-scripts-output.png" alt="HTML markup seen with firebug" height="1021" width="866" /&gt;&lt;/p&gt;
&lt;p&gt;We can see that the external JavaScript file &amp;lt;script&amp;gt; elements have been added first, followed by the script from each of the razor templates involved in rendering the response. In both cases, the order of rendering is bottom-up i.e. those scripts added using the Html helpers near the end of the page have been rendered first.&lt;/p&gt;
&lt;p&gt;I've updated the&lt;a title="an example of how to use the ScriptContext Html Helpers on Bitbucket" target="_blank" href="https://bitbucket.org/forloop/forloop-htmlhelpers"&gt; example source code up on bitbucket&lt;/a&gt; if you want to have a play &lt;img style="border-style: none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="/Media/Default/Windows-Live-Writer/Managing-Scripts-for_799E/wlEmoticon-smile_2.png" /&gt;&lt;/p&gt;</description><pubDate>Wed, 13 Mar 2013 00:20:34 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc</guid></item><item><title>Nuget Package for Managing Scripts in ASP.NET MVC 4</title><link>http://forloop.co.uk:80/blog/nuget-package-for-managing-scripts-in-asp.net-mvc-4</link><description>&lt;p&gt;As per the comments on my previous post about &lt;a target="_blank" href="http://forloop.co.uk/blog/managing-scripts-for-razor-partial-views-and-templates-in-asp.net-mvc"&gt;Managing Scripts for Razor Partial Views and Templates in ASP.NET MVC&lt;/a&gt;, I've created a &lt;a target="_blank" title="Forloop.HtmlHelpers nuget package" href="https://nuget.org/packages/Forloop.HtmlHelpers/"&gt;Nuget package&lt;/a&gt; for the HtmlHelpers used. Go take a look and leave a comment if you find them useful; I plan to add additional helpers to the package over time for general functionality that is useful in any ASP.NET MVC application.&lt;/p&gt;</description><pubDate>Tue, 12 Mar 2013 23:32:52 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/nuget-package-for-managing-scripts-in-asp.net-mvc-4</guid></item><item><title>Web API – Binding Complex types from the URI by default for HTTP GET requests</title><link>http://forloop.co.uk:80/blog/web-api-binding-complex-types-from-the-uri-by-default-for-http-get-requests</link><description>&lt;p&gt;The model binding implementation in &lt;a href="http://www.asp.net/web-api" target="_blank"&gt;ASP.NET Web Api&lt;/a&gt; shares some similarities to the model binding you find in ASP.NET MVC and at the same time has some striking differences. For a more detailed discussion on web api parameter binding, check out &lt;a title="How ASP.NET Web API does parameter binding" href="http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx" target="_blank"&gt;Mike Stall&amp;rsquo;s excellent post on the topic&lt;/a&gt;. The topic of today&amp;rsquo;s post is how we define our own convention for parameter binding complex types when the request is a HTTP GET request.&lt;/p&gt;
&lt;h2&gt;Body Check&lt;/h2&gt;
&lt;p&gt;The &lt;a title="MSDN article on IActionValueBinder" href="http://msdn.microsoft.com/en-us/library/system.web.http.controllers.iactionvaluebinder%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;IActionValueBinder&lt;/code&gt;&lt;/a&gt; interface is the contract for getting the binding information for a web api controller action&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Web.Http.Controllers
{
    public interface IActionValueBinder
    {
        HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor);
    }
}
&lt;/pre&gt;
&lt;p&gt;and &lt;a title="MSDN article on DefaultActionValueBinder" href="http://msdn.microsoft.com/en-us/library/system.web.http.modelbinding.defaultactionvaluebinder%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;DefaultActionValueBinder&lt;/code&gt;&lt;/a&gt; is the default implementation of &lt;code&gt;IActionValueBinder&lt;/code&gt; within a web api application. The route it takes to determine where model binding should attempt to bind values for a parameter action is as follows:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Does the parameter type have a &lt;a title="MSDN article on ParameterBindingAttribute" href="http://msdn.microsoft.com/en-us/library/system.web.http.parameterbindingattribute%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;ParameterBindingAttribute&lt;/code&gt;&lt;/a&gt;? If so, use this for binding&lt;/li&gt;
&lt;li&gt;Look in the &lt;a title="MSDN article on ParameterBindingRulesCollection" href="http://msdn.microsoft.com/en-us/library/system.web.http.modelbinding.parameterbindingrulescollection%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;ParameterBindingRulesCollection&lt;/code&gt;&lt;/a&gt; on the &lt;a title="MSDN article on HttpConfiguration" href="http://msdn.microsoft.com/en-us/library/system.web.http.httpconfiguration%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;HttpConfiguration&lt;/code&gt;&lt;/a&gt;for the application. Is there a binding specified for the parameter in the collection? If so, use this for binding&lt;/li&gt;
&lt;li&gt;Look at the parameter type. Is it a simple type i.e. a primitive, string, DateTime, Decimal, Guid, DateTimeOffset or TimeSpan (or an applicable Nullable version of these)? If so, look at the URI for binding&lt;/li&gt;
&lt;li&gt;Does the parameter type have a string converter defined for it? If so, look at the URI for binding&lt;/li&gt;
&lt;li&gt;Default to looking in the request body for binding&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The fallback option of looking in the request body seems like an odd action to take for a HTTP GET request, with &lt;a title="Roy Fielding's reasoning on a HTTP GET request with a body" href="http://tech.groups.yahoo.com/group/rest-discuss/message/9962" target="_blank"&gt;some much better well informed suggesting that a body has no semantic meaning for a HTTP GET request&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Yes. In other words, any HTTP request message is allowed to contain&lt;br /&gt;a message body, and thus must parse messages with that in mind.&lt;br /&gt;Server semantics for GET, however, are restricted such that a body,&lt;br /&gt;if any, has no semantic meaning to the request. The requirements&lt;br /&gt;on parsing are separate from the requirements on method semantics.&lt;br /&gt;So, yes, you can send a body with GET, and no, it is never useful&lt;br /&gt;to do so.&lt;br /&gt;This is part of the layered design of HTTP/1.1 that will become&lt;br /&gt;clear again once the spec is partitioned (work in progress).&lt;br /&gt;....Roy&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Purism aside, I&amp;rsquo;d like model binding to default to looking at the URI for GET requests when an binding attribute or rule is not specified for the parameter. It&amp;rsquo;s actually straightforward to do by leveraging the &lt;code&gt;DefaultActionValueBinder&lt;/code&gt; and overriding the &lt;code&gt;GetParameterBinding&lt;/code&gt; method&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public class CustomActionValueBinder : DefaultActionValueBinder
{
    protected override HttpParameterBinding GetParameterBinding(HttpParameterDescriptor parameter)
    {
        // Attribute has the highest precedence
        // Presence of a model binder attribute overrides.
        var bindingAttribute = parameter.ParameterBinderAttribute;
        if (bindingAttribute != null)
        {
            return bindingAttribute.GetBinding(parameter);
        }

        // No attribute, so lookup in global map.
        var parameterBindingRules = parameter.Configuration.ParameterBindingRules;
        if (parameterBindingRules != null)
        {
            var binding = parameterBindingRules.LookupBinding(parameter);
            if (binding != null)
            {
                return binding;
            }
        }

        // if we're dealing with a method that supports HTTP Gets, Assume the model is in the URI
        // otherwise fallback to the defaults.
        return parameter.ActionDescriptor.SupportedHttpMethods.Contains(HttpMethod.Get)
                    ? parameter.BindWithAttribute(new FromUriAttribute())
                    : base.GetParameterBinding(parameter);
    }
}
&lt;/pre&gt;
&lt;p&gt;To hook this up for the application, we need to replace the default &lt;code&gt;IActionValueBinder&lt;/code&gt; registered. This can be done in &lt;code&gt;Application_Start&lt;/code&gt; in global.asax&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // replace the default IActionValueBinder
        GlobalConfiguration.Configuration.Services.Replace(typeof(IActionValueBinder), new CustomActionValueBinder());
    }
}
&lt;/pre&gt;
&lt;p&gt;Alternatively, if you&amp;rsquo;re using an Inversion of Control Container for wiring up dependencies then you simply need to register the &lt;code&gt;IActionValueBinder&lt;/code&gt; with your container to allow your &lt;code&gt;IDependencyResolver&lt;/code&gt; to resolve and use it.&lt;/p&gt;</description><pubDate>Mon, 11 Mar 2013 23:13:29 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/web-api-binding-complex-types-from-the-uri-by-default-for-http-get-requests</guid></item><item><title>CSV ValueProvider for model binding to collections</title><link>http://forloop.co.uk:80/blog/csv-valueprovider-for-model-binding-to-collections</link><description>&lt;blockquote&gt;
&lt;h4&gt;TL;DR&lt;/h4&gt;
&lt;p&gt;I have written a ValueProvider for binding model collections from records in a CSV file. &lt;a href="https://bitbucket.org/forloop/csvvalueprovider" target="_blank"&gt;The source code is available on BitBucket.&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src="/Media/Default/BlogPost/blog/csv-valueprovider-for-model-binding-to-collections/csv.png" alt="" align="absmiddle" height="400" width="640" /&gt;&lt;/p&gt;
&lt;p&gt;Model binding in ASP.NET MVC is responsible for binding values to the models that form the parameter arguments to the controller action matched to the route. But where do model binders get these values from? That&amp;rsquo;s where Value Providers come in; A ValueProvider provides values for model binding and there are ValueProviders for providing values from&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a title="ChildActionValueProvider" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.childactionvalueprovider%28v=vs.98%29.aspx" target="_blank"&gt;a parent action (if the action is a child or nested action)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a title="FormValueProvider" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.formvalueprovider%28v=vs.108%29.aspx" target="_blank"&gt;a posted form value collection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a title="JsonValueProviderFactory" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonvalueproviderfactory%28v=vs.98%29.aspx" target="_blank"&gt;posted JSON&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a title="RouteDataValueProvider" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.routedatavalueprovider%28v=vs.108%29.aspx" target="_blank"&gt;route data&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a title="QueryStringValueProvider" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.querystringvalueprovider%28v=vs.108%29.aspx" target="_blank"&gt;the query string&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a title="HttpFileCollectionValueProvider" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.httpfilecollectionvalueprovider%28v=vs.108%29.aspx" target="_blank"&gt;posted files&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;!--more--&gt;
&lt;h2&gt;Design Patterns in action&lt;/h2&gt;
&lt;p&gt;The interface for a ValueProvider is straightforward, comprising only two methods:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Web.Mvc
{
    public interface IValueProvider
    {
        bool ContainsPrefix(string prefix);
        ValueProviderResult GetValue(string key);
    }
}
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;ContainsPrefix&lt;/code&gt; determines whether the provider contains a value with the passed prefix and &lt;code&gt;GetValue&lt;/code&gt; returns a &lt;code&gt;ValueProviderResult&lt;/code&gt; for a given key (or null if the provider cannot provide a result for the key).&lt;/p&gt;
&lt;p&gt;A provider is constructed by a&amp;hellip; &lt;code&gt;ValueProviderFactory&lt;/code&gt;! The &lt;a title="The Factory Method Pattern" href="http://en.wikipedia.org/wiki/Factory_method_pattern" target="_blank"&gt;factory method pattern&lt;/a&gt; is used to construct a provider, with each different framework provider constructed by a different factory class deriving from &lt;a title="ValueProviderFactory" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.valueproviderfactory%28v=vs.108%29.aspx" target="_blank"&gt;&lt;code&gt;ValueProviderFactory&lt;/code&gt;&lt;/a&gt;. The MVC framework has a place to register new factories using the static &lt;code&gt;ValueProviderFactories.Factories&lt;/code&gt; property which is an instance of &lt;code&gt;ValueProviderFactoryCollection&lt;/code&gt;. This collection has a &lt;code&gt;GetValueProvider&lt;/code&gt; method that returns &lt;code&gt;ValueProviderCollection&lt;/code&gt;, a &lt;a title="The Composite Design Pattern" href="http://en.wikipedia.org/wiki/Composite_pattern" target="_blank"&gt;composite&lt;/a&gt; provider that implements &lt;code&gt;IValueProvider&lt;/code&gt; and internally works with an instance of each &lt;code&gt;IValueProvider&lt;/code&gt; constructed by each &lt;code&gt;ValueProviderFactory&lt;/code&gt; registered. That&amp;rsquo;s a lot of detail to describe there and my reason for doing so is because of an important detail that rises from this implementation -&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The first instance of &lt;code&gt;ValueProviderResult&lt;/code&gt; returned from a &lt;code&gt;GetValue&lt;/code&gt; call on an &lt;code&gt;IValueProvider&lt;/code&gt; will be the result used in model binding. &lt;strong&gt;The order of IValueProvider implementations in ValueProviderFactories.Factories is important if more than one can provide a value for model binding.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We'll see a little later why this is important.&lt;/p&gt;
&lt;h2&gt;Providing values for model binding from a CSV file&lt;/h2&gt;
&lt;p&gt;&lt;a title="Comma-separated values" href="http://en.wikipedia.org/wiki/Comma-separated_values" target="_blank"&gt;CSV&lt;/a&gt; (comma/character separated values) are a file format for passing tabular data around in structured plain text and are regularly used to upload collections of records to web applications. In ASP.NET MVC, the HttpFileCollectionValueProvider provides access to uploaded files by specifying the model property to bind to as HttpPostedFileBase. The problem that I find with this approach however is that the responsibility for reading the file, transforming it into something more meaningful such as a collection of types to work with and handling validation errors now usually happens in one of two places&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the controller action&lt;/li&gt;
&lt;li&gt;a custom model binder&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If your application allows users to upload CSV files for creating multiple records for different purposes this can be a lot of repetition. If we know that a file contains CSV data, it would be good if these values were provided for model binding; this way, the mechanism could be re-used anywhere where CSV files are used and more importantly, by being exposed as values for model binding the values will also be validated against the data annotations on the model. Let&amp;rsquo;s go ahead an implement a CSV Value Provider.&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public class CsvValueProvider : IValueProvider
{
    public static readonly CsvConfiguration Configuration = new CsvConfiguration { AllowComments = true };

    private readonly Lazy&amp;lt;PrefixContainer&amp;gt; _prefixContainer;
    private readonly NameValueCollection _values = new NameValueCollection();

    public CsvValueProvider(ControllerContext controllerContext)
    {
        _prefixContainer = new Lazy&amp;lt;PrefixContainer&amp;gt;(() =&amp;gt; new PrefixContainer(_values.AllKeys), true);

        var files = controllerContext.HttpContext.Request.Files;

        if (files.Count == 0)
        {
            return;
        }

        var mapping = new List&amp;lt;KeyValuePair&amp;lt;string, HttpPostedFileBase&amp;gt;&amp;gt;();
        for (var i = 0; i &amp;lt; files.Count; i++)
        {
            var key = files.AllKeys[i];
            if (key != null)
            {
                HttpPostedFileBase file = PostedFileHelper.ChooseFileOrNull(files[i]);

                // we only care about csv files
                if (file != null &amp;amp;&amp;amp; !file.FileName.EndsWith(".csv"))
                {
                    continue;
                }

                mapping.Add(new KeyValuePair&amp;lt;string, HttpPostedFileBase&amp;gt;(key, file));
            }
        }

        var fileGroups = mapping.GroupBy(el =&amp;gt; el.Key, el =&amp;gt; el.Value, StringComparer.OrdinalIgnoreCase);

        foreach (var fileGroup in fileGroups)
        {
            foreach (var file in fileGroup)
            {
                using (var reader = new CsvReader(new StreamReader(file.InputStream), Configuration))
                {
                    int index = 0;
                    long previousCharPosition = 0;
                    while (reader.Read())
                    {
                        long charPosition = reader.Parser.CharPosition;

                        for (var j = 0; j &amp;lt; reader.CurrentRecord.Length; j++)
                        {
                            var subPropertyName = reader.FieldHeaders[j].Trim();
                            var value = reader.CurrentRecord[j];
                            _values.Add(string.Format("{0}[{1}].{2}", fileGroup.Key, index, subPropertyName), value);
                        }

                        // naive way of determining if the file is *really* a csv file.
                        // the csv parser's character position does not change when it can't read
                        // the file as a csv.
                        if (charPosition == previousCharPosition)
                        {
                            return;
                        }

                        previousCharPosition = charPosition;
                        index++;
                    }
                }
            }
        }
    }

    public bool ContainsPrefix(string prefix)
    {
        return _prefixContainer.Value.ContainsPrefix(prefix);
    }

    public ValueProviderResult GetValue(string key)
    {
        if (key == null)
        {
            throw new ArgumentNullException("key");
        }

        if (!_values.AllKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
        {
            return null;
        }

        var rawValue = _values.GetValues(key);
        var attemptedValue = _values[key];
        return new ValueProviderResult(rawValue, attemptedValue, CultureInfo.InvariantCulture);
    }
}
&lt;/pre&gt;
&lt;p&gt;The provider is using the great &lt;a title="A library for reading and writing CSV files" href="https://github.com/JoshClose/CsvHelper" target="_blank"&gt;CsvHelper&lt;/a&gt; nuget package from Josh Close. It looks at the incoming files on the request and for any files with the *.csv file extension, it will open them in turn and attempt to read the records out of the file. For each record that it finds in the CSV, it will take the value and add it to a &lt;code&gt;NameValueCollection&lt;/code&gt; keyed against the header name followed by an indexer indicating the position of the record, and prefixed with the name of the file as posted in the request. It uses a &lt;code&gt;NameValueCollection&lt;/code&gt; so that multiple columns with the same header name can be specified thereby allowing binding to simple property collections on a model.&lt;/p&gt;
&lt;p&gt;In order to create the provider, a factory is required:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public class CsvValueProviderFactory : ValueProviderFactory
{
    public static void AddToValueProviderFactoryCollection()
    {
        AddToValueProviderFactoryCollection(ValueProviderFactories.Factories);
    }

    public static void AddToValueProviderFactoryCollection(ValueProviderFactoryCollection collection)
    {
        var postedFileValueProviderFactory =
            collection.SingleOrDefault(x =&amp;gt; x is System.Web.Mvc.HttpFileCollectionValueProviderFactory);

        if (postedFileValueProviderFactory != null)
        {
            var index = collection.IndexOf(postedFileValueProviderFactory);
            collection.Insert(index, new CustomHttpFileCollectionValueProviderFactory());
            collection.Remove(postedFileValueProviderFactory);
        }

        collection.Add(new CsvValueProviderFactory());
    }

    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        return new CsvValueProvider(controllerContext);
    }
}
&lt;/pre&gt;
&lt;p&gt;The factory is fairly straightforward, with the addition of a couple of static methods that can be used to add the provider to the factories collection.&lt;/p&gt;
&lt;h2&gt;Fightin&amp;rsquo; the Framework&lt;/h2&gt;
&lt;p&gt;The static methods on &lt;code&gt;CsvValueProviderFactory&lt;/code&gt; are there to not only add the factory to the factories collection, but also to remove the &lt;code&gt;System.Web.Mvc.HttpFileCollectionValueProviderFactory&lt;/code&gt; and replace it with our own custom value provider for getting values from posted files. Why do we need to do this I hear you ask? Well, let&amp;rsquo;s go back to the point raised earlier.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The first instance of &lt;code&gt;ValueProviderResult&lt;/code&gt; returned from a &lt;code&gt;GetValue&lt;/code&gt; call on an &lt;code&gt;IValueProvider&lt;/code&gt; will be the result used in model binding. &lt;strong&gt;The order of IValueProvider implementations in ValueProviderFactories.Factories is important if more than one can provide a value for model binding.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Let&amp;rsquo;s imagine we have a view model that has a collection of users on it that we wish to bind that looks like so:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;using System.ComponentModel.DataAnnotations;

public class UsersModel
{
    public UsersModel()
    {
        Users = new List&amp;lt;User&amp;gt;();
    }

    public IList&amp;lt;User&amp;gt; Users { get; set; } 
}

public class User
{
    public User()
    {
        Roles = new string[0];
    }

    [Required]
    public string FullName { get; set; }

    [Required]
    public string Username { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public int? Age { get; set; }

    public string[] Roles { get; set; }
}
&lt;/pre&gt;
&lt;p&gt;Now, we have a controller where users can submit a CSV file:&lt;/p&gt;
&lt;pre class="brush: csharp; toolbar: false;"&gt;public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new UsersModel());
    }

    [HttpPost]
    public ActionResult Index(UsersModel model)
    {
        return View(model);
    }
}&lt;/pre&gt;
&lt;p&gt;and a corresponding view with the following form:&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(m =&amp;gt; m.Users, new { type = "file" })
    &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
} 
&lt;/pre&gt;
&lt;p&gt;Here&amp;rsquo;s what happens when we have the &lt;code&gt;CsvValueProviderFactory&lt;/code&gt; hooked up in addition to &lt;code&gt;System.Web.Mvc.HttpFileCollectionValueProviderFactory&lt;/code&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A user submits a file for the &lt;code&gt;Users&lt;/code&gt; property on &lt;code&gt;UsersModel&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;HttpFileCollectionValueProvider&lt;/code&gt; finds the file in the request and puts it into a dictionary against the string key &lt;em&gt;&amp;ldquo;Users&amp;rdquo;&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;CSVValueProvider&lt;/code&gt;finds the file in the request, determines it&amp;rsquo;s a csv file and reads the records out&lt;/li&gt;
&lt;li&gt;For each record, the provider creates keys named &lt;em&gt;&amp;ldquo;Users[index].FieldHeader&amp;rdquo;&lt;/em&gt; where Users is the filename, index is the record row index and FieldHeader is a column in the csv file that corresponds to a property on the &lt;code&gt;User&lt;/code&gt;type&lt;/li&gt;
&lt;li&gt;When model binding is taking place, the default model binder asks the value providers if they contain the prefix &lt;em&gt;&amp;ldquo;model&amp;rdquo;&lt;/em&gt; first (this is the parameter name on the action; none of the providers have a value for this) and then asks if they contain the prefix &lt;em&gt;&amp;ldquo;Users&amp;rdquo;&lt;/em&gt; (which both &lt;code&gt;HttpFileCollectionValueProvider&lt;/code&gt; and &lt;code&gt;CsvValueProvider&lt;/code&gt;will return true for)&lt;/li&gt;
&lt;li&gt;binding calls &lt;code&gt;GetValue&lt;/code&gt; on each of the ValueProviders passing in the key &lt;em&gt;&amp;ldquo;Users&amp;rdquo;&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;HttpFileCollectionValueProvider&lt;/code&gt; returns an instance of &lt;code&gt;HttpPostedFileBase&lt;/code&gt; for &lt;em&gt;&amp;ldquo;Users&amp;rdquo;&lt;/em&gt; that will fail to be bound to the &lt;code&gt;IList&amp;lt;User&amp;gt;&lt;/code&gt; type for the property &lt;code&gt;Users&lt;/code&gt; on the &lt;code&gt;UsersModel&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Binding will not ask the ValueProviders for any keys further down the property chain for &lt;em&gt;&amp;ldquo;Users&amp;rdquo;&lt;/em&gt; and so the values for &lt;code&gt;CSVValueProvider&lt;/code&gt; will not be used in model binding&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;On the basis of this knowledge, all the &lt;code&gt;CustomHttpFileCollectionValueProvider&lt;/code&gt; constructed by &lt;code&gt;CustomHttpFileCollectionValueProviderFactory&lt;/code&gt; does is to ignore csv files so that they cannot be provided as values for model binding and do not interfere with the function of &lt;code&gt;CSVValueProvider&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Where did the errors happen?&lt;/h2&gt;
&lt;p&gt;I&amp;rsquo;ve put up &lt;a href="https://bitbucket.org/forloop/csvvalueprovider" target="_blank"&gt;the source code and a demo web project on bitbucket&lt;/a&gt; for those interested. What remains is to provide more meaningful error messages back to the user for any rows in the CSV file that fail model validation; at the moment, we can do something simple like:&lt;/p&gt;
&lt;pre class="brush: xml; toolbar: false;"&gt;for (int i = 0; i &amp;lt; Model.Users.Count; i++)
{
    if (!ViewContext.ViewData.ModelState.IsValidField("Users[" + i + "]"))
    {
        &amp;lt;p class="field-validation-error"&amp;gt;Invalid values in row @i&amp;lt;/p&amp;gt;
        @Html.ValidationMessageFor(m =&amp;gt; m.Users[i].Age)
        @Html.ValidationMessageFor(m =&amp;gt; m.Users[i].Email)
        @Html.ValidationMessageFor(m =&amp;gt; m.Users[i].FullName)
        @Html.ValidationMessageFor(m =&amp;gt; m.Users[i].Username)
        @Html.ValidationMessageFor(m =&amp;gt; m.Users[i].Roles)        
    }
}&lt;/pre&gt;
&lt;p&gt;which will tell the user which row was invalid and write out the corresponding error messages. I&amp;rsquo;ll look to make something more generic that can be reused for other models and update &lt;a href="https://bitbucket.org/forloop/csvvalueprovider" target="_blank"&gt;the source on bitbucket&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sat, 02 Mar 2013 22:11:06 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/csv-valueprovider-for-model-binding-to-collections</guid></item><item><title>Presentations from NDC 2012</title><link>http://forloop.co.uk:80/blog/presentations-from-ndc-2012</link><description>&lt;p&gt;The Norwegian Developers Conference is one of the largest .NET Developer conferences of the year, running over several days and including presentations on topics as wide-ranging as software architecture, &lt;a target="_blank" title="SOLID Principles on Wikipedia" href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29"&gt;SOLID principles&lt;/a&gt;, &lt;a target="_blank" title="Test Driven Development on Wikipedia" href="http://en.wikipedia.org/wiki/Test_driven_development"&gt;Test-Driven Development&lt;/a&gt; and more specific introductions to technologies such as &lt;a target="_blank" title="The next version of ASP.NET" href="http://www.asp.net/vnext"&gt;ASP.NET 4.5&lt;/a&gt;, &lt;a target="_blank" title="building REST services with ASP.NET Web API" href="http://www.asp.net/web-api"&gt;Web API&lt;/a&gt;, &lt;a target="_blank" title="web application platform written in JavaScript" href="http://nodejs.org/"&gt;NodeJS&lt;/a&gt; and &lt;a target="_blank" title="Open Source, Enterprise Service Bus for .NET" href="http://nservicebus.com/"&gt;NServiceBus&lt;/a&gt;. Sufficed to say, there is something there for every .NET developer. Interested in seeing what &lt;a target="_blank" title="Async library for .NET to help build real-time, multi-user interactive web applications" href="http://signalr.net/"&gt;SignalR&lt;/a&gt; is all about? Check out the following presentation from Damian Edwards:&lt;/p&gt;
&lt;p&gt;&lt;iframe allowfullscreen="" mozallowfullscreen="" webkitallowfullscreen="" src="http://player.vimeo.com/video/43659069?title=0&amp;amp;byline=0" frameborder="0" height="376" width="670"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;!--more--&gt;
&lt;p&gt;One of the best things about the conference if you're not fortunate to go is that all of the presentations are recorded and can be viewed on the site; take a look at the &lt;a target="_blank" title="NDC 2012 Agenda" href="http://ndcoslo.oktaset.com/Agenda"&gt;agenda&lt;/a&gt; to see which ones pique your interest. If you just have to watch them all then take a look at the &lt;a target="_blank" title="Torrent for all NDC 2012 videos" href="http://www.ndcoslo.com/userfiles/ndc2012.torrent"&gt;torrent&lt;/a&gt; that NDC has created to easily download all of the videos to watch as and when.&lt;/p&gt;
&lt;p&gt;Learn something new today and, if you can, get yourself to next year's event on June 12-14 2013!&lt;/p&gt;</description><pubDate>Sun, 24 Feb 2013 21:40:06 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/presentations-from-ndc-2012</guid></item><item><title>Resolving IoC container services for Validation Attributes in ASP.NET MVC</title><link>http://forloop.co.uk:80/blog/resolving-ioc-container-services-for-validation-attributes-in-asp.net-mvc</link><description>&lt;p&gt;I'm a fan of the &lt;a class="external" title="How to get started with the Data Annotation Validation attributes" href="http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs" target="_blank"&gt;Data Annotation Validation attributes&lt;/a&gt; to validate user input on both the client and server side for ASP.NET MVC applications. I'm also a fan of &lt;a class="external" title="Inversion of Control Wikipedia article" href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank"&gt;Inversion of Control&lt;/a&gt; and &lt;a class="external" title="Dependency Injection Wikipedia article" href="http://en.wikipedia.org/wiki/Dependency_Injection" target="_blank"&gt;Dependency Injection&lt;/a&gt; to create loosely coupled and flexible applications. There are certain situations where one would wish to inject services into a validation attribute to use during validation; a (somewhat contrived and security cautious) example of this might be providing the user with a &amp;lt;select&amp;gt; element and ask them to choose an option from it and then validate that the option that they have chosen is one that actually exists for the type of items represented in the dropdown. Sure, the &lt;a class="external" title="How to implement Remote Validation" href="http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx" target="_blank"&gt;RemoteAttribute&lt;/a&gt; would allow you to call a server side method via AJAX to perform validation but it does not provide any server side validation, making it more of a convenience solution than a complete and robust one. What would be good is if we could&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;provide services to a validation attribute that could be used in the process of validation&lt;/li&gt;
&lt;li&gt;Not have to explicitly resolve services from the container &lt;span class="st"&gt;&amp;agrave; la&lt;/span&gt; &lt;a class="external" title="Mark Seeman's opinion of why Service Locator is an anti-pattern" href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" target="_blank"&gt;the Service Locator (Anti-)Pattern&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;!--more--&gt;
&lt;h2&gt;What the framework giveth...&lt;/h2&gt;
&lt;p class="title"&gt;By default, the MVC framework uses the &lt;a class="external" title="MSDN documentation on DataAnnotationsModelValidator" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelvalidator.aspx" target="_blank"&gt;DataAnnotationsModelValidator&lt;/a&gt; to provide a ValidationContext and Model object to a Validation attribute:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 *
 * This software is subject to the Microsoft Public License (Ms-PL). 
 * A copy of the license can be found in the license.htm file included 
 * in this distribution.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/
 
namespace System.Web.Mvc {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
 
    public class DataAnnotationsModelValidator : ModelValidator {
        public DataAnnotationsModelValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
            : base(metadata, context) {
 
            if (attribute == null) {
                throw new ArgumentNullException("attribute");
            }
 
            Attribute = attribute;
        }
 
        protected internal ValidationAttribute Attribute { get; private set; }
 
        protected internal string ErrorMessage {
            get {
                return Attribute.FormatErrorMessage(Metadata.GetDisplayName());
            }
        }
 
        public override bool IsRequired {
            get {
                return Attribute is RequiredAttribute;
            }
        }
 
        internal static ModelValidator Create(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute) {
            return new DataAnnotationsModelValidator(metadata, context, attribute);
        }
 
        public override IEnumerable&amp;lt;ModelClientValidationRule&amp;gt; GetClientValidationRules() {
            IEnumerable&amp;lt;ModelClientValidationRule&amp;gt; results = base.GetClientValidationRules();
 
            IClientValidatable clientValidatable = Attribute as IClientValidatable;
            if (clientValidatable != null) {
                results = results.Concat(clientValidatable.GetClientValidationRules(Metadata, ControllerContext));
            }
 
            return results;
        }
 
        public override IEnumerable&amp;lt;ModelValidationResult&amp;gt; Validate(object container) {
            // Per the WCF RIA Services team, instance can never be null (if you have
            // no parent, you pass yourself for the "instance" parameter).
            ValidationContext context = new ValidationContext(container ?? Metadata.Model, null, null);
            context.DisplayName = Metadata.GetDisplayName();
 
            ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);
            if (result != ValidationResult.Success) {
                yield return new ModelValidationResult {
                    Message = result.ErrorMessage
                };
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;The Validate method creates a new ValidationContext instance and passes this, along with the model object to the Attribute via the &lt;code&gt;GetValidationResult(object, ValidationContext)&lt;/code&gt; method on the attribute. See those other null parameter arguments passed to the ValidationContext constructor? Those are for an &lt;a class="external" title="MSDN documentation on IServiceProvider" href="http://msdn.microsoft.com/en-us/library/system.iserviceprovider.aspx" target="_blank"&gt;IServiceProvider&lt;/a&gt; and &lt;code&gt;IDictionary&amp;lt;object, object&amp;gt;&lt;/code&gt;, respectively. The former is a contract for one method, &lt;code&gt;GetService(Type)&lt;/code&gt;, that takes a type and returns an object. On this basis, MVC provides a hook for being able to resolve services inside of a validation attribute, but that hook isn't used by default. Luckily, the default can be replaced with our own implementation.&lt;/p&gt;
&lt;h2&gt;A crude solution&lt;/h2&gt;
&lt;p&gt;Let's write our own ModelValidator. Using &lt;a class="external" title="Castle Windsor nuget package" href="http://nuget.org/List/Packages/Castle.Windsor" target="_blank"&gt;Castle Windsor IoC container&lt;/a&gt;, the &lt;a class="external" title="IKernel API documentation" href="http://www.castleproject.org/container/documentation/trunk/manual/mktypedocs/Generated_IKernel.html" target="_blank"&gt;IKernel&lt;/a&gt; implements IServiceProvider already, so we could go with something like this:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class WindsorModelValidator : DataAnnotationsModelValidator
{
    public IKernel Kernel { get; set; }

    public WindsorModelValidator(
        ModelMetadata metadata,
        ControllerContext context,
        ValidationAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable&amp;lt;ModelValidationResult&amp;gt; Validate(object container)
    {
        ValidationContext context = CreateValidationContext(container);

        ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);

        if (result != ValidationResult.Success)
        {
            yield return new ModelValidationResult
                {
                    Message = result.ErrorMessage
                };
        }
    }

    protected virtual ValidationContext CreateValidationContext(object container)
    {
        var context = new ValidationContext(container ?? Metadata.Model, Kernel, null);
        context.DisplayName = Metadata.GetDisplayName();
        return context;
    }
}
&lt;/pre&gt;
&lt;p&gt;Then in &lt;code&gt;Application_Start&lt;/code&gt;, register our &lt;code&gt;WindsorModelValidator&lt;/code&gt; with the container and hook it up to be used as the ModelValidator for the application:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;protected void Application_Start()
{
    // superfluous code here like route registration, etc...

    var container = new WindsorContainer();

    container.Register(AllTypes.FromThisAssembly()
                    .BasedOn&amp;lt;IController&amp;gt;()
                    .If(Component.IsInSameNamespaceAs&amp;lt;HomeController&amp;gt;())
                    .If(t =&amp;gt; t.Name.EndsWith("Controller"))
                    .Configure(c =&amp;gt; c.LifeStyle.Transient));


    container.Register(
        Component.For&amp;lt;ICategoryRepository&amp;gt;().ImplementedBy&amp;lt;CategoryRepository&amp;gt;(),
        Component.For&amp;lt;ModelValidator&amp;gt;().ImplementedBy&amp;lt;WindsorModelValidator&amp;gt;().LifeStyle.Transient);

    ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));

    // hook up our WindsorModelValidator here
    DataAnnotationsModelValidatorProvider.RegisterDefaultAdapterFactory(
         (metadata, context, attribute) =&amp;gt; container.Resolve&amp;lt;ModelValidator&amp;gt;(new { metadata, context, attribute }));
}
&lt;/pre&gt;
&lt;p&gt;Now, inside of validation attributes we can resolve services from the IServiceProvider (provided by the Kernel) on the ValidationContext:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class ValidCategoryAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "'{0}' does not contain a valid category";

    public ValidCategoryAttribute() : base(DefaultErrorMessage)
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var input = Convert.ToString(value, CultureInfo.CurrentCulture);

        // let the Required attribute take care of this validation
        if (string.IsNullOrWhiteSpace(input))
        {
            return null;
        }

        // resolve our ICategoryRepository using IServiceProvider on the ValidationContext
        var categories = validationContext.GetService(typeof(ISettingsRepository)) as ICategoryRepository;
 
        int categoryId;
        if (!int.TryParse(input, out categoryId))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
      
        return categories.Where(c =&amp;gt; c.Id == categoryId).FirstOrDefault() == null ? 
            new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : null;
    }
}
&lt;/pre&gt;
&lt;p&gt;This satisfies Point 1 above, but not Point 2. We don't want to have to explicitly get the service, we want it to be provided to us (i.e. &lt;a class="external" title="The Hollywood Principle Wikipedia article" href="http://en.wikipedia.org/wiki/Hollywood_Principle" target="_blank"&gt;the Hollywood Principle&lt;/a&gt;).&lt;/p&gt;
&lt;h2&gt;A better solution&lt;/h2&gt;
&lt;p&gt;Quite a while ago, &lt;a class="external" title="Jeremy Skinner's article on Dependency Injection with MVC Action Filters" href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/" target="_blank"&gt;Jeremy Skinner wrote an article about Dependency Injection with Action Filters&lt;/a&gt; where he created his own &lt;a class="external" title="MSDN documentation on IActionInvoker" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.iactioninvoker.aspx" target="_blank"&gt;IActionInvoker&lt;/a&gt; that could inject services into ActionFilter attributes. We can do something similar here for Validation attributes. Here is an improved WindsorModelValidator:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class WindsorModelValidator : DataAnnotationsModelValidator
{
    public IKernel Kernel { get; set; }

    public WindsorModelValidator(
        ModelMetadata metadata,
        ControllerContext context,
        ValidationAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable&amp;lt;ModelValidationResult&amp;gt; Validate(object container)
    {
        // inject the services from the container that
        // the Validation attribute requires
        Kernel.InjectProperties(Attribute);

        ValidationContext context = CreateValidationContext(container);

        ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);

        if (result != ValidationResult.Success)
        {
            yield return new ModelValidationResult
                {
                    Message = result.ErrorMessage
                };
        }
    }

    protected virtual ValidationContext CreateValidationContext(object container)
    {
        var context = new ValidationContext(container ?? Metadata.Model, Kernel, null);
        context.DisplayName = Metadata.GetDisplayName();
        return context;
    }
}
&lt;/pre&gt;
&lt;p&gt;Keeping the registration in &lt;code&gt;Application_Start&lt;/code&gt; the same as before, we can now write our &lt;code&gt;ValidCategoryAttribute&lt;/code&gt; like so:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class ValidCategoryAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "{0} is not a valid category";

    public ValidCategoryAttribute() : base(DefaultErrorMessage)
    {
    }

    public ICategoryRepository Categories { get; set; }

    public override bool IsValid(object value)
    {
        var input = Convert.ToString(value, CultureInfo.CurrentCulture);

        // let the Required attribute take care of this validation
        if (string.IsNullOrWhiteSpace(input))
        {
            return null;
        }

        int categoryId;
        if (!int.TryParse(input, out categoryId))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
      
        return Categories.Where(c =&amp;gt; c.Id == categoryId).FirstOrDefault() == null ? 
            new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : null;
    }
}
&lt;/pre&gt;
&lt;p&gt;Much cleaner, yes? The &lt;a class="external" title="InjectProperties extension method for IKernel" href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/" target="_blank"&gt;InjectProperties extension method implementation can be found on Jeremy's blog&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Fri, 03 Aug 2012 10:14:04 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/resolving-ioc-container-services-for-validation-attributes-in-asp.net-mvc</guid></item><item><title>C# 5 asynchronous programming</title><link>http://forloop.co.uk:80/blog/c-sharp-5-asynchronous-programming</link><description>&lt;p&gt;If you missed Anders Hejlsberg talk on the &lt;a target="_blank" href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T"&gt;Future directions for C# and Visual Basic&lt;/a&gt;, go check it out now, I&amp;rsquo;ll wait.&lt;/p&gt;
&lt;p&gt;&lt;iframe src="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-816T/player?w=670&amp;amp;h=410" frameborder="0" height="410" scrolling="no" width="670"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;!--more--&gt;
&lt;p&gt;I hope you'll agree that asynchronous programming just got a whole lot easier to do. The point that Anders made that really cemented in my mind how the new &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt; C# keywords work in practice was this:&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:65945caa-edb0-4595-ba65-140a800690f4" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;public async Task&amp;lt;XElement&amp;gt; GetXmlAsync(string url)
{
    var client = new HttpClient();
    var response = await client.GetAsync(url);
    var text = response.Content.ReadAsString();
    return XElement.Parse(text);
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;which is effectively translated to the following&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:cb50fd66-29c7-4b5d-ba87-0079f069764d" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: c#;"&gt;public Task&amp;lt;XElement&amp;gt; GetXmlAsync(string url)
{
    var tcs = TaskCompletionSource&amp;lt;XElement&amp;gt;();
    var client = new HttpClient();
    client.GetAsync(url).ContinueWith(task =&amp;gt;
        {
            var response = task.Result;
            var text = response.Content.ReadAsString();
            tcs.SetResult(XElement.Parse(text));
        });

    return tcs.Task;
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Something about this feels particularly familiar. If you&amp;rsquo;ve written any type of web application that utilizes AJAX, writing callback functions in JavaScript (or more likely, using a JavaScript library) happens all over the place. You know that when you see this&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:9f48164f-bbb4-470d-9ccd-75d6bb791c68" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;function updatePerson() {
  var returnedMessage;

  $.ajax({
     type: "POST",
     url: "people/update/2",
     data: { firstName : 'John', secondName : 'Smith'  },
     success: function(msg){
       returnedMessage = msg;
     }
   });

  return returnedMessage;
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;that &lt;code&gt;returnedMessage&lt;/code&gt; will be &lt;code&gt;undefined&lt;/code&gt; until the request made via AJAX returns and &lt;code&gt;returnedMessage&lt;/code&gt; is set to the value of &lt;code&gt;msg&lt;/code&gt;&amp;nbsp; returned from the server. This is a common mistake that people make when first using JavaScript to make AJAX requests and may have been some of the impetus behind the introduction of &lt;a class="external" title="jQuery Deferred Object" href="http://api.jquery.com/category/deferred-object/" target="_blank"&gt;&lt;code&gt;$.Deferred()&lt;/code&gt;&lt;/a&gt; in jQuery 1.5. If you wanted the above to work as intended and perhaps be a little clearer, you could rewrite it as&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:6f4782ee-2807-4190-8007-3c8082bd77da" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;function updatePerson() {
  return $.ajax({
     type: "POST",
     url: "/people/update/2",
      data: { firstName : 'John', secondName : 'Smith' }
   }).promise();
}

updatePerson().done(function(msg) {
   // do something with msg
});&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This returns a &lt;code&gt;&lt;a class="external" title="jQuery's Deferred Promise" href="http://api.jquery.com/deferred.promise/" target="_blank"&gt;promise&lt;/a&gt;&lt;/code&gt; that provides a view onto the current state of the task and allows the addition of further callbacks. Here&amp;rsquo;s a demo from jsfiddle:&lt;/p&gt;
&lt;p&gt;&lt;iframe src="http://jsfiddle.net/forloop/up9r4/1/embedded/" height="300" width="600"&gt;&lt;/iframe&gt;&lt;/p&gt;
&lt;p&gt;&lt;a class="external" title="Wikipedia article on Continuation Passing Style" href="http://en.wikipedia.org/wiki/Continuation-passing_style" target="_blank"&gt;Continuation Passing Style&lt;/a&gt;, as it is known, is not a new topic and is one that is most familiar to those engrossed in functional programming languages. If you want to read more about it, &lt;a class="external" title="Eric Lippert on Continuation Passing Style" href="http://blogs.msdn.com/b/ericlippert/archive/2010/10/21/continuation-passing-style-revisited-part-one.aspx" target="_blank"&gt;Eric Lippert wrote a great series of posts on the subject&lt;/a&gt; some time ago and if you&amp;rsquo;re interested in knowing more about how the new C#5 asynchronous programming works under the hood, go check out &lt;a class="external" href="http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx" target="_blank"&gt;Jon Skeet&amp;rsquo;s Eduasync&lt;/a&gt; series. Understanding these well now will mean that one will be able to put them to good use as soon as they&amp;rsquo;re officially released to market.&lt;/p&gt;</description><pubDate>Fri, 03 Aug 2012 10:07:00 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/c-sharp-5-asynchronous-programming</guid></item><item><title>Event Messaging on the client side with jQuery</title><link>http://forloop.co.uk:80/blog/event-messaging-in-client-side-script-with-jquery</link><description>&lt;p&gt;&lt;img src="/Media/Default/BlogPost/blog/event-messaging-in-client-side-script-with-jquery/events.png" alt="event tickets" align="absmiddle" /&gt;&lt;/p&gt;
&lt;p&gt;How many times have you come across the following kind of code in JavaScript&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:64f1aeba-22ff-44f3-96a1-ebbcc6d5ac36" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;// code in script-1.js

// eek, two global variables!
var dialog, 
    updateMessage = function updateMessage (message) {        
      dialog.text(message);    
    }

// function to run when the DOM has loaded
$(function () {
    // #dialog is just a simple &amp;lt;p&amp;gt; element
    dialog = $('#dialog');
});

&lt;/pre&gt;
&lt;/div&gt;
&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;then in another script file&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:f6038fa1-2088-40ae-850f-c492bf013aab" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;// code in script-2.js

// function to run when the DOM has loaded
$(function () {
    $('select').change(function () {
        // update the dialog with the new selection
        updateMessage('the new value is ' + this.value);
    });
});&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;All we&amp;rsquo;re doing here is updating the text of a &amp;lt;p&amp;gt; element in the DOM whenever the value of a &amp;lt;select&amp;gt; element changes. It&amp;rsquo;s a contrived and trivial example but it perfectly demonstrates the tight coupling between these two script files; if the &lt;code&gt;updateMessage&lt;/code&gt; function is renamed, removed or modified to reorder the parameters (let&amp;rsquo;s put aside the use of arguments for a moment), this is going to break script-2 at runtime. What&amp;rsquo;s more, usually with these kinds of changes, it&amp;rsquo;s too easy to forget to search through all script and markup-related files for function usages and modify accordingly. And further still, it's polluted the global namespace with two additional variables (&lt;a title="15 JavaScript Development no nos" href="http://thejavascriptway.com/posts/4-15-javascript-development-no-nos" target="_blank"&gt;a big no no in JavaScript development&lt;/a&gt;), &lt;code&gt;dialog&lt;/code&gt; and &lt;code&gt;updateMessage&lt;/code&gt;, to allow script-2 access to the updateMessage function (which needs access to the &lt;code&gt;dialog&lt;/code&gt; variable). There has to be a better way, and there is.&lt;/p&gt;
&lt;!--more--&gt;
&lt;h2&gt;Custom Events&lt;/h2&gt;
&lt;p&gt;Custom events have been in jQuery core for as long as I can remember, at least back as far as 1.2.6 in 2008. They are similar to an &lt;strong&gt;event bus&lt;/strong&gt; for sending messages (read: objects) when something happens on the client side and subscribing to knowing when that something happens. Let&amp;rsquo;s look at a revised version of the previous code, using jQuery custom events&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:89a32cbd-bd73-4a5a-8d96-829ade476c17" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;// code in script-1.js

// function to run when the DOM has loaded
$(function () {
   // #dialog is just a simple &amp;lt;p&amp;gt; element
    var dialog  = $('#dialog');

    // bind a handler to the custom namespaced event "dialog.updateMessage"
    $(document).on('dialog.updateMessage',  function (e, message) {
        dialog.text(message);
    });
});&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;and now in script 2,&lt;/p&gt;
&lt;div style="margin: 0px; display: inline; float: none; padding: 0px;" id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:0e398414-5fae-4427-ba9f-c9b2914f8907" class="wlWriterEditableSmartContent"&gt;
&lt;pre class="brush: javascript;"&gt;// code in script-2.js

// function to run when the DOM has loaded
$(function () {
    $('select').change(function () {
        // raise the dialog.updateMessage and pass it a message
        $(document).triggerHandler('dialog.updateMessage', ['the new value is ' + this.value]);
    });
});&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;In script 1, we set up an event handler function on document to listen for the &lt;a title="Namespaced events in jQuery" href="http://docs.jquery.com/Namespaced_Events" target="_blank"&gt;namespaced event&lt;/a&gt; &lt;code&gt;&amp;lsquo;dialog.updateMessage&amp;rsquo;&lt;/code&gt;. This takes the event object, &lt;code&gt;e&lt;/code&gt;,&amp;nbsp; and an additional parameter, &lt;code&gt;message&lt;/code&gt;, which it uses to update the text of dialog. In script 2, we set up an event handler on &amp;lt;select&amp;gt; elements so that whenever the change event is raised, the &lt;code&gt;&amp;lsquo;dialog.updateMessage&amp;rsquo;&lt;/code&gt; event is triggered, passing in a string that includes the new values as the first item in an array of additional data arguments. The end result? See for yourselves (hit the play icon on the right of the jsfiddle window):&lt;/p&gt;
&lt;p&gt;&lt;br /&gt;&lt;iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/forloop/x3E8C/embedded/" allowfullscreen="allowfullscreen" frameborder="0"&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;Behaviourally, we can see no difference at all. From a development and maintenance point of view however we have kept our scripts loosely coupled and avoided any runtime errors that may occur from refactoring our code. We&amp;rsquo;ve also made it easier to extend our code and bind additional handler functions to events, something that can be particularly useful for implementing multiple callbacks. Granted, we can still make changes to the code that could cause things to cease functioning as expected, such as renaming the custom event in one location and not in others, but such a change will not throw an error as in the previous example, potentially halting execution of any JavaScript code that follows.&lt;/p&gt;</description><pubDate>Fri, 03 Aug 2012 10:06:13 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/event-messaging-in-client-side-script-with-jquery</guid></item><item><title>Implement Recaptcha properly in ASP.NET MVC</title><link>http://forloop.co.uk:80/blog/implement-recaptcha-properly-in-asp.net-mvc</link><description>&lt;p&gt;Love them or hate them, the humble &lt;a class="external" title="details of a CAPTCHA" href="http://en.wikipedia.org/wiki/CAPTCHA" target="_blank"&gt;CAPTCHA&lt;/a&gt; is a tried and trusted approach to mitigating spam content from infiltrating your beautifully crafted application and flooding it with adverts selling all kinds of nefarious goods. Whilst their effectiveness is debatable and the frustration that they bring about in some high, they are relatively simple to use and catch the bulk of user defined content one would want to filter from their site.&lt;/p&gt;
&lt;h2&gt;Recaptcha to the rescue&lt;/h2&gt;
&lt;p&gt;&lt;a class="external" title="ReCaptcha site" href="http://www.google.com/recaptcha" target="_blank"&gt;Recaptcha&lt;/a&gt; is pretty much the de-facto CAPTCHA implementation and using it helps in &lt;a title="learn more about how using ReCaptcha helps to preserve literature" href="http://www.google.com/recaptcha/learnmore" target="_blank"&gt;digitizing books&lt;/a&gt; too! A &lt;a class="external" title="ReCaptcha Nuget package" href="http://nuget.org/List/Packages/recaptcha" target="_blank"&gt;Nuget package&lt;/a&gt; is available that provides the ability to render a CAPTCHA and validate it. It's as simple to use as&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:ade4f740-989f-4ad3-8b44-8116d192f8af" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;@Html.GenerateCaptcha("id", "white")&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;where &amp;ldquo;id&amp;rdquo; is the id of the control to generate and &amp;ldquo;white&amp;rdquo; is the theme colour to use. This will render code in the response that results in the following displayed in the browser:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://forloop.co.uk/Media/Default/Windows-Live-Writer/Implement-Recaptcha-properly-in-.NET-MVC_6F/captcha-example_2.png"&gt;&lt;img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="A CAPTCHA example" src="http://forloop.co.uk/Media/Default/Windows-Live-Writer/Implement-Recaptcha-properly-in-.NET-MVC_6F/captcha-example_thumb.png" alt="A CAPTCHA example" border="0" height="103" width="244" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If this is rendered inside of a &lt;code&gt;&amp;lt;form&amp;gt;&lt;/code&gt; element, two additional values are posted back to the server; a value keyed against the name &amp;ldquo;&lt;strong&gt;recaptcha_challenge_field&lt;/strong&gt;&amp;rdquo; which is an identifier for the CAPTCHA served to the user and a value keyed against the name "&lt;strong&gt;recaptcha_response_field&lt;/strong&gt;" which holds the value that the user entered. These values can be used to validate the user response and are nicely wrapped up&amp;nbsp; for us in an &lt;code&gt;ActionFilterAttribute&lt;/code&gt;:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:5c3eaa28-f709-41d5-bd7e-c8839cd425d4" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public class CaptchaValidatorAttribute : ActionFilterAttribute
{
    private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
    private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
    private RecaptchaResponse recaptchaResponse;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        RecaptchaValidator recaptchaValidator = new RecaptchaValidator();
        recaptchaValidator.PrivateKey = RecaptchaControlMvc.PrivateKey;
        recaptchaValidator.RemoteIP = filterContext.HttpContext.Request.UserHostAddress;
        recaptchaValidator.Challenge = filterContext.HttpContext.Request.Form["recaptcha_challenge_field"];
        recaptchaValidator.Response = filterContext.HttpContext.Request.Form["recaptcha_response_field"];
        this.recaptchaResponse = !string.IsNullOrEmpty(recaptchaValidator.Challenge) ? (!string.IsNullOrEmpty(recaptchaValidator.Response) ? recaptchaValidator.Validate() : RecaptchaResponse.InvalidResponse) : RecaptchaResponse.InvalidChallenge;
        filterContext.ActionParameters["captchaValid"] = (object)(bool)(this.recaptchaResponse.IsValid ? 1 : 0);
        filterContext.ActionParameters["captchaErrorMessage"] = (object)this.recaptchaResponse.ErrorMessage;
        base.OnActionExecuting(filterContext);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;We can see that we are given the response and an error message (if the response indicates that what the user entered is invalid or some other error, such as invalid keys) as Action parameters. We can supply two parameters with names matching &amp;ldquo;&lt;strong&gt;captchaValid&lt;/strong&gt;&amp;rdquo; and &amp;ldquo;&lt;strong&gt;captchaErrorMessage&lt;/strong&gt;&amp;rdquo; to our controller action to capture these values&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:7df4213b-2782-4e17-84a5-b2f66e404ad8" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: text;"&gt;public class DemoContoller : Controller
{
    [CaptchaValidator]
    public ActionResult Index(PostedModel model, bool captchaValid, string captchaErrorMessage)
    {
        if (!captchaValid)
        {
            // do something to indicate that the user entered the wrong reponse for the CAPTCHA
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;pretty neat and not a lot of effort on our part.&lt;/p&gt;
&lt;h2&gt;So what&amp;rsquo;s wrong?&lt;/h2&gt;
&lt;p&gt;The main problem with the ReCaptcha component as provided is that it will only render a CAPTCHA in response to a full HTTP request i.e. it won&amp;rsquo;t render a CAPTCHA in the response to a request made with &lt;a href="http://adaptivepath.com/ideas/ajax-new-approach-web-applications" target="_blank"&gt;AJAX&lt;/a&gt;. If you look deep down in the code the ReCaptcha &lt;code&gt;HtmlHelper&lt;/code&gt; extension method generates, it renders a &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; element that makes a request and returns a block of JavaScript used to render the CAPTCHA and provide various settings. The script response looks like so&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:edada0d4-bcc1-4537-b771-f9af6379b4ca" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: javascript;"&gt;var RecaptchaState = {
site : '****************************************',
challenge : '03AHJ_VuuAojIMHVd4xlTwTqaPxlDDTHu7dI-GNpOnNMsn9-6QUCtPnDs00KcEUmllKVC8aTM8QnVqczDLB3MxR7QdJSB7GZ45C1vWUz8K9RUczrww4FzAAkpZ8BjbJeKG_-UDusddk-gkJL1NG-b9RurjTDKXmXmtaw',
is_incorrect : false,
programming_error : '',
error_message : '',
server : 'http://www.google.com/recaptcha/api/',
timeout : 18000
};

document.write('&amp;lt;scr'+'ipt type="text/javascript" s'+'rc="' + RecaptchaState.server + 'js/recaptcha.js"&amp;gt;&amp;lt;/scr'+'ipt&amp;gt;'); &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;See the problem? No, it&amp;rsquo;s not the site id that has been masked, it&amp;rsquo;s that &lt;code&gt;document.write()&lt;/code&gt; call made to write another &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; element into the document. I would highly recommend avoiding &lt;code&gt;document.write()&lt;/code&gt; as it can produce different outcomes depending on when it is called. But don&amp;rsquo;t take my word for it, here&amp;rsquo;s what &lt;a class="external" href="http://javascript.crockford.com/script.html" target="_blank"&gt;Doug Crockford&lt;/a&gt; has to say about it:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;document.write&lt;/code&gt; method provides a way of incorporating strings into the HTML content of the page. There are better ways to do that, such as &lt;code&gt;.innerHTML&lt;/code&gt; and &lt;code&gt;.createElement&lt;/code&gt; or HTML cloning patterns. Use of &lt;code&gt;document.write&lt;/code&gt; should be avoided.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;document.write&lt;/code&gt; is recklessly dependent on timing. If &lt;code&gt;document.write&lt;/code&gt; is called before the &lt;code&gt;onload&lt;/code&gt; event, it appends or inserts text into the page. If it is called after &lt;code&gt;onload&lt;/code&gt;, it completely replaces the page, destroying what came before.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;document.write&lt;/code&gt; encourages bad structure, in which script and markup are intermingled. A cleaner structure has minimal interaction between markup and script.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In this case, the &lt;code&gt;document.write()&lt;/code&gt; does not cause the script to be written into the page, whose contents contain the markup to render the CAPTCHA*.&lt;/p&gt;
&lt;h2&gt;ReCaptcha, Refined&lt;/h2&gt;
&lt;p&gt;Here is an improved implementation of the ReCaptcha component that will work no matter how the request has been made:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:9889f3bc-40dc-4078-bafb-b3a972276eaf" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public static class HtmlHelperExtensions
{
    /// &amp;lt;summary&amp;gt;
    /// Renders a ReCaptcha to validate that the user is human
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="helper"&amp;gt;The helper.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="id"&amp;gt;The id.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;an &amp;lt;see cref="IHtmlString"/&amp;gt; containing the recaptcha&amp;lt;/returns&amp;gt;
    public static IHtmlString Captcha(this HtmlHelper helper, string id)
    {
        return Captcha(helper, id, "white");
    }

    /// &amp;lt;summary&amp;gt;
    /// Renders a ReCaptcha to validate that the user is human
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="helper"&amp;gt;The helper.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="id"&amp;gt;The id.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="theme"&amp;gt;The theme.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;an &amp;lt;see cref="IHtmlString"/&amp;gt; containing the recaptcha&amp;lt;/returns&amp;gt;
    public static IHtmlString Captcha(this HtmlHelper helper, string id, string theme)
    {
        string captcha;

        // we can't use the standard Captcha if injecting via an AJAX request so 
        // we need to use the AJAX one instead
        if (helper.ViewContext.HttpContext.Request.IsAjaxRequest())
        {
            var builder = new StringBuilder();
            builder.AppendLine("&amp;lt;div id=\"" + id + "\"&amp;gt;&amp;lt;/div&amp;gt;");
            builder.AppendLine("&amp;lt;script type=\"text/javascript\" src=\"http://www.google.com/recaptcha/api/js/recaptcha_ajax.js\"&amp;gt;&amp;lt;/script&amp;gt;");
            builder.AppendLine("&amp;lt;script type=\"text/javascript\"&amp;gt;");        
            builder.AppendLine("(function() { ");
            builder.AppendLine("var recaptcha_load = setInterval(function() { ");
            builder.AppendLine("if (Recaptcha != undefined) {"); 
            builder.AppendLine("clearInterval(recaptcha_load); Recaptcha.create('" + RecaptchaControlMvc.PublicKey + "', '" + id + "', {");
            builder.AppendLine("theme: '" + theme + "',");
            builder.AppendLine("callback: Recaptcha.focus_response_field");
            builder.AppendLine("}); } }, 10); })();");
            builder.AppendLine("&amp;lt;/script&amp;gt;");

            captcha = builder.ToString();
        }
        else
        {
            captcha = helper.GenerateCaptcha(id, theme);
        }
        
        return new HtmlString(captcha);
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;If the request has been made with AJAX, the response returns a &amp;lt;div&amp;gt; element with an id matching the one supplied and two &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; elements; the first &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; element will get JavaScript code that can be used to create a CAPTCHA on the client side, the second &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; element renders code that waits until the first script has been executed (using the global &lt;code&gt;&lt;a class="external" href="https://developer.mozilla.org/en/window.setInterval"&gt;setInterval&lt;/a&gt;&lt;/code&gt; function) and then creates a CAPTCHA on the client side in the defined &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; element. If the request hasn&amp;rsquo;t been made with AJAX, the ReCaptcha&amp;rsquo;s &lt;code&gt;GenerateCaptcha&lt;/code&gt; method is called as before. The end result is that a CAPTCHA is rendered no matter how a request is made.&lt;/p&gt;
&lt;h2&gt;Cleaning up Validation&lt;/h2&gt;
&lt;p&gt;I&amp;rsquo;m not too keen on having to specify two additional parameters for an action method that is going to be called including ReCaptcha data. I&amp;rsquo;d prefer to use &lt;code&gt;ModelState &lt;/code&gt;as is used for model property binding and validation, so here is an ActionFilter attribute that allows us to use that:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:37ce8dc5-8fe8-47b2-86b8-80d4d5241527" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public sealed class ValidateCaptchaAttribute : ActionFilterAttribute
{
    private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
    private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";

    public override void OnActionExecuting(ActionExecutingContext filterContext)  
    {  
        var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY];  
        var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY];  
        var captchaValidator = new RecaptchaValidator  
                                  {
                                      PrivateKey = RecaptchaControlMvc.PrivateKey,  
                                      RemoteIP = filterContext.HttpContext.Request.UserHostAddress,  
                                      Challenge = captchaChallengeValue,  
                                      Response = captchaResponseValue  
                                  };  
  
        var recaptchaResponse = captchaValidator.Validate();  
  
        if (!recaptchaResponse.IsValid)
        {
            filterContext.Controller.ViewData.ModelState.AddModelError("recaptcha", ValidationResources.InvalidRecaptcha);
        }
  
        base.OnActionExecuting(filterContext);  
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Now we just need to assess whether &lt;code&gt;ModelState&lt;/code&gt; is valid in our controller action:&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:51a0db7c-0673-4924-9618-6e7d363d9913" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;public class DemoContoller : Controller
{
    [ValidateCaptcha]
    public ActionResult Index(PostedModel model)
    {
        if (!ModelState.IsValid)
        {
            // send the user back to the view
           return View(model);
        }
    }
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;We could optionally render a validation message next to the ReCaptcha too using the model key &amp;ldquo;&lt;strong&gt;recaptcha&lt;/strong&gt;&amp;rdquo;&lt;/p&gt;
&lt;div id="scid:f32c3428-b7e9-4f15-a8ea-c502c7ff2e88:0c8ea710-4f27-4d51-9f81-12d090e23330" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;"&gt;
&lt;pre class="brush: c#;"&gt;@Html.ValidationMessage("recaptcha")
@Html.Captcha("recaptcha")&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;span style="font-size: xx-small;"&gt;Hope this helps!&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;span style="font-size: xx-small;"&gt;* My testing has been with jQuery to make an AJAX request to return html that contains the markup rendered by the Captcha HtmlHelper. Looking through &lt;/span&gt;&lt;/em&gt;&lt;a title="jQuery 1.6.1 source code" href="http://code.jquery.com/jquery-1.6.js" target="_blank"&gt;&lt;em&gt;&lt;span style="font-size: xx-small;"&gt;jQuery 1.6.1 source code&lt;/span&gt;&lt;/em&gt;&lt;/a&gt;&lt;em&gt;&lt;span style="font-size: xx-small;"&gt;, I can see nothing special in there that would cause &lt;code&gt;document.write()&lt;/code&gt; to be sanitized in any way, so can only assume that the browser is simply ignoring it as a request is neither being made nor is the document replaced. If you know anything more, please leave a comment!&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 13:18:20 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/implement-recaptcha-properly-in-asp.net-mvc</guid></item><item><title>ASP.NET MVC Permanent 301 redirects for legacy routes</title><link>http://forloop.co.uk:80/blog/asp.net-mvc-permanent-301-redirects-for-legacy-routes</link><description>&lt;p&gt;Having a good url routing scheme is extremely important when developing an application. Urls should be &lt;a class="external" href="http://en.wikipedia.org/wiki/URL_normalization"&gt;canonical&lt;/a&gt; to aid in search engine optimization and &lt;a class="external" href="http://rickosborne.org/blog/2007/04/usability-vs-discoverability/"&gt;discoverable&lt;/a&gt; in order to aid users in learning where to find application functionality for particular tasks. But there are points in an applications lifecycle where one wishes to change the url routing scheme in order to employ a better one. In such instances, &lt;a class="external" href="http://en.wikipedia.org/wiki/URL_redirection"&gt;URL redirection&lt;/a&gt; can be used to preserve search engine rankings, user bookmarks to specific pages or to allow more than one URL to serve up the same content, as is the case when employing &lt;a class="external" href="http://en.wikipedia.org/wiki/URL_shortening"&gt;URL shortening&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;ASP.NET MVC has the &lt;a class="external" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.redirectresult.aspx#Y3"&gt;RedirectResult&lt;/a&gt; to perform a 302 temporarily moved redirection response from one URL to another, but it does not have any built in way to handle permanent "301 moved permanently" redirections. This is the topic of today's post.&lt;/p&gt;
&lt;h2&gt;Dude, Where's my Content?&lt;/h2&gt;
&lt;p&gt;Using an ActionResult to perform redirections works great for the &lt;a class="external" href="http://en.wikipedia.org/wiki/Post/Redirect/Get"&gt;Post-Redirect-Get pattern&lt;/a&gt; in conjunction with 302 temporary redirections, but doesn't fit particularly well for 301 permanent redirections. In the latter case, it would be better if we could let our routing handle this for us and not require a controller action in conjunction with a route as exists in the former case. For permanent redirections then, let's define a &lt;code&gt;LegacyRoute&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Represents a legacy route to a resource 
/// that has been superceded by a new route
/// &amp;lt;/summary&amp;gt;
public class LegacyRoute : Route
{
    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="LegacyRoute"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeHandler"&amp;gt;The route handler.&amp;lt;/param&amp;gt;
    public LegacyRoute(string url, IRouteHandler routeHandler)
        : base(url, routeHandler)
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="LegacyRoute"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="defaults"&amp;gt;The defaults.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeHandler"&amp;gt;The route handler.&amp;lt;/param&amp;gt;
    public LegacyRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
        : base(url, defaults, routeHandler)
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="LegacyRoute"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="defaults"&amp;gt;The defaults.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="constraints"&amp;gt;The constraints.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeHandler"&amp;gt;The route handler.&amp;lt;/param&amp;gt;
    public LegacyRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
        : base(url, defaults, constraints, routeHandler)
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="LegacyRoute"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The URL pattern for the route.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="defaults"&amp;gt;The values to use if the URL does not contain all the parameters.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="constraints"&amp;gt;A regular expression that specifies valid values for a URL parameter.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="dataTokens"&amp;gt;Custom values that are passed to the route handler, but which are not used to determine whether the route matches a specific URL pattern. These values are passed to the route handler, where they can be used for processing the request.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeHandler"&amp;gt;The object that processes requests for the route.&amp;lt;/param&amp;gt;
    public LegacyRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler)
        : base(url, defaults, constraints, dataTokens, routeHandler)
    {
    }

    /// &amp;lt;summary&amp;gt;
    /// Returns information about the URL that is associated with the route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="requestContext"&amp;gt;An object that encapsulates information about the requested route.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="values"&amp;gt;An object that contains the parameters for a route.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;
    /// An object that contains information about the URL that is associated with the route.
    /// &amp;lt;/returns&amp;gt;
    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        // legacy routes NEVER generate outbound URLs
        return null;
    }
}
&lt;/pre&gt;
&lt;p&gt;We inherit from &lt;a class="external" href="http://msdn.microsoft.com/en-us/library/system.web.routing.route.aspx"&gt;Route&lt;/a&gt; and override &lt;code&gt;GetVirtualPath&lt;/code&gt;, a method called when generating outbound URLs. Since we don't &lt;strong&gt;ever&lt;/strong&gt; want legacy routes to take part in outbound URL generation, we simply return &lt;code&gt;null&lt;/code&gt;. The plan is to register the legacy routes before other more generic routes, so we don't want legacy routes providing a match for a URL pattern over other routes.&lt;/p&gt;
&lt;p&gt;Now that we have a route class to use, an &lt;a class="external" href="http://msdn.microsoft.com/en-us/library/system.web.routing.iroutehandler.aspx"&gt;IRouteHandler&lt;/a&gt; is also needed to process the request for a URL pattern matched by a legacy route. Enter &lt;code&gt;LegacyRouteHandler&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Handles legacy routes
/// &amp;lt;/summary&amp;gt;
public class LegacyRouteHandler : IRouteHandler
{
    /// &amp;lt;summary&amp;gt;
    /// Gets or sets the route values.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;value&amp;gt;The route values.&amp;lt;/value&amp;gt;
    public RouteValueDictionary RouteValues { get; set; }

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="LegacyRouteHandler"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="routeValues"&amp;gt;the route values&amp;lt;/param&amp;gt;
    public LegacyRouteHandler(object routeValues)
    {
        RouteValues = new RouteValueDictionary(routeValues);
    }

    /// &amp;lt;summary&amp;gt;
    /// Provides the object that processes the request.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="requestContext"&amp;gt;An object that encapsulates information about the request.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;An object that processes the request.&amp;lt;/returns&amp;gt;
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var urlHelper = new UrlHelper(requestContext);
        var url = urlHelper.Action(null, RouteValues);

        var absoluteUrl = requestContext.HttpContext.Request.Url.Scheme + "://" +
                          requestContext.HttpContext.Request.Url.Authority + url;

        return new RedirectHandler(absoluteUrl);
    }
}
&lt;/pre&gt;
&lt;p&gt;When the &lt;code&gt;LegacyRouteHandler&lt;/code&gt; is instantiated, it is passed route values in the constructor. These will be used when &lt;code&gt;GetHttpHandler&lt;/code&gt; is called to construct the new URL that the old URL should be redirected to. An absolute URL (technically, URI) is constructed and passed to a &lt;code&gt;RedirectHandler&lt;/code&gt; which will be used to set the Location HTTP Header on the response. Whilst most web browsers will support a relative URI, &lt;a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30"&gt;RFC 2616&lt;/a&gt; mandates that the URI should be absolute. The &lt;code&gt;RedirectHandler&lt;/code&gt; looks like so:&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Handles requests with a 301 Moved Permanently response
/// &amp;lt;/summary&amp;gt;
public class RedirectHandler : IHttpHandler
{
    /// &amp;lt;summary&amp;gt;
    /// backing field for the redirect url
    /// &amp;lt;/summary&amp;gt;
    private readonly string _redirectUrl;

    /// &amp;lt;summary&amp;gt;
    /// Initializes a new instance of the &amp;lt;see cref="RedirectHandler"/&amp;gt; class.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="redirectUrl"&amp;gt;The redirect URL.&amp;lt;/param&amp;gt;
    public RedirectHandler(string redirectUrl)
    {
        _redirectUrl = redirectUrl;
    }

    /// &amp;lt;summary&amp;gt;
    /// Gets a value indicating whether another request
    /// can use the &amp;lt;see cref="T:System.Web.IHttpHandler"/&amp;gt; instance.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;value&amp;gt;&amp;lt;/value&amp;gt;
    /// &amp;lt;returns&amp;gt;returns false.&amp;lt;/returns&amp;gt;
    public bool IsReusable
    {
        get { return false; }
    }

    /// &amp;lt;summary&amp;gt;
    /// Processes the request.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="httpContext"&amp;gt;The HTTP context.&amp;lt;/param&amp;gt;
    public void ProcessRequest(HttpContext httpContext)
    {
        httpContext.Response.Clear();
        httpContext.Response.Status = "301 Moved Permanently";
        httpContext.Response.StatusCode = 301;
        httpContext.Response.AppendHeader("Location", _redirectUrl);
        httpContext.Response.Flush();
        httpContext.Response.End();
    }
}
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;RedirectHandler&lt;/code&gt; implements &lt;a class="external" href="http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx"&gt;IHttpHandler&lt;/a&gt;. When the &lt;code&gt;ProcessRequest&lt;/code&gt; method is called by the framework, the handler uses the absolute URL passed to it in the constructor to set the Location HTTP header on the response and returns a 301 HTTP status code with accompanying status message.&lt;/p&gt;
&lt;p&gt;With the classes defined above, one can start implementing redirections for legacy routes immediately using the following inside of &lt;code&gt;RegisterRoutes(RouteCollection routes)&lt;/code&gt; in Global.asax.cs&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;routes.Add(new LegacyRoute("old-route", new LegacyRouteHandler(new { controller = "Home", action = "Index", area = "" })));
&lt;/pre&gt;
&lt;p&gt;It's much cleaner to define some extension methods on &lt;code&gt;RouteCollection&lt;/code&gt; for mapping legacy routes instead:&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Houses extension methods for &amp;lt;see cref="RouteCollection"/&amp;gt;
/// &amp;lt;/summary&amp;gt;
public static class RouteCollectionExtensions
{
    /// &amp;lt;summary&amp;gt;
    /// Maps a legacy route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="routes"&amp;gt;The routes.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The old URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeValues"&amp;gt;The route values.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
    public static Route MapLegacyRoute(this RouteCollection routes, string url, object routeValues)
    {
        return MapLegacyRoute(routes, null, url, routeValues);
    }


    /// &amp;lt;summary&amp;gt;
    /// Maps a legacy route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="routes"&amp;gt;The routes.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="name"&amp;gt;The name.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The old URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeValues"&amp;gt;The route values.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;the &amp;lt;see cref="LegacyRoute"/&amp;gt; created&amp;lt;/returns&amp;gt;
    public static Route MapLegacyRoute(this RouteCollection routes, string name, string url, object routeValues)
    {
        if (routes == null)
        {
            throw new ArgumentNullException("routes");
        }

        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

        var route = new LegacyRoute(url, new LegacyRouteHandler(routeValues))
            {
                Defaults =  new RouteValueDictionary(routeValues),
                DataTokens = new RouteValueDictionary()             
            };

        routes.Add(name, route);

        return route;
    } 
}
&lt;/pre&gt;
&lt;p&gt;Now our RegisterRoutes method looks like&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // map the legacy route above the more generic Default route
        routes.MapLegacyRoute(null, "old-route", new { controller = "Home", action = "Index", area="" });

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", area="", id = UrlParameter.Optional }
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}
&lt;/pre&gt;
&lt;p&gt;The above will permanently redirect requests to &lt;code&gt;/old-route&lt;/code&gt; to &lt;code&gt;/Home/Index&lt;/code&gt; (well, in fact they would redirect to &lt;code&gt;/&lt;/code&gt; as the HomeController and Index action are the default values of the Default route).&lt;/p&gt;
&lt;h2&gt;What about Areas?&lt;/h2&gt;
&lt;p&gt;We can see above that areas get registered before &lt;code&gt;RegisterRoutes&lt;/code&gt; is called. This means that areas have the opportunity to register routes before the main application does. Since the order of routes in the application's &lt;a class="external" href="http://msdn.microsoft.com/en-us/library/system.web.routing.routetable.aspx"&gt;RouteTable&lt;/a&gt; is important for route matching (a top to bottom operation that stops as soon as a match is found), we would want to register any legacy routes for URLs that may be matched by generic routes registered by areas before those generic routes. The following &lt;a class="external"&gt;AreaRegistrationContext&lt;/a&gt; extension methods can be used for this purpose&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;/// &amp;lt;summary&amp;gt;
/// Houses extension methods for &amp;lt;see cref="AreaRegistrationContext"/&amp;gt;
/// &amp;lt;/summary&amp;gt;
public static class AreaRegistrationContextExtensions
{
    /// &amp;lt;summary&amp;gt;
    /// Maps a legacy route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="areaRegistrationContext"&amp;gt;The area registration context.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The old URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeValues"&amp;gt;The route values.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;the &amp;lt;see cref="LegacyRoute"/&amp;gt; created&amp;lt;/returns&amp;gt;
    public static Route MapLegacyRoute(this AreaRegistrationContext areaRegistrationContext, string url, object routeValues)
    {
        return MapLegacyRoute(areaRegistrationContext, null, url, routeValues);
    } 

    /// &amp;lt;summary&amp;gt;
    /// Maps a legacy route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="areaRegistrationContext"&amp;gt;The area registration context.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="name"&amp;gt;The name.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="url"&amp;gt;The old URL.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name="routeValues"&amp;gt;The route values.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;the &amp;lt;see cref="LegacyRoute"/&amp;gt; created&amp;lt;/returns&amp;gt;
    public static Route MapLegacyRoute(this AreaRegistrationContext areaRegistrationContext, string name, string url, object routeValues)
    {
        if (areaRegistrationContext == null)
        {
            throw new ArgumentNullException("areaRegistrationContext");
        }

        if (url == null)
        {
            throw new ArgumentNullException("url");
        }

        var route = areaRegistrationContext.Routes.MapLegacyRoute(name, url, routeValues);
        route.DataTokens["area"] = areaRegistrationContext.AreaName; 

        return route;
    } 
}
&lt;/pre&gt;
&lt;p&gt;As an example, inside of our application's Account area, we would now have&lt;/p&gt;
&lt;pre class="brush:c-sharp;"&gt;public class AccountAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Account";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapLegacyRoute("Account/Home/old-route", new { controller = "Home", action = "Index", area = "" });

        context.MapRoute(
            "Account_default",
            "Account/{controller}/{action}/{id}",
            new { controller="Home" , action = "Index", id = UrlParameter.Optional }
        );
    }
}
&lt;/pre&gt;
&lt;p&gt;The above will redirect the URL &lt;code&gt;/Account/Home/old-route&lt;/code&gt; to &lt;code&gt;/Home/Index&lt;/code&gt; (which, if using the routing in Global.asax.cs defined above would route to &lt;code&gt;/&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;If you're using &lt;a class="external" href="http://mvccontrib.codeplex.com/wikipage?title=T4MVC"&gt;T4MVC&lt;/a&gt; (which I highly recommend you do) then you can replace all of the magic string properties with the generated class properties inside of the anonymous objects passed as route values in &lt;code&gt;MapLegacyRoute&lt;/code&gt;. One could go even further and define extension methods that take an ActionResult instead of a route values object, much like the way T4MVC overloads the common HtmlHelper methods.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 13:17:51 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/asp.net-mvc-permanent-301-redirects-for-legacy-routes</guid></item><item><title>ASP.NET MVC 3  IMetadataAware and custom ModelMetadata attributes</title><link>http://forloop.co.uk:80/blog/asp.net-mvc-3-imetadataaware-and-custom-modelmetadata-attributes</link><description>&lt;blockquote&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; I've added a simple&lt;a class="external" title="Simple Example project" href="https://bitbucket.org/forloop/colorpickerattributeexample/overview" target="_blank"&gt; example project up on bitbucket&lt;/a&gt; to demonstrate the ColorPicker attribute&lt;/blockquote&gt;
&lt;p&gt;ASP.NET MVC 3 introduces a new interface, &lt;a class="external" title="IMetadataAware MSDN documentation" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imetadataaware%28v=vs.98%29.aspx" target="_blank"&gt;IMetadataAware&lt;/a&gt;, for providing additional values to the model metadata at creation time:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 *
 * This software is subject to the Microsoft Public License (Ms-PL). 
 * A copy of the license can be found in the license.htm file included 
 * in this distribution.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

namespace System.Web.Mvc {
    // This interface is implemented by attributes which wish to contribute to the
    // ModelMetadata creation process without needing to write a custom metadata
    // provider. It is consumed by AssociatedMetadataProvider, so this behavior is
    // automatically inherited by all classes which derive from it (notably, the
    // DataAnnotationsModelMetadataProvider).
    public interface IMetadataAware {
        void OnMetadataCreated(ModelMetadata metadata);
    }
}&lt;/pre&gt;
&lt;p&gt;The default ModelMetadataProvider, &lt;a class="external" title="DataAnnotationsModelMetadataProvider MSDN documentation" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelmetadataprovider.aspx" target="_blank"&gt;DataAnnotationsModelMetadataProvider&lt;/a&gt;, derives from &lt;a class="external" title="AssociatedMetadataProvider MSDN documentation" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.associatedmetadataprovider.aspx" target="_blank"&gt;AssociatedMetadataProvider&lt;/a&gt;, which, after creating the metadata for a type or type property, runs through all of the IMetadataAware types (i.e. attributes) applied to the type or property type, passing it the created metadata and allowing each IMetadataAware type to add additional values to the metadata. This is a nice change in MVC 3 as it means that you no longer need to write your own ModelMetadataProvider deriving from DataAnnotationsModelMetadataProvider to add in this functionality as you needed to in MVC 2.&lt;/p&gt;
&lt;p&gt;The framework uses this new interface for two new model metadata attributes, AllowHtmlAttribute and AdditionalMetadataAttribute; AllowHtmlAttribute can be applied to a property to prevent that property from going through request validation, which can be very handy if you are receiving HTML or XML from the client and only want to white-list certain model/viewmodel properties to prevent request validation from being applied to them. AdditionalMetadataAttribute does pretty much what it's name implies; that is to allow you to add additional values to the modelmetadata's additional values dictionary.&lt;/p&gt;
&lt;h2&gt;Creating a custom ColourPicker ModelMetadataAttribute&lt;/h2&gt;
&lt;p&gt;We're going to look at creating our own jQuery ColourPicker ModelMetadata attribute using the IMetadataAware interface. This will allow us to attribute our model / viewmodel property and automagically hook up a jQuery colour picker to the text box in the rendered view. For this, I'll be using the &lt;a class="external" title="Stefan Petre's ColorPicker plugin" href="http://www.eyecon.ro/colorpicker/#about" target="_blank"&gt;awesome colorpicker plugin by Stefan Petre&lt;/a&gt;. Note that I will be using the american spelling of colour to align with the script :)&lt;/p&gt;
&lt;p&gt;First off, the ColorPickerAttribute&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class ColorPickerAttribute : Attribute, IMetadataAware
{
    private const string Template =
        "$('#{0}').ColorPicker({{onSubmit: function(hsb, hex, rgb, el) {{" + 
        "var self = $(el); self.val(hex);self.ColorPickerHide();}}, onBeforeShow: function () " + 
        "{{$(this).ColorPickerSetColor(this.value);}}}}).bind('keyup', function(){{ $(this).ColorPickerSetColor(this.value); }});";
        
    public const string ColorPicker = "_ColorPicker";

    private int _count;

    // if using IoC container, you could inject this into the attribute
    internal HttpContextBase Context
    {
        get { return new HttpContextWrapper(HttpContext.Current); }
    }

    public string Id
    {
        get { return "jquery-colorpicker-" + _count;  }
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        var list = Context.Items["Scripts"] as IList&amp;lt;string&amp;gt; ?? new List&amp;lt;string&amp;gt;();
        _count = list.Count;

        metadata.TemplateHint = ColorPicker;
        metadata.AdditionalValues[ColorPicker] = Id;

        list.Add(string.Format(CultureInfo.InvariantCulture, Template, Id));

        Context.Items["Scripts"] = list;
    }
}
&lt;/pre&gt;
&lt;p&gt;Now let's say we have a simple controller:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new HomeModel());
    }

}
&lt;/pre&gt;
&lt;p&gt;and view model:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public class HomeModel
{
    [ColorPicker]
    public string ColorPicker { get; set; }
}
&lt;/pre&gt;
&lt;p&gt;In order to get this all hooked up, we're going to use an EditorTemplate named _ColorPicker.cshtml:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;@model System.String

@{ var picker = ViewData.GetModelAttribute&amp;lt;ColorPickerAttribute&amp;gt;(); 
   if (picker != null) {  
      @Html.LabelForModel()
      @Html.TextBoxFor(m =&amp;gt; m, new { id = ViewData.ModelMetadata.AdditionalValues[ColorPickerAttribute.ColorPicker] }) 
   }
}
&lt;/pre&gt;
&lt;p&gt;&lt;a class="external" title="Quick tips about editor templates by Nuno Silva" href="http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx" target="_blank"&gt;EditorTemplates&lt;/a&gt; should be put in a location where they will be accessible to the corresponding view engine. In this example, the _ColorPicker razor partial view is in Views/Shared/EditorTemplates. The template uses an extension method on ViewDataDictionary, GetModelAttribute to keep the view clean and allow us to get an attribute of a particular type back. The extension method is defined as so:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public static class ViewDataDictionaryExtensions
{
    public static TAttribute GetModelAttribute&amp;lt;TAttribute&amp;gt;(this ViewDataDictionary viewData, bool inherit = false) where TAttribute : Attribute
    {
        if (viewData == null) throw new ArgumentNullException("viewData");

        var containerType = viewData.ModelMetadata.ContainerType;

        return ((TAttribute[])containerType.GetProperty(viewData.ModelMetadata.PropertyName)
                                            .GetCustomAttributes(typeof (TAttribute), inherit)).FirstOrDefault();
    }
}&lt;/pre&gt;
&lt;p&gt;To make this extension method available in the view, we need to add the namespace to the system.web.webPages.razor section (if using the razor view engine, which I assume you would be with MVC 3!) in the web.config that can be found in the Views folder:&lt;/p&gt;
&lt;pre class="brush:xml;"&gt;  
  &amp;lt;system.web.webPages.razor&amp;gt;
    &amp;lt;host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&amp;gt;
    &amp;lt;pages pageBaseType="System.Web.Mvc.WebViewPage"&amp;gt;
      &amp;lt;namespaces&amp;gt;
        &amp;lt;add namespace="Namespace.For.ViewDataDictionaryExtensions" /&amp;gt;
      &amp;lt;/namespaces&amp;gt;
    &amp;lt;/pages&amp;gt;
  &amp;lt;/system.web.webPages.razor&amp;gt;  
&lt;/pre&gt;
&lt;p&gt;And finally the view:&lt;/p&gt;
&lt;pre class="brush:csharp;&amp;gt; @model DatePickerAttributeDemo.Models.HomeModel  @{     ViewBag.Title = "&gt;&amp;lt;h2&amp;gt;Index&amp;lt;/h2&amp;gt;
@Html.EditorFor(m =&amp;gt; m.ColorPicker)
&lt;/pre&gt;
&lt;p&gt;And the _Layout that the view is using:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;@ViewBag.Title&amp;lt;/title&amp;gt;
    &amp;lt;link href="@Url.Content("~/Content/css/Site.css")" rel="stylesheet" type="text/css" /&amp;gt;
    &amp;lt;link href="@Url.Content("~/Content/css/colorpicker.css")" rel="stylesheet" type="text/css" /&amp;gt;
    &amp;lt;script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="@Url.Content("~/Scripts/colorpicker.js")" type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    @RenderBody()
    @Html.RenderScripts()
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;
&lt;p&gt;A HtmlHelper extension method runs after the body is rendered and this is responsible for writing out all of the scripts:&lt;/p&gt;
&lt;pre class="brush:csharp;"&gt;public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
    var scripts = htmlHelper.ViewContext.HttpContext.Items["Scripts"] as IList&amp;lt;string&amp;gt;;

    if (scripts != null)
    {
        var builder = new StringBuilder();

        builder.AppendLine("&amp;lt;script type='text/javascript'&amp;gt;");
        builder.AppendLine("$(function() {");
        foreach (var script in scripts)
        {
            builder.AppendLine(script);
        }
        builder.AppendLine("});");
        builder.AppendLine("&amp;lt;/script&amp;gt;");

        return new MvcHtmlString(builder.ToString());
    }
    return null;
}&lt;/pre&gt;
&lt;p&gt;The end result and markup are as follows:&lt;/p&gt;
&lt;p&gt;&lt;img style="vertical-align: middle;" src="/Media/Default/post-images/colorpicker.jpg" alt="colorpicker end result in browser" height="279" width="479" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;img style="vertical-align: middle;" src="/Media/Default/post-images/colorpicker-markup.jpg" alt="colorpicker end markup in browser" height="431" width="932" /&gt;&lt;/p&gt;
&lt;p&gt;Putting the script into HttpContext.Items means that we can write the script out at the very end of the view before the closing body tag, which works for when scripts are put in both the head section of the document or before the closing body tag (so long as the call to RenderScripts comes after any required scripts, such as jQuery and the colorpicker script in this case). It also plays well when you have partial views that have markup requiring client side script and can be used for other plugins too, such as &lt;a class="external" title="jQuery DatePicker documentation" href="http://jqueryui.com/demos/datepicker/" target="_blank"&gt;jQuery DatePicker&lt;/a&gt;.&lt;/p&gt;</description><pubDate>Sun, 30 Oct 2011 13:17:21 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/asp.net-mvc-3-imetadataaware-and-custom-modelmetadata-attributes</guid></item><item><title>Wrap child elements in groups in jQuery</title><link>http://forloop.co.uk:80/blog/wrap-child-elements-in-groups-in-jquery</link><description>&lt;p&gt;A while ago, I answered &lt;a class="external" title="StackOverflow - a software developer's best friend!" href="http://stackoverflow.com/questions/1400820/jquery-to-wrap-elements/1402333#1402333"&gt;a Stack Overflow question&lt;/a&gt; about how to wrap child elements matching some selector into groups of a specified size. I had a need for this again recently so I went back to the code, tidied it up and have come up with a slightly more refined plugin.&lt;/p&gt;
&lt;pre class="brush:js;"&gt;// Copyright (c) 2011 Russ Cam
// -------------------------------------------------------
// Dual licensed under the MIT and GPL licenses.
//   - http://www.opensource.org/licenses/mit-license
//   - http://www.opensource.org/licenses/gpl-3.0
(function($){
    $.fn.wrapChildren = function(options) {

        options = $.extend({
                              childElem : undefined,
                              groupSize : 1,
                              wrapper : '&amp;lt;div&amp;gt;'
                            }, options || {});
                            
        if (options.childElem === undefined) return this;

        return this.each(function() {
            var elems = $(this).children(),
                len = pos = 0;
            
            elems.each(function(i,value) {
                len += $(value).is(options.childElem)? 1 : 0;                    
                if (len &amp;gt; 0 &amp;amp;&amp;amp; (len % options.groupSize === 0) || (i === elems.length - 1)) {          
                  elems.slice(pos,i + 1).wrapAll(options.wrapper);
                  len = 0;
                  pos = i + 1;
                }
            });
        }); 
        
    }
})(jQuery);&lt;/pre&gt;
&lt;p&gt;You call the plugin on a matched set and pass it a selector for the child element you wish to group along with a number for how many of the matching child elements should be in a group and a string representing the element in which you wish to group them. Child elements that do not match the passed child element selector will be ignored and will be placed into a group that matches their contiguous position within the child elements.&lt;br /&gt;&lt;br /&gt;Take a look at &lt;a class="external" title="JS Fiddle is great for quickly playing with JavaScript" href="http://jsfiddle.net/russcam/ny33M/1/" target="_blank"&gt;an example up on js fiddle&lt;/a&gt;, or copy/paste the code below into a file and run locally. Hope this helps :)&lt;/p&gt;
&lt;pre class="brush:html;"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;title&amp;gt;wrapChildren Demo&amp;lt;/title&amp;gt;
&amp;lt;meta http-equiv="Content-type" content="text/html; charset=utf-8" /&amp;gt;
&amp;lt;style type="text/css" media="screen"&amp;gt;
	.wrapper { background-color: red; margin: 5px; }
&amp;lt;/style&amp;gt;
&amp;lt;script type="text/javascript"&amp;gt;
(function($){
    $.fn.wrapChildren = function(options) {

        options = $.extend({
                              childElem : undefined,
                              groupSize : 1,
                              wrapper : '&amp;lt;div&amp;gt;'
                            }, options || {});
                            
        if (options.childElem === undefined) return this;

        return this.each(function() {
            var elems = $(this).children(),
                len = pos = 0;
            
            elems.each(function(i,value) {
                len += $(value).is(options.childElem)? 1 : 0;                    
                if (len &amp;gt; 0 &amp;amp;&amp;amp; (len % options.groupSize === 0) || (i === elems.length - 1)) {          
                  elems.slice(pos,i + 1).wrapAll(options.wrapper);
                  len = 0;
                  pos = i + 1;
                }
            });
        }); 
        
    }
})(jQuery);
$(function() {
  $('div').wrapChildren({ childElem : 'a' , groupSize: 4, wrapper : '&amp;lt;div class="wrapper"&amp;gt;'});
});
&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
	&amp;lt;p&amp;gt;anchors wrapped in groups of 4 including non-matching child elements&amp;lt;/p&amp;gt;
	&amp;lt;div&amp;gt;
		&amp;lt;a href="#"&amp;gt;1&amp;lt;/a&amp;gt;
		&amp;lt;a href="#"&amp;gt;2&amp;lt;/a&amp;gt;
		&amp;lt;p&amp;gt;Child element that will be ignored&amp;lt;/p&amp;gt;
		&amp;lt;a href="#"&amp;gt;3&amp;lt;/a&amp;gt;
		&amp;lt;a href="#"&amp;gt;4&amp;lt;/a&amp;gt;
		&amp;lt;p&amp;gt;Another that will be ignored&amp;lt;/p&amp;gt;
		&amp;lt;a href="#"&amp;gt;5&amp;lt;/a&amp;gt;
		&amp;lt;a href="#"&amp;gt;6&amp;lt;/a&amp;gt;
		&amp;lt;a href="#"&amp;gt;7&amp;lt;/a&amp;gt;
		&amp;lt;p&amp;gt;Yet another that will be ignored&amp;lt;/p&amp;gt;
		&amp;lt;a href="#"&amp;gt;8&amp;lt;/a&amp;gt;
		&amp;lt;p&amp;gt;And another&amp;lt;/p&amp;gt;
		&amp;lt;a href="#"&amp;gt;9&amp;lt;/a&amp;gt;
		&amp;lt;a href="#"&amp;gt;10&amp;lt;/a&amp;gt;
	&amp;lt;/div&amp;gt;
	&amp;lt;br/&amp;gt;
	&amp;lt;p&amp;gt;anchors wrapped in groups of 4&amp;lt;/p&amp;gt;
	&amp;lt;div&amp;gt;
		 &amp;lt;a href="#"&amp;gt;1&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;2&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;3&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;4&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;5&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;6&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;7&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;8&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;9&amp;lt;/a&amp;gt;
		 &amp;lt;a href="#"&amp;gt;10&amp;lt;/a&amp;gt;
	 &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;</description><pubDate>Tue, 26 Jul 2011 22:33:09 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/wrap-child-elements-in-groups-in-jquery</guid></item><item><title>This Developer's Life</title><link>http://forloop.co.uk:80/blog/this-developers-life</link><description>&lt;p&gt;I'm probably a little late to the party on this one, but I have just started listening to &lt;a class="external" title="This Developer's Life - Stories about Developers and their lives" href="http://thisdeveloperslife.com/" target="_blank"&gt;This Developer's Life&lt;/a&gt;, a podcast presented by &lt;a class="external" title="Rob Conery - Co-Owner and founder of TekPub" href="http://blog.wekeroad.com/" target="_blank"&gt;Rob Conery&lt;/a&gt; and &lt;a class="external" title="Scott Hanselman - Microsoft Principal Program Manager" href="http://www.hanselman.com/blog/" target="_blank"&gt;Scott Hanselman&lt;/a&gt;. Each episode focuses on a particular topic in the realm of development and technology in general and involves interviews and stories from some of the most well known faces in the industry. There are some genuine legends, both past and more recent, shooting the breeze for our listening pleasure. These stories are interspersed with some great choices of music and short stories from the two presenters. I think there's something in there for everyone interested in technology and, like me, you'll probably find yourself relating to more than one of the topics brought up.&lt;/p&gt;
&lt;p&gt;In all, it makes for a slightly lighter and refreshing change to other technology-focused podcasts out there. &lt;a class="external" title="This Developer's Life - Stories about Developers and their lives" href="http://thisdeveloperslife.com/"&gt;Go listen now, if you haven't already&lt;/a&gt;! I highly recommend starting with the first episode that contains some of the funniest and also darkest stories so far.&lt;/p&gt;</description><pubDate>Tue, 26 Jul 2011 22:33:09 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/this-developers-life</guid></item><item><title>Event Internals in jQuery - Part One</title><link>http://forloop.co.uk:80/blog/event-internals-in-jquery-part-one</link><description>&lt;p&gt;I&amp;rsquo;ve been using &lt;a class="external" title="jQuery - the most awesome JavaScript library" href="http://jquery.com/" target="_blank"&gt;jQuery&lt;/a&gt; for a number of years now and  think it&amp;rsquo;s an awesome JavaScript library for providing a rich client  experience to web applications with little effort.&amp;nbsp; Whilst I advocate  the use of jQuery to quickly and effectively build your client side  solutions, I also think that it&amp;rsquo;s important to understand what&amp;rsquo;s going on  under the hood, particularly as it can help to quickly pinpoint a bug in your own code (and on the rarest of occasions, a bug in the library code).&lt;/p&gt;
&lt;p&gt;In a series of posts, I&amp;rsquo;m going to be peeking under the covers  of the jQuery event system. I&amp;rsquo;ve never seen a comprehensive write-up looking into the  internals of the event system before, so I thought that this might be a good topic to cover. This first post will provide a little background to browser based events and will look at the root event binding function in jQuery, &lt;code&gt;bind()&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Why have an event system?&lt;/h2&gt;
&lt;p&gt;You may be wondering, why does jQuery even need an event system at  all? After all, modern browsers have the ability to bind event handlers to  events raised in the DOM, don&amp;rsquo;t they? Whilst this is true, the event model  that each of the myriad of browsers uses to achieve this can be very  different indeed. The two main event models are so different in fact that, if you&amp;rsquo;re doing any cross  browser client side JavaScript programming, you end up writing an  abstraction yourself to smooth out these browser differences. The way that jQuery  achieves this is really quite elegant, but first a brief history lesson.&lt;/p&gt;
&lt;h2&gt;DOM Level 0 events&lt;/h2&gt;
&lt;p&gt;In the beginning, browsers had basic support for DOM events in the W3C DOM level 0 events (part of the &lt;a class="external" title="W3C DOM Level 1 Specification" href="http://www.w3.org/TR/WD-DOM/level-one-html-971209.html" target="_blank"&gt;DOM level 1 specification&lt;/a&gt;). With this event model, event handlers can be bound in two ways:&lt;/p&gt;
&lt;h3&gt;Inline&lt;/h3&gt;
&lt;pre class="brush:js;"&gt;&amp;lt;a href=&amp;rdquo;#&amp;rdquo; onclick=&amp;rdquo;alert(&amp;lsquo;hello world!&amp;rsquo;);return false;&amp;rdquo;&amp;gt;
    Clicking me will show an alert dialog box with the message &amp;lsquo;hello world!&amp;rsquo;
&amp;lt;/a&amp;gt;
&lt;/pre&gt;
&lt;p&gt;With event handlers inline, the browser creates an anonymous function  with the function body set to the contents of the string assigned to an  element&amp;rsquo;s event attribute value. Ultimately this results in a call to &lt;code&gt;window.eval()&lt;/code&gt; to evaluate the string and execute as JavaScript.&lt;/p&gt;
&lt;h3&gt;Setting the Attribute value&lt;/h3&gt;
&lt;pre class="brush:js;"&gt;&amp;lt;a id=&amp;rdquo;my-anchor&amp;rdquo; href=&amp;rdquo;#&amp;rdquo;&amp;gt; Clicking me will show an alert dialog box with the message &amp;lsquo;hello world!&amp;rsquo;&amp;lt;/a&amp;gt;
&amp;lt;script type=&amp;rdquo;text/javascript&amp;rdquo;&amp;gt;
    var a = document.getElementById(&amp;lsquo;my-anchor&amp;rsquo;);
    a.onclick = function() { alert(&amp;lsquo;hello world!&amp;rsquo;); return false; };
&amp;lt;/script&amp;gt;
&lt;/pre&gt;
&lt;p&gt;With an event attribute on the element set, the anonymous function needs to be bound to the element once it exists in the DOM.&lt;/p&gt;
&lt;p&gt;The DOM level 0 events are still the most widely supported across  browsers, however, they lack the ability to bind more than one event  handler to an event without jumping through hoops (defining an event  handler function that calls all of the event handler functions you want  to bind to the event) and binding events inline does little to promote &lt;a class="external" title="Unobtrusive JavaScript Wikipedia article" href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" target="_blank"&gt;Unobtrusive JavaScript&lt;/a&gt;, which strives for separation of content and behaviour.&lt;/p&gt;
&lt;h2&gt;DOM level 2 events (and Internet Explorer&amp;rsquo;s proprietary event model)&lt;/h2&gt;
&lt;p&gt;With the limitations of DOM level 0 events in mind, modern versions  of Mozilla, Opera, Safari, Chrome and Konqueror browsers use the  standard &lt;a class="external" title="W3C DOM Level 2 Events" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html" target="_blank"&gt;W3C DOM level 2 events&lt;/a&gt; for binding handlers to events raised in the DOM. Internet Explorer on  the other hand, uses a proprietary event model with some fundamental  differences which we&amp;rsquo;ll touch on briefly in a moment (&lt;em&gt;side note:&lt;/em&gt; Internet Explorer 9 is expected to support the &lt;a class="external" title="W3C DOM Level 3 Events Working Specification" href="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html" target="_blank"&gt;W3C DOM level 3 events draft specification&lt;/a&gt; &amp;ndash; this would be very good news indeed).&lt;/p&gt;
&lt;h3&gt;addEventListener and removeEventListener&lt;/h3&gt;
&lt;p&gt;With the DOM level 2 events, there are two functions for binding and  unbinding event handlers to events, &lt;code&gt;addEventListener&lt;/code&gt; and &lt;code&gt;removeEventListener&lt;/code&gt;, respectively&lt;/p&gt;
&lt;pre class="brush:js;"&gt;&amp;lt;a id=&amp;rdquo;my-anchor&amp;rdquo; href=&amp;rdquo;#&amp;rdquo;&amp;gt; Clicking me will show an alert dialog box with the message &amp;lsquo;hello world!&amp;rsquo;&amp;lt;/a&amp;gt;
&amp;lt;script type=&amp;rdquo;text/javascript&amp;rdquo;&amp;gt;
    var a = document.getElementById(&amp;lsquo;my-anchor&amp;rsquo;);
    function handler(e) { /* do something */&amp;nbsp; }

    // to bind&amp;lt;
    a.addEventListener(&amp;lsquo;click&amp;rsquo;, handler , false);

    //to unbind
    a.removeEventListener(&amp;lsquo;click&amp;rsquo;, handler, false);
&amp;lt;/script&amp;gt;
&lt;/pre&gt;
&lt;p&gt;I won&amp;rsquo;t go into a whole load of detail around these as the &lt;a class="external" title="MDC AddEventListener documentation" href="https://developer.mozilla.org/en/DOM/element.addEventListener" target="_blank"&gt;Mozilla  Developer Reference&lt;/a&gt; and &lt;a class="external" title="W3C Event Registration" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration" target="_blank"&gt;W3C specifications&lt;/a&gt; are both comprehensive. Of  particular note however is that the signature for binding an event  handler takes a string argument for the event name, an event handler  function to execute when the event is raised and a Boolean flag to  indicate whether the capture phase of the event should be used.&lt;/p&gt;
&lt;p&gt;See that &lt;code&gt;e&lt;/code&gt; parameter in the function that gets bound as the handler?  In this event model, an event object containing properties related to  the event raised is passed as the first argument to each bound event  handler. This is often useful as depending on the event, it can contain useful properties that can be used to perform logic inside of the  event handler. For example, a keypress event causes an event object to  be passed to an event handler that contains a charCode property which  can be used to determine the key that was pressed.&lt;/p&gt;
&lt;h3&gt;attachEvent and detachEvent&lt;/h3&gt;
&lt;p&gt;Similarly to the w3c event model, the Internet Explorer model also  has two functions for binding and unbinding event handlers to events, &lt;code&gt;attachEvent&lt;/code&gt; and &lt;code&gt;detachEvent&lt;/code&gt;, respectively&lt;/p&gt;
&lt;pre class="brush:js;"&gt;&amp;lt;a id=&amp;rdquo;my-anchor&amp;rdquo; href=&amp;rdquo;#&amp;rdquo;&amp;gt; Clicking me will show an alert dialog box with the message &amp;lsquo;hello world!&amp;rsquo;&amp;lt;/a&amp;gt;
&amp;lt;script type=&amp;rdquo;text/javascript&amp;rdquo;&amp;gt;
    var a = document.getElementById(&amp;lsquo;my-anchor&amp;rsquo;);
    function handler(e) { /* do something */ }

    // to bind
    a.attachEvent(&amp;lsquo;onclick&amp;rsquo;, handler );

    //to unbind
    a.detachEvent(&amp;lsquo;onclick&amp;rsquo;, handler);
&amp;lt;/script&amp;gt;
&lt;/pre&gt;
&lt;p&gt;The first major difference is that the function names used to perform  the binding and unbinding are different in IE&amp;rsquo;s model to that used in the DOM level 2 events model. Secondly, the string name of the  DOM event to which to attach the handler includes the prefix &amp;lsquo;on&amp;rsquo;.  Thirdly, this model does not support using the capture phase of an event to execute a handler function, only the bubbling phase. Peter-Paul Koch (ppk) has a great write-up over at &lt;a class="external" title="Quirksmode is a great resource for web developers" href="http://www.quirksmode.org/js/events_order.html" target="_blank"&gt;quirksmode on event order&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;What is this inside the handler function?&lt;/h3&gt;
&lt;p&gt;One of the biggest differences between the W3C and IE models is what the &lt;code&gt;this&lt;/code&gt; keyword (the function context) refers to inside the event handler function; in the W3C model, &lt;code&gt;this&lt;/code&gt; is a reference to the element on which the event handler is bound but in IE, &lt;code&gt;this&lt;/code&gt; refers to the global object (the &lt;code&gt;window&lt;/code&gt; object in browsers). &lt;em&gt;This&lt;/em&gt; can really trip you up (pun intended) if you're not paying attention!&lt;/p&gt;
&lt;h3&gt;Event object&lt;/h3&gt;
&lt;p&gt;Equally as important as &lt;code&gt;this&lt;/code&gt;, event handler functions do not receive an event object as the first argument (the argument for the &lt;code&gt;e&lt;/code&gt; parameter  will always be &lt;code&gt;undefined&lt;/code&gt;) in IE's model; in IE, the event object is  populated on a property named &lt;code&gt;event&lt;/code&gt; on the global object. Some of the properties that exist on this event object are different to the ones that exist on the W3C event object, that is, different property names may be used that have a value that  purports to the same piece of event data in each case. As an example,  the W3C event object contains a property, &lt;code&gt;target&lt;/code&gt;, that contains a  reference to the element that the event was originally raised on. This same piece of data on IE&amp;rsquo;s event object is assigned to a property named &lt;code&gt;srcElement&lt;/code&gt;. Other properties may purport to the same piece of event data across event models but be calculated differently in different browsers and some event data is implemented in some event models but not others! Enter jQuery.&lt;/p&gt;
&lt;h2&gt;jQuery's Event Model&lt;/h2&gt;
&lt;p&gt;jQuery has done the hard work in abstracting away as many browser differences as possible. There are a number of objects and utility functions involved in the model, starting with &lt;a class="external" href="http://api.jquery.com/bind/" target="_blank"&gt;&lt;code&gt;.bind()&lt;/code&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;jQuery.fn.bind() and friends&lt;/h3&gt;
&lt;p&gt;When you call &lt;code&gt;.bind()&lt;/code&gt; (or one of the specific event handler functions  such as &lt;code&gt;.click()&lt;/code&gt;, &lt;code&gt;.change()&lt;/code&gt;, &lt;code&gt;.keypress()&lt;/code&gt;, etc. which internally will call &lt;code&gt;.bind()&lt;/code&gt; &lt;em&gt;generally&lt;/em&gt;), the event handler function that is passed in, along with each element in the matched set of the jQuery object on which bind is called and any additional data that may also be passed in to bind (and available inside of the handler function) are all used in a call to a utility function, &lt;code&gt;jQuery.event.add&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;the bind function looks like the following:&lt;/p&gt;
&lt;pre class="brush:js"&gt;jQuery.each(["bind", "one"], function( i, name ) {
    jQuery.fn[ name ] = function( type, data, fn ) {
        // Handle object literals
        if ( typeof type === "object" ) {
            for ( var key in type ) {
                this[ name ](key, data, type[key], fn);
            }
            return this;
        }

        if ( jQuery.isFunction( data ) || data === false ) {
            fn = data;
            data = undefined;
        }

        var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
            jQuery( this ).unbind( event, handler );
            return fn.apply( this, arguments );
        }) : fn;

        if ( type === "unload" &amp;amp;&amp;amp; name !== "one" ) {
            this.one( type, data, fn );

        } else {
            for ( var i = 0, l = this.length; i &amp;lt; l; i++ ) {
                jQuery.event.add( this[i], type, handler, data );
            }
        }

        return this;
    };
});
&lt;/pre&gt;
&lt;p&gt;We can see here that an array of strings is iterated over using the  $.each() function. There's a quick check to see if we've been handed an  object literal as the first argument and if so, to go through all of the  properties of that object and bind the property value in each case to  the event identified by the property name.&lt;/p&gt;
&lt;p&gt;Both &lt;code&gt;bind()&lt;/code&gt; and &lt;code&gt;one()&lt;/code&gt; are declared as properties on &lt;code&gt;jQuery.fn&lt;/code&gt;; this is an alias for the &lt;code&gt;jQuery.prototype&lt;/code&gt; object, although in very early versions of the library, this was not the case. Mike Koss has a great introduction to the prototype object in JavaScript in discussing &lt;a class="external" title="Object Oriented Programming in JavaScript by Mike Koss" href="http://mckoss.com/jscript/object.htm" target="_blank"&gt;Object Oriented Programming in JavaScript&lt;/a&gt; if you're interested in more detail.&lt;/p&gt;
&lt;p&gt;Next, there's a check to see if we've been passed an object as an  argument for the data parameter; if data is a function or false, then  data is assigned to fn and it is assumed that this is the event handler  function that is to be bound to the event.&lt;/p&gt;
&lt;p&gt;Now comes an interesting part. Since the source code deals with  setting up both bind and one functions, if the one function is being set  up, the &lt;code&gt;$.proxy()&lt;/code&gt; is used so that the event handler function can be  executed when the event to which it is being registered is raised and  then can be unbound, using the context of an anonymous function that is  also passed to the $.proxy function. &lt;code&gt;$.proxy()&lt;/code&gt; returns a function, which in this case is fn with the context of &lt;code&gt;this&lt;/code&gt; (which is the element on  which the event handler function is being bound) and is passed the  arguments of the anonymous function in which it is scoped. This returned  function is assigned to the variable &lt;code&gt;handler&lt;/code&gt;. In the case of &lt;code&gt;bind&lt;/code&gt;, the fn function is simply assigned to &lt;code&gt;handler.&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Following on, if the event is unload and hasn't been bound with &lt;code&gt;one()&lt;/code&gt;, then &lt;code&gt;one()&lt;/code&gt; is used to register the event handler so that the function is  removed from the internal cache after execution (more on the internal &lt;code&gt;$.cache&lt;/code&gt; in the next part).&lt;/p&gt;
&lt;p&gt;Finally, all of the matched elements in the jQuery object are iterated over and a call to the internal &lt;code&gt;jQuery.event.add&lt;/code&gt; function is  made to actually perform the subscription of the handler to the event.&lt;/p&gt;
&lt;p&gt;In the next part we'll look at &lt;code&gt;jQuery.event&lt;/code&gt; and its functions that underpin the jQuery Event Model.&lt;/p&gt;</description><pubDate>Tue, 26 Jul 2011 22:33:09 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/event-internals-in-jquery-part-one</guid></item><item><title>Event Internals in jQuery - Part Two</title><link>http://forloop.co.uk:80/blog/event-internals-in-jquery-part-two</link><description>&lt;p&gt;&lt;a href="/event-internals-in-jquery-part-one"&gt;Part one of jQuery Event internals&lt;/a&gt; looked at the DOM Event specifications, the history of the Document Object Model (DOM) event models and reasoning behind why jQuery has an event system. In the second part of this series, we'll be looking at the &lt;code&gt;jQuery.event&lt;/code&gt; object and &lt;code&gt;jQuery.Event&lt;/code&gt; constructor function, both of which play a pivotal role in managing events.  Previously, we looked at the &lt;code&gt;bind() &lt;/code&gt;method (and the related specific event handler binding methods such as &lt;code&gt;click()&lt;/code&gt;, &lt;code&gt;keyup()&lt;/code&gt;, etc) and saw that &lt;code&gt;bind()&lt;/code&gt; eventually calls &lt;code&gt;jQuery.event.add&lt;/code&gt;, so let's start by looking at that.&lt;/p&gt;
&lt;h2&gt;jQuery.event.add&lt;/h2&gt;
&lt;p&gt;It helps to have the source to hand when discussing the internals, so here is the source for &lt;code&gt;jQuery.event.add&lt;/code&gt; from &lt;a class="external" title="jQuery source" href="http://code.jquery.com/jquery-1.6.1.js" target="_blank"&gt;jQuery 1.6.1&lt;/a&gt;:&lt;/p&gt;
&lt;pre class="brush:js"&gt;/*!
 * jQuery JavaScript Library v1.6.1
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Thu May 12 15:04:36 2011 -0400
 */

// ... other code omitted, starting at line 2511 of source 
 
jQuery.event = {

	add: function( elem, types, handler, data ) {
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		if ( handler === false ) {
			handler = returnFalse;
		} else if ( !handler ) {
			return;
		}

		var handleObjIn, handleObj;

		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
		}

		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		var elemData = jQuery._data( elem );

		if ( !elemData ) {
			return;
		}

		var events = elemData.events,
			eventHandle = elemData.handle;

		if ( !events ) {
			elemData.events = events = {};
		}

		if ( !eventHandle ) {
			elemData.handle = eventHandle = function( e ) {
				return typeof jQuery !== "undefined" &amp;amp;&amp;amp; (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.handle.apply( eventHandle.elem, arguments ) :
					undefined;
			};
		}

		eventHandle.elem = elem;

		types = types.split(" ");

		var type, i = 0, namespaces;

		while ( (type = types[ i++ ]) ) {
			handleObj = handleObjIn ?
				jQuery.extend({}, handleObjIn) :
				{ handler: handler, data: data };

			if ( type.indexOf(".") &amp;gt; -1 ) {
				namespaces = type.split(".");
				type = namespaces.shift();
				handleObj.namespace = namespaces.slice(0).sort().join(".");

			} else {
				namespaces = [];
				handleObj.namespace = "";
			}

			handleObj.type = type;
			if ( !handleObj.guid ) {
				handleObj.guid = handler.guid;
			}

			var handlers = events[ type ],
				special = jQuery.event.special[ type ] || {};

			if ( !handlers ) {
				handlers = events[ type ] = [];

				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			handlers.push( handleObj );

			jQuery.event.global[ type ] = true;
		}

		elem = null;
	},
    
    // ...
&lt;/pre&gt;
&lt;p&gt;The function kicks off with checking the nodeType of the element to which the event handler will be bound. If the element is a text node (nodeType 3) or a comment node (nodeType 8) then no handler will be bound and the function simply exits at this point. Then follows a check to detect if the element is the &lt;code&gt;window&lt;/code&gt; object and to set it to &lt;code&gt;window&lt;/code&gt; if true to prevent Internet Explorer from erroneously cloning it when passing it around. If &lt;code&gt;false&lt;/code&gt; is passed in for the handler function then the handler is set to a function that returns &lt;code&gt;false&lt;/code&gt;; if no handler is passed in, the add function simply returns. Essentially, there are a number of defensive steps here to avoid doing work unnecessaily and to handle various shorthands for setting up a handler function.&lt;/p&gt;
&lt;p&gt;Next comes a check for &lt;code&gt;handler.handler&lt;/code&gt;. The handler function is given a unique id using &lt;code&gt;jQuery.guid&lt;/code&gt;, a number counter that is held in a &lt;a class="external" href="https://developer.mozilla.org/en/JavaScript/Guide/Closures" target="_blank"&gt;closure&lt;/a&gt; and incremented on each call. &lt;code&gt;jQuery._data(elem)&lt;/code&gt; is used to initialize the internal event structure for the element. Internally, this uses &lt;code&gt;jQuery.data&lt;/code&gt; to initialize a cache for the element; if the element is a JavaScript object, then a cache object is initialized on the object itself using a property name that is constructed by the instance of the jQuery script that runs, using the &lt;code&gt;jQuery.expando:&lt;/code&gt; property. That's defined as such&lt;/p&gt;
&lt;pre class="brush:js"&gt;// line 1384 from the source
jQuery.extend({
	cache: {}, // this is the internal cache object

	uuid: 0,

        // this is essentially a unique id for the instance of jQuery
        // such that two instances of jQuery on the same page do not have the 
        // same expando
	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),

        //...
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;jQuery.expando&lt;/code&gt; serves the purpose of allowing more than once instance of the jQuery library to run on the page, by giving each instance of jQuery a key to use when adding properties to objects and element nodes.&lt;/p&gt;
&lt;p&gt;In the event structure initialization, If the element for which we're setting up event handling is not a JavaScript object but a DOM node then values are assigned to properties on an object created inside of &lt;code&gt;$.cache&lt;/code&gt;; the DOM node is given a unique id using &lt;code&gt;jQuery.uuid&lt;/code&gt;, another number counter that is incremented on each call.&lt;/p&gt;
&lt;p&gt;Once all of the event structure initialization has been done, &lt;code&gt;jQuery._data&lt;/code&gt; returns the cache object for the element. If no object is returned, this indicates that the element in question is not one that can have events bound to it and so the code simply returns at this point. Here comes the interesting part. Two items are retrieved from the cache object (or created if they don't already exist), &lt;code&gt;events&lt;/code&gt; and &lt;code&gt;handle&lt;/code&gt;; &lt;code&gt;events&lt;/code&gt; is an object with properties that match bound event types, with each property assigned an array of event handler functions to run in response to that event type being raised on the element in question. The structure of &lt;code&gt;events&lt;/code&gt; is as follows&lt;/p&gt;
&lt;pre class="brush:js"&gt;events = {
    click :     [{ handler : function (e) { /* click event handler 1 */ }, data : { item: 'item' } },
                 { handler : function (e) { /* click event handler 2 */ }, data : undefined }],
    keyup:      [{ handler : function (e) { /* keyup event handler 1 */ }, data : { additionalData: [1, 2, 3] } }],
    mouseover:  [{ handler : function (e) { /* mouseover event handler 1 */ }, data : undefined }],
    mouseout :  [{ handler : function (e) { /* mouseout event handler 1 */ }, data : undefined }]
};
&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;handle&lt;/code&gt; is a function that, under normal circumstances (i.e. we're not dealing with special events or cross-browser workarounds for specific events), returns the result of applying the &lt;code&gt;jQuery.event.handle&lt;/code&gt; function with the context set to the element on which the event is bound. This is what enables the &lt;code&gt;this&lt;/code&gt; keyword to refer to the element on which the event is raised inside of the event handler function. We'll look at the &lt;code&gt;jQuery.event.handle&lt;/code&gt; function shortly.&lt;/p&gt;
&lt;p&gt;Once the &lt;code&gt;events&lt;/code&gt; object is retrieved from the cache, the space separated event types string passed in the &lt;code&gt;bind()&lt;/code&gt; function call is split and iterated over; in each iteration, a new object containing a handler property with a value set to the function passed into the &lt;code&gt;bind()&lt;/code&gt; call and a data property set to the data passed into the &lt;code&gt;bind()&lt;/code&gt; call is pushed onto an array set against the property name matching the event type on the events object from the cache. Namespaced events are handled by the addition of a namespace property on the object pushed onto the array. If this is the first event handler being bound for the element for the event type, then the &lt;code&gt;handle&lt;/code&gt; function is registered with the browser as an event listener using &lt;code&gt;element.addEventListener&lt;/code&gt; if supported, or &lt;code&gt;element.attachEvent&lt;/code&gt; otherwise.&lt;/p&gt;
&lt;p&gt;The important point to take away here is that &lt;strong&gt;only one function is registered as an event handler with the browser  per element, per event type&lt;/strong&gt;. If I were to guess as to why this is done it would be to&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;allow better control over the function context (what &lt;code&gt;this&lt;/code&gt; refers to) inside event handler functions&lt;/li&gt;
&lt;li&gt;allow patching/augmentation of the browser &lt;code&gt;event&lt;/code&gt; object before passing to event handlers to normalize event properties across browsers. &lt;/li&gt;
&lt;li&gt;keep track of how many event handler functions have been bound and allow for easier clean up when a new page is requested, to avoid browser memory leaks (&lt;a class="external" href="http://javascript.crockford.com/memory/leak.html" target="_blank"&gt;here's looking mainly at you, IE&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Finally, a property matching the event type is set to &lt;code&gt;true&lt;/code&gt; on the &lt;code&gt;jQuery.event.global&lt;/code&gt; object. This is to allow global triggering of event handlers for specific event types.&lt;/p&gt;
&lt;p&gt;With all of this in mind, one can inspect the events set up on an element using jQuery using&lt;/p&gt;
&lt;pre class="brush:js"&gt;    
    var events = $('selector-for-element').data('events');
    // events now contains a reference to the events object held in the cache for &amp;ldquo;selector-for-element&amp;rdquo;, 
    // or undefined if there are no event handlers bound (via jQuery) for the element
&lt;/pre&gt;
&lt;p&gt;This will return the &lt;code&gt;event&lt;/code&gt; object referred to earlier, the one containing properties with names that match the event types to which event handler functions have been bound. If you&amp;rsquo;re a fan of Firefox, there is a add-on for &lt;a class="external" title="IF you use Firefox and don't yet have Firebug, go get it now!" href="http://getfirebug.com/" target="_blank"&gt;Firebug&lt;/a&gt; called &lt;a class="external" title="FireQuery is helpful for inspecting the jQuery cache for elements" href="http://firequery.binaryage.com/" target="_blank"&gt;FireQuery&lt;/a&gt; that shows what is in the cache for each element in the HTML tab of Firebug. What&amp;rsquo;s nice about this is that the cache object links can be clicked, which will take you to the DOM tab and allow you to inspect the object further.&lt;/p&gt;
&lt;p&gt;&lt;img src="/Media/Default/post-images/firequery.jpg" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;A word of caution here - This internal event structure is undocumented in the jQuery source documentation and hence makes it subject to change. So, be particularly careful if you intend to rely on internal event structure inspection in production code as this may break when upgrading to a newer version of the jQuery library.&lt;/p&gt;
&lt;p&gt;Now we know how &lt;code&gt;jQuery.event.add&lt;/code&gt; works, let's look at the function that performs the opposite operation.&lt;/p&gt;
&lt;h2&gt;jQuery.event.remove&lt;/h2&gt;
&lt;p&gt;Once you know how &lt;code&gt;jQuery.event.add&lt;/code&gt; works, there's not really much to discuss with &lt;code&gt;jQuery.event.remove&lt;/code&gt;; it is a function called by &lt;code&gt;unbind()&lt;/code&gt; and does pretty much the reverse of &lt;code&gt;jQuery.event.add&lt;/code&gt;, removing handlers in the cache for the element(s) on which &lt;code&gt;unbind()&lt;/code&gt; is called.  If there are no more handler functions in the cache for a particular event type for an element, then the event listener registered with the browser is removed via &lt;code&gt;element.removeEventListener&lt;/code&gt; if supported, &lt;code&gt;element.detachEvent&lt;/code&gt; otherwise.&lt;/p&gt;
&lt;pre class="brush:js"&gt;jQuery.event = {

    //... starting at line 2640 in the source

    remove: function( elem, types, handler, pos ) {
        if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
            return;
        }

        if ( handler === false ) {
            handler = returnFalse;
        }

        var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
            elemData = jQuery.hasData( elem ) &amp;amp;&amp;amp; jQuery._data( elem ),
            events = elemData &amp;amp;&amp;amp; elemData.events;

        if ( !elemData || !events ) {
            return;
        }

        if ( types &amp;amp;&amp;amp; types.type ) {
            handler = types.handler;
            types = types.type;
        }

        if ( !types || typeof types === "string" &amp;amp;&amp;amp; types.charAt(0) === "." ) {
            types = types || "";

            for ( type in events ) {
                jQuery.event.remove( elem, type + types );
            }

            return;
        }

        types = types.split(" ");

        while ( (type = types[ i++ ]) ) {
            origType = type;
            handleObj = null;
            all = type.indexOf(".") &amp;lt; 0;
            namespaces = [];

            if ( !all ) {
                namespaces = type.split(".");
                type = namespaces.shift();

                namespace = new RegExp("(^|\\.)" +
                    jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
            }

            eventType = events[ type ];

            if ( !eventType ) {
                continue;
            }

            if ( !handler ) {
                for ( j = 0; j &amp;lt; eventType.length; j++ ) {
                    handleObj = eventType[ j ];

                    if ( all || namespace.test( handleObj.namespace ) ) {
                        jQuery.event.remove( elem, origType, handleObj.handler, j );
                        eventType.splice( j--, 1 );
                    }
                }

                continue;
            }

            special = jQuery.event.special[ type ] || {};

            for ( j = pos || 0; j &amp;lt; eventType.length; j++ ) {
                handleObj = eventType[ j ];

                if ( handler.guid === handleObj.guid ) {
                    if ( all || namespace.test( handleObj.namespace ) ) {
                        if ( pos == null ) {
                            eventType.splice( j--, 1 );
                        }

                        if ( special.remove ) {
                            special.remove.call( elem, handleObj );
                        }
                    }

                    if ( pos != null ) {
                        break;
                    }
                }
            }

            if ( eventType.length === 0 || pos != null &amp;amp;&amp;amp; eventType.length === 1 ) {
                if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
                    jQuery.removeEvent( elem, type, elemData.handle );
                }

                ret = null;
                delete events[ type ];
            }
        }

        if ( jQuery.isEmptyObject( events ) ) {
            var handle = elemData.handle;
            if ( handle ) {
                handle.elem = null;
            }

            delete elemData.events;
            delete elemData.handle;

            if ( jQuery.isEmptyObject( elemData ) ) {
                jQuery.removeData( elem, undefined, true );
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;There's not really much more to discuss here, so we'll move on.&lt;/p&gt;
&lt;h2&gt;jQuery.event.handle&lt;/h2&gt;
&lt;p&gt;As highlighted before, &lt;strong&gt;only one handler function is registered with the browser per element, per event type&lt;/strong&gt;. The handler function in question is &lt;code&gt;jQuery.event.handle&lt;/code&gt; and its responsibility is to execute each of the handler functions in the array assigned to the property name on the &lt;code&gt;events&lt;/code&gt; object held in the cache for the element in question, whose name matches the name of the event raised.&lt;/p&gt;
&lt;pre class="brush:js"&gt;    
jQuery.event = {    

    //... starting at line 2903 in the source

    handle: function( event ) {
        event = jQuery.event.fix( event || window.event );

        var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
            run_all = !event.exclusive &amp;amp;&amp;amp; !event.namespace,
            args = Array.prototype.slice.call( arguments, 0 );

        args[0] = event;
        event.currentTarget = this;

        for ( var j = 0, l = handlers.length; j &amp;lt; l; j++ ) {
            var handleObj = handlers[ j ];

            if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {

                event.handler = handleObj.handler;
                event.data = handleObj.data;
                event.handleObj = handleObj;

                var ret = handleObj.handler.apply( this, args );

                if ( ret !== undefined ) {
                    event.result = ret;
                    if ( ret === false ) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }

                if ( event.isImmediatePropagationStopped() ) {
                    break;
                }
            }
        }
        return event.result;
    },

    //...
}
&lt;/pre&gt;
&lt;p&gt;This function simply goes through each handler function in the events object and executes each one in turn. First, the native browser event passed to &lt;code&gt;jQuery.event.handle&lt;/code&gt; is passed into &lt;code&gt;jQuery.event.fix&lt;/code&gt; to normalize the event properties across different browsers. A check is then performed to see if we're dealing with a &lt;a class="external" title="jQuery documentation on namespaced events" href="http://docs.jquery.com/Namespaced_Events" target="_blank"&gt;namespaced event&lt;/a&gt; or an exclusive event (event handers that trigger only for the exact event i.e. no namespaces), and to use this information to filter the handle functions that will be executed accordingly. If a particular handler function returns a boolean result, then this is used to set the result on the event. A return value of &lt;code&gt;false&lt;/code&gt; is shorthand for setting both &lt;code&gt;event.preventDefault()&lt;/code&gt; and &lt;code&gt;event.stopPropagation()&lt;/code&gt;, which are W3C event properties that are normalized to work the same across all browsers by the &lt;code&gt;jQuery.event.fix&lt;/code&gt; method. We'll look at this function in the next part of the series.&lt;/p&gt;
&lt;p&gt;Please leave a comment if this information has been useful :)&lt;/p&gt;</description><pubDate>Tue, 26 Jul 2011 22:33:09 GMT</pubDate><guid isPermaLink="true">http://forloop.co.uk:80/blog/event-internals-in-jquery-part-two</guid></item></channel></rss>
