<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>SquareWidget</title><link>http://squarewidget.com:80/</link><description>SquareWidget</description><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Squarewidget" /><feedburner:info uri="squarewidget" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:browserFriendly></feedburner:browserFriendly><item><title>JQuery Mobile Madness with MVC 4 Web API</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Wed, 23 May 2012 22:48:04 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/jquery-mobile-madness</guid></item><item><title>Fun with MVC 4 Web API</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Wed, 23 May 2012 22:00:41 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/fun-with-mvc-4-web-api</guid></item><item><title>Seismic Shifts in Web Development</title><link>http://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 16:56:18 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/seismic-shifts-in-web-development</guid></item><item><title>Pattern Toolkit Builder (VSPAT)</title><link>http://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>Thu, 15 Mar 2012 04:42:53 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/vspat-pattern-toolkit-builder</guid></item><item><title>IncludeMetadataConvention Deprecated in EF 4.3</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Thu, 16 Feb 2012 18:23:33 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/includemetadataconvention-deprecated-in-ef-4.3</guid></item><item><title>Entity Framework 5.0 Sneak Preview</title><link>http://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>Wed, 15 Feb 2012 17:29:53 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/entity-framework-5.0-sneak-preview</guid></item><item><title>Polling with Knockout, JQuery, AJAX, and MVC</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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="/Media/Default/Images/widgets.png" alt="" width="604" height="357" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;</description><pubDate>Wed, 01 Feb 2012 22:07:45 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/polling-with-knockout-jquery-ajax-and-mvc</guid></item><item><title>ChannelFactory, IDisposable and Handling Faults</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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 02:31:24 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/channelfactory-idisposable-and-handling-faults</guid></item><item><title>Poor Man's Publish-Subscribe WCF Service</title><link>http://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="/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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;span style="white-space: normal;"&gt; &lt;/span&gt;&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Thu, 19 Jan 2012 19:54:49 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/poor-mans-publish-subscribe-wcf-service</guid></item><item><title>Simple and Custom Validation in MVC 3</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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>Mon, 16 Jan 2012 01:09:37 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Simple-and-Custom-Validation-in-MVC-3</guid></item><item><title>Class-Level Validation in MVC 3 with IValidatableObject</title><link>http://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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&gt;
&lt;p&gt;One more thing. Modify the Widget Create.cshtml view and add the two new properties:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;IEnumerable&amp;lt;ValidationResult&amp;gt; Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext)&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Let's implement it now in our Widget class:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&gt;
&lt;p&gt;And of course we need to set our connection string in Web.config:&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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, 16 Jan 2012 01:08:29 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Class-Level-Validation-in-MVC-3-with-IValidatableObject</guid></item><item><title>Delete Like a Rock Star with MVC3, Ajax and jQuery</title><link>http://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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Mon, 16 Jan 2012 01:00:25 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Delete-Like-a-Rock-Star-with-MVC3-Ajax-and-jQuery</guid></item><item><title>Generics and Nullable Types</title><link>http://squarewidget.com:80/Generics-and-Nullable-Types</link><description>&lt;div class="post-body"&gt;
&lt;p&gt;It is often useful in OR mapping to analyze a value type that might be null prior to setting it in a business entity. For instance, SqlDateTime type (in System.Data.SqlTypes namespace) is a value type that is nullable. You can call IsNull to check and Value to retrieve the underlying DateTime type:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;SqlDateTime d = &lt;span class="kwrd"&gt;new&lt;/span&gt; SqlDateTime();
&lt;span class="kwrd"&gt;if&lt;/span&gt; (d.IsNull) 
    Trace.WriteLine(&lt;span class="str"&gt;"SqlDateTime is null"&lt;/span&gt;);
d = DateTime.Now;
Trace.WriteLine(
    &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"SqlDateTime is {0}"&lt;/span&gt;, d.Value.ToString()));&lt;/pre&gt;
&lt;p&gt;This is useful when fetching data from SQLServer. DataSets allow nullable values but strongly-typed classes do not. So if I'm instantiating a business entity, I often call TryParse first to protect against null:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//instantiate SqlCommand cm here&lt;/span&gt;
SomeBusinessEntity obj = &lt;span class="kwrd"&gt;new&lt;/span&gt; SomeBusinessEntity();
DateTime dt = &lt;span class="kwrd"&gt;new&lt;/span&gt; DateTime();
SqlDataReader dr = cm.ExecuteReader();
&lt;span class="kwrd"&gt;if&lt;/span&gt; (dr != &lt;span class="kwrd"&gt;null&lt;/span&gt;) {    
    while (dr.Read()) {        
        obj.ID = (DBNull.Value != dr[&lt;span class="str"&gt;"ID"&lt;/span&gt;]) ? Convert.ToInt32(dr[&lt;span class="str"&gt;"ID"&lt;/span&gt;]) : 0;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (DateTime.TryParse(dr[&lt;span class="str"&gt;"ApprovalDate"&lt;/span&gt;].ToString(), &lt;span class="kwrd"&gt;out&lt;/span&gt; dt))              
            obj.ApprovalDate = dt;
    }
}&lt;/pre&gt;
&lt;p&gt;Wouldn't it be great to have a DateTime struct in C# that allows for null? A bunch of folks have gnashed their teeth over this issue since the release of .NET. And now .NET Framework 3.0 supports nullable value types. But I'm still in 2.0 land and will likely remain there for some time so here's my solution. The goal is to support both the above OR mapping logic via generics and to emulate the nullable feature of the SqlDateTime type. In the end we want to do something like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;Nullable&amp;lt;DateTime&amp;gt; ndt = &lt;span class="kwrd"&gt;new&lt;/span&gt; Nullable&amp;lt;DateTime&amp;gt;();
&lt;span class="kwrd"&gt;if&lt;/span&gt; (Nullable&amp;lt;DateTime&amp;gt;.TryParse(DateTime.Now.ToString(), &lt;span class="kwrd"&gt;out&lt;/span&gt; ndt))
    obj.ApprovalDate = ndt;&lt;/pre&gt;
