<?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/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">

<channel>
	<title>mhinze.com</title>
	
	<link>http://mhinze.com</link>
	<description>Matt Hinze, learning in public</description>
	<lastBuildDate>Tue, 27 Mar 2012 13:56:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain="mhinze.com" port="80" path="/?rsscloud=notify" registerProcedure="" protocol="http-post" />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>mhinze.com</title>
		<link>http://mhinze.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mhinze.com/osd.xml" title="mhinze.com" />
	
		<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/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://mhinze.com/?pushpress=hub" /><item>
		<title>Simple reads with Entity Framework</title>
		<link>http://mhinze.com/2011/03/03/simple-reads-with-entity-framework/</link>
		<comments>http://mhinze.com/2011/03/03/simple-reads-with-entity-framework/#comments</comments>
		<pubDate>Fri, 04 Mar 2011 04:19:18 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">https://mhinze.wordpress.com/?p=327</guid>
		<description><![CDATA[This works nicely for quick reads.&#160; Requires no mappings or any of that junk. Just a DataReader shaped to a type. Edit: Because this is my first day to ever work with EF, my first attempt at this was more &#8230; <a href="http://mhinze.com/2011/03/03/simple-reads-with-entity-framework/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=327&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This works nicely for quick reads.&nbsp; Requires no mappings or any of that junk. Just a DataReader shaped to a type.</p>
<p><strong>Edit</strong>: Because this is my first day to ever work with EF, my first attempt at this was more complicated (you can see this evolution at <a href="https://gist.github.com/854157">the gist</a>).&nbsp; After removing my useless code, you can see it’s just Entity Framework.&nbsp; Sadly I can’t take any credit.&nbsp; Still – this IS cool.&nbsp; Fast, super easy, typed queries with only framework dependencies.&nbsp; I was surprised to see it supported the mapping-less projections.&nbsp; Perfect for all of those fancy <em>persistent view model </em>scenarios all the cool CQRS kids are doing.</p>
<pre class="code"><span style="color:blue;">using </span><span style="color:#00008b;">System</span>;
<span style="color:blue;">using </span><span style="color:#00008b;">System</span>.<span style="color:#00008b;">Collections</span>.<span style="color:#00008b;">Generic</span>;
<span style="color:blue;">using </span><span style="color:#00008b;">System</span>.<span style="color:#00008b;">Data</span>.<span style="color:#00008b;">Entity</span>;

<span style="color:blue;">public static class </span><span style="color:#00008b;">Effin
</span>{
    <span style="color:blue;">public static </span><span style="color:#00008b;">IEnumerable</span>&lt;<span style="color:#00008b;">T</span>&gt; <span style="color:#008b8b;">Query</span>&lt;<span style="color:#00008b;">T</span>&gt;
        (<span style="color:blue;">this string </span>connectionStringName, <span style="color:blue;">string </span>sql,
        <span style="color:blue;">params object</span>[] parameters)
    {
        <span style="color:blue;">return new </span><span style="color:#00008b;">DbContext</span>(connectionStringName)
            .<span style="color:purple;">Database</span>.<span style="color:#008b8b;">SqlQuery</span>&lt;<span style="color:#00008b;">T</span>&gt;(sql, parameters);
    }
}

<span style="color:blue;">public class </span><span style="color:#00008b;">Example
</span>{
    <span style="color:blue;">public void </span><span style="color:#008b8b;">UsingEffin</span>()
    {
        <span style="color:#00008b;">IEnumerable</span>&lt;<span style="color:#00008b;">Name</span>&gt; names =
            <span style="color:#a31515;">"data"</span>.<span style="color:#008b8b;">Query</span>&lt;<span style="color:#00008b;">Name</span>&gt;(<span style="color:#a31515;">"select FirstName from Person"</span>);

        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>name <span style="color:blue;">in </span>names)
        {
            <span style="color:#00008b;">Console</span>.<span style="color:#008b8b;">WriteLine</span>(name.<span style="color:purple;">FirstName</span>);
        }
    }

    <span style="color:blue;">public class </span><span style="color:#00008b;">Name
    </span>{
        <span style="color:blue;">public string </span><span style="color:purple;">FirstName </span>{ <span style="color:#008b8b;">get</span>; <span style="color:#008b8b;">set</span>; }
    }
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/327/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/327/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/327/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=327&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2011/03/03/simple-reads-with-entity-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Reuse is overrated, then came package management</title>
		<link>http://mhinze.com/2011/02/27/reuse-is-overrated-then-came-package-management/</link>
		<comments>http://mhinze.com/2011/02/27/reuse-is-overrated-then-came-package-management/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 06:47:10 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">https://mhinze.wordpress.com/?p=324</guid>
		<description><![CDATA[Reuse is overrated.&#160; True story: a team building a system.&#160; They decide that one chunk of code might be valuable in another project or two.&#160; So they extract it into a library and open source it. Project complete, team reorganizes &#8230; <a href="http://mhinze.com/2011/02/27/reuse-is-overrated-then-came-package-management/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=324&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Reuse is <a href="http://www.infoq.com/news/2007/07/worthless-code">overrated</a>.&nbsp; </p>
<p>True story: a team building a system.&nbsp; They decide that one chunk of code might be valuable in another project or two.&nbsp; So they extract it into a library and open source it. </p>
<p>Project complete, team reorganizes and begins a couple new projects.&nbsp; Both new projects depend on that library.&nbsp; For awhile everything is great. </p>
<p>Sooner or later someone needs to make a change.&nbsp; It’s sort of a pain, because the source code is in another IDE configuration.&nbsp; Actually it’s been awhile since anyone worked on it and it’s hard to find a developer on the team who has that version of the IDE installed.&nbsp; But the change happens, painful as it may be, because it has to. </p>
<p>Someone later gets lazy.&nbsp; They build it locally and copy the assemblies directly into the lib folder.&nbsp; Now the library was compiled from source code that’s not in the version control system.&nbsp; This is spinning out of control.&nbsp; Or maybe that was intentional – because the other team is using the library too, but they have different needs and we’ve sort of been in a mutually-assured-destruction paralysis about what changes to make. </p>
<p>Eventually someone realizes the solution is not to depend on this library, the compiled bits, but to just copy the source code over.&nbsp; We need to make our tweaks, they need to make their tweaks.&nbsp; It makes sense.&nbsp;&nbsp; So we lose our code reuse; does anyone care?&nbsp; </p>
<p>This dirty-feeling code copying can be a good idea for a non-technical reason:&nbsp; it emphasizes that <strong>the important element of reuse is the human expertise to understand, create, use and modify a solution that solves a particular problem</strong>.</p>
<p>Turns out NuGet is great for this.&nbsp; I noticed that Rob Conery packaged his <a href="http://nuget.org/Packages/Packages/Details/Massive-1-0">Massive</a> library as just a file.&nbsp; A source code file.&nbsp; Not a .dll.&nbsp; Great idea, and I immediately thought of all the code that I want to share among many projects but also have the flexibility to change, <em>now – without context switching or fear of repercussions</em>.</p>
<p>You just put the files in a Content subdirectory and the NuGet process will shove them in the project root or App_Code or wherever.</p>
<p>I <a href="http://nuget.org/Packages/Packages/Details/Enumeration-1-0-2">did the same</a> with a little <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx">utility class</a> that we use a lot, and I’m going to do it some more.&nbsp; </p>
<p>For many teams, a <a href="http://nuget.codeplex.com/wikipage?title=Hosting%20Your%20Own%20Local%20and%20Remote%20NuPack%20Feeds">hosted NuGet feed</a> with content files is the new helper library.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/324/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/324/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/324/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=324&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2011/02/27/reuse-is-overrated-then-came-package-management/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Type systems and their advantages</title>
		<link>http://mhinze.com/2010/12/02/type-systems-and-their-advantages/</link>
		<comments>http://mhinze.com/2010/12/02/type-systems-and-their-advantages/#comments</comments>
		<pubDate>Fri, 03 Dec 2010 05:23:03 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Deep thoughts]]></category>

		<guid isPermaLink="false">https://mhinze.wordpress.com/2010/12/02/type-systems-and-their-advantages/</guid>
		<description><![CDATA[Typing is not the bottleneck.  Neither is typing. If you’ve been a programmer sometime in the last fourteen billion years you’ve noticed that there’s this conversation about type systems, specifically about comparing static type systems to dynamic type systems. Dynamic &#8230; <a href="http://mhinze.com/2010/12/02/type-systems-and-their-advantages/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=286&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<blockquote><p><a href="http://twitter.com/mhinze/status/27258450868">Typing is not the bottleneck.  Neither is typing.</a></p></blockquote>
<p>If you’ve been a programmer sometime in the last fourteen billion years you’ve noticed that there’s this conversation about type systems, specifically about comparing static type systems to dynamic type systems.</p>
<p>Dynamic typing doesn’t mean you can change the type of a <em>thing (</em>even though you sometimes can) it means you can change the shape of <em>types themselves</em> at run time.  It means that you can tell a variable to write itself some new, strange, dynamic behavior, but you don’t tell it what to write, you tell it how to decide what to write.  And you can eliminate a lot of duplication this way.</p>
<p>But static type systems don’t give you that ability.  You have to define the shape and behavior of a type at compile time.</p>
<p>I know what you’re thinking: that really stinks!  I want the ability to muck about with my variables, and have them run my code against their own internals and have them write new methods for themselves, and decide how they handle calls against methods that don’t exist, and even crazier things.</p>
<p>The static type system folks can do something that’s really powerful.  They can use the type system itself as a global registry.</p>
<p>You see this in a lot of the C# written today, especially the stuff that makes heavy use of an IOC tool and generics.  They’ll ask the system to get all the types that implement some interface, or for the types that close some interface and another type.  Then they take these types and instantiate one instance of each of them, and use those instances in some way.  Each instance runs in a chain or pipeline, or to apply a series of filtering functions to a data set.</p>
<p>The type system becomes a big dispatch table, with type names as global keys, but it’s more like a dispatch tree, because of polymorphism and generic type parameters and all that.</p>
<p>It’s freakin’ cool, once you start doing it &#8211; it’s elegant and easy compared to the old stodgy way of programming.  And the IOC tools they use keep getting more interesting features that let them query the type-system-as-dispatch-tree in novel ways.</p>
<p>The dynamic type system folks will shrug and suggest implementing dispatch table with a hash like they’ve been doing in Perl for 15 years.</p>
<p>The static type system folks keep losing because their arguments are bad – <em>Compile Time Checking</em> and <em>Tooling</em> just aren’t cutting it.  But they may be onto something if they could articulate the benefits of this global registry better than I can.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/286/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/286/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/286/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=286&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2010/12/02/type-systems-and-their-advantages/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Easy ways to maximize the value of TDD</title>
		<link>http://mhinze.com/2010/12/02/easy-ways-to-maximize-the-value-of-tdd/</link>
		<comments>http://mhinze.com/2010/12/02/easy-ways-to-maximize-the-value-of-tdd/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 14:07:58 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">https://mhinze.wordpress.com/2010/12/02/easy-ways-to-maximize-the-value-of-tdd/</guid>
		<description><![CDATA[Before we’ve made it pass the first time, a failing test tells us what code to write. When it fails later, it can tell us what we broke.&#160; Failing tests alert us to regressions before we integrate. A test is &#8230; <a href="http://mhinze.com/2010/12/02/easy-ways-to-maximize-the-value-of-tdd/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=285&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Before we’ve made it pass the first time, a failing test tells us what code to write. </p>
<p>When it fails later, it can tell us what we broke.&nbsp; Failing tests alert us to regressions before we integrate.</p>
<p>A test is most valuable when it fails.</p>
<p>This is why the number-one-most-important rule of TDD is to maintain One Logical Assertion Per Test.&nbsp; If you have more than one, a failing test becomes ambiguous.&nbsp; This helps in writing the test and in understanding its failure, also known as diagnostics.&nbsp; </p>
<p>When a test fails you should know exactly why.</p>
<p>
<hr /> Before we’ve written a test we must <em>articulate</em> the rationale behind the whole deal in the first place, and this process helps us reason abut the production system and its design.</p>
<p>After we’ve made it pass the first time, it becomes one in a suite of passing test cases we regularly run.&nbsp;&nbsp; Now it can tell us what the system is doing in a way more understandable than the implementation code.&nbsp; </p>
<p>A test is most valuable when it describes the behavior of the system rather than the implementation. </p>
<p>This is why the number-one-most-important rule of TDD is No Implementation Semantics.</p>
<hr />
<p>Almost every time I’ve found myself struggling to deliver value with TDD it’s because I’ve failed to follow these two, coequal, number-one-most-important rules: <strong>One Logical Assertion Per Test</strong> and <strong>No Implementation Semantics</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/285/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/285/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/285/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=285&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2010/12/02/easy-ways-to-maximize-the-value-of-tdd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Focusing on the controller's responsibility</title>
		<link>http://mhinze.com/2010/04/20/focusing-on-the-controllers-responsibility/</link>
		<comments>http://mhinze.com/2010/04/20/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 &#8230; <a href="http://mhinze.com/2010/04/20/focusing-on-the-controllers-responsibility/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=166&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/166/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/166/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/166/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=166&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2010/04/20/focusing-on-the-controllers-responsibility/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>JSON Hijacking in ASP.NET MVC 2</title>
		<link>http://mhinze.com/2010/04/13/json-hijacking-in-asp-net-mvc-2/</link>
		<comments>http://mhinze.com/2010/04/13/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 &#8230; <a href="http://mhinze.com/2010/04/13/json-hijacking-in-asp-net-mvc-2/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=165&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/165/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/165/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/165/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=165&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2010/04/13/json-hijacking-in-asp-net-mvc-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Serializing models for RouteValueDictionary and later model binding</title>
		<link>http://mhinze.com/2010/03/17/serializing-models-for-routevaluedictionary-and-later-model-binding/</link>
		<comments>http://mhinze.com/2010/03/17/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 &#8230; <a href="http://mhinze.com/2010/03/17/serializing-models-for-routevaluedictionary-and-later-model-binding/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=162&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/162/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=162&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2010/03/17/serializing-models-for-routevaluedictionary-and-later-model-binding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>Aggregated specifications</title>
		<link>http://mhinze.com/2009/10/08/aggregated-specifications/</link>
		<comments>http://mhinze.com/2009/10/08/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 &#8230; <a href="http://mhinze.com/2009/10/08/aggregated-specifications/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=150&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/150/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=150&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2009/10/08/aggregated-specifications/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
		<item>
		<title>AutoMapper in NerdDinner</title>
		<link>http://mhinze.com/2009/07/06/automapper-in-nerddinner/</link>
		<comments>http://mhinze.com/2009/07/06/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 &#8230; <a href="http://mhinze.com/2009/07/06/automapper-in-nerddinner/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=134&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></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="display:inline;border-width:0;margin:0 0 15px 20px;" 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="display:inline;border-width:0;" 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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/134/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=134&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2009/07/06/automapper-in-nerddinner/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>

		<media:content url="http://mhinze.com/wp-content/uploads/2009/07/logo_thumb.png" medium="image">
			<media:title type="html">logo</media:title>
		</media:content>

		<media:content url="http://mhinze.com/wp-content/uploads/2009/07/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>More On Value Objects</title>
		<link>http://mhinze.com/2009/02/19/more-on-value-objects/</link>
		<comments>http://mhinze.com/2009/02/19/more-on-value-objects/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 23:57:52 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[ddd]]></category>
		<category><![CDATA[value objects]]></category>

		<guid isPermaLink="false">http://mhinze.com/more-on-value-objects/</guid>
		<description><![CDATA[A few days ago Dylan Beattie wrote a nice post about value objects.&#160; He explains the idea in a more palatable way than my attempt: If it’s not clear how to model a particular element in your model, try asking &#8230; <a href="http://mhinze.com/2009/02/19/more-on-value-objects/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=114&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A few days ago Dylan Beattie wrote a nice <a href="http://dylanbeattie.blogspot.com/2009/02/is-crisp-value-object.html">post about value objects</a>.&nbsp; He explains the idea in a more <em>palatable</em> way than <a href="http://mhinze.com/there-is-never-a-collection-of-value-objects/">my attempt</a>:</p>
<blockquote><p>If it’s not clear how to model a particular element in your model, try asking “which one?” If the question makes sense within your own scenario then you’re probably dealing with entities. If the question “which one” is meaningless <strong>in the context of your domain </strong>then you’re probably better off modeling the subject of the question as a value object.</p>
</blockquote>
<p> I suggest that if you&#8217;re <em>maintaining</em> a collection, you implicitly care <em>which one</em>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mhinze.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mhinze.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mhinze.wordpress.com/114/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mhinze.com&amp;blog=678824&amp;post=114&amp;subd=mhinze&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mhinze.com/2009/02/19/more-on-value-objects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/0d6043840ea98542a9c9331c7e7940b1?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">mhinze</media:title>
		</media:content>
	</item>
	</channel>
</rss>

