<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title> - JQuery Mobile</title><link>http://www.squarewidget.com:80/Tags/JQuery%20Mobile</link><description> - JQuery Mobile</description><item><title>Ales Holecek: Windows 8 Unplugged</title><link>http://www.squarewidget.com:80/ales-holecek-windows-8-unplugged</link><description>&lt;p&gt;Ales Holecek opened the day at the p&amp;amp;p symposium this morning with a keynote address on Windows 8. Here are my live blogging notes that contain a mixture of his comments and my own commentary as he went along. Holecek is in charge of WinOS 8. He said that mobility was the primary driver for them when they started thinking about WinOS 8 back in 2009. Given that they promoted touch to a first-class citizen. Future releases will be optimized around touch. The holy grail for a future OS is speech but we're not there yet.&lt;/p&gt;
&lt;p&gt;Holecek says that form factors (devices) are a moving target right now. They are shrinking for sure. But no one knows where the trend is going. Like everyone else Microsoft expects a lot of change in this area. Social media and web browsing in general are changing how they think about their OS. Users today expect data to follow them around on their tablet, phone, and laptop.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Holecek takes a trip down memory lane: in 1995 you had a stack of floppy disks on your desk. And if you had a PC you were sort of geeky. Today computing devices are a given.&lt;/p&gt;
&lt;p&gt;Holecek reminded the devs in the audience that most people just want to get things done. Don't listen to industry pundits or bloggers who claim that if your app doesn't do "X" then it's too late and someone else has beat you to it. Focus on end users rather than pleasing the trend setters.&lt;/p&gt;
&lt;p&gt;One paradigm that WinOS 8 embraces is connection to services. Internet connectivity is now a given. Gone are the days of the self-contained native app that stored data on your hard drive. WinOS 8 apps are lean and mean and state lives out in the cloud. Azure updates (every 3 weeks or so) are moving to support this paradigm (e.g., Azure web or mobile services).&lt;/p&gt;
&lt;p&gt;WinOS 8 was built using open standards. C#, HTML, and Javascript are native languages in the OS. Interestingly enough you can build a Windows Store app using HTML and javascript. All native languages support async programming so that long-running tasks are no longer hanging on the UI thread. In fact, async will be a challenge (or at least cause a rethink) of many devs. Fortunately, .NET 4.5 makes async programming a lot easier.&lt;/p&gt;
&lt;p&gt;As a dev you need to think about your app as a "global citzen" on the OS. The user is in control. Your app is run in isolation and has its resources throttled. Users want to install, run, and uninstall apps effortlessly.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In WinOS 7 an app was either running or terminated. In WinOS 8 an app can have a third state in between those two: suspended. The Task Manager will show this new state. A suspended app has no CPU time allocated to it. Users can resume an app that was suspended when they fip back to it. This all happens automatically by the OS process management when it realizes the app is longer in the foreground. An event will fire to say that your app is now suspended so you can handle that. So as a dev you need to think about the battery. You need to be efficient.&lt;/p&gt;
&lt;p&gt;Holecek next ran through a demo in which he explained how the live tiles work. It's a lot like background computing. We went through a small code run building a live tile using C#. Essentially you ask the TileUpdateManager (a broker) for an updater. Then you tell it what periodic updates you want (for example hourly). Then you start the updater. I think it was about 3 lines of code. So the plumbing is out of the way and you can focus on your app.&lt;/p&gt;
&lt;p&gt;Next he showed how he prepared his slide stack last night and ran through changes that get automatically synced between the phone, tablet and laptop via Skydrive and Onenote. It was very impressive. I have to say that Office 365 is very very impressive. Google apps looks really lame compared to Office on Skydrive. This is coming from someone who thought a few years ago that Office was dead.&lt;/p&gt;
&lt;p&gt;That bar that pops out on the right hand side? Think of it as an OS contract that you should implement in your Win 8 app. The contract is brokered by the OS for you. It has search, share, and settings.&lt;/p&gt;
&lt;p&gt;In closing he said that they're now at 60M WinOS 8 licenses. The number of apps in the store has quadrupled with more than 10K addd in the last month. Obviously, the ultimate success of Win 8 will depend on a rich ecosystem of apps for the new OS. Holecek emphasized that WinOS 8 is not a fad and they're not rolling back or rethinking their direction. So he made a "call to action": write Win 8 apps and start right now! :) Yes the certification process can take a month. Obviously their number one goal is to maintain confidence in the store and protect users from malicious apps. One bad (app)le can erode that confidence in a hurry. And it's hard to get it back. But they're learning. And they're improving the "onboarding pipeline." He asks for patience right now.&lt;/p&gt;</description><pubDate>Thu, 17 Jan 2013 02:12:44 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/ales-holecek-windows-8-unplugged</guid></item><item><title>Greg Young on CQRS</title><link>http://www.squarewidget.com:80/greg-young-on-cqrs</link><description>&lt;p&gt;When Greg Young's talk on &lt;a href="http://msdn.microsoft.com/en-us/library/jj554200.aspx"&gt;CQRS&lt;/a&gt; began I was prepared for a long look at patterns, reliability, transactions, MQs with Azure, WCF, and interface contracts and how Microsoft products were the best way to get you from Point A to Point B. But I was wrong. He showed no code. He didn't mention Azure once. In fact, he didn't talk about specific tooling or tech stacks at all.&lt;/p&gt;
&lt;p&gt;What we got was a refreshing reminder that as developers our data-centric approach to modeling and solving business problems is killing us. Young reminded us that state is a first-level derivative of the constant stream of events in the business. (An aside: this is an enduring concept in Buddhism too and the meaning of Heraclitus' dictum that you can never step in the same stream twice.) Simply put: tools and frameworks come and go but the concepts and ideas remain the same.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Young advised to stop looking at state and start looking at business problems as a series of events that taken together comprise the business process. "Try modeling the full process before the parts of the process." Also, forget the buzzwords. Look at the problem and the process, not "SQL Server" or "Azure Service Bus." To start with the tooling is "developer porn."&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Event messaging has been around for thousands of years. The ancient Sumerians wrote accounting info on clay tablets and baked them. That document stored events in time. Immutable events. In fact, documents are built up of events (think of a passport with its many timestamps).&lt;/p&gt;
&lt;p&gt;"Focus on strategic design first."&lt;/p&gt;
&lt;p&gt;"There's no such thing as a one-way command." These are called "events." They happened in the real world. They cannot be rolled back. Commands and events are both just messages. We just give them different names.&lt;/p&gt;
&lt;p&gt;Overall a fascinating talk because it said nothing new. In fact, I've been evangelizing this way of looking at business problems at my workplace. But this sort of back-to-basics wake up call is exactly what most of us need to hear.&lt;/p&gt;</description><pubDate>Wed, 16 Jan 2013 04:52:04 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/greg-young-on-cqrs</guid></item><item><title>ScheduleWidget Is Now Open Source</title><link>http://www.squarewidget.com:80/schedulewidget-is-now-open-source</link><description>&lt;p&gt;I had no idea that in the few short months since ScheduleWidget went live on &lt;a href="http://nuget.org/packages/ScheduleWidget"&gt;NuGet&lt;/a&gt; it would be so popular. That tells me that other devs have a real need for the tool just like I did in my own project. That's the good news. The bad news is the feature requests are coming in and I can't support it alone. So she's going open source!&amp;nbsp;I've created a repo and done the initial commit into GitHub. The repo on&amp;nbsp;github.com is &lt;a href="https://github.com/jamesstill/ScheduleWidget"&gt;here&lt;/a&gt;. When I have time there are two features that I want to add:&lt;/p&gt;
&lt;p&gt;(1) Allow quarterly events (in addition to one-time, daily, weekly, and monthly recurrences).&lt;/p&gt;
&lt;p&gt;(2) Allow temporal expressions such as "the 24th of every month"&lt;/p&gt;
&lt;p&gt;Maybe you'd like to contribute? That would be very much appreciated. If you're not familiar with github I highly recommend downloading &lt;a href="http://windows.github.com/"&gt;GitHub for Windows&lt;/a&gt;. It's free and makes working with the repo a breeze. Then you're going to want to check out &lt;a href="https://help.github.com/articles/fork-a-repo"&gt;how to fork a repository&lt;/a&gt; in order to contribute to ScheduleWidget.&lt;/p&gt;
&lt;p&gt;Maybe down the road I'll set up an automated build. But for right now it's just the raw source. When a good stable release is ready I'll be responsible for getting it into NuGet.&amp;nbsp;&lt;/p&gt;



</description><pubDate>Tue, 25 Sep 2012 06:44:10 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/schedulewidget-is-now-open-source</guid></item><item><title>Pluggable Architecture in ASP.NET MVC 4</title><link>http://www.squarewidget.com:80/pluggable-architecture-in-asp.net-mvc-4</link><description>&lt;p&gt;&lt;em&gt;All problems in computer science can be solved by another level of indirection.&lt;/em&gt; --David Wheeler&lt;/p&gt;
&lt;p&gt;&lt;em&gt;...except for the problem of too many layers of indirection.&lt;/em&gt; --Kevlin Henney&lt;/p&gt;
&lt;p&gt;Wouldn't it be cool to create a module that can be "plugged" into an existing ASP.NET MVC 4 web&amp;nbsp;app? I'm going to walk through just such a solution. First let me say that I'm indebted to &lt;a href="http://blog.longle.net/2012/03/29/building-a-composite-mvc3-application-with-pluggable-areas/"&gt;Long&amp;nbsp;Le&lt;/a&gt; for his approach to the problem. I used his work as a basis for my own streamlined solution.&lt;/p&gt;
&lt;p&gt;The bedrock of software engineering is to &lt;strong&gt;minimize coupling&lt;/strong&gt; and &lt;strong&gt;maximize cohesion&lt;/strong&gt;. This is one of those truisms that every geek is supposed to have tatooed on his arm or something. Of course I'm not sure if that will help you with the ladies. In any case, elements are&amp;nbsp;said to be tightly-coupled if a change in one forces a change in the other. An element is&amp;nbsp;cohesive if its functionality hangs together. For instance a class that parses strings, formats&amp;nbsp;URLs, and creates text files has low cohesion. A class that does one and only one thing (parses&amp;nbsp;strings) has high cohesion. Which do you think is easier to maintain a year from now?&lt;/p&gt;
&lt;p&gt;So our goal is to create a "core" web application that changes very rarely and a series of plugins or modules that can be added over time. As far as the end user is concerned it looks like a single web application with new features popping up now and then. So let's start with the core web app.&lt;/p&gt;
&lt;h3&gt;Core Web Application&lt;/h3&gt;
&lt;p&gt;Create a MVC 4 web app using the basic project template. Call it "Core" (how imaginative). Add a HomeController to it as well as a default Index View with the following markup:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;@{
    ViewBag.Title = "Index";
}

&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Welcome to the Core Web App&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
@Html.ActionLink("Plugin", "Index", "Plugin")&lt;/pre&gt;
&lt;p&gt;Fire it up and you should see the home page rendered. If you were to click on the link you'd get&amp;nbsp;a 404 of course. Before we create the plugin we need to do four things:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create an Areas folder where plugin views will live.&lt;/li&gt;
&lt;li&gt;Reference and configure Ninject for constructor injection on the plugins.&lt;/li&gt;
&lt;li&gt;Create a customized RazorViewEngine to support our plugins.&lt;/li&gt;
&lt;li&gt;Register the custom view engine.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Create Areas Folder&lt;/h3&gt;
&lt;p&gt;Create a folder called &lt;strong&gt;Areas&lt;/strong&gt; in the project root. This is where all of our plugin Views (areas) will live.&lt;/p&gt;
&lt;h3&gt;Ninject&lt;/h3&gt;
&lt;p&gt;A DI tool like &lt;a href="http://www.ninject.org/"&gt;Ninject&lt;/a&gt; is very helpful to our goal of minimizing coupling. We want to be able to&amp;nbsp;bind instances to interfaces in the code. Yet, the core is completely ignorant of its plugins. So&amp;nbsp;we can't just do something like this in the core when the kernel is created:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;Bind&amp;lt;IPluginRepository&amp;gt;().To&amp;lt;PluginRepository&amp;gt;();&lt;/pre&gt;
&lt;p&gt;We need a way of binding that uses reflection through all present (and future) plugin assemblies&amp;nbsp;to get the interfaces. So add the following three nuget packages:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Ninject&lt;/li&gt;
&lt;li&gt;Ninject.MVC3&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Ninject.Extensions.Conventions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After adding these packages the &lt;strong&gt;NinjectWebCommon&lt;/strong&gt; bootstrapper is added to your &lt;strong&gt;App_Start&lt;/strong&gt; folder.&amp;nbsp;Go down to the &lt;strong&gt;RegisterServices&lt;/strong&gt; method and add this code:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="rem"&gt;/// Load your modules or register your services here!&lt;/span&gt;
&lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
&lt;span class="rem"&gt;/// &amp;lt;param name="kernel"&amp;gt;The kernel.&amp;lt;/param&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RegisterServices(IKernel kernel)
{
    &lt;span class="rem"&gt;// using System.IO;&lt;/span&gt;
    &lt;span class="rem"&gt;// using Ninject.Extensions.Conventions;&lt;/span&gt;
    &lt;span class="rem"&gt;// bind plugin assemblies in bin folder&lt;/span&gt;
    &lt;span class="kwrd"&gt;var&lt;/span&gt; path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &lt;span class="str"&gt;"bin"&lt;/span&gt;);
    kernel.Bind(a =&amp;gt; a.FromAssembliesInPath(path).SelectAllClasses().BindDefaultInterface());
}  &lt;/pre&gt;
&lt;p&gt;As you can see we're pointing to the Core's bin folder and telling Ninject to find all&amp;nbsp;assemblies there and create bindings for all of the concrete classes that implement an interface.&amp;nbsp;So Ninject gives us the ability to add plugins at any time in the future and at app start the&amp;nbsp;bindings will automatically be mapped for us. We'll see this in action in a little bit.&lt;/p&gt;
&lt;h3&gt;Customized RazorViewEngine&lt;/h3&gt;
&lt;p&gt;Next we have to override the default view engine with our own. To the project&amp;nbsp;root add this class:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.IO;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Reflection;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web.Mvc;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Core
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; CoreRazorViewEngine : RazorViewEngine
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; CoreRazorViewEngine()
        {
            AreaMasterLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt;[]
            {
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.vbhtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.vbhtml"&lt;/span&gt;
            };

            AreaPartialViewLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt;[]
            {
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.vbhtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.vbhtml"&lt;/span&gt;
            };

            &lt;span class="kwrd"&gt;var&lt;/span&gt; areaViewAndPartialViewLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;
            {
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/{1}/{0}.vbhtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Areas/{2}/Views/Shared/{0}.vbhtml"&lt;/span&gt;
            };

            &lt;span class="kwrd"&gt;var&lt;/span&gt; partialViewLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;
            {
                &lt;span class="str"&gt;"~/Views/{1}/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/{1}/{0}.vbhtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/Shared/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/Shared/{0}.vbhtml"&lt;/span&gt;
            };

            &lt;span class="kwrd"&gt;var&lt;/span&gt; masterLocationFormats = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;
            {
                &lt;span class="str"&gt;"~/Views/{1}/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/{1}/{0}.vbhtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/Shared/{0}.cshtml"&lt;/span&gt;,
                &lt;span class="str"&gt;"~/Views/Shared/{0}.vbhtml"&lt;/span&gt;
            };

            &lt;span class="kwrd"&gt;var&lt;/span&gt; fullPluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &lt;span class="str"&gt;"bin"&lt;/span&gt;);
            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;var&lt;/span&gt; file &lt;span class="kwrd"&gt;in&lt;/span&gt; Directory.EnumerateFiles(fullPluginPath, &lt;span class="str"&gt;"*Plugin*.dll"&lt;/span&gt;))
            {
                &lt;span class="kwrd"&gt;var&lt;/span&gt; assembly = Assembly.LoadFile(file);
                &lt;span class="kwrd"&gt;var&lt;/span&gt; plugin = assembly.GetName().Name;

                masterLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.cshtml"&lt;/span&gt;);
                masterLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.vbhtml"&lt;/span&gt;);
                masterLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/Shared/{1}/{0}.cshtml"&lt;/span&gt;);
                masterLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/Shared/{1}/{0}.vbhtml"&lt;/span&gt;);

                partialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.cshtml"&lt;/span&gt;);
                partialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.vbhtml"&lt;/span&gt;);
                partialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/Shared/{0}.cshtml"&lt;/span&gt;);
                partialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/Shared/{0}.vbhtml"&lt;/span&gt;);

                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.cshtml"&lt;/span&gt;);
                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Views/{1}/{0}.vbhtml"&lt;/span&gt;);
                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Areas/{2}/Views/{1}/{0}.cshtml"&lt;/span&gt;);
                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Areas/{2}/Views/{1}/{0}.vbhtml"&lt;/span&gt;);
                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Areas/{2}/Views/Shared/{0}.cshtml"&lt;/span&gt;);
                areaViewAndPartialViewLocationFormats.Add(&lt;span class="str"&gt;"~/Areas/"&lt;/span&gt; + plugin + &lt;span class="str"&gt;"/Areas/{2}/Views/Shared/{0}.vbhtml"&lt;/span&gt;);
            }

            ViewLocationFormats = partialViewLocationFormats.ToArray();
            MasterLocationFormats = masterLocationFormats.ToArray();
            PartialViewLocationFormats = partialViewLocationFormats.ToArray();
            AreaPartialViewLocationFormats = areaViewAndPartialViewLocationFormats.ToArray();
            AreaViewLocationFormats = areaViewAndPartialViewLocationFormats.ToArray();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The Core project is complete. Now it's time to create a plugin for it.&lt;/p&gt;