&lt;p&gt;We start with a basic generics-enabled struct with exposed properties Value and IsNull:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; Nullable&amp;lt;T&amp;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; _isnull;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; T _value;
 
    &lt;span class="kwrd"&gt;static&lt;/span&gt; Nullable() {
        _isnull = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsNull {
        &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; _isnull; }
    }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; T Value {
        &lt;span class="kwrd"&gt;get&lt;/span&gt; {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; _value;
        }
        &lt;span class="kwrd"&gt;set&lt;/span&gt; {
            _value = value;
            _isnull = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The struct has a private _isnull member which is set to true in the static constructor. Only when the value is set does that flag flip to false. So by default it will be null even if the type is not really null; for instance if the underlying DateTime is initialized at 1/1/0001 or the underlying Int32 is initialized at 0. Now we support the TryParse functionality by adding a delegate function that mimics the signature. Note that I'm not supporting the overloaded method for IFormatProvider but rather keeping it simple:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; TryParseDelegate&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; T result);&lt;/pre&gt;
&lt;p&gt;Then add a private static function to do the work:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&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; ParseNullable&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; Nullable result, TryParseDelegate Parse) where T : &lt;span class="kwrd"&gt;struct&lt;/span&gt; {
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(s)) {
        result = &lt;span class="kwrd"&gt;default&lt;/span&gt;(Nullable&amp;lt;T&amp;gt;);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;
    }
    &lt;span class="kwrd"&gt;else&lt;/span&gt; {
        T t;
        &lt;span class="kwrd"&gt;bool&lt;/span&gt; success = Parse(s, &lt;span class="kwrd"&gt;out&lt;/span&gt; t);
        Nullable&amp;lt;T&amp;gt; n = &lt;span class="kwrd"&gt;new&lt;/span&gt; Nullable&amp;lt;T&amp;gt;();
        n.Value = t;
        result = n;
        &lt;span class="kwrd"&gt;return&lt;/span&gt; success;
    }
}&lt;/pre&gt;
&lt;p&gt;At this point it's just a matter of adding public methods for each type that you need to support. I've added two methods, one for DateTime and one for Int32. Here is the complete Nullable struct:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;struct&lt;/span&gt; Nullable&amp;lt;T&amp;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; _isnull;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; T _value;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; TryParseDelegate&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; T result);
 
    &lt;span class="kwrd"&gt;static&lt;/span&gt; Nullable() {
        _isnull = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    }
        
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsNull {
        &lt;span class="kwrd"&gt;get&lt;/span&gt; { &lt;span class="kwrd"&gt;return&lt;/span&gt; _isnull; } 
    }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; T Value {
        &lt;span class="kwrd"&gt;get&lt;/span&gt; {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; _value;
        }
        &lt;span class="kwrd"&gt;set&lt;/span&gt; {
            _value = value;
            _isnull = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
        }
    }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; TryParse(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; Nullable&amp;lt;Int32&amp;gt; result) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; ParseNullable&amp;lt;Int32&amp;gt;(s, &lt;span class="kwrd"&gt;out&lt;/span&gt; result, Int32.TryParse);
    }
 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; TryParse(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; Nullable&amp;lt;DateTime&amp;gt; result) {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; ParseNullable&amp;lt;DateTime&amp;gt;(s, &lt;span class="kwrd"&gt;out&lt;/span&gt; result, DateTime.TryParse);
    }
 
    &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; ParseNullable&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; s, &lt;span class="kwrd"&gt;out&lt;/span&gt; Nullable&amp;lt;T&amp;gt; result, TryParseDelegate&amp;lt;T&amp;gt; Parse) where T : &lt;span class="kwrd"&gt;struct&lt;/span&gt; {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(s)) {
            result = &lt;span class="kwrd"&gt;default&lt;/span&gt;(Nullable&amp;lt;T&amp;gt;);
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;
        }
        &lt;span class="kwrd"&gt;else&lt;/span&gt; {
            T t;
            &lt;span class="kwrd"&gt;bool&lt;/span&gt; success = Parse(s, &lt;span class="kwrd"&gt;out&lt;/span&gt; t);
            Nullable&amp;lt;T&amp;gt; n = &lt;span class="kwrd"&gt;new&lt;/span&gt; Nullable&amp;lt;T&amp;gt;();
            n.Value = t;
            result = n;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; success;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;To exercise the struct:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Program {
    &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args) {
            
        &lt;span class="rem"&gt;// exercise Nullable&amp;lt;T&amp;gt; with type DateTime&lt;/span&gt;
        Nullable&amp;lt;DateTime&amp;gt; ndt = &lt;span class="kwrd"&gt;new&lt;/span&gt; Nullable&amp;lt;DateTime&amp;gt;();
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Is null? {0}"&lt;/span&gt;, ndt.IsNull.ToString()));
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Value is {0}"&lt;/span&gt;, ndt.Value.ToString()));
        ndt.Value = DateTime.Now;
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Is null? {0}"&lt;/span&gt;, ndt.IsNull.ToString()));
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Value is {0}"&lt;/span&gt;, ndt.Value.ToString()));
        Console.WriteLine();
            
        &lt;span class="rem"&gt;// exercise Nullable&amp;lt;T&amp;gt; with type Int32&lt;/span&gt;
        Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; nint = &lt;span class="kwrd"&gt;new&lt;/span&gt; Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Is null? {0}"&lt;/span&gt;, nint.IsNull.ToString()));
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Value is {0}"&lt;/span&gt;, nint.Value.ToString()));
        nint.Value = 42;
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Is null? {0}"&lt;/span&gt;, nint.IsNull.ToString()));
        Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Value is {0}"&lt;/span&gt;, nint.Value.ToString()));
            
        &lt;span class="rem"&gt;// exercise TryParse functionality&lt;/span&gt;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (Nullable&amp;lt;DateTime&amp;gt;.TryParse(DateTime.Now.ToString(), &lt;span class="kwrd"&gt;out&lt;/span&gt; ndt)) {
            Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Successful TryParse with result {0}"&lt;/span&gt;, ndt.Value.ToString()));
        }
 
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;.TryParse(&lt;span class="str"&gt;"99"&lt;/span&gt;, &lt;span class="kwrd"&gt;out&lt;/span&gt; nint)) {
            Console.WriteLine(&lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;"Successful TryParse with result {0}"&lt;/span&gt;, nint.Value.ToString()));
        }
        Console.ReadKey();         
    }
}&lt;/pre&gt;
&lt;p&gt;Looking for custom .NET solutions or help with an existing project? Contact me at james AT squarewidget DOT com and let's talk about your situation.&lt;/p&gt;
&lt;/div&gt;</description><pubDate>Sat, 14 Jan 2012 21:35:40 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Generics-and-Nullable-Types</guid></item><item><title>Taking Your Game to the Next Level: FluentValidation</title><link>http://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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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;p&gt;&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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;&lt;/p&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>Wed, 11 Jan 2012 06:07:40 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Taking-Your-Game-to-the-Next-Level-FluentValidation</guid></item><item><title>Snuggle up to jquery $.ajax</title><link>http://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;!-- code formatted by http://manoli.net/csharpformat/ --&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;!-- code formatted by http://manoli.net/csharpformat/ --&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;p&gt;&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;&lt;/p&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>Wed, 11 Jan 2012 06:03:15 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Snuggle-up-to-jquery-ajax</guid></item><item><title>InvalidOperationException Using EF Code First</title><link>http://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&lt;br /&gt;
Message=The model backing the 'MyContext' context has changed since&lt;br /&gt;
the database was created. Either manually delete/update the database,&lt;br /&gt;
or call Database.SetInitializer with an IDatabaseInitializer instance.&lt;br /&gt;
For example, the DropCreateDatabaseIfModelChanges strategy will &lt;br /&gt;
automatically delete and recreate the database, and optionally seed it&lt;br /&gt;
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;!-- code formatted by http://manoli.net/csharpformat/ --&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>Tue, 10 Jan 2012 05:00:54 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/InvalidOperationException-Using-EF-Code-First</guid></item><item><title>Render HTML for Menu in MVC 3 Using SiteMapProvider</title><link>http://squarewidget.com:80/Render-HTML-for-Menu-in-MVC-3-Using-SiteMapProvider</link><description>&lt;div&gt;There are several good jQuery menu plugins but I like the old skool ASP.NET SiteMapProvider because I can declare my app roles in there and get security trimming for free. Add and configure the default XmlSiteMapProvider or customize one to override the IsAccessibleToUser method. Your choice. Then add this MenuHelper static class to your project:&lt;/div&gt;&lt;div&gt;&amp;nbsp;&lt;/div&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;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MenuHelper&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;static&lt;/span&gt; MvcHtmlString Menu(&lt;span class="kwrd"&gt;this&lt;/span&gt; HtmlHelper helper)&lt;/pre&gt;&lt;pre&gt;        {&lt;/pre&gt;&lt;pre class="alt"&gt;            var sb = &lt;span class="kwrd"&gt;new&lt;/span&gt; StringBuilder();&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;            sb.Append(&lt;span class="str"&gt;&amp;quot;&amp;lt;ul id=&amp;#39;nav&amp;#39;&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="rem"&gt;// Render each top level node&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;            var topLevelNodes = SiteMap.RootNode.ChildNodes;&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (SiteMapNode node &lt;span class="kwrd"&gt;in&lt;/span&gt; topLevelNodes)&lt;/pre&gt;&lt;pre&gt;            {&lt;/pre&gt;&lt;pre class="alt"&gt;                sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;li&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;                sb.AppendFormat(&lt;span class="str"&gt;&amp;quot;&amp;lt;a href=&amp;#39;{0}&amp;#39;&amp;gt;{1}&amp;lt;/a&amp;gt;&amp;quot;&lt;/span&gt;, node.Url, helper.Encode(node.Title));&lt;/pre&gt;&lt;pre&gt;                &lt;/pre&gt;&lt;pre class="alt"&gt;                &lt;span class="kwrd"&gt;if&lt;/span&gt; (node.HasChildNodes)&lt;/pre&gt;&lt;pre&gt;                {&lt;/pre&gt;&lt;pre class="alt"&gt;                    sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;ul&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;                    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (SiteMapNode childNode &lt;span class="kwrd"&gt;in&lt;/span&gt; node.ChildNodes)&lt;/pre&gt;&lt;pre class="alt"&gt;                    {&lt;/pre&gt;&lt;pre&gt;                        sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;li&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre class="alt"&gt;                        sb.AppendFormat(&lt;span class="str"&gt;&amp;quot;&amp;lt;a href=&amp;#39;{0}&amp;#39;&amp;gt;{1}&amp;lt;/a&amp;gt;&amp;quot;&lt;/span&gt;, childNode.Url, helper.Encode(childNode.Title));&lt;/pre&gt;&lt;pre&gt;                        sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;/li&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre class="alt"&gt;                    }&lt;/pre&gt;&lt;pre&gt;                    sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;/ul&amp;gt;&amp;quot;&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;                sb.AppendLine(&lt;span class="str"&gt;&amp;quot;&amp;lt;/li&amp;gt;&amp;quot;&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="rem"&gt;// Close unordered list tag&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;            sb.Append(&lt;span class="str"&gt;&amp;quot;&amp;lt;/ul&amp;gt;&amp;quot;&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; MvcHtmlString(sb.ToString());&lt;/pre&gt;&lt;pre&gt;        }&lt;/pre&gt;&lt;pre class="alt"&gt;    }&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp;&lt;/div&gt;&lt;div&gt;If this is the first helper for the project then add the namespace where your MenuHelper class lives to your Views Web.config file:&lt;/div&gt;&lt;div&gt;&amp;nbsp;&lt;/div&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;system.web.webPages.razor&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;host&lt;/span&gt; &lt;span class="attr"&gt;factoryType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;pages&lt;/span&gt; &lt;span class="attr"&gt;pageBaseType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Mvc.WebViewPage&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;namespaces&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&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;namespace&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Mvc&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&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;namespace&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Mvc.Ajax&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&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;namespace&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Mvc.Html&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&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;namespace&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;System.Web.Routing&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&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;namespace&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;YOUR.NAMESPACE.GOES.HERE&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;namespaces&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;pages&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;system.web.webPages.razor&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&amp;nbsp;&lt;/div&gt;&lt;div&gt;Good to go. Now in your _Layout.cshtml (razor) page you can swap out the default menu behavior and call the helper class:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&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;id&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;menucontainer&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;    @Html.Menu()&lt;/pre&gt;&lt;pre class="alt"&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;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That&amp;#39;s all there is to it. Well that and doing some CSS work for designing it. In my current project I&amp;#39;m using jQuery to show and hide submenu links as well but that&amp;#39;s another blog post.&lt;/div&gt;</description><pubDate>Wed, 01 Jun 2011 05:51:07 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Render-HTML-for-Menu-in-MVC-3-Using-SiteMapProvider</guid></item><item><title>More Awesomeness: Post JSON to an Action Method</title><link>http://squarewidget.com:80/More-Awesomeness-Post-JSON-to-an-Action-Method</link><description>&lt;p&gt;Fortunately I came late to the party and didn&amp;#39;t develop MVC 2 web apps. I understand that back in those ancient days (about 6 months ago) you had to walk uphill both ways to post JSON data back to an action method. Phil Haack has a &lt;a href="http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx"&gt;great blog post&lt;/a&gt; on the topic. Basically, you had to write a custom filter, register a JsonValueProviderFactory in application startup, and decorate your action method with the JSON serializer attributes. What a pain. In MVC 3 it&amp;#39;s super easy to use AJAX to post JSON back to an action method. Here are the steps. &lt;/p&gt;&lt;p&gt;Create a new MVC 3 web application. Add a new Model called Widget (what else?): &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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; Widget&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;int&lt;/span&gt; ID { get; set; }&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Shape { get; set; }&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; Color { get; set; }&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;In the HomeController add an action method to take a Widget instance: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult GetData(Widget widget)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="rem"&gt;// using System.Diagnostics&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;    Debug.WriteLine(&lt;span class="str"&gt;&amp;quot;Got a &amp;quot;&lt;/span&gt; + &lt;/pre&gt;&lt;pre class="alt"&gt;        widget.Shape + &lt;span class="str"&gt;&amp;quot; &amp;quot;&lt;/span&gt; + &lt;/pre&gt;&lt;pre&gt;        widget.Color + &lt;span class="str"&gt;&amp;quot; widget with id &amp;quot;&lt;/span&gt; + &lt;/pre&gt;&lt;pre class="alt"&gt;        widget.ID);&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Add a route to the map for this new action method: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;routes.MapRoute(&lt;/pre&gt;&lt;pre&gt;    &lt;span class="str"&gt;&amp;quot;Widget&amp;quot;&lt;/span&gt;, &lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="str"&gt;&amp;quot;{Home}/{GetData}&amp;quot;&lt;/span&gt;, &lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;&amp;quot;Home&amp;quot;&lt;/span&gt;, action = &lt;span class="str"&gt;&amp;quot;GetData&amp;quot;&lt;/span&gt; }&lt;/pre&gt;&lt;pre class="alt"&gt;);&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;Get the &lt;a href="http://www.JSON.org/json2.js"&gt;json2.js script&lt;/a&gt; so you can use the stringify function. Put it in your Scripts folder and reference it at the top of your shared _Layout.cshtml page so it&amp;#39;s available application wide. Now go to the Home Index.cshml file and add some javascript below the awesome &amp;quot;learn more about ASP.NET MVC&amp;quot; p tag and link: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&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;=&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;    $(document).ready(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {&lt;/pre&gt;&lt;pre class="alt"&gt;        $(&lt;span class="str"&gt;&amp;#39;a&amp;#39;&lt;/span&gt;).click(&lt;span class="kwrd"&gt;function&lt;/span&gt; () {&lt;/pre&gt;&lt;pre&gt;            &lt;span class="kwrd"&gt;var&lt;/span&gt; widget = {&lt;/pre&gt;&lt;pre class="alt"&gt;                ID: &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;666&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;                Shape: &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;purple&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre class="alt"&gt;                Color: &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;octagonal&amp;quot;&lt;/span&gt; + &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;            };&lt;/pre&gt;&lt;pre class="alt"&gt;            $.ajax({&lt;/pre&gt;&lt;pre&gt;                url: &lt;span class="str"&gt;&amp;quot;/Home/Index&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre class="alt"&gt;                async: &lt;span class="kwrd"&gt;true&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;                type: &lt;span class="str"&gt;&amp;quot;post&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre class="alt"&gt;                datatype: &lt;span class="str"&gt;&amp;#39;json&amp;#39;&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;                data: JSON.stringify(widget),&lt;/pre&gt;&lt;pre class="alt"&gt;                contentType: &lt;span class="str"&gt;&amp;#39;application/json&amp;#39;&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;                error: &lt;span class="kwrd"&gt;function&lt;/span&gt; (xhr) {&lt;/pre&gt;&lt;pre class="alt"&gt;                    alert(&lt;span class="str"&gt;&amp;#39;Something went wrong buddy! &amp;#39;&lt;/span&gt; + xhr.statusText);&lt;/pre&gt;&lt;pre&gt;                }&lt;/pre&gt;&lt;pre class="alt"&gt;            });&lt;/pre&gt;&lt;pre&gt;        });&lt;/pre&gt;&lt;pre class="alt"&gt;    });&lt;/pre&gt;&lt;pre&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;/div&gt;&lt;br /&gt;&lt;p&gt;That&amp;#39;s it. What&amp;#39;s going on here? After the DOM has fully loaded I&amp;#39;m registering a function on the a tag click event. So when you click the oddly compelling &amp;quot;learn more&amp;quot; link on the home page a widget will get created and posted asynchronously to our action method. Put a break on the Debug.WriteLine if you want or just watch your Output window. Fire up the app and click on the very persuasive ASP.NET MVC learn more link. If everything is wired up correctly you&amp;#39;ll see the debug output: &lt;/p&gt;&lt;blockquote&gt;			&lt;p&gt;		&lt;strong&gt;Got a purple octagonal widget with id 666&lt;/strong&gt; 		&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;This is a very simple example. The point here is that you&amp;#39;re not stuck building url strings like &amp;quot;/Home/Index/6&amp;quot; but rather in MVC 3 you can post complex JSON data to an action method with very little plumbing. &lt;/p&gt;</description><pubDate>Wed, 30 Mar 2011 07:12:22 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/More-Awesomeness-Post-JSON-to-an-Action-Method</guid></item><item><title>Implement jQuery FullCalendar Plugin in MVC 3</title><link>http://squarewidget.com:80/Implement-jQuery-FullCalendar-Plugin-in-MVC-3</link><description>&lt;p&gt;Let&amp;#39;s implement Shaw&amp;#39;s awesome &lt;a href="http://arshaw.com/fullcalendar/"&gt;FullCalendar jQuery plugin&lt;/a&gt; with an MVC 3 project. I&amp;#39;ll assume you&amp;#39;ve downloaded the bits and have included the fullcalendar.min.js script in your project. Here I want to illustrate two things: (1) populating the calendar with events from the database; and (2) handling the calendar&amp;#39;s dayClick event to create a new event. &lt;/p&gt;&lt;p&gt;But first we need a model to represent an event: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&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; EventModel&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;int&lt;/span&gt; ID { get; set; }&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Title { get; set; }&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTime StartDateTime { get; set; }&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTime EndDateTime { get; set; }&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsAllDay { get; set; }&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Just drop that in your Models folder or the project where your domain model lives. Next create a CalendarController that knows about the EventModel and passes it to your views. I&amp;#39;ve done that below. And to populate the calendar I&amp;#39;ll add a GetEvents action method that will be called asynchronously. &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&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; CalendarController : Controller&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; EventModel _eventModel;&lt;/pre&gt;&lt;pre&gt;        &lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; CalendarController()&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        _eventModel = &lt;span class="kwrd"&gt;new&lt;/span&gt; EventModel();&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;public&lt;/span&gt; ActionResult Index()&lt;/pre&gt;&lt;pre class="alt"&gt;    {&lt;/pre&gt;&lt;pre&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; View();&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; JsonResult GetEvents(&lt;span class="kwrd"&gt;double&lt;/span&gt; start, &lt;span class="kwrd"&gt;double&lt;/span&gt; end)&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        var startDateTime = FromUnixTimestamp(start);&lt;/pre&gt;&lt;pre&gt;        var endDateTime = FromUnixTimestamp(end);&lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;        var repository = &lt;span class="kwrd"&gt;new&lt;/span&gt; EventRepository();&lt;/pre&gt;&lt;pre class="alt"&gt;        var events = repository.GetEvents(startDateTime, endDateTime);&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;        var clientList = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var e &lt;span class="kwrd"&gt;in&lt;/span&gt; events)&lt;/pre&gt;&lt;pre&gt;        {&lt;/pre&gt;&lt;pre class="alt"&gt;            clientList.Add(&lt;/pre&gt;&lt;pre&gt;                &lt;span class="kwrd"&gt;new&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;                {&lt;/pre&gt;&lt;pre&gt;                    id = e.ID,&lt;/pre&gt;&lt;pre class="alt"&gt;                    title = e.Title,&lt;/pre&gt;&lt;pre&gt;                    description = e.Description,&lt;/pre&gt;&lt;pre class="alt"&gt;                    start = e.StartUnixTimestamp,&lt;/pre&gt;&lt;pre&gt;                    end = e.EndUnixTimestamp,&lt;/pre&gt;&lt;pre class="alt"&gt;                    allDay = e.IsAllDay,&lt;/pre&gt;&lt;pre&gt;                    url = e.Url&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; Json(clientList.ToArray(), JsonRequestBehavior.AllowGet);&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;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; DateTime FromUnixTimestamp(&lt;span class="kwrd"&gt;double&lt;/span&gt; timestamp)&lt;/pre&gt;&lt;pre class="alt"&gt;    {&lt;/pre&gt;&lt;pre&gt;        var origin = &lt;span class="kwrd"&gt;new&lt;/span&gt; DateTime(1970, 1, 1, 0, 0, 0, 0);&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; origin.AddSeconds(timestamp);&lt;/pre&gt;&lt;pre&gt;    }&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;I won&amp;#39;t go into the repository since that&amp;#39;s just standard data access plumbing. You might use LINQ against EF 4 or NHibernate against MySQL. It doesn&amp;#39;t matter. For our purposes the call to our repository returns an IQueryable collection called events. We then enumerate over this collection and transform it into an object notation (JSON) that the calendar will understand. And since FullCalendar works with Unix timestamps we have a little helper method in there to convert the double into a .NET DateTime. &lt;/p&gt;&lt;p&gt;Right click on the Index action method and create a bare bones view. For this walkthrough don&amp;#39;t bother creating a strongly-typed view, a partial view, or a layout/master page view. Just a bare bones Index.cshtml to host the calendar plugin is sufficient. In the header reference the scripts per FullCalendar&amp;#39;s specification. Here&amp;#39;s the whole Index.cshtml page in all its glory: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;@{&lt;/pre&gt;&lt;pre class="alt"&gt;    Layout = &lt;span class="kwrd"&gt;null&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;&amp;lt;!DOCTYPE html&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;&amp;lt;html&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;    &amp;lt;head&amp;gt;&lt;/pre&gt;&lt;pre&gt;        &amp;lt;title&amp;gt;Calendar Demo&amp;lt;/title&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;        &amp;lt;link href=&lt;span class="str"&gt;&amp;quot;@Url.Content(&amp;quot;&lt;/span&gt;~/Content/fullcalendar.css&lt;span class="str"&gt;&amp;quot;)&amp;quot;&lt;/span&gt; rel=&lt;span class="str"&gt;&amp;quot;stylesheet&amp;quot;&lt;/span&gt; type=&lt;span class="str"&gt;&amp;quot;text/css&amp;quot;&lt;/span&gt; /&amp;gt;&lt;/pre&gt;&lt;pre&gt;        &amp;lt;script src=&lt;span class="str"&gt;&amp;quot;@Url.Content(&amp;quot;&lt;/span&gt;~/Scripts/jquery-1.5.min.js&lt;span class="str"&gt;&amp;quot;)&amp;quot;&lt;/span&gt; type=&lt;span class="str"&gt;&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;        &amp;lt;script src=&lt;span class="str"&gt;&amp;quot;@Url.Content(&amp;quot;&lt;/span&gt;~/Scripts/jquery-ui-1.8.9.custom.min.js&lt;span class="str"&gt;&amp;quot;)&amp;quot;&lt;/span&gt; type=&lt;span class="str"&gt;&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;pre&gt;        &amp;lt;script src=&lt;span class="str"&gt;&amp;quot;@Url.Content(&amp;quot;&lt;/span&gt;~/Scripts/fullcalendar.min.js&lt;span class="str"&gt;&amp;quot;)&amp;quot;&lt;/span&gt; type=&lt;span class="str"&gt;&amp;quot;text/javascript&amp;quot;&lt;/span&gt;&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;/pre&gt;&lt;pre&gt;        &amp;lt;script type=&lt;span class="str"&gt;&amp;#39;text/javascript&amp;#39;&lt;/span&gt;&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;            function padDigits(n, totalDigits) {&lt;/pre&gt;&lt;pre class="alt"&gt;                n = n.toString();&lt;/pre&gt;&lt;pre&gt;                var pd = &lt;span class="str"&gt;&amp;#39;&amp;#39;&lt;/span&gt;;&lt;/pre&gt;&lt;pre class="alt"&gt;                &lt;span class="kwrd"&gt;if&lt;/span&gt; (totalDigits &amp;gt; n.length) {&lt;/pre&gt;&lt;pre&gt;                    &lt;span class="kwrd"&gt;for&lt;/span&gt; (i = 0; i &amp;lt; (totalDigits - n.length); i++) {&lt;/pre&gt;&lt;pre class="alt"&gt;                        pd += &lt;span class="str"&gt;&amp;#39;0&amp;#39;&lt;/span&gt;;&lt;/pre&gt;&lt;pre&gt;                    }&lt;/pre&gt;&lt;pre class="alt"&gt;                }&lt;/pre&gt;&lt;pre&gt;                &lt;span class="kwrd"&gt;return&lt;/span&gt; pd + n.toString();&lt;/pre&gt;&lt;pre class="alt"&gt;            }&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;            function createEvent(date, allDay, jsEvent, View) {&lt;/pre&gt;&lt;pre&gt;                var eventDate = padDigits(date.getMonth() + 1, 2) + &lt;span class="str"&gt;&amp;#39;-&amp;#39;&lt;/span&gt; + &lt;/pre&gt;&lt;pre class="alt"&gt;                    padDigits(date.getDate(), 2) + &lt;span class="str"&gt;&amp;#39;-&amp;#39;&lt;/span&gt; + &lt;/pre&gt;&lt;pre&gt;                    padDigits(date.getFullYear(), 4);&lt;/pre&gt;&lt;pre class="alt"&gt;                window.location.href = &lt;span class="str"&gt;&amp;quot;/Calendar/Create/&amp;quot;&lt;/span&gt; + eventDate;               &lt;/pre&gt;&lt;pre&gt;            }  &lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;            $(document).ready(function () {&lt;/pre&gt;&lt;pre class="alt"&gt;                $(&lt;span class="str"&gt;&amp;#39;#calendar&amp;#39;&lt;/span&gt;).fullCalendar({&lt;/pre&gt;&lt;pre&gt;                    editable: &lt;span class="kwrd"&gt;true&lt;/span&gt;,&lt;/pre&gt;&lt;pre class="alt"&gt;                    events: &lt;span class="str"&gt;&amp;quot;/Calendar/GetEvents&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;                    eventClick: function (calEvent, jsEvent, view) {&lt;/pre&gt;&lt;pre class="alt"&gt;                        alert(&lt;span class="str"&gt;&amp;#39;Event: &amp;#39;&lt;/span&gt; + calEvent.title);&lt;/pre&gt;&lt;pre&gt;                    },&lt;/pre&gt;&lt;pre class="alt"&gt;                    dayClick: function (date, allDay, jsEvent, view) {&lt;/pre&gt;&lt;pre&gt;                        createEvent(date, allDay, jsEvent, view);&lt;/pre&gt;&lt;pre class="alt"&gt;                    }&lt;/pre&gt;&lt;pre&gt;                });&lt;/pre&gt;&lt;pre class="alt"&gt;            });&lt;/pre&gt;&lt;pre&gt;        &amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;        &amp;lt;style type=&lt;span class="str"&gt;&amp;#39;text/css&amp;#39;&lt;/span&gt;&amp;gt;&lt;/pre&gt;&lt;pre&gt;            &lt;/pre&gt;&lt;pre class="alt"&gt;            body {&lt;/pre&gt;&lt;pre&gt;        margin-top: 40px;&lt;/pre&gt;&lt;pre class="alt"&gt;        text-align: center;&lt;/pre&gt;&lt;pre&gt;        font-size: 14px;&lt;/pre&gt;&lt;pre class="alt"&gt;        font-family: &lt;span class="str"&gt;&amp;quot;Lucida Grande&amp;quot;&lt;/span&gt;,Helvetica,Arial,Verdana,sans-serif;&lt;/pre&gt;&lt;pre&gt;        }&lt;/pre&gt;&lt;pre class="alt"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre&gt;        #calendar {&lt;/pre&gt;&lt;pre class="alt"&gt;        width: 900px;&lt;/pre&gt;&lt;pre&gt;        margin: 0 auto;&lt;/pre&gt;&lt;pre class="alt"&gt;        }&lt;/pre&gt;&lt;pre&gt;        &lt;/pre&gt;&lt;pre class="alt"&gt;        &amp;lt;/style&amp;gt;&lt;/pre&gt;&lt;pre&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="alt"&gt;    &amp;lt;/head&amp;gt;&lt;/pre&gt;&lt;pre&gt;    &lt;/pre&gt;&lt;pre class="alt"&gt;    &amp;lt;body&amp;gt;&lt;/pre&gt;&lt;pre&gt;        &amp;lt;div id=&lt;span class="str"&gt;&amp;quot;calendar&amp;quot;&lt;/span&gt;&amp;gt;&amp;lt;/div&amp;gt;&lt;/pre&gt;&lt;pre class="alt"&gt;    &amp;lt;/body&amp;gt;&lt;/pre&gt;&lt;pre&gt;&amp;lt;/html&amp;gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Pretty straightforward stuff. The calendar plugin automatically calls its events function to populate the calendar and will pass in two Unix timestamp values &amp;quot;start&amp;quot; and &amp;quot;end&amp;quot; to the route we specify (in this case &amp;quot;/Calendar/GetEvents&amp;quot;). Our CalendarController must convert those values to .NET DateTime types to call the repository and get the events in that date range. So we&amp;#39;re set on populating the calendar. &lt;/p&gt;&lt;p&gt;Now we want to implement the creation of new events. To do that I recommend handling the FullCalendar dayClick event. Notice that the first argument &amp;quot;date&amp;quot; is the date of the selected cell. That&amp;#39;s all I care about. What we want to do is pass it along to our own createEvent function and use the padDigits helper to format it in the form mm-dd-yyyy. Why? Because we can leverage the MVC framework, which will automatically cast it to a .NET DateTime for us. Here&amp;#39;s where the javascript is going to call our controller: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;window.location.href = &lt;span class="str"&gt;&amp;quot;/Calendar/Create/&amp;quot;&lt;/span&gt; + eventDate;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Of course in MVC we have to have a route added to our map to support that extensionless url. So go into Global.asax and add it before the Default route: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;routes.MapRoute(&lt;/pre&gt;&lt;pre&gt;    &lt;span class="str"&gt;&amp;quot;CreateNewCalendarEvent&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="str"&gt;&amp;quot;Calendar/{action}/{eventDate}&amp;quot;&lt;/span&gt;,&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;&amp;quot;Calendar&amp;quot;&lt;/span&gt;, action = &lt;span class="str"&gt;&amp;quot;Create&amp;quot;&lt;/span&gt; }&lt;/pre&gt;&lt;pre class="alt"&gt;);&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Notice that &amp;quot;eventDate&amp;quot; is spelled exactly like the javascript variable. This is the querystring name that javascript will use. If you don&amp;#39;t use an identical name then the Controller base class will not find the value in the Request.QueryString and pass a null to your parameter in the action method instead. Anyway, time to create the action method in the CalendarController class: &lt;/p&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ActionResult Create(DateTime eventDate)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    _eventModel.StartDateTime = eventDate;&lt;/pre&gt;&lt;pre&gt;    _eventModel.EndDateTime = eventDate;&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; View(_eventModel);&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;That&amp;#39;s it! Here&amp;#39;s where the magic happens. The MVC framework is smart enough to convert the querystring parameter &amp;quot;eventDate&amp;quot; into a DateTime. If it fails then you&amp;#39;ll get a runtime exception. But we&amp;#39;re passing it in the format mm-dd-yyyy which MVC can easily convert into a .NET DateTime type. That&amp;#39;s the day on the calendar that the user clicked on so we&amp;#39;ve already got one property set. I won&amp;#39;t show it here but the obvious next step is to pass the EventModel instance to a view scaffolded with the Create template so that the end user can provide a title as well as a begin and end time for the event. That will get posted back as a FormCollection like any other MVC create action method where you&amp;#39;d first save it to the database and then redirect the user back to the calendar page. The new event shows up on the day along with the others and you&amp;#39;re good to go. &lt;/p&gt;&lt;p&gt;I also won&amp;#39;t go into handling the FullCalendar eventClick event. You&amp;#39;ll notice above I just stubbed it out with a simple alert. If you want to allow users to edit existing events then you&amp;#39;ll want to replace that functionality with something similar to what I&amp;#39;ve described here. &lt;/p&gt;</description><pubDate>Wed, 30 Mar 2011 07:11:53 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/Implement-jQuery-FullCalendar-Plugin-in-MVC-3</guid></item><item><title>TruthWidget Launch Part 2</title><link>http://squarewidget.com:80/TruthWidget-Launch-Part-2</link><description>&lt;a href="http://www.truthwidget.com" target="_blank"&gt;TruthWidget.com&lt;/a&gt; is fully ported over to MVC 3 from Silverlight 4. I ran through all of my tests and so it&amp;#39;s up and running live. The awesome part was being able to reuse Entity Framework 4 and the repository wrappers. I took the RIA web services and put them into MVC services. I&amp;#39;ve seen examples where the controller calls EF directly but that makes me uncomfortable so I wanted that additional layer of abstraction. The bulk of my work was throwing away the XAML and recreating Html (Razor) web pages. What I liked about my experience is how I can create HtmlHelpers (little helper methods that emit small chunks of HTML), partial views, and stitch them together to create the whole view. This enabled me to follow the DRY principle a lot more than in XAML where I tended to have big bloated views -- especially if I did it in Blend. I&amp;#39;m really happy with my experience. I&amp;#39;ll blog on specific tips and tricks when I have time. For now I&amp;#39;ll just say that everything just works in MVC 3. It&amp;#39;s a real joy to work with it. 
</description><pubDate>Sun, 13 Mar 2011 14:29:27 GMT</pubDate><guid isPermaLink="true">http://squarewidget.com:80/TruthWidget-Launch-Part-2</guid></item></channel></rss>

