<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>IExtendable</title>
	<atom:link href="http://crmckenzie.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://crmckenzie.wordpress.com</link>
	<description>Continuous Improvement with Chris McKenzie</description>
	<lastBuildDate>Mon, 19 Sep 2011 15:43:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='crmckenzie.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>IExtendable</title>
		<link>http://crmckenzie.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://crmckenzie.wordpress.com/osd.xml" title="IExtendable" />
	<atom:link rel='hub' href='http://crmckenzie.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Blog.ChangeUrl(&#8220;IExtendible.com&#8221;);</title>
		<link>http://crmckenzie.wordpress.com/2011/09/19/blog-changeurliextendible-com/</link>
		<comments>http://crmckenzie.wordpress.com/2011/09/19/blog-changeurliextendible-com/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 15:42:36 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://crmckenzie.wordpress.com/?p=139</guid>
		<description><![CDATA[This blog has moved! If you are one of the 3 people following this blog please update your RSS reader to point to IExtendible.com. Thanks!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=139&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This blog has moved! If you are one of the 3 people following this blog please update your RSS reader to point to <a href="http://iextendible.com/" target="_blank">IExtendible.com</a>.</p>
<p>Thanks!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/139/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/139/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/139/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=139&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2011/09/19/blog-changeurliextendible-com/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>WPF/Silverlight View-ViewModel Binding Patterns</title>
		<link>http://crmckenzie.wordpress.com/2011/08/01/wpfsilverlight-view-viewmodel-binding-patterns/</link>
		<comments>http://crmckenzie.wordpress.com/2011/08/01/wpfsilverlight-view-viewmodel-binding-patterns/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 19:39:09 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2011/08/01/wpfsilverlight-view-viewmodel-binding-patterns/</guid>
		<description><![CDATA[I’m trying to catalog View-ViewModel Binding Patterns so that I can compare their strengths and weaknesses. So far I can think of 2 basic ones. The names I gave them are made up. What are the others? Name: View-Instantiation. Description: The View directly instantiates the ViewModel and assigns it to the data context. Sample: &#60;Window.DataContext&#62; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=137&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’m trying to catalog View-ViewModel Binding Patterns so that I can compare their strengths and weaknesses. So far I can think of 2 basic ones. The names I gave them are made up. What are the others?</p>
<p><strong>Name:</strong> View-Instantiation.</p>
<p><strong>Description: </strong>The View directly instantiates the ViewModel and assigns it to the data context.</p>
<p><strong>Sample:</strong> </p>
<p><code>&lt;</code><code>Window.DataContext</code><code>&gt;</code></p>
<blockquote><p><code></code><code>&lt;</code><code>ViewModels:MyViewModel</code><code>/&gt;</code></p>
</blockquote>
<p><code></code><code>&lt;/</code><code>Window.DataContext</code><code>&gt;</code></p>
<p><strong>Pros: </strong>Easy to set up and get going. Easy to add design-time data.</p>
<p><strong>Cons: </strong>Requires default constructor on ViewModel. This makes Dependency Injection scenarios difficult.</p>
<p>&#160;</p>
<p><strong>Name:</strong> View Templates</p>
<p><strong>Description: </strong>The View is chosen by a data template associated with the ViewModel type.</p>
<p><strong>Pros: </strong>ViewModels fit easily into Dependency Injection scenarios.</p>
<p><strong>Cons: </strong>Design-time data is more difficult to accommodate. Tooling cannot tell the type of the ViewModel associated to the View during View development.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/137/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=137&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2011/08/01/wpfsilverlight-view-viewmodel-binding-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>Installing all NuGet Packages in the Solution</title>
		<link>http://crmckenzie.wordpress.com/2011/07/05/installing-all-nuget-packages-in-the-solution/</link>
		<comments>http://crmckenzie.wordpress.com/2011/07/05/installing-all-nuget-packages-in-the-solution/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 19:40:59 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Practices]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2011/07/05/installing-all-nuget-packages-in-the-solution/</guid>
		<description><![CDATA[The benefits of using NuGet to manage your project dependencies should be well-known by now. If not, read this. There’s one area where NuGet is still somewhat deficient: Team Workflow. Ideally, when you begin work on a new solution, you should follow these steps: 1) Get the latest version of the source code. 2) Run [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=134&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The benefits of using NuGet to manage your project dependencies should be well-known by now.</p>
<p>If not, read <a href="http://nuget.codeplex.com/wikipage?title=Getting%20Started">this</a>.</p>
<p>There’s one area where NuGet is still somewhat deficient: Team Workflow.</p>
<p>Ideally, when you begin work on a new solution, you should follow these steps:</p>
<p>1) Get the latest version of the source code.</p>
<p>2) Run a command to install any dependent packages.</p>
<p>3) Build!</p>
<p>It’s step 2 in this process that is causing some trouble. NuGet does offer a command to install packages for a single project, but the developer is required to run this command for each project that has package references. It would be nice if NuGet would install all packages for all projects using packages/repositories.config, but at the time of this writing it will not. However, it is fairly easy to add a powershell function to the NuGet package manager console that will do this for you.</p>
<p>First, you should download the NuGet executable and add its directory to your PATH Environment variable. I placed mine in C:\devutils\NuGet\&lt;version&gt;\. You’ll need to be able to access the executable from the command-line.</p>
<p>Second, you need to identify the expected location of the NuGet Powershell profile. You can do this be launching Visual Studio, opening the Package Manager Console, type $profile, then press enter. The console will show you the expected profile path. In Windows 7 it will probably be: “C:\Users\&lt;user&gt;\Documents\WindowsPowerShell\NuGet_profile.ps1”</p>
<p>Next you need to create a file with that name in that directory.</p>
<p>Next, paste the following powershell code into the file:</p>
<p>function Install-NuGetPackagesForSolution()   <br />{    <br />&#160;&#160;&#160; write-host &quot;Installing packages for the following projects:&quot;    <br />&#160;&#160;&#160; $projects = get-project -all    <br />&#160;&#160;&#160; $projects    <br />&#160;&#160;&#160; <br />&#160;&#160;&#160; foreach($project in $projects)    <br />&#160;&#160;&#160; {    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; Install-NuGetPackagesForProject($project)    <br />&#160;&#160;&#160; }</p>
<p>}</p>
<p>function Install-NuGetPackagesForProject($project)   <br />{    <br />&#160;&#160;&#160; if ($project -eq $null)    <br />&#160;&#160;&#160; {    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; write-host &quot;Project is required.&quot;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; return    <br />&#160;&#160;&#160; }</p>
<p>&#160;&#160;&#160; $projectName = $project.ProjectName;   <br />&#160;&#160;&#160; write-host &quot;Checking packages for project $projectName&quot;    <br />&#160;&#160;&#160; write-host &quot;&quot;    <br />&#160;&#160;&#160; <br />&#160;&#160;&#160; $projectPath = $project.FullName    <br />&#160;&#160;&#160; $projectPath    <br />&#160;&#160;&#160; <br />&#160;&#160;&#160; $dir = [System.IO.Path]::GetDirectoryName($projectPath)    <br />&#160;&#160;&#160; $packagesConfigFileName = [System.IO.Path]::Combine($dir, &quot;packages.config&quot;)    <br />&#160;&#160;&#160; $hasPackagesConfig = [System.IO.File]::Exists($packagesConfigFileName)    <br />&#160;&#160;&#160; <br />&#160;&#160;&#160; if ($hasPackagesConfig -eq $true)    <br />&#160;&#160;&#160; {    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; write-host &quot;Installing packages for $projectName using $packagesConfigFileName.&quot;    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; nuget i $packagesConfigFileName -o ./packages    <br />&#160;&#160;&#160; }</p>
<p>}   </p>
<p>Restart Visual Studio 2010. After the package manager console loads, you should be able to run the Install-NuGetPackagesForSolution command. The command will iterate over each of your projects, check to see if the project contains a packages.config file, and if so run NuGet install against the packages.config.</p>
<p>You may also wish to do this from the PowerShell console outside of visual studio. If you are in the solution root directoy you can run the following two commands:</p>
<p>$files = gci -Filter packages.config -Recurse   <br />$files | ForEach-Object {nuget i $_.FullName -o .\packages} </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/134/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/134/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/134/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=134&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2011/07/05/installing-all-nuget-packages-in-the-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>Smart Enumerations, or Using Flyweight to Beat Enums Into Submission</title>
		<link>http://crmckenzie.wordpress.com/2011/04/19/smart-enumerations-or-using-flyweight-to-beat-enums-into-submission/</link>
		<comments>http://crmckenzie.wordpress.com/2011/04/19/smart-enumerations-or-using-flyweight-to-beat-enums-into-submission/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 01:48:04 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/?p=127</guid>
		<description><![CDATA[System.Enum is a powerful type to use in the .NET Framework. It’s best used when the list of possible states are known and are defined by the system that uses them. Enumerations are not good in any situation that requires third party extensibility. While I love enumerations, they do present some problems. First, the code [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=127&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/system.enum.aspx">System.Enum</a> is a powerful type to use in the .NET Framework. It’s best used when the list of possible states are known and are defined by the system that uses them. Enumerations are not good in any situation that requires third party extensibility. While I love enumerations, they do present some problems. </p>
<p>First, the code that uses them often exists in the form of switch statements that get repeated about the code base. This violation of <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> is not good. </p>
<p>Second, if a new value is added to the enumeration, any code that relies on the enumeration must take the new value into account. While not technically a violation of the <a href="http://www.objectmentor.com/resources/articles/lsp.pdf">LSP</a>, it’s close.</p>
<p>Thrid, Enums are limited in what they can express. They are basically a set of named integer constants treated as a separate type. Any other data or functionality you might wish them to have has to be added on through other objects. A common requirement is to present a human-readable version of the enum field to the user, which is most often accomplished through the use of the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute.aspx">Description Attribute</a>. A further problem is the fact that they are often serialized as integers, which means that the textual representation has to be reproduced in whatever database, reporting tool, or other system that consumes the serialized value.</p>
<p>Polymorphism is always an alternative to enumerations. Polymorphism brings a problem of its own—lack of discoverability. It would be nice if we could have the power of a polymorphic type coupled with the discoverability of an enumeration.</p>
<p>Fortunately, we can. It’s a variation on the <a href="http://en.wikipedia.org/wiki/Flyweight_pattern">Flyweight</a> pattern. I don’t think it fits the technical definition of the Flyweight pattern because it has a different purpose. Flyweight is generally employed to minimize memory usage. We’re going to use some of the <em>mechanics</em> of the pattern employed to a different purpose.</p>
<p>Consider a simple domain model with two objects: Task, and TaskState. A Task has a Name, Description, and TaskState. A TaskState has a Name, Value, and boolean method that indicates if a task can move from one state to the other. The available states are Pending, InProgress, Completed, Deferred, and Cancelled.</p>
<p>If we implemented this polymorphically, we’d create an abstract class or interface to represent the TaskState. Then we’d provide the various property and method implementations for each subclass. We would have to search the type system to discover which subclasses are available to represent TaskStates.</p>
<p>Instead, let’s create a sealed TaskState class with a defined list of static TaskState instances and a private constructor. We seal the class because our system controls the available TaskStates. We privatize the constructor because we want clients of this class to be forced to use the pre-defined static instances. Finally, we initialize the static instances in a static constructor on the class. Here’s what the code looks like:</p>
<pre class="code"><span style="color:blue;">public sealed class </span><span style="color:#2b91af;">TaskState
</span>{
    <span style="color:blue;">public static </span><span style="color:#2b91af;">TaskState </span>Pending { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
    <span style="color:blue;">public static </span><span style="color:#2b91af;">TaskState </span>InProgress { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
    <span style="color:blue;">public static </span><span style="color:#2b91af;">TaskState </span>Completed { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>;}
    <span style="color:blue;">public static </span><span style="color:#2b91af;">TaskState </span>Deferred { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
    <span style="color:blue;">public static </span><span style="color:#2b91af;">TaskState </span>Canceled { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }

    <span style="color:blue;">public string </span>Name { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
    <span style="color:blue;">public string </span>Value { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }

    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">TaskState</span>&gt; _transitions = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">TaskState</span>&gt;();

    <span style="color:blue;">private </span><span style="color:#2b91af;">TaskState </span>AddTransition(<span style="color:#2b91af;">TaskState </span>value)
    {
        <span style="color:blue;">this</span>._transitions.Add(value);
        <span style="color:blue;">return this</span>;
    }

    <span style="color:blue;">public bool </span>CanTransitionTo(<span style="color:#2b91af;">TaskState </span>value)
    {
        <span style="color:blue;">return this</span>._transitions.Contains(value);
    }

    <span style="color:blue;">private </span>TaskState()
    {

    }

    <span style="color:blue;">static </span>TaskState()
    {
        BuildStates();
        ConfigureTransitions();
    }

    <span style="color:blue;">private static void </span>ConfigureTransitions()
    {
        Pending.AddTransition(InProgress).AddTransition(Canceled);
        InProgress.AddTransition(Completed).AddTransition(Deferred).AddTransition(Canceled);
        Deferred.AddTransition(InProgress).AddTransition(Canceled);
    }

    <span style="color:blue;">private static void </span>BuildStates()
    {
        Pending = <span style="color:blue;">new </span><span style="color:#2b91af;">TaskState</span>()
                      {
                          Name = <span style="color:#a31515;">&quot;Pending&quot;</span>,
                          Value = <span style="color:#a31515;">&quot;Pending&quot;</span>,
                      };
        InProgress = <span style="color:blue;">new </span><span style="color:#2b91af;">TaskState</span>()
                         {
                             Name = <span style="color:#a31515;">&quot;In Progress&quot;</span>,
                             Value = <span style="color:#a31515;">&quot;InProgress&quot;</span>,
                         };
        Completed = <span style="color:blue;">new </span><span style="color:#2b91af;">TaskState</span>()
                        {
                            Name = <span style="color:#a31515;">&quot;Completed&quot;</span>,
                            Value = <span style="color:#a31515;">&quot;Completed&quot;</span>,
                        };
        Deferred = <span style="color:blue;">new </span><span style="color:#2b91af;">TaskState</span>()
                       {
                           Name = <span style="color:#a31515;">&quot;Deferred&quot;</span>,
                           Value = <span style="color:#a31515;">&quot;Deferred&quot;</span>,
                       };
        Canceled = <span style="color:blue;">new </span><span style="color:#2b91af;">TaskState</span>()
                       {
                           Name = <span style="color:#a31515;">&quot;Canceled&quot;</span>,
                           Value = <span style="color:#a31515;">&quot;Canceled&quot;</span>,
                       };
    }
}</pre>
<p>&#160;</p>
<p>This pattern allows us to <em>consume</em> the class as if it were an enumeration:</p>
<pre class="code">var task = <span style="color:blue;">new </span>Task()
               {
                   State = TaskState.Pending,
               };

<span style="color:blue;">if </span>(task.State.CanTransitionTo(<span style="color:#2b91af;">TaskState</span>.Completed))
{
    <span style="color:green;">// do something
</span>}</pre>
<p>We still have the flexibility of polymorphic instances. I’ve used this pattern several times with great effect in my software. I hope it benefits you as much as it has me.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/127/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/127/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/127/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=127&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2011/04/19/smart-enumerations-or-using-flyweight-to-beat-enums-into-submission/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>Refactoring Q &amp; A: When Should I Refactor?</title>
		<link>http://crmckenzie.wordpress.com/2010/11/07/refactoring-q-a-when-should-i-refactor/</link>
		<comments>http://crmckenzie.wordpress.com/2010/11/07/refactoring-q-a-when-should-i-refactor/#comments</comments>
		<pubDate>Sun, 07 Nov 2010 16:00:53 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Practices]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2010/11/07/refactoring-q-a-when-should-i-refactor/</guid>
		<description><![CDATA[Answer: When you have to spend too long figuring out what the code does. Consider the following partial implementation of a ShoppingCart class. public class ShoppingCart { public ShoppingCart() { this._readOnlyDetails = new ReadOnlyCollection&#60;OrderDetail&#62;(_details); } private readonly List&#60;OrderDetail&#62; _details = new List&#60;OrderDetail&#62;(); private readonly ReadOnlyCollection&#60;OrderDetail&#62; _readOnlyDetails; public ReadOnlyCollection&#60;OrderDetail&#62; Details { get { return _readOnlyDetails; } [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=119&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Answer</strong>: <em>When you have to spend too long figuring out what the code does</em>. </p>
<p>Consider the following partial implementation of a ShoppingCart class.</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">ShoppingCart
</span>{
    <span style="color:blue;">public </span>ShoppingCart()
    {
        <span style="color:blue;">this</span>._readOnlyDetails = <span style="color:blue;">new </span><span style="color:#2b91af;">ReadOnlyCollection</span>&lt;<span style="color:#2b91af;">OrderDetail</span>&gt;(_details);
    }

    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">OrderDetail</span>&gt; _details = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">OrderDetail</span>&gt;();
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ReadOnlyCollection</span>&lt;<span style="color:#2b91af;">OrderDetail</span>&gt; _readOnlyDetails;
    <span style="color:blue;">public </span><span style="color:#2b91af;">ReadOnlyCollection</span>&lt;<span style="color:#2b91af;">OrderDetail</span>&gt; Details
    {
        <span style="color:blue;">get
        </span>{
            <span style="color:blue;">return </span>_readOnlyDetails;
        }
    }</pre>
<p><a href="http://11011.net/software/vspaste"></a>Our ShoppingCart class is simply hiding the internal storage mechanism of Details so that clients of ShoppingCart cannot add or remove products directly. For this reason, ShoppingCart must provide its own methods for modifying the OrderDetails collection. In <a href="http://crmckenzie.wordpress.com/2010/11/07/tdd-talking-point-tdd-is-more-about-api-than-implementation/" target="_blank">this post</a> I implemented this method and applied some heavy refactoring. Don’t read the implementation just yet. </p>
<p>Consider the requirements: When adding a product to the shopping cart, I must provide an OrderDetail that indicates the quantity of that product that has been ordered. Subsequent additions of the same product to the shopping cart should not result in additional order details. Rather, the existing OrderDetail should reflect the sum of all quantities of the product being ordered.</p>
<p>Imagine that you open the source file to see how this is done, but you have all the outlining collapsed so that all you see is method signatures. Imagine that these are the method signatures you see:</p>
<pre class="code"><span style="color:blue;">public void </span>AddProduct(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindOrCreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>CreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindDetailByProductSku(<span style="color:blue;">string </span>productSku)
<span style="color:blue;">private bool </span>HasDetailForProductSku(<span style="color:blue;">string </span>productSku)</pre>
<p>Just read each one of these method signatures. Each method states clearly exactly what it is going to do. Now for each of the method signatures, imagine that you were going to expand the outlining so you can see the method body. What code would you expect to find in each one. Seriously, pause for a moment and think about what you would expect to find in each method body. Got it? Okay, now read the actual implementations of these methods.</p>
<pre class="code"><span style="color:blue;">public void </span>AddProduct(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <span style="color:blue;">var </span>detail = FindOrCreateDetailForProduct(product);
    detail.Quantity += quantity;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindOrCreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = HasDetailForProductSku(product.Sku) ?
        FindDetailByProductSku(product.Sku) :
        CreateDetailForProduct(product);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>CreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
    <span style="color:blue;">this</span>._details.Add(detail);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindDetailByProductSku(<span style="color:blue;">string </span>productSku)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == productSku);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private bool </span>HasDetailForProductSku(<span style="color:blue;">string </span>productSku)
{
    <span style="color:blue;">return this</span>.Details.Any(d =&gt; d.Product.Sku == productSku);
}</pre>
<p>I’m sure that some of the implementations are different than you imagined, but are they different in any substantial way? Probably not. A method called HasDetailForProductSku can have only so many <em>syntactic</em> implementations, all of which are <em>semantically</em> identical. The method names and signatures state what our code is doing in English-language terms that are meaningful to a person. The bodies of these methods provide the <em>syntax</em> that is meaningful to the compiler. Class, method, parameter, and variable names are targeted at <em>people</em>. Their purpose is to express the intent of the code to <em>people</em>. Conditionals, loops, and other statements are the basic forms in which we code, but their target audience is the compiler. To put this in the form of a general principle: “<strong>Refactor when the <em>semantic</em> meaning of the code is hidden or obscured by the <em>syntax </em>required by the compiler</strong>,” or <strong>“Refactor when you have to spend too long figuring out what the code does.”</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/119/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/119/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/119/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=119&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/11/07/refactoring-q-a-when-should-i-refactor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>TDD Talking Point: TDD is more about API than Implementation</title>
		<link>http://crmckenzie.wordpress.com/2010/11/07/tdd-talking-point-tdd-is-more-about-api-than-implementation/</link>
		<comments>http://crmckenzie.wordpress.com/2010/11/07/tdd-talking-point-tdd-is-more-about-api-than-implementation/#comments</comments>
		<pubDate>Sun, 07 Nov 2010 15:23:53 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Practices]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/?p=117</guid>
		<description><![CDATA[One of the points I tried to make in my talk about TDD yesterday is that TDD is more focused on the clarity and expressiveness of your code than on its actual implementation. I wanted to take a little time and expand on what I meant. I used a Shopping Cart as an TDD sample. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=117&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the points I tried to make in my talk about TDD yesterday is that TDD is more focused on the clarity and expressiveness of your code than on its actual implementation. I wanted to take a little time and expand on what I meant.</p>
<p>I used a Shopping Cart as an TDD sample. In the sample, the requirement is that as products are added to the shopping cart, the cart should contain a list or OrderDetails that are distinct by product sku. Here is the test I wrote for this case (this is <a href="https://bitbucket.org/crmckenzie/demo.tdd.shoppingcart/changesets" target="_blank">commit #8</a> if you want to follow along):</p>
<pre class="code">[<span style="color:#2b91af;">Test</span>]
<span style="color:blue;">public void </span>Details_AfterAddingSameProductTwice_ShouldDefragDetails()
{
    <span style="color:green;">// Arrange: Declare any variables or set up any conditions
    //          required by your test.
    </span><span style="color:blue;">var </span>cart = <span style="color:blue;">new </span>Lib.<span style="color:#2b91af;">ShoppingCart</span>();
    <span style="color:blue;">var </span>product = <span style="color:blue;">new </span><span style="color:#2b91af;">Product</span>() { Sku = <span style="color:#a31515;">&quot;ABC&quot;</span>, Description = <span style="color:#a31515;">&quot;Test&quot;</span>, Price = 1.99 };
    <span style="color:blue;">const int </span>firstQuantity = 5;
    <span style="color:blue;">const int </span>secondQuantity = 3;

    <span style="color:green;">// Act:     Perform the activity under test.
    </span>cart.AddToCart(product, firstQuantity);
    cart.AddToCart(product, secondQuantity);

    <span style="color:green;">// Assert:  Verify that the activity under test had the
    //          expected results
    </span><span style="color:#2b91af;">Assert</span>.That(cart.Details.Count, <span style="color:#2b91af;">Is</span>.EqualTo(1));
    <span style="color:blue;">var </span>detail = cart.Details.Single();
    <span style="color:blue;">var </span>expectedQuantity = firstQuantity + secondQuantity;
    <span style="color:#2b91af;">Assert</span>.That(detail.Quantity, <span style="color:#2b91af;">Is</span>.EqualTo(expectedQuantity));
    <span style="color:#2b91af;">Assert</span>.That(detail.Product, <span style="color:#2b91af;">Is</span>.SameAs(product));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The naive implementation of AddToCart is currently as follows:</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <span style="color:blue;">this</span>._details.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>()
                          {
                              Product = product,
                              Quantity = quantity
                          });
}</pre>
<p>&#160;</p>
<p>This implementation of AddToCart fails the test case since it does not account for adding the same product sku twice. In order to get to the “Green” step, I made these changes:</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
<strong>    <span style="color:blue;">if </span>(<span style="color:blue;">this</span>.Details.Any(detail =&gt; detail.Product.Sku == product.Sku))
    {
        <span style="color:blue;">this</span>.Details.First(detail =&gt; detail.Product.Sku == product.Sku).Quantity += quantity;
    }
    </strong><strong><span style="color:blue;">else
    </span>{</strong>
        <span style="color:blue;">this</span>._details.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>()
        {
            Product = product,
            Quantity = quantity
        });
    <strong>}</strong>

}</pre>
<p>At this point, the test passes, but I think the above implementation is kind of ugly. Having the code in this kind of ugly state is still a value though because now I know I have solved the problem correctly. Let’s start by using Extract Condition on the conditional expression.</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <strong><span style="color:blue;">var </span>detail = <span style="color:blue;">this</span>.Details.SingleOrDefault(d =&gt; d.Product.Sku == product.Sku);
    <span style="color:blue;">if </span>(detail != <span style="color:blue;">null</span>)
    {
        detail.Quantity += quantity;
    }</strong>
    <span style="color:blue;">else
    </span>{
        <span style="color:blue;">this</span>._details.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>()
        {
            Product = product,
            Quantity = quantity
        });
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The algorithm being used is becoming clearer.</p>
<ol>
<li>Determine if I have an OrderDetail matching the Product Sku.</li>
<li>If I do, increment the quantity.</li>
<li>If I do not, create a new OrderDetail matching the product sku and set it’s quantity.</li>
</ol>
<p>It’s a pretty simple algorithm. Let’s do a little more refactoring. Let’s apply Extract Method to the lambda expression.</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <strong><span style="color:blue;">var </span>detail = GetProductDetail(product);</strong>
    <span style="color:blue;">if </span>(detail != <span style="color:blue;">null</span>)
    {
        detail.Quantity += quantity;
    }
    <span style="color:blue;">else
    </span>{
        <span style="color:blue;">this</span>._details.Add(<span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>()
        {
            Product = product,
            Quantity = quantity
        });
    }
}

<strong><span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>GetProductDetail(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">return this</span>.Details.SingleOrDefault(d =&gt; d.Product.Sku == product.Sku);
}
</strong></pre>
<p>&#160;</p>
<p>This reads still more clearly. This is also where I stopped in my talk. Note that it has not been necessary to make changes to the my test case because the changes I have made go to the private implementation of the class. I’d like to go a little further now and say that if I change the algorithm I can actually make this code even clearer. What if the algorithm was changed to:</p>
<ol>
<li>Find or Create an OrderDetail matching the product sku.</li>
<li>Update the quantity.</li>
</ol>
<p>In the first algorithm, I am taking different action with the quantity depending on whether or not the detail exists. In the new algorithm, I’m demoting the importance of whether the order detail already exists so that I can always take the same action with respect to the quantity. Here’s the naive implementation:</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <span style="color:#2b91af;">OrderDetail </span>detail;

    <span style="color:blue;">if </span>(<span style="color:blue;">this</span>.Details.Any(d =&gt; d.Product.Sku == product.Sku))
    {
        detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == product.Sku);
    }
    <span style="color:blue;">else
    </span>{
        detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
        <span style="color:blue;">this</span>._details.Add(detail);
    }

    detail.Quantity += quantity;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The naive implementation is a little clearer. Let’s apply some refactoring effort and see what happens.. Let’s apply Extract Method to the entire process of getting the order detail.</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
 <strong>   <span style="color:blue;">var </span>detail = GetDetail(product);</strong>

    detail.Quantity += quantity;
}

<strong><span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>GetDetail(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:#2b91af;">OrderDetail </span>detail;

    <span style="color:blue;">if </span>(<span style="color:blue;">this</span>.Details.Any(d =&gt; d.Product.Sku == product.Sku))
    {
        detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == product.Sku);
    }
    </strong><strong><span style="color:blue;">else
    </span>{
        detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
        <span style="color:blue;">this</span>._details.Add(detail);
    }
    <span style="color:blue;">return </span>detail;
}
</strong></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is starting to take shape. However, “GetDetail” does not really communicate that we may be creating a new detail instead of just returning an existing one. If we rename it to FindOrCreateOrderDetailForProduct, we may get that clarity.</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <span style="color:blue;">var </span>detail = FindOrCreateDetailForProduct(product);

    detail.Quantity += quantity;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindOrCreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:#2b91af;">OrderDetail </span>detail;

    <span style="color:blue;">if </span>(<span style="color:blue;">this</span>.Details.Any(d =&gt; d.Product.Sku == product.Sku))
    {
        detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == product.Sku);
    }
    <span style="color:blue;">else
    </span>{
        detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
        <span style="color:blue;">this</span>._details.Add(detail);
    }
    <span style="color:blue;">return </span>detail;
}</pre>
<p>AddToCart() looks pretty good now. It’s easy to read, and each line communicates the intent of our code clearly. FindOrCreateDetailForProduct() on the other hand is less easy to read. I’m going to apply Extract Conditional to the if statement, and Extract Method to each side of the expression. Here is the result:</p>
<pre class="code"><span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindOrCreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = HasProductDetail(product) ?
        FindDetailForProduct(product) :
        CreateDetailForProduct(product);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>CreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
    <span style="color:blue;">this</span>._details.Add(detail);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == product.Sku);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private bool </span>HasProductDetail(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">return this</span>.Details.Any(d =&gt; d.Product.Sku == product.Sku);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Now I’ve noticed that HasProductDetail and FindDetailForProduct are only using the product sku. I’m going to change the signature of these methods to accept only the sku, and I’ll change the method names accordingly.</p>
<pre class="code"><span style="color:blue;">public void </span>AddToCart(<span style="color:#2b91af;">Product </span>product, <span style="color:blue;">int </span>quantity)
{
    <span style="color:blue;">var </span>detail = FindOrCreateDetailForProduct(product);
    detail.Quantity += quantity;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindOrCreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
<strong>    <span style="color:blue;">var </span>detail = HasDetailForProductSku(product.Sku) ?
        FindDetailByProductSku(product.Sku) :</strong>
        CreateDetailForProduct(product);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>CreateDetailForProduct(<span style="color:#2b91af;">Product </span>product)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">new </span><span style="color:#2b91af;">OrderDetail</span>() { Product = product };
    <span style="color:blue;">this</span>._details.Add(detail);
    <span style="color:blue;">return </span>detail;
}

<strong><span style="color:blue;">private </span><span style="color:#2b91af;">OrderDetail </span>FindDetailByProductSku(<span style="color:blue;">string </span>productSku)
{
    <span style="color:blue;">var </span>detail = <span style="color:blue;">this</span>.Details.Single(d =&gt; d.Product.Sku == productSku);
    <span style="color:blue;">return </span>detail;
}

<span style="color:blue;">private bool </span>HasDetailForProductSku(<span style="color:blue;">string </span>productSku)
{
    <span style="color:blue;">return this</span>.Details.Any(d =&gt; d.Product.Sku == productSku);
}</strong></pre>
<p>At this point, the AddToCart() method has gone through some pretty extensive refactoring. The basic algorithm has been changed, and the implementation of the new algorithm has been changed a lot. Now let me point something out: <strong>At no time during any of these changes did our test fail, and at no time during these changes did our test fail to express the intended behavior of the class. </strong>We made changes to every aspect of the <em>implementation</em>: We changed the order of the steps in the algorithm. We constantly added and renamed methods until we had very discrete well-named functions that stated explicitly what the code is doing. The unit test remained a valid expression of intended behavior despite all of these changes. <em>This</em> is what it means to say that a test is more about API than implementation. The unit-test should not depend on the implementation, nor does it necessarily imply a particular implementation.</p>
<p>Happy Coding!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=117&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/11/07/tdd-talking-point-tdd-is-more-about-api-than-implementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>TDD Presentation Resources</title>
		<link>http://crmckenzie.wordpress.com/2010/11/05/tdd-presentation-resources/</link>
		<comments>http://crmckenzie.wordpress.com/2010/11/05/tdd-presentation-resources/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 23:12:25 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Practices]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2010/11/05/tdd-presentation-resources/</guid>
		<description><![CDATA[Tomorrow I will be giving a talk on TDD at CMAP. The demo code and outline I will be using can be found on bitbucket here. Here is the outline for the talk: I. Tools A. Framework B. Test Runner C. Brains II. Test Architecture A. Test Fixture B. Setup C. Test Method D. TearDown [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=114&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Tomorrow I will be giving a talk on TDD at <a href="http://www.cmap-online.org/CodeCamp/Sessions.aspx">CMAP.</a> The demo code and outline I will be using can be found on <a href="https://bitbucket.org/crmckenzie/demo.tdd.shoppingcart">bitbucket here</a>.</p>
<p>Here is the outline for the talk:</p>
<ul>
<li>I. Tools</li>
<ul>
<li>A. Framework</li>
<li>B. Test Runner</li>
<li>C. Brains</li>
</ul>
<li>II. Test Architecture</li>
<ul>
<li>A. Test Fixture</li>
<li>B. Setup</li>
<li>C. Test Method</li>
<li>D. TearDown</li>
</ul>
<li>III. Process</li>
<ul>
<li>A. Red</li>
<li>B. Green.</li>
<li>C. Refactor.</li>
<li>D. Rinse and Repeat.</li>
</ul>
<li>IV. Conventions</li>
<ul>
<li>A. At least one testfixture per class.</li>
<li>B. At least one test method per public method.</li>
<li>C. Test Method naming conventions</li>
<ul>
<li>i. MethodUnderTest_ConditionUnderTest_ExpectedResult</li>
</ul>
<li>D. Test Method section conventions</li>
<ul>
<li>i. Arrange</li>
<li>ii. Act</li>
<li>iii. Assert</li>
</ul>
</ul>
<li>V. Other Issues</li>
<ul>
<li>A. <a href="http://www.springerlink.com/content/q91566748q234325/">Productivity Study</a></li>
<li>B. Testing the UI</li>
<ul>
<li>i. Not technically possible without more tooling/infrastructure</li>
<li>ii. MVC patterns increate unit-test coverage.</li>
<li>iii. Legacy code.</li>
<ul>
<li>a. Presents special problems.</li>
<li>b. Touching untested legacy code is dangerous.</li>
<li>c. Boy-Scout rule.</li>
<li>d. Use your own judgment</li>
</ul>
</ul>
<li>C. Pros and Cons</li>
<ul>
<li>i. Pros</li>
<ul>
<li>a. Quality.</li>
<li>b. Encourage a more loosely-coupled design.</li>
<li>c. Document the work that is done.</li>
<li>d. Regression testing.</li>
<li>e. Increased confidence in working code means changes are easier to make.</li>
<li>f. Encourages devs to think about code in terms of API instead of implementation.</li>
<ul>
<li>1. Makes code more readable.</li>
<li>2. Readable code communicates intent more clearly.</li>
<li>3. Readable code reduces the need for additional non-code documentation.</li>
</ul>
</ul>
<li>ii. Cons</li>
<ul>
<li>a. Takes longer to develop.</li>
<li>b. Test code must be maintained as well.</li>
<li>c. Requires that devs adapt to new ways of thinking about code.</li>
</ul>
</ul>
<li>D. Notes</li>
<ul>
<li>i. You&#8217;re already doing it.</li>
<li>ii. &quot;<a href="http://www.amazon.com/Art-Unit-Testing-Examples-Net/dp/1933988274/ref=sr_1_1?ie=UTF8&amp;qid=1288998608&amp;sr=8-1">The Art of Unit Testing</a>&quot; by Roy Osherove</li>
<li>iii. &quot;<a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1288998662&amp;sr=1-1">Clean Code</a>&quot; by Robert C. Martin</li>
<li>iv. &quot;<a href="http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1288998683&amp;sr=1-1">Head First Design Patterns</a>” by Elizabeth and Eric Freeman, Bert Bates, and Kathy Sierra</li>
</ul>
</ul>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/114/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=114&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/11/05/tdd-presentation-resources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing EF4 Change Interceptors</title>
		<link>http://crmckenzie.wordpress.com/2010/10/20/implementing-ef4-change-interceptors/</link>
		<comments>http://crmckenzie.wordpress.com/2010/10/20/implementing-ef4-change-interceptors/#comments</comments>
		<pubDate>Thu, 21 Oct 2010 01:14:20 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Data]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2010/10/20/implementing-ef4-change-interceptors/</guid>
		<description><![CDATA[Interceptors are a great way to handle some repetitive and predictable data management tasks. NHibernate has good support for Interceptors both at the change and query levels. I wondered how hard it would be to write interceptors for the new EF4 CTP and was surprised at how easy it actually was… well, for the change [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=112&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Interceptors are a great way to handle some repetitive and predictable data management tasks. <a href="http://community.jboss.org/wiki/NHibernateforNET">NHibernate</a> has good support for Interceptors both at the change and query levels. I wondered how hard it would be to write interceptors for the new EF4 CTP and was surprised at how easy it actually was… well, for the change interceptors anyway. It looks like query interceptors would require a complete reimplementation of the Linq provider—not something I feel like undertaking right now.</p>
<p>On to the Code!</p>
<p>This is the first interface we’ll use to create a class that can respond to changes in the EF4 data context.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:d3e6a191-b182-42c5-98bd-0485680dfa95" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">namespace</span> Yodelay.Data.Entity</li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#808080;">///</span><span style="color:#008000;"> </span><span style="color:#808080;">&lt;summary&gt;</span></li>
<li style="background:#f3f3f3;">    <span style="color:#808080;">///</span><span style="color:#008000;"> Interface to support taking some action in response</span></li>
<li>    <span style="color:#808080;">///</span><span style="color:#008000;"> to some activity taking place on an ObjectStateEntry item.</span></li>
<li style="background:#f3f3f3;">    <span style="color:#808080;">///</span><span style="color:#008000;"> </span><span style="color:#808080;">&lt;/summary&gt;</span></li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> <span style="color:#2b91af;">IInterceptor</span></li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">void</span> Before(<span style="color:#2b91af;">ObjectStateEntry</span> item);</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">void</span> After(<span style="color:#2b91af;">ObjectStateEntry</span> item);</li>
<li>    }</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>We’ll also use this interface to add some conditional execution support.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:4ba26b8c-a86a-4333-b637-b7b2ddc208a3" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">namespace</span> Yodelay.Data.Entity</li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#808080;">///</span><span style="color:#008000;"> </span><span style="color:#808080;">&lt;summary&gt;</span></li>
<li style="background:#f3f3f3;">    <span style="color:#808080;">///</span><span style="color:#008000;"> Adds conditional execution to an IInterceptor.</span></li>
<li>    <span style="color:#808080;">///</span><span style="color:#008000;"> </span><span style="color:#808080;">&lt;/summary&gt;</span></li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> <span style="color:#2b91af;">IConditionalInterceptor</span> : <span style="color:#2b91af;">IInterceptor</span></li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">bool</span> IsTargetEntity(<span style="color:#2b91af;">ObjectStateEntry</span> item);        </li>
<li>    }</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>The first interceptor I want to write is one that manages four audit columns automatically. First I need an interface that provides the audit columns:</p>
<p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:2b6962c3-c3fa-4939-b83e-cf2cfb943f7a" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> <span style="color:#2b91af;">IAuditEntity</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#2b91af;">DateTime</span> InsertDateTime { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">    <span style="color:#2b91af;">DateTime</span> UpdateDateTime { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li>    <span style="color:#0000ff;">string</span> InsertUser { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">string</span> UpdateUser { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
</p>
<p>The EF4 DbContext class provides an override for SaveChanges() that I can use to start handling the events. I decided to subclass DbContext and add the interception capability to the new class. I snipped the constructors for brevity, but all of the constructors from the base class are bubbled.</p>
<p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:2463ad58-b024-4f19-83cd-10ff070705e0" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">DataContext</span> : <span style="color:#2b91af;">DbContext</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">readonly</span> <span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">IInterceptor</span>&gt; _interceptors = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">IInterceptor</span>&gt;();</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">IInterceptor</span>&gt; Interceptors</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">this</span>._interceptors; }</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> InterceptBefore(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">this</span>.Interceptors.ForEach(intercept =&gt; intercept.Before(item));</li>
<li style="background:#f3f3f3;">    }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> InterceptAfter(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">this</span>.Interceptors.ForEach(intercept =&gt; intercept.After(item));</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">int</span> SaveChanges()</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">const</span> <span style="color:#2b91af;">EntityState</span> entitiesToTrack = <span style="color:#2b91af;">EntityState</span>.Added | </li>
<li style="background:#f3f3f3;">                                            <span style="color:#2b91af;">EntityState</span>.Modified |</li>
<li>                                            <span style="color:#2b91af;">EntityState</span>.Deleted;</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">var</span> elementsToSave =</li>
<li>            <span style="color:#0000ff;">this</span>.ObjectContext</li>
<li style="background:#f3f3f3;">                .ObjectStateManager</li>
<li>                .GetObjectStateEntries(entitiesToTrack)</li>
<li style="background:#f3f3f3;">                .ToList();</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">        elementsToSave.ForEach(InterceptBefore);</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">var</span> result = <span style="color:#0000ff;">base</span>.SaveChanges();</li>
<li>        elementsToSave.ForEach(InterceptAfter);</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">return</span> result;</li>
<li>    }</li>
</ol></div>
</p></div>
</p></div>
</p>
<p>&#160;</p>
<p>I only want the AuditChangeInterceptor to fire if the object implements the IAuditEntity interface. I <em>could</em> have directly implemented IConditionalInterceptor, but I decided to extract the object-type criteria into a super-class. </p>
<p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:de92da7c-67c3-4ea1-9648-cdd63800e511" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">abstract</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">TypeInterceptor</span> : <span style="color:#2b91af;">IConditionalInterceptor</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">readonly</span> System.<span style="color:#2b91af;">Type</span> _targetType;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">Type</span> TargetType { <span style="color:#0000ff;">get</span> { <span style="color:#0000ff;">return</span> _targetType; }}</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">protected</span> TypeInterceptor(System.<span style="color:#2b91af;">Type</span> targetType)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">this</span>._targetType = targetType;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">bool</span> IsTargetEntity(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">return</span> item.State != <span style="color:#2b91af;">EntityState</span>.Detached &amp;&amp; </li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">this</span>.TargetType.IsInstanceOfType(item.Entity);</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> Before(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.IsTargetEntity(item))</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">this</span>.OnBefore(item);</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">abstract</span> <span style="color:#0000ff;">void</span> OnBefore(<span style="color:#2b91af;">ObjectStateEntry</span> item);</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">void</span> After(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.IsTargetEntity(item))</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">this</span>.OnAfter(item);</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">abstract</span> <span style="color:#0000ff;">void</span> OnAfter(<span style="color:#2b91af;">ObjectStateEntry</span> item);</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
</p>
<p>&#160;</p>
<p>I also decided that the super-class should provide obvious method-overrides for BeforeInsert, AfterInsert, BeforeUpdate, etc.. For that I created a generic class that sub-classes TypeInterceptor and provides friendlier methods to work with.</p>
</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9fea66b7-e5e5-4752-a6fa-99c29fdf0c9b" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">ChangeInterceptor</span>&lt;T&gt; : <span style="color:#2b91af;">TypeInterceptor</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">#region</span> Overrides of Interceptor</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnBefore(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        T tItem = (T) item.Entity;</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">switch</span>(item.State)</li>
<li>        {</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Added:</li>
<li>                <span style="color:#0000ff;">this</span>.OnBeforeInsert(item.ObjectStateManager, tItem);</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">break</span>;</li>
<li>            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Deleted:</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">this</span>.OnBeforeDelete(item.ObjectStateManager, tItem);</li>
<li>                <span style="color:#0000ff;">break</span>;</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Modified:</li>
<li>                <span style="color:#0000ff;">this</span>.OnBeforeUpdate(item.ObjectStateManager, tItem);</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">break</span>;</li>
<li>        }</li>
<li style="background:#f3f3f3;">    }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span>  OnAfter(<span style="color:#2b91af;">ObjectStateEntry</span> item)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        T tItem = (T)item.Entity;</li>
<li>        <span style="color:#0000ff;">switch</span> (item.State)</li>
<li style="background:#f3f3f3;">        {</li>
<li>            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Added:</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">this</span>.OnAfterInsert(item.ObjectStateManager, tItem);</li>
<li>                <span style="color:#0000ff;">break</span>;</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Deleted:</li>
<li>                <span style="color:#0000ff;">this</span>.OnAfterDelete(item.ObjectStateManager, tItem);</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">break</span>;</li>
<li>            <span style="color:#0000ff;">case</span> <span style="color:#2b91af;">EntityState</span>.Modified:</li>
<li style="background:#f3f3f3;">                <span style="color:#0000ff;">this</span>.OnAfterUpdate(item.ObjectStateManager, tItem);</li>
<li>                <span style="color:#0000ff;">break</span>;</li>
<li style="background:#f3f3f3;">        }        </li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">#endregion</span></li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnBeforeInsert(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">return</span>;</li>
<li style="background:#f3f3f3;">    }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnAfterInsert(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">return</span>;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnBeforeUpdate(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">return</span>;</li>
<li style="background:#f3f3f3;">    }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnAfterUpdate(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">return</span>;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnBeforeDelete(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">return</span>;</li>
<li style="background:#f3f3f3;">    }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">virtual</span> <span style="color:#0000ff;">void</span> OnAfterDelete(<span style="color:#2b91af;">ObjectStateManager</span> manager, T item)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">return</span>;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> ChangeInterceptor() : <span style="color:#0000ff;">base</span>(<span style="color:#0000ff;">typeof</span>(T))</li>
<li style="background:#f3f3f3;">    {</li>
<li>        </li>
<li style="background:#f3f3f3;">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>Finally, I created subclassed ChangeInterceptor&lt;IAuditEntity&gt;.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:151a9676-0934-45f6-b29e-7a9ca3439777" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">AuditChangeInterceptor</span> : <span style="color:#2b91af;">ChangeInterceptor</span>&lt;<span style="color:#2b91af;">IAuditEntity</span>&gt;</li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnBeforeInsert(<span style="color:#2b91af;">ObjectStateManager</span> manager, <span style="color:#2b91af;">IAuditEntity</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">base</span>.OnBeforeInsert(manager, item);</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>        item.InsertDateTime = <span style="color:#2b91af;">DateTime</span>.Now;</li>
<li style="background:#f3f3f3;">        item.InsertUser = System.Threading.<span style="color:#2b91af;">Thread</span>.CurrentPrincipal.Identity.Name;</li>
<li>        item.UpdateDateTime = <span style="color:#2b91af;">DateTime</span>.Now;</li>
<li style="background:#f3f3f3;">        item.UpdateUser = System.Threading.<span style="color:#2b91af;">Thread</span>.CurrentPrincipal.Identity.Name;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnBeforeUpdate(<span style="color:#2b91af;">ObjectStateManager</span> manager, <span style="color:#2b91af;">IAuditEntity</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">base</span>.OnBeforeUpdate(manager, item);</li>
<li style="background:#f3f3f3;">        item.UpdateDateTime = <span style="color:#2b91af;">DateTime</span>.Now;</li>
<li>        item.UpdateUser = System.Threading.<span style="color:#2b91af;">Thread</span>.CurrentPrincipal.Identity.Name;</li>
<li style="background:#f3f3f3;">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>I plugged this into my app, and it worked on the first go.</p>
<p>Another common scenario I encounter is “soft-deletes.” A “soft-delete” is a virtual record deletion that does not actual remove the record from the database. Instead it sets an IsDeleted flag on the record, and the record is then excluded from other queries. The problem with soft-deletes is that developers and report writers always have to remember to add the “IsDeleted == false” criteria to every query in the system that touches the affected records. It would be great to replace the standard delete functionality with a soft-delete, and to modify the IQueryable to return only records for which “IsDeleted == false.” Unfortunately, I was unable to find a clean way to add query-interceptors to the data model to keep deleted records from being returned. However, I was able to get the basic soft-delete ChangeInterceptor to work. Here is that code.</p>
<p>&#160;</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a6a65c9d-40a6-404e-ad70-7869afd5e6e0" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> <span style="color:#2b91af;">ISoftDelete</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">bool</span> IsDeleted { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:aca1c08a-b120-4cb4-8c02-ed7da9d5e4f3" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">SoftDeleteChangeInterceptor</span> : <span style="color:#2b91af;">ChangeInterceptor</span>&lt;<span style="color:#2b91af;">ISoftDelete</span>&gt;</li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnBeforeInsert(<span style="color:#2b91af;">ObjectStateManager</span> manager, <span style="color:#2b91af;">ISoftDelete</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">base</span>.OnBeforeInsert(manager, item);</li>
<li style="background:#f3f3f3;">        item.IsDeleted = <span style="color:#0000ff;">false</span>;</li>
<li>    }</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnBeforeDelete(<span style="color:#2b91af;">ObjectStateManager</span> manager, <span style="color:#2b91af;">ISoftDelete</span> item)</li>
<li style="background:#f3f3f3;">    {</li>
<li>        <span style="color:#0000ff;">if</span> (item.IsDeleted)</li>
<li style="background:#f3f3f3;">            <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">InvalidOperationException</span>(<span style="color:#a31515;">&quot;Item is already deleted.&quot;</span>);</li>
<li>        </li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">base</span>.OnBeforeDelete(manager, item);</li>
<li>        item.IsDeleted = <span style="color:#0000ff;">true</span>;</li>
<li style="background:#f3f3f3;">        manager.ChangeObjectState(item, <span style="color:#2b91af;">EntityState</span>.Modified);</li>
<li>    }</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>Here’s the complete diagram of the code:</p>
<p><a href="http://crmckenzie.files.wordpress.com/2010/10/image.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="image" border="0" alt="image" src="http://crmckenzie.files.wordpress.com/2010/10/image_thumb.png?w=912&#038;h=337" width="912" height="337" /></a> </p>
<p>EF4 has come a long way with respect to supporting extensibility. It still needs query-interceptors to be feature-parable with other ORM tools such as NHibernate, but I suspect that it is just a matter of time before the MS developers get around to adding that functionality. For now, you can use the interceptor model I’ve demo’ed here to add functionality to your data models. Perhaps you could use them to add logging, validation, or security checks to your models. What can you come up with?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/112/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=112&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/10/20/implementing-ef4-change-interceptors/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>

		<media:content url="http://crmckenzie.files.wordpress.com/2010/10/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>CMAP Presentation</title>
		<link>http://crmckenzie.wordpress.com/2010/10/20/cmap-presentation/</link>
		<comments>http://crmckenzie.wordpress.com/2010/10/20/cmap-presentation/#comments</comments>
		<pubDate>Wed, 20 Oct 2010 12:28:45 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Practices]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://crmckenzie.wordpress.com/?p=108</guid>
		<description><![CDATA[My &#8220;Introduction to Test Driven Development&#8221; talk was accepted for the Fall 2010 CMAP! From the talk description: This talk will demonstrate the basics of writing unit-tests, as well as how Test Driven Development solves many common software development problems. We will cover some of the research that has been done on the effectiveness of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=108&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="color:#888888;">My &#8220;Introduction to Test Driven Development&#8221; talk was accepted for the <a href="http://www.cmap-online.org/CodeCamp/Sessions.aspx">Fall 2010 CMAP</a>! From the talk description:</span></p>
<blockquote><p><span style="color:#888888;">This talk will demonstrate the basics of writing unit-tests, as well as how Test Driven Development solves many common software development problems. We will cover some of the research that has been done on the effectiveness of TDD. We will also deal some of the more common questions and concerns surrounding TDD such as productivity, testing the UI, and testing legacy code.</span></p></blockquote>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=108&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/10/20/cmap-presentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>
	</item>
		<item>
		<title>Understanding the Fluent Configuration API for One-To-Many Relationships in &#8220;Code-First&#8221; EF4</title>
		<link>http://crmckenzie.wordpress.com/2010/10/17/understanding-the-fluent-configuration-api-for-one-to-many-relationships-in-code-first-ef4/</link>
		<comments>http://crmckenzie.wordpress.com/2010/10/17/understanding-the-fluent-configuration-api-for-one-to-many-relationships-in-code-first-ef4/#comments</comments>
		<pubDate>Sun, 17 Oct 2010 15:10:38 +0000</pubDate>
		<dc:creator>Chris McKenzie</dc:creator>
				<category><![CDATA[Data]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">https://crmckenzie.wordpress.com/2010/10/17/understanding-the-fluent-configuration-api-for-one-to-many-relationships-in-code-first-ef4/</guid>
		<description><![CDATA[Configuring ORM’s through fluent api calls is relatively new to me. For the last three years or so I’ve been using EF1 and Linq-To-Sql as my data modeling tools of choice. My first exposure to a code-first ORM tool came in June when I started working with Fluent NHibernate. As interesting as that has been, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=107&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Configuring ORM’s through fluent api calls is relatively new to me. For the last three years or so I’ve been using EF1 and Linq-To-Sql as my data modeling tools of choice. My first exposure to a code-first ORM tool came in June when I started working with <a href="http://fluentnhibernate.org/">Fluent NHibernate</a>. As interesting as that has been, I hadn’t really be faced with the issue of proper configuration because I’ve had someone on our team that does it easily. This weekend I started working on a sample project using the EF4 CTP, and the biggest stumbling block has been modeling the relationships.</p>
<p>The context code is a SCRUM process management app I’m writing. Here’s the model:</p>
<p><a href="http://crmckenzie.files.wordpress.com/2010/10/model.jpg"><img style="display:inline;border-width:0;" title="Model" border="0" alt="Model" src="http://crmckenzie.files.wordpress.com/2010/10/model_thumb.jpg?w=537&#038;h=347" width="537" height="347" /></a> </p>
<p>The relationship I tried to model was the one between Project and Story via the Backlog property. Since “Project” is the first entity I needed to write, my natural inclination was to model the relationship to “Story” first. </p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:fa0fc41f-a87e-435c-8a1a-6d775786bd5d" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> <span style="color:#2b91af;">DataContext</span> : <span style="color:#2b91af;">DbContext</span></li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">Project</span>&gt; Projects { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">Resource</span>&gt; Resources { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">Sprint</span>&gt; Sprints { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">Story</span>&gt; Stories { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li>    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">StoryStatus</span>&gt; StoryStatuses { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">public</span> <span style="color:#2b91af;">DbSet</span>&lt;<span style="color:#2b91af;">Task</span>&gt; Tasks { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnModelCreating(System.Data.Entity.ModelConfiguration.<span style="color:#2b91af;">ModelBuilder</span> builder)</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">base</span>.OnModelCreating(builder);</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">        builder</li>
<li>            .Entity&lt;<span style="color:#2b91af;">Project</span>&gt;()</li>
<li style="background:#f3f3f3;">            .HasMany(e =&gt; e.BackLog);</li>
</ol></div>
</p></div>
</p></div>
<p>I knew that “Story” would be slightly more complex because it has two properties that map back to “Project.” These are the “Project” property ,and the “ProjectId” property. Some of the EF4 samples I found refer to a “Relationship” extension method that I was unable to find in the API, so I was fairly confused. I finally figured out what I needed to do by reading <a href="http://www.hanselman.com/blog/SimpleCodeFirstWithEntityFramework4MagicUnicornFeatureCTP4.aspx">this post</a> from Scott Hanselman, though he doesn’t specifically highlight the question I was trying to answer.</p>
<p>This is the mapping code I created for “Story:”</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:676a2d37-d489-4c03-8c6e-17e2b302b9f0" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2em;padding:0 0 0 5px;">
<li>builder.Entity&lt;<span style="color:#2b91af;">Story</span>&gt;()</li>
<li style="background:#f3f3f3;">    .HasRequired(s =&gt; s.Project)</li>
<li>    .HasConstraint((story, project) =&gt; story.ProjectId == project.Id);</li>
</ol></div>
</p></div>
</p></div>
<p>and this is the code I’m using to create a new Story for a project:</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:dc46e8db-0233-4d0a-bdd3-323854fb9193" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li>[<span style="color:#2b91af;">HttpPost</span>]</li>
<li style="background:#f3f3f3;"><span style="color:#0000ff;">public</span> <span style="color:#2b91af;">ActionResult</span> Create(<span style="color:#2b91af;">Story</span> model)</li>
<li>{</li>
<li style="background:#f3f3f3;">    <span style="color:#0000ff;">using</span> (<span style="color:#0000ff;">var</span> context = <span style="color:#0000ff;">new</span> <span style="color:#2b91af;">DataContext</span>())</li>
<li>    {</li>
<li style="background:#f3f3f3;">        <span style="color:#0000ff;">var</span> project = context.Projects.Single(p =&gt; p.Id == model.ProjectId);</li>
<li>        project.BackLog.Add(model);</li>
<li style="background:#f3f3f3;">        context.SaveChanges();</li>
<li>        <span style="color:#0000ff;">return</span> RedirectToAction(<span style="color:#a31515;">&quot;Backlog&quot;</span>, <span style="color:#a31515;">&quot;Story&quot;</span>, <span style="color:#0000ff;">new</span> {id = project.Id});</li>
<li style="background:#f3f3f3;">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>&#160;</p>
<p>When I tried to save the story, the data context threw various exceptions. I thought I could avoid the problem by rewriting the code so that I was just adding the story directly to the “Stories” table on the DataContext (which I think will ultimately be the right thing as it saves an unnecessary database call), but that would have been hacking around the problem and not really understanding what was wrong with what I was doing. It just took some staring at Scott Hanselman’s code sample for awhile to realize what was wrong with my approach. Before I explain it, let me show you the mapping code that works.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:80f06d06-622d-464b-a451-30380f85f0be" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2.5em;padding:0 0 0 5px;">
<li><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">void</span> OnModelCreating(System.Data.Entity.ModelConfiguration.<span style="color:#2b91af;">ModelBuilder</span> builder)</li>
<li style="background:#f3f3f3;">{</li>
<li>    <span style="color:#0000ff;">base</span>.OnModelCreating(builder);</li>
<li style="background:#f3f3f3;">&nbsp;</li>
<li>    builder</li>
<li style="background:#f3f3f3;">        .Entity&lt;<span style="color:#2b91af;">Project</span>&gt;()</li>
<li>        .Property(p =&gt; p.Title)</li>
<li style="background:#f3f3f3;">        .IsRequired();</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">    <span style="color:#008000;">// api no longer has Relationship() extension method.</span></li>
<li>    builder.Entity&lt;<span style="color:#2b91af;">Story</span>&gt;()</li>
<li style="background:#f3f3f3;">        .HasRequired(s =&gt; s.Project)</li>
<li>        .WithMany(p =&gt; p.BackLog)</li>
<li style="background:#f3f3f3;">        .HasConstraint((story, project) =&gt; story.ProjectId == project.Id);</li>
<li>&nbsp;</li>
<li style="background:#f3f3f3;">}</li>
</ol></div>
</p></div>
</p></div>
<p>Notice what’s missing? I completely yanked the mapping of “Project-&gt;Stories” from the “Project” model’s perspective. Instead, I map the one-to-many relationship from the child-entity’s perspective, i.e., “Story.” Here’s how to read the mapping.</p>
<div style="display:inline;float:none;margin:0;padding:0;" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ed4dd080-2532-41b9-ace1-1ddb4d9ffc58" class="wlWriterEditableSmartContent">
<div style="border:#000080 1px solid;color:#000;font-family:'Courier New', Courier, Monospace;font-size:10pt;">
<div style="background:#ddd;max-height:500px;overflow:auto;">
<ol style="background:#ffffff;margin:0 0 0 2em;padding:0 0 0 5px;">
<li><span style="color:#008000;">// api no longer has Relationship() extension method.</span></li>
<li style="background:#f3f3f3;">builder.Entity&lt;<span style="color:#2b91af;">Story</span>&gt;() <span style="color:#008000;">// The entity story</span></li>
<li>    .HasRequired(s =&gt; s.Project) <span style="color:#008000;">// has a required property called &quot;Project&quot; of type &quot;Project&quot;</span></li>
<li style="background:#f3f3f3;">    .WithMany(p =&gt; p.BackLog) <span style="color:#008000;">// and &quot;Project&quot; has a reference back to &quot;Story&quot; through it&#039;s &quot;Backlog&quot; collection property</span></li>
<li>    .HasConstraint((story, project) =&gt; story.ProjectId == project.Id); <span style="color:#008000;">// and Story.ProjectId is the same as Story.Project.Id</span></li>
<li style="background:#f3f3f3;">;</li>
</ol></div>
</p></div>
</p></div>
<p>The key here is understanding that one-to-many relationships must be modeled from the perspective of the child-entity.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/crmckenzie.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/crmckenzie.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/crmckenzie.wordpress.com/107/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=crmckenzie.wordpress.com&amp;blog=9993560&amp;post=107&amp;subd=crmckenzie&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://crmckenzie.wordpress.com/2010/10/17/understanding-the-fluent-configuration-api-for-one-to-many-relationships-in-code-first-ef4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c6f153da0c942369289863942e65433b?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">crmckenzie</media:title>
		</media:content>

		<media:content url="http://crmckenzie.files.wordpress.com/2010/10/model_thumb.jpg" medium="image">
			<media:title type="html">Model</media:title>
		</media:content>
	</item>
	</channel>
</rss>