&lt;h3&gt;Create the Plugin&lt;/h3&gt;
&lt;p&gt;Close the Core solution and create a new MVC 4 web&amp;nbsp;application called "Plugin" using the Empty template. Add the Core project to Plugin and set it&amp;nbsp;as the startup project. Go ahead and run it and click on the Plugin link. You should still get a&amp;nbsp;404 because we haven't created the plugin yet. Let's do that now.&amp;nbsp;There are three things we need to do:&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Create a simple interface to demonstrate how Ninject binding in the core works for us&lt;/li&gt;
&lt;li&gt;Create a Plugin controller and an Index view for it&lt;/li&gt;
&lt;li&gt;Create an AreaRegistration so that MVC menu routing will work&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;IMessageRepository&lt;/h3&gt;
&lt;p&gt;Let's keep it simple. We want to display a message on the view that comes from an interface&amp;nbsp;implementation. Here's the interface, go ahead and add it to the project root:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Plugin
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IMessageRepository
    {
        &lt;span class="kwrd"&gt;string&lt;/span&gt; Message();
    }
}&lt;/pre&gt;
&lt;p&gt;And now here's an implementation:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Plugin
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MessageRepository : IMessageRepository
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Message()
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"Welcome to the plugin!"&lt;/span&gt;;
        }
    }
}&lt;/pre&gt;
&lt;h3&gt;Plugin Controller&lt;/h3&gt;
&lt;p&gt;Create a new PluginController class where we do constructor injection of the IMessageRepository:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Plugin.Controllers
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PluginController : Controller
    {
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IMessageRepository _repository;

        &lt;span class="kwrd"&gt;public&lt;/span&gt; PluginController(IMessageRepository repository)
        {
            _repository = repository;
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Index()
        {
            &lt;span class="kwrd"&gt;var&lt;/span&gt; message = _repository.Message();
            ViewBag.Message = message;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; View();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Notice that we have not added Ninject to the plugin project. You could do that but what if you&amp;nbsp;have dozens of plugins? The idea here is to add it just once to the core and have it work for all&amp;nbsp;of the plugins in the application. Now create a default Index View by right-clicking on the word&amp;nbsp;View and choosing Add View. Since we put the repository message in the ViewBag let's display it&amp;nbsp;in our View. Add this snippet:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;@ViewBag.Message&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;One last thing: Below the Views folder add a &lt;strong&gt;_ViewStart.cshtml&lt;/strong&gt; file with the path to the Core master page:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}&lt;/pre&gt;
&lt;h3&gt;AreaRegistration&lt;/h3&gt;
&lt;p&gt;So that the routing engine picks up the new plugin area we need to add an AreaRegistration:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; Plugin
{
    &lt;span class="rem"&gt;// using System.Web.Mvc;&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PluginAreaRegistration : AreaRegistration
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; AreaName
        {
            &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"Plugin"&lt;/span&gt;; }
        }

        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                &lt;span class="str"&gt;"Plugin"&lt;/span&gt;,
                &lt;span class="str"&gt;"Plugin/{controller}/{action}/{id}"&lt;/span&gt;,
                &lt;span class="kwrd"&gt;new&lt;/span&gt; { action = &lt;span class="str"&gt;"Index"&lt;/span&gt;, id = UrlParameter.Optional }
                );
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Now we're code complete on our plugin. At this point we'd want to add an installer or your&amp;nbsp;favorite web setup project to bundle up the plugin for later deployment. But I've noticed that&amp;nbsp;none shipped with Visual Studio 2012 the other day. When &lt;a href="http://wix.sourceforge.net/"&gt;WIX&lt;/a&gt; is ready as a nuget package for VS 2012 I'll probably use that but&amp;nbsp;for now let's just keep things very simple. Edit the Plugin project properties (Alt+Enter) and&amp;nbsp;make these two configuration changes:&lt;/p&gt;
&lt;p&gt;(1) On the &lt;strong&gt;Build&lt;/strong&gt; tab change the Output path to drop the Plugin.dll in the Core bin folder:&lt;/p&gt;
&lt;pre&gt;..\..\Core\Core\bin\&lt;/pre&gt;
&lt;p&gt;(2) On the &lt;strong&gt;Build Events&lt;/strong&gt; tab add this post-build event command:&lt;/p&gt;
&lt;pre&gt;xcopy "$(ProjectDir)\Views" "..\Areas\$(ProjectName)\Views" /s /i /y&lt;/pre&gt;
&lt;p&gt;This will copy our plugin views over to the Core project's Areas folder that we created earlier.&lt;/p&gt;
&lt;p&gt;Go ahead and build the solution and then run it. Now when you click on the action link you should get the message served up by the &lt;strong&gt;IMessageRepository&lt;/strong&gt; implementation rather than a 404. If you get a runtime error double-check the path locations of the two build configurations above.&lt;/p&gt;
&lt;p&gt;That's pretty much it. One of the things I've done is to create a separate WCF service called CoreService where I've fronted all of my ORM plumbing to the database with operation contracts. Any repository classes I have in my core or plugin assemblies can call a service for data. That way I can version the operation contracts and/or their implementations without needing to touch the core and its plugins. But that's a topic for another post.&lt;/p&gt;</description><pubDate>Sat, 15 Sep 2012 05:30:12 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/pluggable-architecture-in-asp.net-mvc-4</guid></item><item><title>ScheduleWidget 2.0 Released</title><link>http://www.squarewidget.com:80/schedulewidget-2.0-released</link><description>&lt;p&gt;Without much fanfare I'd like to announce the release of &lt;a href="http://www.squarewidget.com/schedulewidget"&gt;ScheduleWidget&lt;/a&gt;. ScheduleWidget is a .NET 4.0 scheduling engine that handles recurring events for calendars. I was influenced by Martin Fowler's white paper "&lt;a href="http://martinfowler.com/apsupp/recurring.pdf"&gt;Recurring Events for Calendars&lt;/a&gt;" in which he describes the broad software architecture for a recurring events scheduling engine. But I did not find any implementation of his idea in the wild. So this led me to write it myself. It is available as a nuget package here:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://nuget.org/packages/ScheduleWidget"&gt;http://nuget.org/packages/ScheduleWidget&amp;nbsp;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The page above has some unit tests to get you going on using the engine. As time permits I'll make some blog posts on how to use it effectively. For instance, it supports one-time only events as well as recurring schedules. But for now I'll just announce it and leave it at that. :)&lt;/p&gt;</description><pubDate>Sat, 16 Jun 2012 09:23:18 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/schedulewidget-2.0-released</guid></item><item><title>JQuery Mobile Madness with MVC 4 Web API</title><link>http://www.squarewidget.com:80/jquery-mobile-madness</link><description>&lt;p&gt;In my last post I introduced &lt;a href="http://www.asp.net/mvc/mvc4"&gt;MVC 4 Web API&lt;/a&gt;. In keeping with the spirit of things I'd like to throw a little &lt;a href="http://jquerymobile.com/"&gt;JQuery Mobile&lt;/a&gt; into the mix for fun. As in my &lt;a href="http://squarewidget.com/fun-with-mvc-4-web-api"&gt;previous blog post&lt;/a&gt; fire up Visual Studio 11 Beta and create a new MVC 4 Web API project. Last time we posted a plain old string value back to the ValuesController. Now let's post a Widget class back. Go ahead and add this model to the project:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; ID { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Color { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Shape { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;p&gt;Modify the ValuesController and replace the out-of-the-box Post verb method with this one:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; HttpResponseMessage&amp;lt;Widget&amp;gt; Post(Widget value)
{
    &lt;span class="kwrd"&gt;var&lt;/span&gt; r = &lt;span class="kwrd"&gt;new&lt;/span&gt; Random();
    value.ID = r.Next(1, 1000); &lt;span class="rem"&gt;// using System.Net;&lt;/span&gt;
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage&amp;lt;Widget&amp;gt;(value, HttpStatusCode.Created);
}&lt;/pre&gt;
&lt;p&gt;I'm really digging the new HttpResponseMessage. You can get really fancy with custom formatters here but I want to keep it really simple. So we're going to simulate a database call by just randomly picking an ID value and returning it back to the UI.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Ok now add this navigation method to the HomeController:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Widget()
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View();
}&lt;/pre&gt;
&lt;p&gt;With that in place we need to provide a Widget view. Go ahead and add Widget.cshtml as a partial view in the Home folder and put in this simple Widget data entry form:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ul&lt;/span&gt; &lt;span class="attr"&gt;data-role&lt;/span&gt;&lt;span class="kwrd"&gt;="listview"&lt;/span&gt; &lt;span class="attr"&gt;data-inset&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt; &lt;span class="attr"&gt;data-role&lt;/span&gt;&lt;span class="kwrd"&gt;="list-divider"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Create Widget&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt; &lt;span class="attr"&gt;data-role&lt;/span&gt;&lt;span class="kwrd"&gt;="fieldcontain"&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="ui-hide-label"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;label&lt;/span&gt; &lt;span class="attr"&gt;for&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-color"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Color&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;label&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;input&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text"&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-color"&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-color"&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=""&lt;/span&gt; &lt;span class="attr"&gt;placeholder&lt;/span&gt;&lt;span class="kwrd"&gt;="Color"&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;label&lt;/span&gt; &lt;span class="attr"&gt;for&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-shape"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Shape&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;label&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;input&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text"&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-shape"&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-shape"&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;=""&lt;/span&gt; &lt;span class="attr"&gt;placeholder&lt;/span&gt;&lt;span class="kwrd"&gt;="Shape"&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt; &lt;span class="attr"&gt;data-role&lt;/span&gt;&lt;span class="kwrd"&gt;="fieldcontain"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;input&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="submit-button"&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="submit"&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;="OK"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="post-result"&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ul&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    $(&lt;span class="str"&gt;'#submit-button'&lt;/span&gt;).click(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; color = $(&lt;span class="str"&gt;'#widget-color'&lt;/span&gt;).val();
        &lt;span class="kwrd"&gt;var&lt;/span&gt; shape = $(&lt;span class="str"&gt;'#widget-shape'&lt;/span&gt;).val();
        $.post(&lt;span class="str"&gt;"/api/values"&lt;/span&gt;, { Color: color, Shape: shape },
            &lt;span class="kwrd"&gt;function&lt;/span&gt; (data) {
                $(&lt;span class="str"&gt;'#post-result'&lt;/span&gt;).text(&lt;span class="str"&gt;'Success posting '&lt;/span&gt; + data.Color + &lt;span class="str"&gt;' '&lt;/span&gt; + data.Shape + &lt;span class="str"&gt;'widget with ID '&lt;/span&gt; + data.ID);
            }
        );
    });
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;The last step is to put a plain old anchor tag in the Home Index.html page so that we can navigate to the data entry form. Insert this just above the H1 welcome tag:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    @Html.ActionLink("Favorite Widget", "Widget", "Home")
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;h1&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Welcome to ASP.NET Web API!&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;h1&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Enough code. Fire this guy up and make sure it works. Go ahead and click on the "Favorite Widget" link to be taken to the data entry form. Pretty ugly huh? That's because the markup in Widget.cshtml is using an unordered list that has no style. That's by design. I want to illustrate how JQuery Mobile transforms this into something that looks awesome on a smart phone.&lt;/p&gt;
&lt;p&gt;To see this in action go into the Shared _Layout.cshtml file and replace the three references to the CSS and javascript files with these JQuery Mobile references:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;&amp;lt;!-- JQuery Mobile --&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;link&lt;/span&gt; &lt;span class="attr"&gt;rel&lt;/span&gt;&lt;span class="kwrd"&gt;="stylesheet"&lt;/span&gt; &lt;span class="attr"&gt;href&lt;/span&gt;&lt;span class="kwrd"&gt;="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt; &lt;span class="attr"&gt;src&lt;/span&gt;&lt;span class="kwrd"&gt;="http://code.jquery.com/jquery-1.7.1.min.js"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&amp;lt;script type=&lt;span class="str"&gt;"text/javascript"&lt;/span&gt; src=&lt;span class="str"&gt;"http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"&lt;/span&gt;&amp;gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Now fire up the app and navigate to the form. Mobile friendly!&lt;/p&gt;</description><pubDate>Thu, 24 May 2012 05:48:04 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/jquery-mobile-madness</guid></item><item><title>Fun with MVC 4 Web API</title><link>http://www.squarewidget.com:80/fun-with-mvc-4-web-api</link><description>&lt;p&gt;To check out the new Web API templates bundled up in Visual Studio 11, &lt;a href="http://www.microsoft.com/visualstudio/11/en-us"&gt;download&lt;/a&gt; and install VS 11 Beta.&lt;/p&gt;
&lt;p&gt;In this walkthrough I'm using VS 11 Express for Web. Create a new ASP.NET MVC 4 Web Application and choose the Web API project template. Notice the new ApiController class from which ValuesController derives. Let's take it for a test drive. There are two action methods that implement the GET verb:&lt;/p&gt;
&lt;div&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;// GET /api/values&lt;/span&gt;
&lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Get()
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;"value1"&lt;/span&gt;, &lt;span class="str"&gt;"value2"&lt;/span&gt; };
}

