<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>mhinze.com</title>
	
	<link>http://mhinze.com</link>
	<description>Matt Hinze, learning in public</description>
	<lastBuildDate>Tue, 20 Apr 2010 22:42:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/mhinzecom" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="mhinzecom" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Focusing on the controller’s responsibility</title>
		<link>http://mhinze.com/focusing-on-the-controllers-responsibility/</link>
		<comments>http://mhinze.com/focusing-on-the-controllers-responsibility/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 13:52:16 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://mhinze.com/focusing-on-the-controllers-responsibility/</guid>
		<description><![CDATA[The following is an excerpt from ASP.NET MVC 2 in Action, a book from Manning appearing in bookstores in May.&#160; The early access (MEAP) edition is available now on http://manning.com/palermo2.&#160; Authors include Jeffrey Palermo, Ben Scheirman, Jimmy Bogard, Eric Hexter and Matt Hinze.&#160; Technically edited by Jeremy Skinner. This selection is from chapter 19, Lightweight [...]]]></description>
			<content:encoded><![CDATA[<p>The following is an excerpt from <a href="http://manning.com/palermo2">ASP.NET MVC 2 in Action</a>, a book from Manning appearing in bookstores in May.&#160; The early access (MEAP) edition is available now on <a href="http://manning.com/palermo2">http://manning.com/palermo2</a>.&#160; Authors include <a href="http://jeffreypalermo.com">Jeffrey Palermo</a>, <a href="http://flux88.com/">Ben Scheirman</a>, <a href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx">Jimmy Bogard</a>, <a href="http://www.lostechies.com/blogs/hex/" target="_blank">Eric Hexter</a> and <a href="http://mhinze.com" target="_blank">Matt Hinze</a>.&#160; Technically edited by <a href="http://www.jeremyskinner.co.uk/">Jeremy Skinner</a>.</p>
<p>This selection is from chapter 19, Lightweight controllers.&#160; All hyperlinks were added for this post.</p>
<hr />
<p>A quick way to lighten the controller&#8217;s load is to simply remove responsibilities from it. Consider the burdened action, shown below:</p>
<h5>A heavyweight controller</h5>
<pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">RedirectToRouteResult </span>Ship(<span style="color: blue">int </span>orderId)
{
   <span style="color: #2b91af">User </span>user = _userSession.GetCurrentUser();
   <span style="color: #2b91af">Order </span>order = _repository.GetById(orderId);

   <span style="color: blue">if </span>(order.IsAuthorized)
   {
      <span style="color: #2b91af">ShippingStatus </span>status = _shippingService.Ship(order);

      <span style="color: blue">if </span>(!<span style="color: blue">string</span>.IsNullOrEmpty(user.EmailAddress))
      {
         <span style="color: #2b91af">Message </span>message = _messageBuilder
            .BuildShippedMessage(order, user);

         _emailSender.Send(message);
      }

      <span style="color: blue">if </span>(status.Successful)
      {
         <span style="color: blue">return </span>RedirectToAction(<span style="color: #a31515">&quot;Shipped&quot;</span>, <span style="color: #a31515">&quot;Order&quot;</span>, <span style="color: blue">new </span>{orderId});
      }
   }
   <span style="color: blue">return </span>RedirectToAction(<span style="color: #a31515">&quot;NotShipped&quot;</span>, <span style="color: #a31515">&quot;Order&quot;</span>, <span style="color: blue">new </span>{orderId});
}</pre>
<p>This action is doing a lot of work-it&#8217;s incomprehensible at first glance. You can almost count its jobs by the number of if statements. Beyond its appropriate role as director of the storyboard flow of the user interface, this action is deciding if the Order is appropriate for shipping and determining whether or not to send the User a notification email. Not only is it doing those things, but it&#8217;s deciding how to do them-it&#8217;s determining what it means for an Order to be appropriate for shipping and how the notification email should be sent.</p>
<p>Logic like this-domain logic, business logic-should generally not be in a user interface class like a controller. It violates the single responsibility principle, obfuscating both the true intention of the domain and the actual duties of the controller, which is redirecting to the proper action. Testing and maintaining an application written like this is difficult.</p>
<blockquote>
<h6>Cyclomatic complexity: source code viscosity</h6>
<p><a href="http://www.aivosto.com/project/help/pm-complexity.html">Cyclomatic</a> <a href="http://www.ibm.com/developerworks/java/library/j-cq03316/">complexity</a> is a metric we can use to analyze the complexity of code. The more logical paths a method or function presents, the higher its cyclomatic complexity. In order to fully understand the implication of a particular procedure, each logical path must be evaluated. For example, each simple if statement presents two paths-one when the condition is true, and another when it&#8217;s false. Functions with high cyclomatic complexity are more <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity#Implications_for_Software_Testing">difficult to test</a> and to understand and have been <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity#Correlation_to_number_of_defects">correlated with increased defect rates</a>.</p>
</blockquote>
<p>A simple refactoring that can ease this is called Refactor Architecture by Tiers. It directs the software designer to move processing logic out of the presentation tier into the business tier.</p>
<p>After we move the logic for shipping an order to an OrderShippingService, our action is much simpler.</p>
<h5>A simpler action after refactoring architecture by tiers</h5>
<pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">RedirectToRouteResult </span>Ship(<span style="color: blue">int </span>orderId)
{
   <span style="color: blue">var </span>status = _orderShippingService.Ship(orderId);
   <span style="color: blue">if </span>(status.Successful)
   {
      <span style="color: blue">return </span>RedirectToAction(<span style="color: #a31515">&quot;Shipped&quot;</span>, <span style="color: #a31515">&quot;Order&quot;</span>, <span style="color: blue">new </span>{orderId});
   }
   <span style="color: blue">return </span>RedirectToAction(<span style="color: #a31515">&quot;NotShipped&quot;</span>, <span style="color: #a31515">&quot;Order&quot;</span>, <span style="color: blue">new </span>{orderId});
}</pre>
<p>Everything having to do with shipping the order and sending the notification has been moved out of the controller into a new class. The controller is left with the single responsibility of deciding where to redirect the client. The new class can fetch the Order, get the User, and do all the rest.</p>
<p>But the result of the refactoring is more than just a move. It&#8217;s a semantic break that puts the onus of managing these tasks in the right place. This change has resulted in a clean abstraction that our controller can use to represent what it was doing before. Other logical endpoints can reuse the OrderShippingService, such as other controllers or services that participate in the order shipping process. This new abstraction is clear, and it can change internally without affecting the presentation duties of the controller. </p>
<p>Refactoring doesn&#8217;t get much simpler than this, but a simple change can result in significantly lower cyclomatic complexity and can ease the testing effort and maintenance burden associated with a complex controller.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/focusing-on-the-controllers-responsibility/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JSON Hijacking in ASP.NET MVC 2</title>
		<link>http://mhinze.com/json-hijacking-in-asp-net-mvc-2/</link>
		<comments>http://mhinze.com/json-hijacking-in-asp-net-mvc-2/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 12:27:11 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://mhinze.com/json-hijacking-in-asp-net-mvc-2/</guid>
		<description><![CDATA[The following is an excerpt from ASP.NET MVC 2 in Action, a book from Manning appearing in bookstores in May.&#160; The early access (MEAP) edition is available now on http://manning.com/palermo2.&#160; Authors include Jeffrey Palermo, Ben Scheirman, Jimmy Bogard, Eric Hexter and Matt Hinze.&#160; Technically edited by Jeremy Skinner. JSON (pronounced like the English name, Jason) [...]]]></description>
			<content:encoded><![CDATA[<p>The following is an excerpt from <a href="http://manning.com/palermo2">ASP.NET MVC 2 in Action</a>, a book from Manning appearing in bookstores in May.&#160; The early access (MEAP) edition is available now on <a href="http://manning.com/palermo2">http://manning.com/palermo2</a>.&#160; Authors include <a href="http://jeffreypalermo.com">Jeffrey Palermo</a>, <a href="http://flux88.com/">Ben Scheirman</a>, <a href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx">Jimmy Bogard</a>, <a href="http://www.lostechies.com/blogs/hex/" target="_blank">Eric Hexter</a> and <a href="http://mhinze.com" target="_blank">Matt Hinze</a>.&#160; Technically edited by <a href="http://www.jeremyskinner.co.uk/">Jeremy Skinner</a>.</p>
<hr />
<p>JSON (pronounced like the English name, Jason) hijacking is a rare hack similar to XSRF, except it&#8217;s targeted to request secure JSON from vulnerable applications. The JSON hijacking process involves several steps:</p>
<p>1. A conspiring site, via JavaScript, instructs the victim&#8217;s browser to request some secure JSON data from another site.</p>
<p>2. The evil JavaScript receives the JSON data.</p>
<p>3. If the JSON is formatted as an array, the evil script can exploit browser JavaScript processing code to read the JSON data and transmit it back to the attacking site.</p>
<h4>Allow JSON via POST only</h4>
<p>The solution to this exploit offered by ASP.NET MVC 2 is to only accept requests for JSON data by HTTP POST requests, rather than by GETs. This is baked into and enforced by the standard JsonResult action result that ships with the framework. If we were to request data to be returned by JsonResult with a GET request, we wouldn&#8217;t receive the JSON data. </p>
<p>Listing 11.12 shows how we must issue a POST from JavaScript code requesting JSON data.</p>
<h5>Listing 11.12 Requesting JSON data via POST</h5>
<pre class="code">&lt;script type=<span style="color: #a31515">&quot;text/javascript&quot;</span>&gt;
    $.postJSON = <span style="color: blue">function</span>(url, data, callback) {
        $.post(url, data, callback, <span style="color: #a31515">&quot;json&quot;</span>);
    };                                                         

    $(<span style="color: blue">function</span>() {
    $.postJSON(<span style="color: #a31515">'/post/getsecurejsonpost'</span>,
        <span style="color: blue">function</span>(data) {
            <span style="color: blue">var </span>options = <span style="color: #a31515">''</span>;
            <span style="color: blue">for </span>(<span style="color: blue">var </span>i = 0; i &lt; data.length; i++) {
                options += <span style="color: #a31515">'&lt;option value=&quot;' </span>+  #|2
                data[i].Id + <span style="color: #a31515">'&quot;&gt;' </span>+ data[i].Title +
                <span style="color: #a31515">'&lt;/option&gt;'</span>;
            }
            $(<span style="color: #a31515">'#securepost'</span>).html(options);                    

        });
    });
&lt;/script&gt;

 &lt;h2&gt;Secure Json (Post)&lt;/h2&gt;
  &lt;div&gt;
    &lt;select id=<span style="color: #a31515">&quot;securepost&quot;</span>/&gt;
 &lt;/div&gt;</pre>
<p>Listing 11.12 uses the jQuery JavaScript library to craft a special POST request for our JSON data.&#160; When the results are returned, the function populates the select list with them.</p>
<h4>Override defaults for GET access</h4>
<p>The problem with this approach isn&#8217;t technical-this works and it prevents JSON hijacking. But it&#8217;s a workaround that&#8217;s sometimes unnecessary and can interfere with systems developed using the REST architectural style. </p>
<p>If this approach causes problems, we have additional options. First, we can explicitly enable JSON requests from GETs with the code shown in listing 11.13.</p>
<h5>Listing 11.13 Directing JsonResult to accept GETs</h5>
<pre class="code">[HttpGet]
<span style="color: blue">public </span>JsonResult GetInsecureJson()
{
    <span style="color: blue">object </span>data = GetData();

    <span style="color: blue">return </span>Json(data, JsonRequestBehavior.AllowGet);
}</pre>
<p>This will allow our action to respond to normal JSON GET requests. Finally, we can scrap JsonResult itself, instead using an action result to return only non-vulnerable, non-array formatted, JSON. </p>
<h4>Modifying the JSON response</h4>
<p>The code in listing 11.14 shows a special action result that wraps vulnerable JSON data in a variable, d.</p>
<h5>Listing 11.14 <a></a><a>Creating a </a>SecureJsonResult encapsulates serialization logic</h5>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">SecureJsonResult </span>: ActionResult
{
    <span style="color: blue">public string </span>ContentType { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public </span>Encoding ContentEncoding { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public object </span>Data { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    <span style="color: blue">public override void </span>ExecuteResult(ControllerContext context)
    {
         <span style="color: blue">if </span>(context == <span style="color: blue">null</span>)
         {
              <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;context&quot;</span>);
         }
         HttpResponseBase response = context.HttpContext.Response;
         <span style="color: blue">if </span>(!<span style="color: blue">string</span>.IsNullOrEmpty(ContentType))
         {
              response.ContentType = ContentType;
         }
         <span style="color: blue">else
         </span>{
              response.ContentType = <span style="color: #a31515">&quot;application/json&quot;</span>;
         }
         <span style="color: blue">if </span>(ContentEncoding != <span style="color: blue">null</span>)
         {
              response.ContentEncoding = ContentEncoding;
         }
         <span style="color: blue">if </span>(Data != <span style="color: blue">null</span>)
         {
              <span style="color: blue">var </span>enumerable = Data <span style="color: blue">as </span>IEnumerable;
              <span style="color: blue">if </span>(enumerable != <span style="color: blue">null</span>)
              {
                    Data = <span style="color: blue">new </span>{d = enumerable};
              }
              <span style="color: blue">var </span>serializer = <span style="color: blue">new </span>JavaScriptSerializer();
              response.Write(serializer.Serialize(Data));
         }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This action result encapsulates the tricky code to output the proper JSON, and it works well. The downside to this approach is that we must use this d variable in our JavaScript code. Listing 11.15 <a></a><a>shows consuming the serialized data using jQuery</a><a href="#_msocom_1" name="_msoanchor_1">.</a></p>
<h5>Listing 11.15 Consuming SecureJsonResult with jQuery</h5>
<pre class="code">$(<span style="color: blue">function</span>() {
$.getJSON(<span style="color: #a31515">'/post/getsecurejson'</span>,
    <span style="color: blue">function</span>(data) {
        <span style="color: blue">var </span>options = <span style="color: #a31515">''</span>;
        <span style="color: blue">for </span>(<span style="color: blue">var </span>i = 0; i &lt; data.d.length; i++) {
            options += <span style="color: #a31515">'&lt;option value=&quot;' </span>+
            data.d[i].Id + <span style="color: #a31515">'&quot;&gt;' </span>+ data.d[i].Title +
            <span style="color: #a31515">'&lt;/option&gt;'</span>;
        }
        $(<span style="color: #a31515">'#secure'</span>).html(options);
    });
});</pre>
<p>Using this technique, we can still use GETs to retrieve our JSON data, but the JSON is secure because it&#8217;s never just an array-any arrays are wrapped in a d variable. We just must be sure to access values through the d variable. </p>
<p>This unconventional code can be confusing. We recommend using the default behavior of using HTTP POST requests to retrieve JSON data. If that becomes a problem, you can switch to this technique.</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/json-hijacking-in-asp-net-mvc-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing models for RouteValueDictionary and later model binding</title>
		<link>http://mhinze.com/serializing-models-for-routevaluedictionary-and-later-model-binding/</link>
		<comments>http://mhinze.com/serializing-models-for-routevaluedictionary-and-later-model-binding/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 20:47:17 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://mhinze.com/serializing-models-for-routevaluedictionary-and-later-model-binding/</guid>
		<description><![CDATA[(tl;dr : The bits, serializing to IDictionary&#60;string, object&#62; for RouteValueDictionary) We have several spots in our ASP.NET MVC 2 app that need to serialize an object into a RouteValueDictionary so that, in a subsequent request, it can be inflated, resurrected by the model binding infrastructure. We wrote extension method called ToHttpDictionary and we used it [...]]]></description>
			<content:encoded><![CDATA[<p>(tl;dr : <a href="http://unbinder.codeplex.com">The bits</a>, serializing to IDictionary&lt;string, object&gt; for RouteValueDictionary)</p>
<p>We have several spots in our ASP.NET MVC 2 app that need to serialize an object into a RouteValueDictionary so that, in a subsequent request, it can be inflated, resurrected by the model binding infrastructure.</p>
<p>We wrote extension method called ToHttpDictionary and we used it like this:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Url.Action(<span style="color: #a31515">&quot;index&quot;</span>, <span style="color: #a31515">&quot;something&quot;</span>, <span style="color: blue">new </span><span style="color: #2b91af">RouteValueDictionary</span>(Model.ToHttpDictionary())) <span style="background: #ffee62">%&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>or like this:</p>
<pre class="code">RedirectToAction(<span style="color: #a31515">&quot;index&quot;</span>, <span style="color: blue">new </span><span style="color: #2b91af">RouteValueDictionary</span>(form.ToHttpDictionary()))</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>(<em>and no, we do not use those raw helper method, we wrap them with a <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/14/a-new-breed-of-magic-strings-in-asp-net-mvc.aspx">strong-typed, smarter one</a>&#160; = ) </em>)</p>
<p>The goal is to transfer this example object, that we might accept as an action parameter: </p>
<pre class="code"><span style="color: blue">var </span>spec = <span style="color: blue">new </span><span style="color: #2b91af">SearchSpecification
</span>{
    FirstName = <span style="color: #a31515">&quot;John&quot;</span>,
    LastName = <span style="color: #a31515">&quot;Doe&quot;
</span>};</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Into the arguments for another request: </p>
<p>http://example.com/search<strong>?FirstName=John&amp;LastName=Doe</strong></p>
<p>That&#8217;s a lot easier than creating a form and a bunch of hidden fields just to store parameters for a GET request, or using that kludge anonymous type business.&#160; It also makes working with RedirectResult extremely easy, skipping all the nasty TempData stuff you might be tempted to use.</p>
<p>At first we just needed some small, flat objects to be &#8220;un bound&#8221;, but then once we needed prefixes, the ability to skip properties, support for custom unbinders, and to handle arrays we decided to pull it into <a href="http://unbinder.codeplex.com">its own library and put it on CodePlex</a>. </p>
<pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; ToHttpDictionary&lt;T&gt;
    (<span style="color: blue">this </span>T model, <span style="color: blue">params </span><span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">object</span>&gt;&gt;[] propertiesToSkip)
{
    <span style="color: #2b91af">SpecificValueUnbinderFactory</span>.CustomUnbinders =
        () =&gt; <span style="color: blue">new </span><span style="color: #2b91af">ISpecificValueUnbinder</span>[]
        {
            <span style="color: blue">new </span><span style="color: #2b91af">EnumerationValueUnbinder</span>(),
            <span style="color: blue">new </span><span style="color: #2b91af">PersistentObjectValueUnbinder</span>()
        };

    <span style="color: blue">return new </span><span style="color: #2b91af">Unbinder</span>().Unbind(x =&gt; x.Source(model).SkipProperties(propertiesToSkip));
}</pre>
<p>Custom value unbinders are the analog to custom model binders.&#160; For example, I&#8217;ve seen model binders that take the Id of an Entity from the request and hydrate a full Entity object from persistence.&#160; In that case we need an unbinder (sorry, I really can&#8217;t think of a better name for the concept) to serialize the Entity as the Id property.&#160; That would look something like this:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">PersistentObjectValueUnbinder </span>: <span style="color: #2b91af">ISpecificValueUnbinder
</span>{
    <span style="color: blue">public string </span>UnbindValue(<span style="color: blue">object </span>value)
    {
        <span style="color: blue">return </span>((<span style="color: #2b91af">PersistentObject</span>)value).Id.ToString();
    }

    <span style="color: blue">public bool </span>AppropriatelyUnbinds(<span style="color: blue">object </span>value)
    {
        <span style="color: blue">return </span>value <span style="color: blue">is </span><span style="color: #2b91af">PersistentObject</span>;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And you&#8217;d plug it in to the factory function like in the above example.</p>
<p>It&#8217;s just a simple helper function, but the technique has been useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/serializing-models-for-routevaluedictionary-and-later-model-binding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>January Events</title>
		<link>http://mhinze.com/january-events/</link>
		<comments>http://mhinze.com/january-events/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 14:28:57 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Community]]></category>

		<guid isPermaLink="false">http://mhinze.com/january-events/</guid>
		<description><![CDATA[Got a couple training events to plug. First, a fast paced and code-heavy journey towards understanding IOC.&#160; This free event features about 20 minutes of slides and another hour of live coding.&#160; We talk basics but quickly dive into advanced techniques.&#160; We had a packed house last time, so please register early. Free Inversion of [...]]]></description>
			<content:encoded><![CDATA[<p>Got a couple training events to plug.</p>
<p>First, a fast paced and code-heavy journey towards understanding IOC.&#160; This free event features about 20 minutes of slides and another hour of live coding.&#160; We talk basics but quickly dive into advanced techniques.&#160; We had a packed house last time, so please register early.</p>
<p><strong><a href="http://www.headspringsystems.com/community/workshop/">Free Inversion of Control Workshop</a>       <br />Tuesday, January 19 2:00 pm to 4:30 pm       <br />at the <a href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=9606+N+Mo+Pac+Expy,+Austin,+TX+78759&amp;sll=37.0625,-95.677068&amp;sspn=49.310476,78.574219&amp;ie=UTF8&amp;ll=30.385611,-97.736092&amp;spn=0.211461,0.306931&amp;z=12&amp;iwloc=A">Microsoft offices in Austin, Texas</a></strong></p>
<p>Also, I&#8217;m working another <a href="http://www.headspringsystems.com/services/agile-training/agile-boot-camp-part-I/">Headspring Agile Bootcamp</a> class this month.&#160; It&#8217;s three intense days of TDD and object oriented design.&#160; If you have any specific questions about this course, check the info page on the Headspring site, leave a comment or <a href="http://mhinze.com/about">shoot me an email</a>.</p>
<p><strong><a href="http://www.headspringsystems.com/services/agile-training/agile-boot-camp-part-I/">Headspring Agile Bootcamp</a>       <br />January 20 to January 22       <br />Austin, Texas</strong><strong>      <br /><strong>Call Headspring to Enroll: (877) 459-2260</strong></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/january-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Breaking up with the ternary operator</title>
		<link>http://mhinze.com/breaking-up-with-the-ternary-operator/</link>
		<comments>http://mhinze.com/breaking-up-with-the-ternary-operator/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 11:17:58 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://mhinze.com/breaking-up-with-the-ternary-operator/</guid>
		<description><![CDATA[I love the ternary operator.&#160; It&#8217;s so terse and clever.&#160; It&#8217;s been my bread and butter for years.&#160; It does things no other operator can do, and on three operands!&#160; It&#8217;s really a shining example of programming language designer genius.&#160; But lately we&#8217;ve been having problems.&#160; Things between us just aren&#8217;t working out. I generally [...]]]></description>
			<content:encoded><![CDATA[<p>I love the ternary operator.&#160; It&#8217;s so terse and clever.&#160; It&#8217;s been my bread and butter for years.&#160; It does things no other operator can do, and on three operands!&#160; It&#8217;s really a shining example of programming language designer <em>genius</em>.&#160; </p>
<p>But lately we&#8217;ve been having problems.&#160; Things between us just aren&#8217;t working out.</p>
<p>I generally catch it sneaking around, hiding complexity in a quick line of seemingly meaningless symbols.&#160; I won&#8217;t stand for it any longer.&#160; </p>
<p>I hardly ever actually type it out, anyway.&#160; I always use Resharper to craft it from an existing if statement. </p>
<p>It&#8217;s not that I don&#8217;t understand the ternary operator.&#160; I do.&#160; But as it increases the time-to-comprehension while reading and maintaining source code by even one tick, its unholy presence can accumulate an untenable viscosity in my workflow.</p>
<p>Reading code I&#8217;ve previously written, I find myself using Resharper to decode those same ternary operators back into if statements.</p>
<p>Source code should be easy to write and easy to read.&#160; There are very few contexts in which I&#8217;ll tolerate greater terseness over comprehensibility.</p>
<p>Ternary operator, pack your bags.&#160; It&#8217;s not you it&#8217;s me.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/breaking-up-with-the-ternary-operator/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Aggregated specifications</title>
		<link>http://mhinze.com/aggregated-specifications/</link>
		<comments>http://mhinze.com/aggregated-specifications/#comments</comments>
		<pubDate>Thu, 08 Oct 2009 11:07:53 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>

		<guid isPermaLink="false">http://mhinze.com/aggregated-specifications/</guid>
		<description><![CDATA[An example from my inversion of control talk involves a message formatter.&#160; It applies formatting rules to a string. public interface IMessageFomatter { string Format(string message); } Instead of doing all the work in the implementation of this interface, the message formatter will aggregate several distinct rules.&#160; An inversion of control tool is configured to [...]]]></description>
			<content:encoded><![CDATA[<p>An example from my inversion of control talk involves a message formatter.&#160; It applies formatting rules to a string. </p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IMessageFomatter
</span>{
    <span style="color: blue">string </span>Format(<span style="color: blue">string </span>message);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Instead of doing all the work in the implementation of this interface, the message formatter will aggregate several distinct rules.&#160; An inversion of control tool is configured to compose these rules and provide them to the formatter.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">MessageFomatter </span>: <span style="color: #2b91af">IMessageFomatter
</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">IFormatRule</span>[] _rules;

    <span style="color: blue">public </span>MessageFomatter(<span style="color: #2b91af">IFormatRule</span>[] rules)
    {
        _rules = rules;
    }

    <span style="color: blue">public string </span>Format(<span style="color: blue">string </span>message)
    {
        <span style="color: blue">foreach </span>(<span style="color: blue">var </span>action <span style="color: blue">in </span>_rules)
        {
            message = action.ApplyRule(message);
        }
        <span style="color: blue">return </span>message;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In this way each rule can be small, testable, and have only one job.&#160; I can add functionality to the formatting process without changing the formatter or any existing rule.&#160; </p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">string </span>ApplyRule(<span style="color: blue">string </span>text);
}

<span style="color: blue">public class </span><span style="color: #2b91af">DisclaimerRule </span>: <span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">public string </span>ApplyRule(<span style="color: blue">string </span>text)
    {
        <span style="color: blue">return </span>text + <span style="color: #a31515">&quot;\nDisclaimer: This message will self-destruct&quot;</span>;
    }
}

<span style="color: blue">public class </span><span style="color: #2b91af">UppercaseRule </span>: <span style="color: #2b91af">IFormatRule
</span>{
    <span style="color: blue">public string </span>ApplyRule(<span style="color: blue">string </span>text)
    {
        <span style="color: blue">return </span>text.ToUpper();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This technique is extremely powerful and <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/a-better-model-binder.aspx">we use it all over the place in our projects</a>.</p>
<p>Recently we were building a search screen.&#160; It has several text input boxes and select lists and radio button groups, you know, the standard enterprisey UI mess.&#160; Anyway, that&#8217;s what it was and it&#8217;s a common feature in the apps I work on. I&#8217;ve seen the scenario over and over. But armed with the above technique and LINQ to NHibernate, we were able to craft a much more elegant solution than we had previously created.</p>
<p>First we have a type that represents the search query.&#160; It could be implemented by the class that represents the user interface form or be built by the user interface layer.&#160; It&#8217;s sent to a service that will perform the query.</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductSearchQuery
</span>{
    <span style="color: blue">decimal</span>? Price { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">int</span>? PriceRange { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">string </span>Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: #2b91af">ProductCategory </span>Category { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: green">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductRepository
</span>{
    <span style="color: #2b91af">Product</span>[] Search(<span style="color: #2b91af">IProductSearchQuery </span>query);
    <span style="color: green">// ...
</span>}</pre>
<p>What we don&#8217;t want is a huge method that checks to see if a search criteria exists and then conditionally appends predicates to a database query.&#160; That&#8217;s the old school way, and it&#8217;s a beast to test and to change.&#160; Adding a user interface element, like a new text input field, would require us to change that big method by introducing repetitive and dangerous new code.</p>
<p>What we do want are <a href="http://ubik.com.au/article/named/implementing_the_specification_pattern_with_linq">small, isolated specifications</a> that we can aggregate like the message formatter.</p>
<pre class="code"><span style="color: blue">public interface </span><span style="color: #2b91af">IProductSearchFilter
</span>{
    <span style="color: blue">bool </span>ShouldApply(<span style="color: #2b91af">IProductSearchQuery </span>query);
    <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; Filter(<span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; candidates, <span style="color: #2b91af">IProductSearchQuery </span>query);
}</pre>
<p>An example filter:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">PriceRangeFilter </span>: <span style="color: #2b91af">IProductSearchFilter
</span>{
    <span style="color: blue">public bool </span>ShouldApply(<span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">return </span>query.Price.HasValue &amp;&amp; query.PriceRange.HasValue;
    }

    <span style="color: blue">public </span><span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; Filter(<span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; candidates, <span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">return from </span>product <span style="color: blue">in </span>candidates
               <span style="color: blue">where </span>product.Price &lt;= (query.Price + query.PriceRange)
               &amp;&amp; product.Price &gt;= (query.Price - query.PriceRange)
               <span style="color: blue">select </span>product;
    }
}</pre>
<p>You can test drive this thing.&#160; It&#8217;s small and distinct.&#160; And using LINQ to NHibernate you can combine several of them in a way that produces one select.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ProductRepository </span>: <span style="color: #2b91af">IProductRepository
</span>{
    <span style="color: blue">private readonly </span><span style="color: #2b91af">ISession </span>_session;
    <span style="color: blue">private readonly </span><span style="color: #2b91af">IProductSearchFilter</span>[] _filters;

    <span style="color: blue">public </span>ProductRepository(<span style="color: #2b91af">ISession </span>session, <span style="color: #2b91af">IProductSearchFilter</span>[] filters)
    {
        _session = session;
        _filters = filters;
    }

    <span style="color: blue">public </span><span style="color: #2b91af">Product</span>[] Search(<span style="color: #2b91af">IProductSearchQuery </span>query)
    {
        <span style="color: blue">var </span>products = _session.Linq&lt;<span style="color: #2b91af">Product</span>&gt;();
        <span style="color: blue">return </span>_filters
            .Where(x =&gt; x.ShouldApply(query))
            .Aggregate(products, (candidates, filter) =&gt;
                filter.Filter(candidates, query)).ToArray();
    }

    <span style="color: green">// ...
</span>}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>One tricky spot for a lot of people is that Aggregate call.&#160; It does the exact same thing as the foreach in the message formatter: passes the seed (products, in this case) through the filters aggregating the result.&#160; The lambda parameter variable candidates is the result of the previous filter (or the seed for the first filter).&#160; In other ecosystems besides .NET, Aggregate is called reduce.&#160; You can see why &#8211; each filter reduces the candidates according to its specification.</p>
<p>When you think about it, an <a href="http://www.google.com/webhp#hl=en&amp;q=mapreduce+architecture">entire architecture could be a reduce</a>. That would be <em>really</em> interesting.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/aggregated-specifications/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Microsoft MVP</title>
		<link>http://mhinze.com/microsoft-mvp/</link>
		<comments>http://mhinze.com/microsoft-mvp/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 20:15:53 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Community]]></category>

		<guid isPermaLink="false">http://mhinze.com/microsoft-mvp/</guid>
		<description><![CDATA[I received word today that I&#8217;m a Microsoft MVP for C#.&#160; Cool. This next bit is going to read like some phony sales pitch or something but it&#8217;s legitimate: I got the award because I work at a great company that nurtures community involvement, encourages open source contribution and gives me the opportunity to develop [...]]]></description>
			<content:encoded><![CDATA[<p>I received word today that I&#8217;m a Microsoft MVP for C#.&#160; Cool.</p>
<p>This next bit is going to read like some phony sales pitch or something but it&#8217;s legitimate:</p>
<p>I got the award because I work at a <a href="http://headspringsystems.com">great company</a> that nurtures community involvement, encourages open source contribution and gives me the opportunity to develop and deliver high quality courseware for programmers.&#160; I also work every day in the IDE and whiteboard trenches with an incredibly talented team of developers who foster a real culture of continuous improvement.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/microsoft-mvp/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>AutoMapper in NerdDinner</title>
		<link>http://mhinze.com/automapper-in-nerddinner/</link>
		<comments>http://mhinze.com/automapper-in-nerddinner/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 11:00:00 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Tools]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[automapper]]></category>

		<guid isPermaLink="false">http://mhinze.com/automapper-in-nerddinner/</guid>
		<description><![CDATA[Speaking of NerdDinner, Scott asked me to use it to create an AutoMapper example. AutoMapper, the brainchild of Jimmy Bogard, is an object-to-object mapper.&#160; What that means is up to you &#8211; but we&#8217;ll use it here to map from the domain model to a view model.&#160; The view model is an object heirarchy that [...]]]></description>
			<content:encoded><![CDATA[</p>
<p><a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/07/03/how-not-to-do-dependency-injection-in-nerddinner.aspx">Speaking</a> of <a href="http://nerddinner.codeplex.com/">NerdDinner</a>, <a href="http://www.hanselman.com/blog/">Scott</a> <a href="http://twitter.com/shanselman/status/2441262483">asked me</a> to use it to create an <a href="http://code.google.com/p/automapperhome/">AutoMapper</a> example. <a href="http://mhinze.com/wp-content/uploads/2009/07/logo.png"><img title="logo" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin: 0px 0px 15px 20px; border-right-width: 0px" height="90" alt="logo" src="http://mhinze.com/wp-content/uploads/2009/07/logo_thumb.png" width="244" align="right" border="0" /></a> </p>
<p>AutoMapper, the brainchild of <a href="http://www.lostechies.com/blogs/jimmy_bogard/default.aspx">Jimmy Bogard</a>, is an object-to-object mapper.&#160; What that means is up to you &#8211; but we&#8217;ll use it here to map from the domain model to a view model.&#160; The view model is an object heirarchy that represents the screen.&#160; It&#8217;s as dumb as possible, just like the view.</p>
<p>We get a lot of nice things out of it and it helps us go faster.&#160; You can read more about it AutoMapper from <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/tags/AutoMapper/default.aspx">Jimmy</a> or at the website on <a href="http://www.codeplex.com/AutoMapper">Codeplex</a>.</p>
<p>For starters, NerdDinner isn&#8217;t the best scenario in which to apply AutoMapper.&#160; NerdDinner is very small so there&#8217;s not much reuse to harvest. For example, if you format dates the same way a million times you can use AutoMapper to only write that formatting code once.&#160; In a small application you may format dates two ways and only use the resulting text in two views.&#160; It doesn&#8217;t make a lot of sense to extract a class just for that &#8211; it will seem like a lot of overhead.&#160; </p>
<p>Also NerdDinner doesn&#8217;t have a rich domain model &#8211; there&#8217;s just not that much to do.&#160; So the AutoMapper feature of <a href="http://automapper.codeplex.com/Wiki/View.aspx?title=Flattening">flattening complex hierarchies</a> can&#8217;t be appreciated. </p>
<p>I posted <a href="http://mhinze.com/static-content/nerddinner-23425-automapper.zip"><strong>the result of this quick and dirty spike</strong></a> as a sample project &#8211; hopefully this will help you get started looking at it.</p>
<p>First, I copypasted a class to bootstrap AutoMapper:</p>
<pre class="code"><span style="color: blue">namespace </span>NerdDinner.Helpers.AutoMapper
{
    <span style="color: blue">public class </span><span style="color: #2b91af">AutoMapperConfiguration
    </span>{
        <span style="color: blue">public static void </span>Configure()
        {
            <span style="color: #2b91af">Mapper</span>.Initialize(x =&gt; x.AddProfile&lt;<span style="color: #2b91af">ViewModelProfile</span>&gt;());
        }
    }
}</pre>
<p>.. which will be called when the application starts:</p>
<pre class="code"><span style="color: blue">void </span>Application_Start()
{
    <span style="color: #2b91af">AutoMapperConfiguration</span>.Configure();

    RegisterRoutes(<span style="color: #2b91af">RouteTable</span>.Routes);

    <span style="color: #2b91af">ViewEngines</span>.Engines.Clear();
    <span style="color: #2b91af">ViewEngines</span>.Engines.Add(<span style="color: blue">new </span><span style="color: #2b91af">MobileCapableWebFormViewEngine</span>());
}</pre>
<p>I copypasted another class that will check the mapping configuration for errors, providing fast feedback should I make a mistake. </p>
<pre class="code">[<span style="color: #2b91af">TestClass</span>]
<span style="color: blue">public class </span><span style="color: #2b91af">AutoMapperConfigurationTester
</span>{
    [<span style="color: #2b91af">TestMethod</span>]
    <span style="color: blue">public void </span>Should_map_dtos()
    {
        <span style="color: #2b91af">AutoMapperConfiguration</span>.Configure();
        <span style="color: #2b91af">Mapper</span>.AssertConfigurationIsValid();
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Now I&#8217;m ready to begin creating the view model and configuring AutoMapper. </p>
<p>To design a view model, start with the screen.&#160; What&#8217;s displayed will be represented in the model.&#160; Again: the view model is an object hierarchy that represents the user interface.&#160; I picked the Dinner Details screen, by the way. </p>
<p>The current model being used by the view was the Dinner entity itself.&#160; There was a lot of formatting in the view and a lot of duplication.</p>
<p>Almost every property was surrounded by code that would HtmlEncode it (it will be nice to have AutoMapper do this for us):</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Html.Encode(Model.Title) <span style="background: #ffee62">%&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>And there is a lot of formatting to do:</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">abbr </span><span style="color: red">class</span><span style="color: blue">=&quot;dtstart&quot; </span><span style="color: red">title</span><span style="color: blue">=&quot;</span><span style="background: #ffee62">&lt;%</span>= Model.EventDate.ToString(&quot;s&quot;) <span style="background: #ffee62">%&gt;</span><span style="color: blue">&quot;&gt;
    </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.EventDate.ToString(<span style="color: #a31515">&quot;MMM dd, yyyy&quot;</span>) <span style="background: #ffee62">%&gt;</span>
    <span style="color: blue">&lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>@<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.EventDate.ToShortTimeString() <span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;/</span><span style="color: #a31515">abbr</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>Imagine a project with 300 screens and a team of analysts and you can imagine that specifying this formatting over and over again in requirements documents and planning would become tedious.&#160; Not to mention coding it.&#160; It&#8217;d be easier to just say: &#8220;Format this date in the standard way.&#8221; You can also imagine the security implications of forgetting to encode even one value.</p>
<p>In converting these screens to use a view model instead of the domain model I didn&#8217;t want to change existing functionality.&#160; So I took this:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">@ </span><span style="color: #a31515">Page </span><span style="color: red">Language</span><span style="color: blue">=&quot;C#&quot; </span><span style="color: red">Inherits</span><span style="color: blue">=&quot;System.Web.Mvc.ViewPage&lt;NerdDinner.Models.Dinner&gt;&quot;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>and changed it to this:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">@ </span><span style="color: #a31515">Page </span><span style="color: red">Language</span><span style="color: blue">=&quot;C#&quot; </span><span style="color: red">Inherits</span><span style="color: blue">=&quot;System.Web.Mvc.ViewPage&lt;DinnerDetailsViewModel&gt;&quot;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>See what I did there?&#160; I just changed the type of the Model property to a new DinnerDetailsViewModel type.</p>
<p>The view will receive a view model mapped from the domain model when I apply a special action filter to the controller action:</p>
<pre class="code">[<span style="color: #2b91af">AutoMap</span>(<span style="color: blue">typeof</span>(<span style="color: #2b91af">Dinner</span>), <span style="color: blue">typeof</span>(<span style="color: #2b91af">DinnerDetailsViewModel</span>))]</pre>
<p>The code&#8217;s in the sample, straight from <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx">Jimmy&#8217;s post</a>.</p>
<p>I started out with DinnerDetailsViewModel being an empty class definition and used Resharper to generate each property as I encountered it.&#160; I removed the formatting and the ubiquitous encoding from the parameters, turning this:</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">div </span><span style="color: red">id</span><span style="color: blue">=&quot;dinnerDiv&quot; </span><span style="color: red">class</span><span style="color: blue">=&quot;vevent&quot;&gt;

    &lt;</span><span style="color: #a31515">h2 </span><span style="color: red">class</span><span style="color: blue">=&quot;summary&quot;&gt;</span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Html.Encode(Model.Title) <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">h2</span><span style="color: blue">&gt;

    &lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">a </span><span style="color: red">href</span><span style="color: blue">=&quot;http://feeds.technorati.com/events/</span><span style="background: #ffee62">&lt;%</span>= Url.AbsoluteAction(&quot;Details&quot;, new { id = Model.DinnerID }) <span style="background: #ffee62">%&gt;</span><span style="color: blue">&quot;&gt;
            </span>Add event to your calendar (iCal)
        <span style="color: blue">&lt;/</span><span style="color: #a31515">a</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;

    &lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>When:<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
&lt;</span><span style="color: #a31515">abbr </span><span style="color: red">class</span><span style="color: blue">=&quot;dtstart&quot; </span><span style="color: red">title</span><span style="color: blue">=&quot;</span><span style="background: #ffee62">&lt;%</span>= Model.EventDate.ToString(&quot;s&quot;) <span style="background: #ffee62">%&gt;</span><span style="color: blue">&quot;&gt;
</span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.EventDate.ToString(<span style="color: #a31515">&quot;MMM dd, yyyy&quot;</span>) <span style="background: #ffee62">%&gt;</span>
<span style="color: blue">&lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>@<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
</span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.EventDate.ToShortTimeString() <span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;/</span><span style="color: #a31515">abbr</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>into this:</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">h2 </span><span style="color: red">class</span><span style="color: blue">=&quot;summary&quot;&gt;</span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.Title <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">h2</span><span style="color: blue">&gt;

&lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">a </span><span style="color: red">href</span><span style="color: blue">=&quot;http://feeds.technorati.com/events/</span><span style="background: #ffee62">&lt;%</span>= Url.AbsoluteAction(&quot;Details&quot;, new { id = Model.DinnerID }) <span style="background: #ffee62">%&gt;</span><span style="color: blue">&quot;&gt;
        </span>Add event to your calendar (iCal)
    <span style="color: blue">&lt;/</span><span style="color: #a31515">a</span><span style="color: blue">&gt;
&lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;

&lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>When:<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>Model.EventDate <span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>I had to write a formatter to replace the custom formatting performed by the view. </p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">AttendeeNameFormatter </span>: <span style="color: #2b91af">BaseFormatter</span>&lt;<span style="color: blue">string</span>&gt;
{
    <span style="color: blue">protected override string </span>FormatValueCore(<span style="color: blue">string </span>value)
    {
        <span style="color: blue">return </span>value.Replace(<span style="color: #a31515">&quot;@&quot;</span>, <span style="color: #a31515">&quot; at &quot;</span>);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>See how testable that is; small and reusable?</p>
<p><a href="http://11011.net/software/vspaste"></a>I also moved some methods that were previously being called from the view directly into the domain model which AutoMapper will evaluate at runtime. </p>
<p>Before:</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">p </span><span style="color: red">id</span><span style="color: blue">=&quot;whoscoming&quot;&gt;
    &lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>Who's Coming:<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">if </span>(Model.RSVPs.Count == 0){<span style="background: #ffee62">%&gt;
</span>          No one has registered.
    <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>After:</p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">p </span><span style="color: red">id</span><span style="color: blue">=&quot;whoscoming&quot;&gt;
    &lt;</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;</span>Who's Coming:<span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">if </span>(Model.IsNobodyRegistered){<span style="background: #ffee62">%&gt;
</span>          No one has registered.
    <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;</span></pre>
<p>The view model for this screen ends up looking like this:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">DinnerDetailsViewModel
</span>{
    <span style="color: blue">public string </span>Address { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Title { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>DinnerID { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>EventDate { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Country { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Latitude { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Longitude { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Description { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>HostedBy { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>ContactPhone { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public bool </span>IsAnyoneRegistered { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public bool </span>IsNobodyRegistered { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public bool </span>IsCurrentUserRegistered { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public bool </span>IsCurrentUserHosting { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    <span style="color: blue">public </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">RsvpViewModel</span>&gt; RSVPs { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }

    <span style="color: blue">public class </span><span style="color: #2b91af">RsvpViewModel
    </span>{
        <span style="color: blue">public string </span>AttendeeName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    }
}</pre>
<p>The really key part is the AutoMapper configuration profile.&#160; You can group configurations with profiles.&#160; Maybe in one profile you format dates in one way, in another profile you format dates in another way.&#160; I&#8217;m just using one profile here.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ViewModelProfile </span>: <span style="color: #2b91af">Profile
</span>{
    <span style="color: blue">protected override string </span>ProfileName
    {
        <span style="color: blue">get </span>{ <span style="color: blue">return </span><span style="color: #a31515">&quot;ViewModel&quot;</span>; }
    }

    <span style="color: blue">protected override void </span>Configure()
    {
        AddFormatter&lt;<span style="color: #2b91af">HtmlEncoderFormatter</span>&gt;();
        ForSourceType&lt;<span style="color: #2b91af">DateTime</span>&gt;().AddFormatter&lt;<span style="color: #2b91af">StandardDateFormatter</span>&gt;();

        CreateMap&lt;<span style="color: #2b91af">Dinner</span>, <span style="color: #2b91af">DinnerDetailsViewModel</span>&gt;()
            .ForMember(x =&gt; x.IsCurrentUserRegistered, o =&gt; o.ResolveUsing&lt;<span style="color: #2b91af">CurrentUserRegisteredResolver</span>&gt;())
            .ForMember(x =&gt; x.IsCurrentUserHosting, o =&gt; o.ResolveUsing&lt;<span style="color: #2b91af">CurrentUserHostingResolver</span>&gt;())
            .ForMember(x =&gt; x.EventDate, o =&gt; o.SkipFormatter&lt;<span style="color: #2b91af">HtmlEncoderFormatter</span>&gt;());

        CreateMap&lt;<span style="color: #2b91af">RSVP</span>, <span style="color: #2b91af">DinnerDetailsViewModel</span>.<span style="color: #2b91af">RsvpViewModel</span>&gt;()
            .ForMember(x =&gt; x.AttendeeName, o =&gt; o.AddFormatter&lt;<span style="color: #2b91af">AttendeeNameFormatter</span>&gt;());
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>Most properties of the view model are mapped conventionally.&#160; The property names match up so AutoMapper knows exactly what do do with them.&#160; AutoMapper will do a lot more for you if you&#8217;d like it to.&#160; This is actually a pretty hefty configuration.&#160; In a different scenario it&#8217;d be likely that almost everything is mapped conventionally.</p>
<p>Note the first AddFormatter call.&#160; That&#8217;s instructing AutoMapper to html encode everything.&#160; I skip it for a property later.&#160; The possibilities here are endless.&#160; One cool thing we do <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/04/24/how-we-do-mvc.aspx">in another project</a> is wrap each property in a span that&#8217;s given a conventionally named CSS class.&#160; In automated UI tests, we can use that class to find the proper element and ensure that the screen is displaying the right thing.</p>
<p><a href="http://mhinze.com/wp-content/uploads/2009/07/image.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="204" alt="image" src="http://mhinze.com/wp-content/uploads/2009/07/image_thumb.png" width="244" border="0" /></a></p>
<p>Let me know if you have any questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/automapper-in-nerddinner/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Free ASP.NET MVC event in Austin</title>
		<link>http://mhinze.com/free-aspnet-mvc-event-in-austin/</link>
		<comments>http://mhinze.com/free-aspnet-mvc-event-in-austin/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 11:59:59 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Community]]></category>
		<category><![CDATA[training]]></category>

		<guid isPermaLink="false">http://mhinze.com/free-aspnet-mvc-event-in-austin/</guid>
		<description><![CDATA[Jeffrey and Eric will be delivering a free afternoon of ASP.NET MVC in Austin on Tuesday, June 16th.&#160; If you haven&#8217;t yet had a run-in with the new framework or if you&#8217;re ready to see what we&#8217;ve learned using ASP.NET MVC in the field, this afternoon will be an excellent opportunity to compress learning and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jeffreypalermo.com">Jeffrey</a> and <a href="http://www.lostechies.com/blogs/hex/">Eric</a> will be delivering a free <a href="http://www.headspringsystems.com/services/agile-training/mvc-training/">afternoon of ASP.NET MVC in Austin on Tuesday, June 16th</a>.&nbsp; If you haven&#8217;t yet had a run-in with the new framework or if you&#8217;re ready to see what we&#8217;ve learned using ASP.NET MVC in the field, this afternoon will be an excellent opportunity to compress learning and maximize your time&#8230;&nbsp; </p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/free-aspnet-mvc-event-in-austin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Nested Closure</title>
		<link>http://mhinze.com/simple-nested-closure/</link>
		<comments>http://mhinze.com/simple-nested-closure/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 02:42:33 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[fluent interface]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://mhinze.com/simple-nested-closure/</guid>
		<description><![CDATA[Nested closure is one of those fancy patterns Martin Fowler first coined (as far as I know) and published on his DSL WIP site. His formal definition: Express statement sub-elements of a function call by putting them into a closure in an argument. You pass a delegate as a method parameter. The receiving method executes [...]]]></description>
			<content:encoded><![CDATA[<p>Nested closure is one of those fancy patterns <a href="http://martinfowler.com/dslwip/NestedClosure.html">Martin Fowler first coined</a> (as far as I know) and published on his <a href="http://martinfowler.com/dslwip/index.html">DSL WIP</a> site. His formal definition:</p>
<blockquote><p><i>Express statement sub-elements of a function call by putting them into a closure in an argument.</i></p>
</blockquote>
<p>You pass a delegate as a method parameter. The receiving method executes the function represented by that delegate against an object it controls.&nbsp; Nested closure in C# is easy to spot because the delegate is usually typed as <em>Action&lt;T&gt;</em>, where <em>T</em> is the type of the object that the called method will provide as a parameter to our argument function.</p>
<p>The most obvious example is a common extension method:</p>
<pre class="code"><span style="color: blue">public static void </span>ForEach&lt;T&gt;(<span style="color: blue">this </span><span style="color: #2b91af">IEnumerable</span>&lt;T&gt; items, <span style="color: #2b91af">Action</span>&lt;T&gt; action)
{
    <span style="color: blue">foreach </span>(T item <span style="color: blue">in </span>items)
    {
        action(item);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Nested closure is like <a href="http://www.dofactory.com/Patterns/PatternTemplate.aspx">template method</a>, but instead of deriving from a base class to affect behavior, the additional behavior is provided as an argument.&nbsp; In the same way that template method is great when you want to communicate behavior from derivations to base classes, nested closure works when you want to communicate behavior as you call a method.</p>
<p>Consider working with a common series of steps when writing repository methods against NHibernate:</p>
<pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">Order</span>[] GetAllOpenOrders(<span style="color: #2b91af">Customer </span>customer)
{
    <span style="color: #2b91af">ISession </span>session = GetSession();
    <span style="color: #2b91af">IQuery </span>query = session.CreateQuery(<span style="color: #a31515">"from Order o where o.Resolution is null and o.Customer = ?"</span>);
    query.SetEntity(0, customer);
    <span style="color: blue">var </span>results = query.List&lt;<span style="color: #2b91af">Order</span>&gt;().ToArray();
    <span style="color: blue">return </span>results;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Code like this &#8211; where you have the same basic structure in several methods &#8211; can be made more terse by using a nested closure.</p>
<pre class="code"><span style="color: blue">public </span><span style="color: #2b91af">Order</span>[] GetShippedOrders(<span style="color: #2b91af">Customer </span>customer)
{
    <span style="color: blue">const string </span>hql = <span style="color: #a31515">"select distinct s.Order from Shipment s where s.Order.Customer = ?"</span>;

    <span style="color: blue">return </span>Hql(hql, x =&gt; x.SetEntity(0, customer));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The second parameter is an <em>Action&lt;IQuery&gt;</em>.</p>
<pre class="code"><span style="color: blue">protected </span>T[] Hql(<span style="color: blue">string </span>query, <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">IQuery</span>&gt; additionalWork)
{
    <span style="color: #2b91af">IQuery </span>iquery = GetSession().CreateQuery(query);

    <span style="color: blue">if </span>(additionalWork != <span style="color: blue">null</span>)
        additionalWork(iquery);

    <span style="color: blue">return </span>iquery.List&lt;T&gt;().ToArray();
}</pre>
<p>Nested closures are also good for adding fluency to APIs.&nbsp; This is the context of Fowler&#8217;s writing, and you can see it clearly in Rhino Mocks:</p>
<pre class="code">repository.AssertWasCalled(x =&gt; x.Save(<span style="color: blue">null</span>), o =&gt;
    {
        o.IgnoreArguments();
        o.Constraints(<span style="color: #2b91af">Property</span>.AllPropertiesMatch(visitToSave));
    });</pre>
<p>In this scenario we&#8217;re passing a delegate that, when invoked later, helps Rhino Mocks configure options for its expectations.</p>
]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/simple-nested-closure/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