&lt;span class="rem"&gt;// GET /api/values/5&lt;/span&gt;
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Get(&lt;span class="kwrd"&gt;int&lt;/span&gt; id)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;"value"&lt;/span&gt;;
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Go under Views/Home and edit Index.cshtml. After the last DIV tag add the following script:&lt;/p&gt;
&lt;div&gt;
&lt;pre class="csharpcode"&gt;&amp;lt;script type=&lt;span class="str"&gt;"text/javascript"&lt;/span&gt;&amp;gt;
    $(document).ready(function () {
        $.getJSON(&lt;span class="str"&gt;"api/values"&lt;/span&gt;, function (data) {
            $.each(data, function (key, val) {
                &lt;span class="rem"&gt;// useless but dramatic jQuery animation&lt;/span&gt;
                $(&lt;span class="str"&gt;'.round'&lt;/span&gt;).append(&lt;span class="str"&gt;'&amp;lt;li class='&lt;/span&gt; + key + &lt;span class="str"&gt;'&amp;gt;'&lt;/span&gt; + val + &lt;span class="str"&gt;'&amp;lt;/li&amp;gt;'&lt;/span&gt;);
                $(&lt;span class="str"&gt;'.'&lt;/span&gt; + key + &lt;span class="str"&gt;''&lt;/span&gt;).text(val).animate({ fontSize: &lt;span class="str"&gt;'+=5em'&lt;/span&gt; }, 1200);
                $(&lt;span class="str"&gt;'.'&lt;/span&gt; + key + &lt;span class="str"&gt;''&lt;/span&gt;).text(val).animate({ fontSize: &lt;span class="str"&gt;'-=5em'&lt;/span&gt; }, 1200);
            });
        });
});
&amp;lt;/script&amp;gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;This is just a simple JQuery ajax call to exercise the out-of-the-box ValuesController. Run it and see the cheap animation. But hey at least it wasn't a blink tag. To pass in an ID to the other GET method the above javascript could be modified to call url api/values/1 instead. How about posting? Modify the POST method to this so that we get back a warm fuzzy response:&lt;/p&gt;
&lt;div&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;// POST /api/values&lt;/span&gt;
&lt;span class="kwrd"&gt;public&lt;/span&gt; HttpResponseMessage&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Post(&lt;span class="kwrd"&gt;string&lt;/span&gt; value)
{
    value = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Concat(value, &lt;span class="str"&gt;" processed!"&lt;/span&gt;); &lt;span class="rem"&gt;//using System.Net;&lt;/span&gt;
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; HttpResponseMessage&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(value, HttpStatusCode.Created);
}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Change the javascript to post a very exciting "value3" string to the controller:&lt;/p&gt;
&lt;div&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    $(document).ready(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {
        $.post(&lt;span class="str"&gt;"/api/values"&lt;/span&gt;, { value: &lt;span class="str"&gt;"value3"&lt;/span&gt; }, &lt;span class="kwrd"&gt;function&lt;/span&gt; (data) {
            $(&lt;span class="str"&gt;'.one h5'&lt;/span&gt;).text(data);
        });
    });
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;Run the app and you should see the response written to the first bullet list item.&lt;/p&gt;</description><pubDate>Thu, 24 May 2012 04:56:44 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/fun-with-mvc-4-web-api</guid></item><item><title>Seismic Shifts in Web Development</title><link>http://www.squarewidget.com:80/seismic-shifts-in-web-development</link><description>&lt;p&gt;Not really. But then again &lt;em&gt;really&lt;/em&gt;. What I mean is the role of the web developer is changing fast and it's only been in recent months that I've looked up from my keyboard to see how the ground has shifted substantially. Some developer friends and I have often joked that the back end -- the database, object-relational mapping, domain model, business logic, and the controllers for the UI -- take us about a fraction of the time it takes us to get the UI right. We will sit for hours just to get the HTML right, float div tags, give up and go with the table tag, try again, move on, and so on and on.&amp;nbsp;And now with awesome tools like EF and LINQ it's a breeze to do the sort of plumbing work that used to take weeks.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I think those of us who consider ourselves to be web developers need to come around to a simple truth. Increasingly we are needed for front-end skills and not the back end stuff. For some that will be a blow to the ego. I went to school for this stuff! I'm an engineer not a designer! But the demand now and into the future is going to be for the kind of web developer that knows everything from soup to nuts. Those who know jQuery, JSON, Ajax, Knockout.js, CSS3, good design principles, and can make a web page look and feel gorgeous will be worth their weight in gold. This will be our primary selling point and the back end stuff that we take so much pride in now will be a skill that's assumed. I'm not talking about very complicated business domains here of course. I'm talking about simple to medium complexity projects, the bulk of them out there, where the customer does not want to pay for a designer. In fact, he resents your suggestion and wonders why you can't make a web page look decent to save your life.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;I used to be one of those developers who would surf for guidance on floating div tags only to run into yet another designer's blog who seemed more interested in showing off how clever, artistic, and utterly esoteric he could be rather than simply putting up clear and concise HTML markup. But I can't afford to sport that attitude any longer. The front end is changing fast and for the better with HTML5 and CSS3.&amp;nbsp;I (and we) need to bridge the gap and move more into their camp. Right now if you call yourself a web developer you should read Ethan Marcotte's article entitled&amp;nbsp;&lt;a href="http://www.alistapart.com/articles/responsive-web-design/"&gt;Responsive Web Design&lt;/a&gt;&amp;nbsp;and other articles like it. This is where things are going. I've come to the conclusion that it's no longer enough to be a web developer who passes things off to a designer. We need to be designers as well.&lt;/p&gt;</description><pubDate>Thu, 10 May 2012 23:56:18 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/seismic-shifts-in-web-development</guid></item><item><title>Pattern Toolkit Builder (VSPAT)</title><link>http://www.squarewidget.com:80/vspat-pattern-toolkit-builder</link><description>&lt;p&gt;A few days ago Jezz Santos at Microsoft Consulting &lt;a href="http://bit.ly/yCenMg"&gt;announced the release&lt;/a&gt; of Pattern Toolkit Builder (VSPAT) for Visual Studio 2010. Why not VSPTB? I think PA originally stood for "pattern automation" and the marketing folks just haven't nailed this down yet. Anyway, this promises to be the sort of game changer I've been looking for in my organization. I remember the software factory idea that the P&amp;amp;P team worked on a few years ago. It sort of died on the vine. The idea with pattern automation or "software factories" is that a very senior developer can create interactive, prescriptive (or merely helpful), project templates that junior developers can use to get started on a new project. The toolkit lets you create guidance and proven patterns in the actual code that gets unpacked from the project template so that junior developers aren't faced with the "blank slate how-do-I-get-started" problem.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;So you can imagine I was very eager to download the bits and take it for a spin. I have Visual Studio 2010 SP1 Ultimate. The prereqs for the extension are NuGet Package Manager v1.6.21215.x and VS 2010 SP1 SDK. I installed both.&amp;nbsp;Unfortunately, I could not get VSPAT installed correctly. It installs without errors but a post-install configuration step fails. I looked at the activity log and it has to do with a conflict with another extension in the builder itself. The builder relies upon two other extensions: Pattern Toolkit Automation Library and Feature Builder Tools.&lt;/p&gt;
&lt;p&gt;I tried various install/uninstall steps but nothing worked.&amp;nbsp;I've commented at Santos' blog but I don't think he's checking in there. If anyone knows the fix for this I would love to get the answer.&lt;/p&gt;
&lt;p&gt;[&lt;em&gt;Update&lt;/em&gt;: Problem solved! See comments below...]&lt;/p&gt;</description><pubDate>Wed, 14 Mar 2012 06:41:51 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/vspat-pattern-toolkit-builder</guid></item><item><title>IncludeMetadataConvention Deprecated in EF 4.3</title><link>http://www.squarewidget.com:80/includemetadataconvention-deprecated-in-ef-4.3</link><description>&lt;p&gt;In an &lt;a href="http://squarewidget.com/InvalidOperationException-Using-EF-Code-First"&gt;earlier blog post&lt;/a&gt; I showed how to remove the IncludeMetadataConvention convention from your DbContext configuration. This is necessary up through EF 4.2 to prevent model metadata changes from being written to the database, something you don't want for legacy systems.&amp;nbsp;Beginning with EF 4.3 this pluggable convention has been deprecated. As posted on the ADO.NET team blog:&lt;/p&gt;
&lt;blockquote&gt;In CTP5 we have removed the need to perform additional configuration when mapping to an existing database. If Code First detects that it is pointing to an existing database schema that it did not create then it will 'trust you' and attempt to use code first with the schema.&lt;/blockquote&gt;
&lt;p&gt;Super cool. I like it when the tool trusts me. If I get a schema error then let me handle it in my fluent API mapping. Don't try to create tables or columns for me. So with the obsolesence of IncludeMetadataConvention the MyContext class is much simpler:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyContext : DbContext
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DbSet&amp;lt;Foo&amp;gt; Foos { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DbSet&amp;lt;Bar&amp;gt; Bars { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;</description><pubDate>Fri, 17 Feb 2012 02:23:05 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/includemetadataconvention-deprecated-in-ef-4.3</guid></item><item><title>Entity Framework 5.0 Sneak Preview</title><link>http://www.squarewidget.com:80/entity-framework-5.0-sneak-preview</link><description>&lt;p&gt;In the &lt;a href="http://blogs.msdn.com/b/adonet/archive/2012/02/14/sneak-preview-entity-framework-5-0-performance-improvements.aspx"&gt;upcoming EF 5.0&lt;/a&gt; Microsoft has improved performance due mainly to caching of inline LINQ queries. The benchmarks are impressive:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-68-19-metablogapi/6724.ExecutionTimeResults_5F00_thumb_5F00_347404AB.png" alt="" width="575" height="308"&gt;&lt;/p&gt;
&lt;p&gt;Although EF will be twice as slow as native ADO.NET (I assume the benchmark here refers to a SqlDataReader) that is still an awesome trade off for the efficiency and maintainability you get from LINQ queries.&amp;nbsp;&lt;/p&gt;</description><pubDate>Thu, 16 Feb 2012 01:24:50 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/entity-framework-5.0-sneak-preview</guid></item><item><title>Polling with Knockout, JQuery, AJAX, and MVC</title><link>http://www.squarewidget.com:80/polling-with-knockout-jquery-ajax-and-mvc</link><description>&lt;p&gt;Some colleagues and I have been taking a close look at &lt;a href="http://knockoutjs.com"&gt;Knockout&lt;/a&gt;, the javascript library that implements the MVVM pattern for rich client UI. Knockout takes advantage of the new &lt;a href="http://dev.w3.org/html5/spec/global-attributes.html#custom-data-attribute"&gt;custom data attributes&lt;/a&gt; (data-*) in HTML 5 to bind declaratively a javascript view model to UI elements. That's pretty cool. But even better, Knockout will update your UI automatically whenever the underlying view model changes. It does this when you declare your model as an observable:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;var&lt;/span&gt; WidgetViewModel = {
    shape: ko.observable(&lt;span class="str"&gt;'Square'&lt;/span&gt;),
    color: ko.observable(&lt;span class="str"&gt;'Purple'&lt;/span&gt;),
    teeth: ko.observable(12)
};&lt;/pre&gt;
&lt;p&gt;How about a demonstration? Let's say we want to monitor several running widgets and update their operational&amp;nbsp;status on a web page every 5 seconds. That means polling with a timer. I'm going to show you one way to do it.&lt;/p&gt;
&lt;p&gt;Fire up Visual Studio and create a new MVC 3 project called "WidgetMonitor". Knockout (currently v2.0) is&amp;nbsp;available through NuGet so search for knockoutjs and add it to the project. You can also add it with the console by running the command &lt;strong&gt;Install-Package knockoutjs&lt;/strong&gt;. In your &lt;strong&gt;_Layout.cshtml&lt;/strong&gt; reference the library:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; 
    &lt;span class="attr"&gt;src&lt;/span&gt;&lt;span class="kwrd"&gt;="@Url.Content("&lt;/span&gt;~/&lt;span class="attr"&gt;Scripts&lt;/span&gt;/&lt;span class="attr"&gt;knockout-2&lt;/span&gt;.&lt;span class="attr"&gt;0&lt;/span&gt;.&lt;span class="attr"&gt;0&lt;/span&gt;.&lt;span class="attr"&gt;js&lt;/span&gt;&lt;span class="kwrd"&gt;")"&lt;/span&gt; 
    &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Add a new Widget model to your solution:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsSpinning { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Shape { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Color { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;p&gt;Now we need to modify our &lt;strong&gt;HomeController&lt;/strong&gt; to return a collection of widgets. To keep it simple it will have a single &lt;strong&gt;GetWidgets&lt;/strong&gt; method. And to make it interesting each widget will have a random boolean value for its &lt;strong&gt;IsSpinning&lt;/strong&gt; property:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HomeController : Controller
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Index()
    {
        ViewBag.Message = &lt;span class="str"&gt;"Welcome to SquareWidget.com!"&lt;/span&gt;;
        &lt;span class="kwrd"&gt;return&lt;/span&gt; View();
    }

    [OutputCache(Duration = 0)]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; JsonResult GetWidgets()
    {
        IEnumerable&amp;lt;Widget&amp;gt; widgets = &lt;span class="kwrd"&gt;new&lt;/span&gt;[]
        {
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget { IsSpinning = CheckWidget(), Shape = &lt;span class="str"&gt;"Round"&lt;/span&gt;, Color = &lt;span class="str"&gt;"Orange"&lt;/span&gt; },
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget { IsSpinning = CheckWidget(), Shape = &lt;span class="str"&gt;"Square"&lt;/span&gt;, Color = &lt;span class="str"&gt;"Purple"&lt;/span&gt; },
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget { IsSpinning = CheckWidget(), Shape = &lt;span class="str"&gt;"Triangular"&lt;/span&gt;, Color = &lt;span class="str"&gt;"Blue"&lt;/span&gt; }
        };

        &lt;span class="kwrd"&gt;return&lt;/span&gt; Json(widgets, JsonRequestBehavior.AllowGet);
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; CheckWidget()
    {
        Thread.Sleep(100);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Random().Next() % 2 == 0;
    }
}&lt;/pre&gt;
&lt;p&gt;So far this is standard MVC stuff. Go to the &lt;strong&gt;Index.cshtml&lt;/strong&gt; view for the HomeController. First, we're going to create a table to hold our widgets. The table will be ordinary in all respects except Knockout requires us to use declarative binding with the data-bind attribute for our properties that will be bound to the javascript view model:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;@{
    ViewBag.Title = "Widget Page";
}

&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Widgets&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;table&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;thead&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Spinning&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Shape&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Color&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;thead&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;tbody&lt;/span&gt; &lt;span class="attr"&gt;data-bind&lt;/span&gt;&lt;span class="kwrd"&gt;="foreach: widgets"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt; &lt;span class="attr"&gt;data-bind&lt;/span&gt;&lt;span class="kwrd"&gt;="text: spinning"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt; &lt;span class="attr"&gt;data-bind&lt;/span&gt;&lt;span class="kwrd"&gt;="text: shape"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt; &lt;span class="attr"&gt;data-bind&lt;/span&gt;&lt;span class="kwrd"&gt;="text: color"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;tbody&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;table&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href="http://knockoutjs.com/documentation/text-binding.html"&gt;text binding&lt;/a&gt; is the workhorse of Knockout but there are others. Behind the scenes it will update the innerText (or textContent) for the element to which it is bound. Notice the foreach binding. Just like the foreach statement in C# this is the way you handle an array of data in Knockout.&lt;/p&gt;
&lt;p&gt;Ok, we've got our UI above. Now let's dive right into the javascript. Below the table create a script region and declare a local variable called widgets:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;var&lt;/span&gt; widgets = ko.observableArray([]);

&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;According to the Knockout &lt;a href="http://knockoutjs.com/documentation/observableArrays.html"&gt;documentation on observables&lt;/a&gt; "if you want to detect and respond to changes on one object, you&amp;rsquo;d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray." In our case we're monitoring a collection of widgets so we want to use an observableArray. Notice that it is initialized to an empty list. Below the array add these two view models:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;function Widget(spinning, shape, color) {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.spinning = ko.observable(spinning);
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.shape = ko.observable(shape);
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.color = ko.observable(color);
}

function WidgetListViewModel() {
    &lt;span class="kwrd"&gt;var&lt;/span&gt; self = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
    self.widgets = widgets;
}&lt;/pre&gt;
&lt;p&gt;Notice that &lt;strong&gt;Widget&lt;/strong&gt; is sort of like a data transfer object, or at least identical to our server-side object. Each property is declared as an observable. The &lt;strong&gt;WidgetListViewModel&lt;/strong&gt; is nothing more than a container for our widgets. When it is initialized or updated it will always set its local widgets property to the widgets observable array.&lt;/p&gt;
&lt;p&gt;So far so good. We've got our client-side view models declared. Now for the polling part that will update them every 5 seconds. Below the WidgetListViewModel add these two functions:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;function pollSystems() {

    widgets.removeAll();
        
    $.getJSON(&lt;span class="str"&gt;'/Home/GetWidgets'&lt;/span&gt;, function (data) {
        $.each(data, function () {
            widgets.push(&lt;span class="kwrd"&gt;new&lt;/span&gt; Widget(&lt;span class="kwrd"&gt;this&lt;/span&gt;.IsSpinning, &lt;span class="kwrd"&gt;this&lt;/span&gt;.Shape, &lt;span class="kwrd"&gt;this&lt;/span&gt;.Color));
        });
    });

    setTimeout(&lt;span class="str"&gt;"pollSystems()"&lt;/span&gt;, 5000);
}
    
$(function () {
    pollSystems();
});&lt;/pre&gt;
&lt;p&gt;Notice that most of this is just plain old jQuery. The document ready event calls the pollSystems function to kick things off. It will call setTimeout so it calls itself every 5 seconds. The Knockout magic comes in with the push function call. Knockout will add the new Widget to the widgets observableArray and then notify its listeners of the change. Those listeners will update your UI table automatically. What is the glue that binds the data-bind elements with the observables? The magic is with a function call applyBindings. Add it now:&lt;/p&gt;
&lt;pre class="csharpcode"&gt;ko.applyBindings(&lt;span class="kwrd"&gt;new&lt;/span&gt; WidgetListViewModel());&lt;/pre&gt;
&lt;p&gt;This is how you activate Knockout. Build and run the app and you should see a list of widgets that update every 5 seconds:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://squarewidget.azurewebsites.net/Media/Default/Media/Default/Images/widgets.png" alt="" width="604" height="357"&gt;&lt;/p&gt;
</description><pubDate>Thu, 02 Feb 2012 05:51:38 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/polling-with-knockout-jquery-ajax-and-mvc</guid></item><item><title>ChannelFactory, IDisposable and Handling Faults</title><link>http://www.squarewidget.com:80/channelfactory-idisposable-and-handling-faults</link><description>&lt;p&gt;In my last post (&lt;a href="http://squarewidget.com/poor-mans-publish-subscribe-wcf-service" target="_blank"&gt;Poor Man's Publish-Subscribe WCF Service&lt;/a&gt;) I used the ChannelFactory to build a communication channel that I could use to call a WCF service. There's something about that implementation that I wanted to explain in more detail. Notice the try-catch block surrounding the using statement:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    &lt;span class="kwrd"&gt;var&lt;/span&gt; channel = BuildSubscriberClientChannel(subscriber);
    &lt;span class="kwrd"&gt;using&lt;/span&gt; (channel &lt;span class="kwrd"&gt;as&lt;/span&gt; IDisposable)
    {
        channel.Notify(eventCode);
    }
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt;
{
    &lt;span class="rem"&gt;// in case using statement throws error&lt;/span&gt;
}&lt;/pre&gt;
&lt;p&gt;The ChannelFactory explicitly implements IDisposable.Dispose. And of course a call to CreateChannel returns an instance of the contract for the service. That's why I can convert the channel to IDisposable. This will force a call to Dispose, which is the same as a call to Close, when the code leaves the using block. But if an exception is thrown and the channel is faulted then you should be prepared to handle it. In my case I didn't want the exception to bubble all the way up to the client. So I wrapped it in a try-catch block. This is useful for another reason. I can let the GC take care of the faulted channel and create another one to retry the caller later.&lt;/p&gt;
&lt;p&gt;Certainly channels are expensive to set up and tear down. But this is the cost of doing business when WCF services call each other. They have explicit boundaries and we're not dealing here with simple calls to objects on the heap. So you have to think about a strategy for what happens when the channel is faulted. In my case I wanted to build in some message durability. So in the catch block I save the message and subscriber ID in a local failed message table. Then I have a job that kicks off at regular intervals and checks the failed message table for messages. For each one it attempts to resend the message. On success it deletes the entry from the failed messages table. If the channel still faults or there is some other exception then it does nothing so that we can try again later.&lt;/p&gt;</description><pubDate>Mon, 23 Jan 2012 10:27:52 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/channelfactory-idisposable-and-handling-faults</guid></item><item><title>Poor Man's Publish-Subscribe WCF Service</title><link>http://www.squarewidget.com:80/poor-mans-publish-subscribe-wcf-service</link><description>&lt;p&gt;I'm going to describe a WCF implementation of a publish-subscribe pattern that is used here at a medium-sized organization where I'm a lead developer. For reasons I won't go into MSMQ and the cloud were not options for us. Yet we needed durability, reliability, and all of the goodness that comes with a service bus. So we rolled our own "poor man's" pub sub (or observer pattern) service a simplified version of which I'll describe here.&lt;/p&gt;
&lt;p&gt;First a big shout out to Juval Loewy whose book &lt;em&gt;Programming WCF Services&lt;/em&gt; describes a publish-subscribe framework. It's well thought out and I highly recommend it. My implementation is inspired by his framework. I'm going to assume you already know a good deal about WCF but if you don't get Loewy's book.&lt;/p&gt;
&lt;p&gt;This diagram explains the pub sub architecture. A message or event is raised and sent to the publisher. The publisher in turn is responsible for notifying all of the subscribers of that event. In this way the originator of the message is decoupled from the subscribers.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://squarewidget.azurewebsites.net/Media/Default/Media/Default/Images/publisher.png" alt="" align="middle" width="300" height="260"&gt;&lt;/p&gt;
&lt;p&gt;I organized the WCF publisher service into three projects:&amp;nbsp;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Publisher&lt;/li&gt;
&lt;li&gt;Publisher.Contracts&lt;/li&gt;
&lt;li&gt;Publisher.Domain&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Publisher is the main WCF service application with two files: Publisher.svc and Web.config.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Publisher.Contracts contains the service and operation contracts for the Publisher service. And following Miguel Castro's advice I put all domain functionality, the models, repositories, and Entity Framework wiring into the separate Publisher.Domain project. This project is ignorant of WCF and can be reused in other solutions. I won't go into all of the EF plumbing but let's look at the Subscription model:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Subscription
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; ID { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; EventCode { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Address { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; EndpointIdentity { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;p&gt;By way of example if you wanted to simulate a SubscriptionRepository class to serve up test subscriptions here is one:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SubscriptionRepository
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IList&amp;lt;Subscription&amp;gt; GetSubscriptions(&lt;span class="kwrd"&gt;string&lt;/span&gt; eventCode)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; GetMockSubscriptions()
            .Where(s =&amp;gt; s.EventCode == eventCode.Trim().ToUpper())
            .ToList();
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Subscription&amp;gt; GetMockSubscriptions()
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt;[]
        {
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Subscription()
            {
                ID = 1,
                Name = &lt;span class="str"&gt;"Subscriber 1"&lt;/span&gt;,
                EventCode = &lt;span class="str"&gt;"EVENT_A"&lt;/span&gt;,
                Address = &lt;span class="str"&gt;"net.tcp://foo.com/Subscriber1/Subscriber.svc"&lt;/span&gt;,
                EndpointIdentity = &lt;span class="str"&gt;"serviceaccountuser@domain.com"&lt;/span&gt;
            },
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Subscription()
            {
                ID = 2,
                Name = &lt;span class="str"&gt;"Subscriber 1"&lt;/span&gt;,
                EventCode = &lt;span class="str"&gt;"EVENT_B"&lt;/span&gt;,
                Address = &lt;span class="str"&gt;"net.tcp://foo.com/Subscriber1/Subscriber.svc"&lt;/span&gt;,
                EndpointIdentity = &lt;span class="str"&gt;"serviceaccountuser@domain.com"&lt;/span&gt;
            },
            &lt;span class="kwrd"&gt;new&lt;/span&gt; Subscription()
            {
                ID = 3,
                Name = &lt;span class="str"&gt;"Subscriber 2"&lt;/span&gt;,
                EventCode = &lt;span class="str"&gt;"EVENT_B"&lt;/span&gt;,
                Address = &lt;span class="str"&gt;"net.tcp://bar.com/Subscriber2/Subscriber.svc"&lt;/span&gt;,
                EndpointIdentity = &lt;span class="str"&gt;"serviceaccountuser@domain.com"&lt;/span&gt;
            },
        };
    }
}&lt;/pre&gt;
&lt;p&gt;So as you can see we have subscriptions and a repository to return them based on the event code passed in. The idea with the publish-subscribe pattern is that every publisher will have zero or more subscribers. In this example there is only one subscriber who wants to be notified when event code A is published. But there are two subscribers who want to be notified when event code B is published. Notice the Address and EndpointIdentity properties of a Subscription. That will come in handy later because given those two pieces of information we can create a channel to call the subscriber.&lt;/p&gt;
&lt;p&gt;Let's look at the Publisher.Contracts project and the brains behind it all. The service contract does one thing and and one thing only:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[ServiceContract]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; INotification
{
    [OperationContract]
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Notify(&lt;span class="kwrd"&gt;string&lt;/span&gt; eventCode);
}&lt;/pre&gt;
&lt;p&gt;Pretty straightforward. Before I describe the service itself let's look at a base class from which the service will derive. This base class has one job: given a Subscription build and return a communication channel that the publisher can use to communicate with the subscriber service.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PublisherBase&amp;lt;T&amp;gt; where T : &lt;span class="kwrd"&gt;class&lt;/span&gt;
{
    &lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T BuildSubscriberClientChannel(Subscription subscriber)
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; binding = CreateNetTcpBinding();
        &lt;span class="kwrd"&gt;var&lt;/span&gt; endpoint = CreateEndpointAddress(subscriber);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; ChannelFactory&amp;lt;T&amp;gt;.CreateChannel(binding, endpoint);
    }

    &lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; NetTcpBinding CreateNetTcpBinding()
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; binding = &lt;span class="kwrd"&gt;new&lt;/span&gt; NetTcpBinding
        {
            ReliableSession = { Enabled = &lt;span class="kwrd"&gt;true&lt;/span&gt; },
            TransactionFlow = &lt;span class="kwrd"&gt;false&lt;/span&gt;,
            Security = { Mode = SecurityMode.Transport }
        };

        binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
        binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
        binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
        &lt;span class="kwrd"&gt;return&lt;/span&gt; binding;
    }

    &lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; EndpointAddress CreateEndpointAddress(Subscription subscriber)
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; uri = &lt;span class="kwrd"&gt;new&lt;/span&gt; Uri(subscriber.Address);
        &lt;span class="kwrd"&gt;var&lt;/span&gt; identity = EndpointIdentity.CreateUpnIdentity(subscriber.EndpointIdentity);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; EndpointAddress(uri, identity, &lt;span class="kwrd"&gt;new&lt;/span&gt; AddressHeaderCollection());
    }
}&lt;/pre&gt;
&lt;p&gt;For the sake of simplicity in this post, I'm making some design-time decisions. All of our subscribers must use the net.tcp protocol, authenticate with Windows Kerberos security, and communicate over an encrypted transport. The identity used to authenticate the call (serviceaccountuser@domain.com) is a user principal name that your sysadmin will need to configure on the IIS server:&lt;/p&gt;
&lt;pre&gt;    setspn -a HTTP/domain.com DOMAIN\serviceaccountuser
    setspn -a HTTP/server DOMAIN\serviceaccountuser&lt;/pre&gt;
&lt;p&gt;Like I said earlier I'm going to assume you're up to speed on WCF security. See Loewy's book or MSDN for selecting transport and credential types in your particular situation. I &amp;nbsp;can tell you that the security here is perfect for an intranet environment. By choosing transport security as our security mode the channel over which the messages are sent is both encrypted and signed. I have not seen performance issues with this configuration. And it's way better than the old days when an ASMX service had to send and receive SOAP packets over a much slower SSL. Other than the decision to use NetTcpBinding in an intranet scenario I'm using the ChannelFactory class to generate the communication channel we'll need to call the subscriber.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Last, we need to create a PublisherService that implements our INotification service contract (the Notify operation). But I want to do it in such a way that the caller is not hanging out waiting a long time for the request-reply operation to complete. If there are 12 subscribers for an event then I don't want the caller blocking and taking up that connection while our publisher service generates 12 channels and calls each subscriber before a TimeoutException occurs. I could have configured a one-way operation and perhaps you'll want to do that. But for our purposes here I'm using a simple delegate function to pass off the work to another thread so I can respond back to the client right away.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PublisherService : PublisherBase&amp;lt;INotification&amp;gt;, INotification
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; PublishEventDelegate(&lt;span class="kwrd"&gt;string&lt;/span&gt; eventCode);

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Notify(&lt;span class="kwrd"&gt;string&lt;/span&gt; eventCode)
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; eventDelegate = &lt;span class="kwrd"&gt;new&lt;/span&gt; PublishEventDelegate(PublishEvent);
        eventDelegate.BeginInvoke(eventCode, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; PublishEvent(&lt;span class="kwrd"&gt;string&lt;/span&gt; eventCode)
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; subscribers = SubscriptionRepository.GetSubscriptions(eventCode);
        &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;var&lt;/span&gt; subscriber &lt;span class="kwrd"&gt;in&lt;/span&gt; subscribers)
        {
            &lt;span class="kwrd"&gt;try&lt;/span&gt;
            {
                &lt;span class="kwrd"&gt;var&lt;/span&gt; channel = BuildSubscriberClientChannel(subscriber);
                &lt;span class="kwrd"&gt;using&lt;/span&gt; (channel &lt;span class="kwrd"&gt;as&lt;/span&gt; IDisposable)
                {
                    channel.Notify(eventCode);
                }
            }
            &lt;span class="kwrd"&gt;catch&lt;/span&gt;
            {
                Debug.WriteLine(&lt;span class="str"&gt;"Unable to publish event to subscriber"&lt;/span&gt;);
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;That's pretty much it. The PublisherService receives an event code (a very generic payload in this case, perhaps a more robust data contract in your situation) and for each subscription to that event creates a communication channel and calls the Notify operation. Notice the catch block. What I did in my implementation was build in some durability there instead of just throwing it away. Perhaps I'll describe that in another blog post.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here's my service configuration in Web.config:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;service&lt;/span&gt;
    &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="Publisher.Contracts.PublisherService"&lt;/span&gt;
    &lt;span class="attr"&gt;behaviorConfiguration&lt;/span&gt;&lt;span class="kwrd"&gt;="publisherServiceBehavior"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;endpoint&lt;/span&gt;
      &lt;span class="attr"&gt;address&lt;/span&gt;&lt;span class="kwrd"&gt;="net.tcp://localhost/Publisher/Publisher.svc"&lt;/span&gt;
      &lt;span class="attr"&gt;binding&lt;/span&gt;&lt;span class="kwrd"&gt;="netTcpBinding"&lt;/span&gt;
      &lt;span class="attr"&gt;contract&lt;/span&gt;&lt;span class="kwrd"&gt;="Publisher.Contracts.INotification"&lt;/span&gt;
      &lt;span class="attr"&gt;bindingConfiguration&lt;/span&gt;&lt;span class="kwrd"&gt;="reliableTCPBinding"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;endpoint&lt;/span&gt;
      &lt;span class="attr"&gt;address&lt;/span&gt;&lt;span class="kwrd"&gt;="mex"&lt;/span&gt;
      &lt;span class="attr"&gt;binding&lt;/span&gt;&lt;span class="kwrd"&gt;="mexTcpBinding"&lt;/span&gt;
      &lt;span class="attr"&gt;contract&lt;/span&gt;&lt;span class="kwrd"&gt;="IMetadataExchange"&lt;/span&gt;
    &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;service&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;There's not much to the binding because the security was done programmatically above in the PublisherBase class:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;bindings&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;netTcpBinding&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;binding&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="reliableTCPBinding"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;reliableSession&lt;/span&gt; &lt;span class="attr"&gt;enabled&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;binding&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;netTcpBinding&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;bindings&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;The service behavior is straight out of the box:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;behaviors&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;serviceBehaviors&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;behavior&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="publisherServiceBehavior"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;serviceMetadata&lt;/span&gt; 
          &lt;span class="attr"&gt;httpGetEnabled&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt; 
          &lt;span class="attr"&gt;policyVersion&lt;/span&gt;&lt;span class="kwrd"&gt;="Policy12"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;serviceDebug&lt;/span&gt; 
          &lt;span class="attr"&gt;httpHelpPageEnabled&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt; 
          &lt;span class="attr"&gt;includeExceptionDetailInFaults&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;behavior&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;serviceBehaviors&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;behaviors&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;We now have a bare-bones secure publish-subscribe service. There's room for improvement. For instance Loewy's implementation supports concurrent publishing of the events with a WaitCallback delegate function. So if it's important for all of the subscribers to get notifications in near real time then you'll want to take a look at that. Message durability is also missing in this example. What I did was to save the failed message for that subscriber in a local store. Then I have a process to check for failed messages at regular intervals and to try to resend them. That's the "poor man" part of this implementation because you get that for free with MSMQ. But it works like a champ so I'm not going to complain.&lt;/p&gt;</description><pubDate>Fri, 20 Jan 2012 03:35:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/poor-mans-publish-subscribe-wcf-service</guid></item><item><title>Snuggle up to jquery $.ajax</title><link>http://www.squarewidget.com:80/Snuggle-up-to-jquery-ajax</link><description>&lt;p&gt;In an &lt;a href="http://bit.ly/ikwRq9"&gt;earlier post&lt;/a&gt; I described how to use the MVC 3 Ajax.ActionLink to post an async delete back to the server. Ajax.ActionLink depends upon jquery.unobtrusive-ajax.js, a script included with the MVC 3 project template. As &lt;a href="http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-
ajax.html"&gt;Brad Wilson&lt;/a&gt; has blogged, and I demonstrated, you create an &lt;a href="http://msdn.microsoft.com/en-
us/library/system.web.mvc.ajax.ajaxoptions.aspx"&gt;AjaxOptions&lt;/a&gt; class and pass it into the ActionLink method constructor. When the view is rendered those properties are emitted with the anchor tag as HTML 5 &lt;a href="http://dev.w3.org/html5/spec/Overview.html#custom-data-attribute"&gt;data-* attributes&lt;/a&gt;:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;a&lt;/span&gt; &lt;span class="attr"&gt;data-ajax&lt;/span&gt;&lt;span class="kwrd"&gt;="true"&lt;/span&gt; 
   &lt;span class="attr"&gt;data-ajax-confirm&lt;/span&gt;&lt;span class="kwrd"&gt;="Are you sure you want to delete this widget?"&lt;/span&gt; 
   &lt;span class="attr"&gt;data-ajax-method&lt;/span&gt;&lt;span class="kwrd"&gt;="POST"&lt;/span&gt; 
   &lt;span class="attr"&gt;data-ajax-success&lt;/span&gt;&lt;span class="kwrd"&gt;="deleteConfirmation"&lt;/span&gt; 
   &lt;span class="attr"&gt;href&lt;/span&gt;&lt;span class="kwrd"&gt;="/Widget/Delete/1"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Delete&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;a&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Enter the jquery.unobtrusive-ajax.js script. I won't go into too much detail (because you can see it for yourself) but essentially the asyncRequest function takes those HTML 5 data attributes and builds a call to the jquery $.ajax function. Is it just a wrapper? Well yes, but a very convenient one because it promotes strong typing in your razor view and saves you from the messy details of creating a $.ajax function call on your own.&lt;/p&gt;
&lt;p&gt;If you don't like the Ajax.ActionLink helper you're always free to roll your own. And it's easy. Take the same project from my previous blog post. Nothing changes with the Widget and WidgetController classes. Now in the Index.cshtml file replace the Ajax.ActionLink with a plain old anchor tag:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&amp;lt;a href=&lt;span class="str"&gt;"javascript:void(0)"&lt;/span&gt; id=&lt;span class="str"&gt;"@item.Id"&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt;=&lt;span class="str"&gt;"delete-widget-link"&lt;/span&gt;&amp;gt;Delete&amp;lt;/a&amp;gt;&lt;/pre&gt;
&lt;p&gt;Then replace the script region with the following ajax funtion call:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&amp;lt;script type=&lt;span class="str"&gt;"text/javascript"&lt;/span&gt;&amp;gt;
 
    $(&lt;span class="str"&gt;'.delete-widget-link'&lt;/span&gt;).click(function() {
        &lt;span class="rem"&gt;// get the id of the selected widget&lt;/span&gt;
        &lt;span class="kwrd"&gt;var&lt;/span&gt; id = $(&lt;span class="kwrd"&gt;this&lt;/span&gt;).attr(&lt;span class="str"&gt;"Id"&lt;/span&gt;);
 
        &lt;span class="rem"&gt;// delete on server&lt;/span&gt;
        $.ajax({
            type: &lt;span class="str"&gt;"POST"&lt;/span&gt;,
            url: &lt;span class="str"&gt;"Widget/Delete/"&lt;/span&gt; + id,
            success: handleDeleteSuccess,
            error: function () {
                $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).text(&lt;span class="str"&gt;'Delete failed...'&lt;/span&gt;);
                $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).effect(&lt;span class="str"&gt;"highlight"&lt;/span&gt;, {}, 3000);
            }         
        });
    })
 
    function handleDeleteSuccess(data) {
        &lt;span class="rem"&gt;// remove the row from the table&lt;/span&gt;
        &lt;span class="kwrd"&gt;var&lt;/span&gt; rowId = &lt;span class="str"&gt;"#widget-id-"&lt;/span&gt; + data.id;
        $(&lt;span class="str"&gt;'.widgets'&lt;/span&gt;).find(rowId).remove();
 
        &lt;span class="rem"&gt;// display a status message with highlight&lt;/span&gt;
        $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).text(data.message);
        $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).effect(&lt;span class="str"&gt;"highlight"&lt;/span&gt;, {}, 3000);
    }
    
&amp;lt;/script&amp;gt;&lt;/pre&gt;

&lt;p&gt;That's it. You're still unobtrusive. But you're now making a direct call to the jquery $.ajax function instead of going through the jquery.unobtrusive-ajax.js script.&lt;/p&gt;</description><pubDate>Sat, 18 Jun 2011 16:49:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/Snuggle-up-to-jquery-ajax</guid></item><item><title>InvalidOperationException Using EF Code First</title><link>http://www.squarewidget.com:80/InvalidOperationException-Using-EF-Code-First</link><description>&lt;p&gt;If you're using EF 4.1 "Code First" and make changes to your model you get the following error:&lt;/p&gt;
&lt;pre&gt;System.InvalidOperationException was unhandled by user code
Message=The model backing the 'MyContext' context has changed since
the database was created. Either manually delete/update the database,
or call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will 
automatically delete and recreate the database, and optionally seed it
with new data.&lt;/pre&gt;
&lt;p&gt;I've mentioned this in previous blog posts and it's annoying. If you want to make it go away add the following line to your DbContext instance. Just remember, by doing this you're telling EF that you will be responsible for keeping the mapping between the database and your entities in sync.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyContext : DbContext
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DbSet&amp;lt;Foo&amp;gt; Foos { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DbSet&amp;lt;Bar&amp;gt; Bars { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnModelCreating(DbModelBuilder modelBuilder)
    {
        &lt;span class="kwrd"&gt;base&lt;/span&gt;.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove&amp;lt;System.Data.Entity
           .Infrastructure.IncludeMetadataConvention&amp;gt;(); 
    }
}&lt;/pre&gt;</description><pubDate>Thu, 09 Jun 2011 14:26:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/InvalidOperationException-Using-EF-Code-First</guid></item><item><title>Taking Your Game to the Next Level: FluentValidation</title><link>http://www.squarewidget.com:80/Taking-Your-Game-to-the-Next-Level-FluentValidation</link><description>&lt;p&gt;This is the last in a three-part series on validation techniques in MVC 3. See the &lt;a href="http://bit.ly/lLdcyI"&gt;first post&lt;/a&gt; and the &lt;a href="http://bit.ly/inaZvC"&gt;second post&lt;/a&gt; to get the solution set up.&lt;/p&gt;
&lt;p&gt;Try this experiment: make sure your Global.asax Application_Start or database context does not have a database SetInitializer method exposed. That's the one that drops and recreates the database if the model changes. Ok, now go into your Widget model class and remove an attribute. Maybe one of the [Required] attributes above Name or Color. Now build and run the app and go to the Widget list. Yep, the app throws an InvalidOperationException with the error message "The model backing the 'WidgetApplicationContext' context has changed since the database was created." Oops, that would mean your database gets wiped out and you have to re-run your populate scripts. Nice huh?&lt;/p&gt;
&lt;p&gt;So why do we care? We'll have our properties decorated at design time and we won't mess with them. That's true for the obvious ones like GreaterThan, Length, or Required. But what about the custom attributes? NameAvailableAttribute is required today but it might not be tomorrow. We might have other business rules we want to implement as we go along and what a hassle it would be add and remove attributes, thus breaking our EF model. Wouldn't it be cool to decouple as much as possible the validators and business rules from the model class? There are several good ways to do it but I want to illustrate &lt;a href="http://fluentvalidation.codeplex.com/"&gt;FluentValidation&lt;/a&gt; written by Jeremy Skinner because I think it's one of the most elegant solutions to this problem.&lt;/p&gt;
&lt;p&gt;To install make sure you have &lt;a href="http://nuget.codeplex.com/wikipage?title=Getting%20Started"&gt;nuget&lt;/a&gt; installed. Then right-click on your References folder and choose "Add Library Package Reference". Search online for FluentValidation and install the FluentValidation.MVC3 package.&lt;/p&gt;
&lt;p&gt;If you look at &lt;a href="http://bit.ly/inaZvC"&gt;part two in this series&lt;/a&gt; you'll notice that our Widget class is pretty busy. I don't know about you but I don't really like those validation attributes over each property (of course they are needed for client-side javascript validation). Also, for anything but the most trivial application putting all of your business rules in the Validate method is not going to work. FluentValidation will let us abstract the validator attributes and the business rules out into a separate class. Once they're there we can remove and add business rules all day long and we won't break our EF backing model.&lt;/p&gt;
&lt;p&gt;Let's get started. Create a new class in your Validators folder called WidgetValidator. Then move all of your rules into it so it looks like this:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; WidgetApplication.Models;
&lt;span class="kwrd"&gt;using&lt;/span&gt; FluentValidation;
 
&lt;span class="kwrd"&gt;namespace&lt;/span&gt; WidgetApplication.Validators
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; WidgetValidator : AbstractValidator&amp;lt;Widget&amp;gt;
    {
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MIN_RED_TEETH = 0;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MAX_RED_TEETH = 6;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MIN_BLUE_TEETH = 8;
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MAX_BLUE_TEETH = 12;
 
        &lt;span class="kwrd"&gt;public&lt;/span&gt; WidgetValidator()
        {
            RuleFor(w =&amp;gt; w.Name).NotEmpty();
            RuleFor(w =&amp;gt; w.Name).Length(1, 10);
            RuleFor(w =&amp;gt; w.NumberOfTeeth).NotEmpty();
            RuleFor(w =&amp;gt; w.Color).NotEmpty();
            RuleFor(w =&amp;gt; w)
                .Must(BeValidRedColor)
                .WithName(&lt;span class="str"&gt;"NumberOfTeeth"&lt;/span&gt;)
                .WithMessage(&lt;span class="str"&gt;"Wrong red tooth count."&lt;/span&gt;);
            RuleFor(w =&amp;gt; w)
                .Must(BeValidBlueColor)
                .WithName(&lt;span class="str"&gt;"NumberOfTeeth"&lt;/span&gt;)
                .WithMessage(&lt;span class="str"&gt;"Wrong blue tooth count."&lt;/span&gt;);
            RuleFor(w =&amp;gt; w)
                .Must(NameIsAvailable)
                .WithName(&lt;span class="str"&gt;"Name"&lt;/span&gt;)
                .WithMessage(ValidationMessagesResource.NameIsTaken);
        }
 
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; BeValidRedColor(Widget widget)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (widget.Color.ToUpper().Equals(&lt;span class="str"&gt;"RED"&lt;/span&gt;))
            {
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (widget.NumberOfTeeth &amp;lt; MIN_RED_TEETH || 
                    widget.NumberOfTeeth &amp;gt; MAX_RED_TEETH)
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;
            }
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;
        }
 
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; BeValidBlueColor(Widget widget)
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (widget.Color.ToUpper().Equals(&lt;span class="str"&gt;"BLUE"&lt;/span&gt;))
            {
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (widget.NumberOfTeeth &amp;lt; MIN_BLUE_TEETH || 
                    widget.NumberOfTeeth &amp;gt; MAX_BLUE_TEETH)
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;
            }
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;
        }
 
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; NameIsAvailable(Widget widget)
        {
            &lt;span class="kwrd"&gt;var&lt;/span&gt; context = &lt;span class="kwrd"&gt;new&lt;/span&gt; WidgetApplicationContext();
            &lt;span class="kwrd"&gt;var&lt;/span&gt; widgets = context.Widgets.ToList();
            &lt;span class="kwrd"&gt;return&lt;/span&gt; (!widgets.Any(w =&amp;gt; w.Name.ToLower().Equals(widget.Name.ToLower())));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;That greatly simplifies our Widget class. Now our Validate method just needs to call the WidgetValidator to get any broken rules:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.DataAnnotations;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;
&lt;span class="kwrd"&gt;using&lt;/span&gt; WidgetApplication.Validators;
&lt;span class="kwrd"&gt;using&lt;/span&gt; FluentValidationResult = FluentValidation.Results.ValidationResult;
 
&lt;span class="kwrd"&gt;namespace&lt;/span&gt; WidgetApplication.Models
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget : IValidatableObject
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; NumberOfTeeth { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Color { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;ValidationResult&amp;gt; Validate(ValidationContext validationContext)
        {
            &lt;span class="kwrd"&gt;var&lt;/span&gt; validator = &lt;span class="kwrd"&gt;new&lt;/span&gt; WidgetValidator();
            &lt;span class="kwrd"&gt;var&lt;/span&gt; results = validator.Validate(&lt;span class="kwrd"&gt;this&lt;/span&gt;);
 
            &lt;span class="kwrd"&gt;return&lt;/span&gt; results.Errors.Select(e =&amp;gt; 
                &lt;span class="kwrd"&gt;new&lt;/span&gt; ValidationResult(e.ErrorMessage, &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { e.PropertyName })
            );       
        }
    }
}&lt;/pre&gt;

&lt;p&gt;That's much cleaner. Our Widget class doesn't know about the business rules, all it knows is that the WidgetValidator has them and will return any broken ones through its IValidatableObject Validate wrapper. You'll notice also that pretty much any kind of business rule you can think of can be accomodated in this pattern. There are RuleFor validators for plain old Required and Length attributes, RuleFor validators for cross-property validation on the class between Color and NumberOfTeeth, and in the NameIsAvailable method there is even a call to the database.&lt;/p&gt;</description><pubDate>Mon, 06 Jun 2011 17:06:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/Taking-Your-Game-to-the-Next-Level-FluentValidation</guid></item><item><title>Class-Level Validation in MVC 3 with IValidatableObject</title><link>http://www.squarewidget.com:80/Class-Level-Validation-in-MVC-3-with-IValidatableObject</link><description>&lt;p&gt;In a previous post I covered &lt;a href="http://squarewidget.com/Simple-and-Custom-Validation-in-MVC-3"&gt;simple and custom validators&lt;/a&gt; for model properties. Do read that post first to get a sample MVC 3 solution set up. Essentially at this point we have one out-of-the-box and one custom validator on our Widget class:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    [NameAvailable]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;Now let's say a widget has two new required properties: NumberOfTeeth and Color. Here we go:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; classWidget
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; intId { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    [NameAvailable]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; stringName { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; NumberOfTeeth { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    publicstring Color { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;We need to modify our faked out list in WidgetController to return a list with the new properties:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//&lt;/span&gt;
&lt;span class="rem"&gt;// GET: /Widget/&lt;/span&gt;
 
&lt;span class="kwrd"&gt;public&lt;/span&gt; ViewResult Index()
{
    &lt;span class="kwrd"&gt;var&lt;/span&gt; widgets = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;Widget&amp;gt;
    {
        &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() 
        {
            Id = 1, 
            Name = &lt;span class="str"&gt;"SquareWidget"&lt;/span&gt;, 
            NumberOfTeeth = 6, 
            Color = &lt;span class="str"&gt;"Red"&lt;/span&gt;
        },
        &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() 
        {
            Id = 2, 
            Name = &lt;span class="str"&gt;"RoundWidget"&lt;/span&gt;, 
            NumberOfTeeth = 8, 
            Color = &lt;span class="str"&gt;"Blue"&lt;/span&gt;
        }
    };

    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widgets);
}&lt;/pre&gt;

&lt;p&gt;One more thing. Modify the Widget Create.cshtml view and add the two new properties:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;@model WidgetApplication.Models.Widget
 
@{
    ViewBag.Title = "Create";
}
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Create&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;src&lt;/span&gt;&lt;span class="kwrd"&gt;="@Url.Content("&lt;/span&gt;~/&lt;span class="attr"&gt;Scripts&lt;/span&gt;/&lt;span class="attr"&gt;jquery&lt;/span&gt;.&lt;span class="attr"&gt;validate&lt;/span&gt;.&lt;span class="attr"&gt;min&lt;/span&gt;.&lt;span class="attr"&gt;js&lt;/span&gt;&lt;span class="kwrd"&gt;")"&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&amp;lt;script src=&lt;span class="str"&gt;"@Url.Content("&lt;/span&gt;~/Scripts/jquery.validate.unobtrusive.min.js&lt;span class="str"&gt;")"&lt;/span&gt; type=&lt;span class="str"&gt;"text/javascript"&lt;/span&gt;&amp;gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;fieldset&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;legend&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Widget&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;legend&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-label"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.LabelFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Name)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-field"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.EditorFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Name)
            @Html.ValidationMessageFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Name)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-label"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.LabelFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.NumberOfTeeth)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-field"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.EditorFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.NumberOfTeeth)
            @Html.ValidationMessageFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.NumberOfTeeth)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-label"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.LabelFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Color)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="editor-field"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.EditorFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Color)
            @Html.ValidationMessageFor(model =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; model.Color)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;input&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="submit"&lt;/span&gt; &lt;span class="attr"&gt;value&lt;/span&gt;&lt;span class="kwrd"&gt;="Create"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;fieldset&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
}
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    @Html.ActionLink("Back to List", "Index")
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Ok we're set up with a Widget class that is a little more complicated and lends itself to some basic cross-property validation. For instance let's say that all red widgets are small in size and have teeth no greater than 6. All blue widgets are medium in size and must have between 8 and 12 teeth. Since these two rules involve more than one property of the class this is a perfect candidate for implementing IValidatableObject on the Widget class. The interface is found in System.ComponentModel.DataAnnotations which is convenient since we've already referenced it in our class. IValidatableObject has one method we need to implement:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;IEnumerable&amp;lt;ValidationResult&amp;gt; Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)&lt;/pre&gt;

&lt;p&gt;Let's implement it now in our Widget class:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;public &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget : IValidatableObject
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MIN_RED_TEETH = 0;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MAX_RED_TEETH = 6;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MIN_BLUE_TEETH = 8;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; MAX_BLUE_TEETH = 12;
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    [NameAvailable]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; NumberOfTeeth { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    [Required]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Color { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;ValidationResult&amp;gt; Validate(ValidationContext validationContext)
    {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (Color.ToUpper().Equals(&lt;span class="str"&gt;"RED"&lt;/span&gt;))
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (NumberOfTeeth &amp;lt; MIN_RED_TEETH ||
                NumberOfTeeth &amp;gt; MAX_RED_TEETH)
 
                yield &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ValidationResult(
                ValidationMessagesResource.IncorrectRedWidgetToothCount,
                &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;"NumberOfTeeth"&lt;/span&gt; });
        }
 
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (Color.ToUpper().Equals(&lt;span class="str"&gt;"BLUE"&lt;/span&gt;))
        {
            NumberOfTeeth &amp;lt; MIN_BLUE_TEETH ||
            NumberOfTeeth &amp;gt; MAX_BLUE_TEETH)
            
            yield &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ValidationResult(
                ValidationMessagesResource.IncorrectBlueWidgetToothCount,
                &lt;span class="kwrd"&gt;new&lt;/span&gt;[] { &lt;span class="str"&gt;"NumberOfTeeth"&lt;/span&gt; });
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Well we've put off creating a database long enough. Now we need one because IValidatableObject requires a database context to do its thing. If you installed the the &lt;a href="http://bit.ly/g8M99D"&gt;VS 2010 SP1 WebPI Bundle&lt;/a&gt; you also installed SQL Server 4.0 Compact Edition. I'm going to use that database because it's quick, easy, and free. Here are the steps:&lt;/p&gt;
&lt;p&gt;First hook up the controller to our context. We need our Index method to fetch all widgets in the (soon to be created) database and we need our Create method to write new ones to it:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ViewResult Index()
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(db.Widgets.ToList());
}

[HttpPost]
&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Create(Widget widget)
{
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (ModelState.IsValid)
    {
        db.Widgets.Add(widget);
        db.SaveChanges();
        &lt;span class="kwrd"&gt;return&lt;/span&gt; RedirectToAction(&lt;span class="str"&gt;"Index"&lt;/span&gt;);  
    }
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widget);
}&lt;/pre&gt;

&lt;p&gt;Remember the WidgetApplicationContext file we created back with the scaffolder? That's what EF Code First 4.1 will use to create the database. But we have to initialize it so go into your Global.asax and paste this into your Application_Start method:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;System.Data.Entity.Database.SetInitializer(&lt;span class="kwrd"&gt;new&lt;/span&gt; System.Data.Entity.CreateDatabaseIfNotExists&amp;lt;WidgetApplication.Models.WidgetApplicationContext&amp;gt;());
&lt;/pre&gt;

&lt;p&gt;And of course we need to set our connection string in Web.config:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;connectionStrings&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;add&lt;/span&gt; &lt;span class="attr"&gt;name&lt;/span&gt;&lt;span class="kwrd"&gt;="WidgetApplicationContext"&lt;/span&gt;
        &lt;span class="attr"&gt;connectionString&lt;/span&gt;&lt;span class="kwrd"&gt;="data source=|DataDirectory|WidgetDatabase.sdf; Persist Security Info=false;"&lt;/span&gt; &lt;span class="attr"&gt;providerName&lt;/span&gt;&lt;span class="kwrd"&gt;="System.Data.SqlServerCe.4.0"&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;connectionStrings&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;/pre&gt;

&lt;p&gt;That's it. We've told EF to create a SQL Server 4.0 CE database in our App_Data folder and to use the models in our WidgetApplicationContext to create tables for us automatically. Go ahead and fire up the app and create a new widget called "PurpleWidget" that has 10 teeth and is colored purple (what else?). Notice that EF created our database for us and has inserted the new widget in there. Now let's add some code to our WidgetController Create method to check for class-level validation errors before saving it to the database:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;[HttpPost]
&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Create(Widget widget)
{
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (ModelState.IsValid)
    {
        &lt;span class="kwrd"&gt;var&lt;/span&gt; errors = db.GetValidationErrors();
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (errors.Count() &amp;gt; 0)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widget);
        }
        db.Widgets.Add(widget);
        db.SaveChanges();
        &lt;span class="kwrd"&gt;return&lt;/span&gt; RedirectToAction(&lt;span class="str"&gt;"Index"&lt;/span&gt;);  
    }
 
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widget);
}
&lt;/pre&gt;

&lt;p&gt;Now's a good time to add a couple of error messages to your string table or just hard-code them in the Validate method. Now build the app and fire it up. Create a new widget called "RedWidget" with 50 teeth and the color Red. Notice how our class-level validation kicks in and your error message displays next to the correct property.&lt;/p&gt;</description><pubDate>Mon, 06 Jun 2011 12:36:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/Class-Level-Validation-in-MVC-3-with-IValidatableObject</guid></item><item><title>Simple and Custom Validation in MVC 3</title><link>http://www.squarewidget.com:80/Simple-and-Custom-Validation-in-MVC-3</link><description>&lt;p&gt;This is the first of a series on validation and business rules in MVC 3. I'll start out simple and we'll work out way up to the more complex. I'm going to build on the solution created in the previous blog post (&lt;a href="http://squarewidget.com/Delete-Like-a-Rock-Star-with-MVC3-Ajax-and-jQuery"&gt;Delete Like a Rock Star&lt;/a&gt;) so go there and get set up.&lt;/p&gt;
&lt;p&gt;Ok. MVC 3 models (POCOs, classes, whatever) can take advantage of a whole host of validation attributes located in System.ComponentModel.DataAnnotations. Throw the object browser on there and you can see them all. Let's take a basic one. Who doesn't love a required field? Let's put one on our Widget name:&lt;/p&gt;

&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.DataAnnotations;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Linq;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Web;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; YourSolutionNamespace.Validators;&lt;/pre&gt;
&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; YourSolutionNamespace.Models&lt;/pre&gt;
&lt;pre class="alt"&gt;{&lt;/pre&gt;
&lt;pre&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget&lt;/pre&gt;
&lt;pre class="alt"&gt;    {&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { get; set; }&lt;/pre&gt;
&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;        [Required]&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { get; set; }&lt;/pre&gt;
&lt;pre class="alt"&gt;    }&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Notice I'm using System.ComponentModel.DataAnnotations. Before we fire up the app comment out the two lines in the controller's Create method that would ordinarily call EF:&lt;/p&gt;

&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;[HttpPost]&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Create(Widget widget)&lt;/pre&gt;
&lt;pre class="alt"&gt;{&lt;/pre&gt;
&lt;pre&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (ModelState.IsValid)&lt;/pre&gt;
&lt;pre class="alt"&gt;    {&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="rem"&gt;//db.Widgets.Add(widget);&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="alt"&gt;        &lt;span class="rem"&gt;//db.SaveChanges();&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; RedirectToAction(&lt;span class="str"&gt;"Index"&lt;/span&gt;);  &lt;/pre&gt;
&lt;pre class="alt"&gt;    }&lt;/pre&gt;
&lt;pre&gt; &lt;/pre&gt;
&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widget);&lt;/pre&gt;
&lt;pre&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now fire up the application, navigate to Widgets, and click the Create new link to be taken to the create new widget view. Try to save it without entering in a value for the name field. You get some nice out-of-the-box behavior. Now let's write a custom validator. Let's say that a new widget name cannot be the same as one already in the system. We'll need a custom validator called NameAvailableAttribute that encapsulates this requirement. Create a new folder called Validators. Then drop this class into the new folder:&lt;/p&gt;

&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; NameAvailableAttribute : ValidationAttribute&lt;/pre&gt;
&lt;pre&gt;{&lt;/pre&gt;
&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsValid(&lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;    {&lt;/pre&gt;
&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;value&lt;/span&gt; == &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;        {&lt;/pre&gt;
&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;&lt;/pre&gt;
&lt;pre&gt;        }&lt;/pre&gt;
&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; ((&lt;span class="kwrd"&gt;value&lt;/span&gt; &lt;span class="kwrd"&gt;is&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;) &amp;amp;&amp;amp; &lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty((&lt;span class="kwrd"&gt;string&lt;/span&gt;)&lt;span class="kwrd"&gt;value&lt;/span&gt;))&lt;/pre&gt;
&lt;pre class="alt"&gt;        {&lt;/pre&gt;
&lt;pre&gt;            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;&lt;/pre&gt;
&lt;pre class="alt"&gt;        }&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre class="alt"&gt;        var name = &lt;span class="kwrd"&gt;value&lt;/span&gt;.ToString().ToLower();&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre class="alt"&gt;        &lt;span class="rem"&gt;// fake a database lookup and bring back two widgets&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;        var widgetNames = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;Widget&amp;gt;()&lt;/pre&gt;
&lt;pre class="alt"&gt;        {&lt;/pre&gt;
&lt;pre&gt;            &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() { Id = 1, Name = &lt;span class="str"&gt;"SquareWidget"&lt;/span&gt;},&lt;/pre&gt;
&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() { Id = 2, Name = &lt;span class="str"&gt;"RoundWidget"&lt;/span&gt;}&lt;/pre&gt;
&lt;pre&gt;        };&lt;/pre&gt;
&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; (!widgetNames.Any(w =&amp;gt; w.Name.ToLower().Equals(name)));&lt;/pre&gt;
&lt;pre class="alt"&gt;    }&lt;/pre&gt;
&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; FormatErrorMessage(&lt;span class="kwrd"&gt;string&lt;/span&gt; name)&lt;/pre&gt;
&lt;pre&gt;    {&lt;/pre&gt;
&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; ValidationMessagesResource.NameIsTaken;&lt;/pre&gt;
&lt;pre&gt;    }&lt;/pre&gt;
&lt;pre class="alt"&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Two things here: I'm not talking to a database but just faking it out (in a future blog post I'll expand on this code). Second, I put an error code in a resource table and from FormatErrorMessage I just call it. You could just as easily hard-code the string here. Call me crazy but I like string tables for this sort of thing.&lt;/p&gt;
&lt;p&gt;Now we need to decorate our Name property in the Widget class. Reference the namespace to the new validator and add the new attribute:&lt;/p&gt;

&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;[Required]&lt;/pre&gt;
&lt;pre&gt;[NameAvailable]&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { get; set; }&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Build and fire up the app and go through the process of creating a new widget again. This time enter something like "Purple Widget" and make sure it behaves correctly. Then enter "SquareWidget" and you should see your custom error message.&lt;/p&gt;
&lt;p&gt;That's it for now. Places to go from here are client-side AJAX calls to our custom validators for database lookup scenarios, implementing class-level validation with IValidatableObject, and using Ninject to inject business rules (or services that know how to get them) into your model. These are topics for future blog posts.&lt;/p&gt;</description><pubDate>Sun, 05 Jun 2011 19:03:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/Simple-and-Custom-Validation-in-MVC-3</guid></item><item><title>Delete Like a Rock Star with MVC3, Ajax and jQuery</title><link>http://www.squarewidget.com:80/Delete-Like-a-Rock-Star-with-MVC3-Ajax-and-jQuery</link><description>&lt;p&gt;Sure you can be a chump and use the out-of-the-box delete functionality that the MvcScaffolding gives you. Or you can use a little jQuery and delete like a rock star. Get your project set up first. Create a new MVC3 web app in Visual Studio 2010. If you have SP1 you have a choice now: internet or intranet. I'll assume we're creating an internet app but it doesn't matter really. Next add a new model called Widget:&lt;/p&gt;


&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Widget
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Id { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name { &lt;span class="kwrd"&gt;get&lt;/span&gt;; &lt;span class="kwrd"&gt;set&lt;/span&gt;; }
}&lt;/pre&gt;
&lt;p&gt;Build the solution. Then right-click on Controllers folder and add a new controller called (what else?) WidgetController. Use the EF template and let the scaffolder do its thing. If your popup doesn't look like mine then you probably don't have SP1 installed:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://farm3.static.flickr.com/2697/5795167860_0a6be40343.jpg" alt=""&gt;&lt;/p&gt;
&lt;p&gt;Your WidgetController will be stubbed out for you. We're going to ignore the DbContext it references because this blog post ain't about EF. Just return a static list of widgets from your Index method:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ViewResult Index()
{
    &lt;span class="kwrd"&gt;var&lt;/span&gt; widgets = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;Widget&amp;gt;
    {
        &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() {Id = 1, Name = &lt;span class="str"&gt;"Purple Square Widget"&lt;/span&gt;},
        &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() {Id = 2, Name = &lt;span class="str"&gt;"Red Round Widget"&lt;/span&gt;},
        &lt;span class="kwrd"&gt;new&lt;/span&gt; Widget() {Id = 3, Name = &lt;span class="str"&gt;"Blue Octagonal Widget"&lt;/span&gt;}
    };
    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(widgets);
}&lt;/pre&gt;
&lt;p&gt;One last little detail. In your Shared folder edit _Layout.cshtml to add a menu link to the widget page:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;@Html.ActionLink("Widgets", "Index", "Widget")&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;li&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Ok build and run the app. Click on the Widgets tab and you should see your stubbed-out list of three widgets. Now click on the Delete link for one of them. See that postback with the big delete button? Do you really like that behavior? Neither do I. Wouldn't it be cooler to click the Delete link and be able to confirm and delete on the index page without posting back the entire page? That's the real subject of this post. So let's do it. Close your browser and get back into VS 2010.&lt;/p&gt;
&lt;p&gt;We're going to use jQuery for some client-side magic so in your _Layout.cshtml page reference two scripts:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;jquery-ui-1.8.11.min.js&lt;/li&gt;
&lt;li&gt;jquery.unobtrusive-ajax.min.js&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Now back at the WidgetController. You can see how the scaffolder created an action method for the GET verb and then another for the eventual POST from the confirmation page. Go ahead and comment out both of those methods and add this one:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[AcceptVerbs(HttpVerbs.Post)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; JsonResult Delete(&lt;span class="kwrd"&gt;int&lt;/span&gt; id)
{
    &lt;span class="rem"&gt;// let's just pretend we deleted it from the database&lt;/span&gt;
    &lt;span class="kwrd"&gt;var&lt;/span&gt; message = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Deleted Id '{0}' from the database!"&lt;/span&gt;, id);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Json(&lt;span class="kwrd"&gt;new&lt;/span&gt;
    {
        id = id,
        message = message
    });
}&lt;/pre&gt;
&lt;p&gt;Two things. I changed the return type to a JsonResult and I added a POST verb attribute to the method as a matter of best practice.&lt;/p&gt;
&lt;p&gt;Ok now go to your Widget Index.cshtml page. We want to do four things here. First, put a span tag above the table for a confirmation message. Second, change the Delete ActionLink to an Ajax call. Third, add a javascript function to handle the Ajax success callback. Finally, put some class names on the table so we can refer to them later. Rather than waste your time and mine let me just show the entire Index.cshtml page with all four of these changes:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;@model IEnumerable&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;WidgetApplication.Models.Widget&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
@{
    ViewBag.Title = "Index";
}
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Index&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;h2&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    @Html.ActionLink("Create New", "Create")
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;p&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;span&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="actionMessage"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;span&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;table&lt;/span&gt; &lt;span class="attr"&gt;class&lt;/span&gt;&lt;span class="kwrd"&gt;="widgets"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            Name
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;th&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
@foreach (var item in Model)
 {
     &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt; &lt;span class="attr"&gt;id&lt;/span&gt;&lt;span class="kwrd"&gt;="widget-id-@item.Id"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.DisplayFor(modelItem =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; item.Name)
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            @Html.ActionLink("Edit", "Edit", new {id = item.Id}) |
            @Html.ActionLink("Details", "Details", new {id = item.Id}) |
            @Ajax.ActionLink("Delete", "Delete", "Widget",
                new {id = item.Id},
                new AjaxOptions {
                    HttpMethod = "POST",
                    Confirm = "Are you sure you want to delete this widget?",
                    OnSuccess = "deleteConfirmation"
                })
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;td&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;tr&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
}
 
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;table&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt; &lt;span class="attr"&gt;type&lt;/span&gt;&lt;span class="kwrd"&gt;="text/javascript"&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
 
    &lt;span class="kwrd"&gt;function&lt;/span&gt; deleteConfirmation(response, status, data) {
 
        &lt;span class="rem"&gt;// remove the row from the table&lt;/span&gt;
        &lt;span class="kwrd"&gt;var&lt;/span&gt; rowId = &lt;span class="str"&gt;"#widget-id-"&lt;/span&gt; + response.id;
        $(&lt;span class="str"&gt;'.widgets'&lt;/span&gt;).find(rowId).remove();
 
        &lt;span class="rem"&gt;// display a status message with highlight&lt;/span&gt;
        $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).text(response.message);
        $(&lt;span class="str"&gt;'#actionMessage'&lt;/span&gt;).effect(&lt;span class="str"&gt;"highlight"&lt;/span&gt;, {}, 3000);
    }
    
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;script&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;See how the old delete ActionLink is now replaced with an Ajax action link? It's a little more verbose but not too bad. You have to tell it the controller name following the MVC convention. And there's a new AJaxOptions parameter with three settings: (1) HttpMethod to force a POST to the server; (2) Confirm to require client-side confirmation as a condition of the AJax post; and (3) OnSuccess to define a javascript callback function when we have a response.&lt;/p&gt;
&lt;p&gt;The jQuery magic is in that deleteConfirmation javascript function. Since the widget was deleted successfully server-side we need to remove it from the table. Since our table rows have a unique id on them we can find the exact tr tag and remove it from the table. That's a lot more elegant than calling a window.location.reload() or redirecting to the Index page again like the scaffolder does. We removed the table row but that might be a bit sudden for our end users. So we put a message in the actionMessage span tag and give it a highlight effect for 3 seconds so it catches their eye and gives them a warm fuzzy that everything is ok.&lt;/p&gt;
&lt;p&gt;Time to run it? Go for it. Now delete a row or two and relish in the awesomeness that jQuery gives us. And our code changes weren't all that complex either. Enjoy.&lt;/p&gt;</description><pubDate>Fri, 03 Jun 2011 17:42:00 GMT</pubDate><guid isPermaLink="true">http://www.squarewidget.com:80/Delete-Like-a-Rock-Star-with-MVC3-Ajax-and-jQuery</guid></item></channel></rss>