<?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>Thoughtology</title>
	<atom:link href="http://megakemp.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://megakemp.wordpress.com</link>
	<description>The art of thinking about technology</description>
	<lastBuildDate>Mon, 23 Jan 2012 15:56:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='megakemp.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/3c23d5ca864e4cdac09348530fb3a7c6?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Thoughtology</title>
		<link>http://megakemp.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://megakemp.wordpress.com/osd.xml" title="Thoughtology" />
	<atom:link rel='hub' href='http://megakemp.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Better DIFFs with PowerShell</title>
		<link>http://megakemp.wordpress.com/2012/01/19/better-diffs-with-powershell/</link>
		<comments>http://megakemp.wordpress.com/2012/01/19/better-diffs-with-powershell/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 12:25:42 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Diff]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=1005</guid>
		<description><![CDATA[I love working with the command line. In fact, I love it so much that I even use it as my primary way of interacting with the source control repositories of all the projects I&#8217;m involved in. It&#8217;s a matter of personal taste, admittedly, but there&#8217;s also a practical reason for that. Depending on what [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=1005&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I love working with the command line. In fact, I love it so much that I even use it as my primary way of interacting with the source control repositories of all the projects I&#8217;m involved in. It&#8217;s a matter of personal taste, admittedly, but there&#8217;s also a practical reason for that.</p>
<p>Depending on what I&#8217;m working on, I regularly have to switch among several different source control systems. Just to give you an example, just in the last six months I&#8217;ve been using <a href="http://mercurial.selenic.com">Mercurial</a>, <a href="http://git-scm.com">Git</a>, <a href="http://subversion.tigris.org">Subversion</a> and <a href="http://msdn.microsoft.com/en-us/vstudio/ff637362">TFS</a> on a weekly basis. Instead of having to learn and get used to different UIs (whether it be standalone clients or IDE plugins), I find that I can be more productive by sticking to the <em>uniform experience</em> of the command line based tools.</p>
<p>To enforce my point, let me show you how to check in some code in the source control systems I mentioned above:</p>
<ul>
<li><strong>Mercurial:</strong> <code>hg commit -m "Awesome feature"</code></li>
<li><strong>Git:</strong> <code>git commit -m "Awesome feature"</code></li>
<li><strong>Subversion:</strong> <code>svn commit -m "Awesome feature"</code></li>
<li><strong>TFS:</strong> <code>tf checkin /comment:"Awesome feature"</code></li>
</ul>
<p>As you can see, it looks pretty much the same across the board. </p>
<p>Of course, you need to be aware of the fundamental differences in how <a href="http://en.wikipedia.org/wiki/Distributed_revision_control">Distributed Version Control Systems (DVCS)</a> such as Mercurial and Git behave compared to traditional centralized <a href="http://en.wikipedia.org/wiki/Revision_control">Version Control Systems (VCS)</a> like Subversion and TFS. In addition to that, each system tries to characterize itself by having its own set of features or by solving a common problem (like <a href="http://en.wikipedia.org/wiki/Branching_(software)">branching</a>) in a unique way.<br />
However, there aspects must be taken into consideration regardless of your client of choice.<br />
What I&#8217;m saying is that the command line interface <em>at least</em> offers a single point of entry into those systems, which in the end makes me more productive.</p>
<h2>Unified DIFFs</h2>
<p>One of the most basic features of any source control system is the ability to compare two versions of the same file to see what&#8217;s changed. The output of such comparison, or <a href="http://en.wikipedia.org/wiki/Diff">DIFF</a>, is commonly represented in text using the <a href="http://en.wikipedia.org/wiki/Diff#Unified_format">Unified DIFF format</a>, which looks something like this:</p>
<p><pre class="brush: diff; gutter: false;">
--- a/QuoteBookTests/Classes/Models/QuoteTest.h
+++ b/QuoteBookTests/Classes/Models/QuoteTest.h
@@ -6,12 +6,10 @@
 //  Copyright 2011 Thoughtology. All rights reserved.
 //

-#import &lt;SenTestingKit/SenTestingKit.h&gt;
-#import &lt;UIKit/UIKit.h&gt;
-
 @interface QuoteTest : SenTestCase {    
 }

 - (void)testQuoteForInsert_ReturnsNotNull;
+- (void)testQuoteForInsert_ReturnsPersistedQuote;

 @end
</pre></p>
<p>In the Unified DIFF format changes are displayed at the line level through a set of well-known prefixes. The rule is simple:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;">
A line can either be <strong>added</strong>, in which case it will be preceded by a <code>+</code> sign, or <strong>removed</strong>, in which case it will be preceded by a <code>-</code> sign. <strong>Unchanged</strong> lines are preceded by a whitespace.</div>
<p>In addition to that, each modified section, referred to as <em>hunk</em>, is preceded by a header that indicates the position and size of the section in the original and modified file respectively. For example this <em>hunk header</em>:</p>
<p><pre class="brush: diff; light: true;">
@@ -6,12 +6,10 @@
</pre></p>
<p>means that in <strong>the original file</strong> the modified lines start at <code>line 6</code> and continue for <code>12 lines</code>. In <strong>the new file</strong>, instead, that same change starts at <code>line 6</code> and includes a total of <code>10 lines</code>.</p>
<h2>True Colors</h2>
<p>At this point, you may wonder what all of this has to do with PowerShell, and rightly so. Remember when I said that I prefer to work with source control from the command line? Well, it turns out that <em>scrolling through gobs of text</em> in a console window isn&#8217;t always the best way to figure out what has changed between two change sets.</p>
<p>Fortunately, since PowerShell allows to <a href="http://technet.microsoft.com/en-us/library/dd347596.aspx">print text in the console window using different colors</a>, it only took a switch statement and a couple of regular expressions, to turn that <a href="http://www.walloftext.net">wall of text</a> into something more readable. That&#8217;s how the <strong>Out-Diff</strong> cmdlet was born:</p>
<p><pre class="brush: powershell; gutter: false;">
function Out-Diff {
&lt;#
.Synopsis
    Redirects a Universal DIFF encoded text from the pipeline to the host using colors to highlight the differences.
.Description
    Helper function to highlight the differences in a Universal DIFF text using color coding.
.Parameter InputObject
    The text to display as Universal DIFF.
#&gt;
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [PSObject]$InputObject
)
    Process {
        $contentLine = $InputObject | Out-String
        if ($contentLine -match &quot;^Index:&quot;) {
            Write-Host $contentLine -ForegroundColor Cyan -NoNewline
        } elseif ($contentLine -match &quot;^(\+|\-|\=){3}&quot;) {
            Write-Host $contentLine -ForegroundColor Gray -NoNewline
        } elseif ($contentLine -match &quot;^\@{2}&quot;) {
            Write-Host $contentLine -ForegroundColor Gray -NoNewline
        } elseif ($contentLine -match &quot;^\+&quot;) {
            Write-Host $contentLine -ForegroundColor Green -NoNewline
        } elseif ($contentLine -match &quot;^\-&quot;) {
            Write-Host $contentLine -ForegroundColor Red -NoNewline
        } else {
            Write-Host $contentLine -NoNewline
        }
    }
}
</pre></p>
<p>Let&#8217;s break this function down into logical steps:</p>
<ol>
<li>Take whatever input comes from <a href="http://powershell.com/cs/blogs/ebook/archive/2008/11/23/chapter-5-the-powershell-pipeline.aspx">the PowerShell pipeline</a> and convert it to a string.</li>
<li>Match that string against a set of regular expressions to determine whether it&#8217;s part of the <a href="http://en.wikipedia.org/wiki/Diff#Unified_format">Unified DIFF format</a>.</li>
<li>Print the string to the console with the appropriate color: <span style="color:green;">green</span> for added, <span style="color:red;">red</span> for removed and <span style="color:gray;">gray</span> for the headers.</li>
</ol>
<p>Pretty simple. And using it is even simpler: just load the script into your PowerShell session using <a href="http://technet.microsoft.com/en-us/library/ee176949.aspx#ECAA">dot sourcing</a> or by <a href="http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-10-scripts.aspx#profile-autostart-scripts">adding it to your profile</a> and <strong>redirect the output of a &#8216;diff&#8217; command to the Out-Diff cmdlet through piping</strong> to start enjoying colorized DIFFs. For example the following commands:</p>
<p><pre class="brush: powershell; light: true;">
. .\Out-Diff.ps1
git diff | Out-Diff
</pre></p>
<p>will generate this output in PowerShell:</p>
<p><a href="http://megakemp.files.wordpress.com/2012/01/outdiff-powershell-screenshot.png"><img src="http://megakemp.files.wordpress.com/2012/01/outdiff-powershell-screenshot_thumb.png?w=480" alt="The Out-Diff cmdlet in action" title="The Out-Diff cmdlet in action" /></a></p>
<p>One thing I&#8217;d like to point out is that even if the output of <code>git diff</code> consists of many lines of text, PowerShell will redirect them to the <code>Out-Diff</code> function <strong>one line at a time</strong>. This is called a <a href="http://powershell.com/cs/blogs/ebook/archive/2008/11/23/chapter-5-the-powershell-pipeline.aspx#streaming-real-time-processing-or-not">streaming pipeline</a> and it allows PowerShell to be responsive and consume less memory even when processing large amounts of data, which is neat.</p>
<h2>Wrapping up</h2>
<p>PowerShell is an extremely versatile console. In this case, it allowed me to enhance a traditional command line tool (<code>diff</code>) through a simple script. Other projects, like <a href="https://github.com/dahlbyk/posh-git">Posh-Git</a> and <a href="http://poshhg.codeplex.com">Posh-Hg</a>, take it even further and leverage PowerShell&#8217;s rich programming model to provide a better experience on top of existing console based source control tools. If you enjoy working with the command line, I seriously encourage you to check them out.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-left:5px;padding-right:5px;">
<p style="margin-top:0;">
<img src="http://megakemp.files.wordpress.com/2009/07/download.gif?w=480" alt="Download" style="margin:10px 5px 0 10px;" /> Download <a href="http://gist.github.com/1635952"><strong>Out-Diff.ps1</strong></a> from <a href="http://github.com/">GitHub</a></p>
</div>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a>, <a href='http://megakemp.wordpress.com/category/tools/'>Tools</a> Tagged: <a href='http://megakemp.wordpress.com/tag/diff/'>Diff</a>, <a href='http://megakemp.wordpress.com/tag/git/'>Git</a>, <a href='http://megakemp.wordpress.com/tag/powershell/'>PowerShell</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/1005/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/1005/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/1005/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=1005&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2012/01/19/better-diffs-with-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/01/outdiff-powershell-screenshot_thumb.png" medium="image">
			<media:title type="html">The Out-Diff cmdlet in action</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/07/download.gif" medium="image">
			<media:title type="html">Download</media:title>
		</media:content>
	</item>
		<item>
		<title>Keep your unit tests DRY with AutoFixture Customizations</title>
		<link>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/</link>
		<comments>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 13:51:54 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=942</guid>
		<description><![CDATA[When I first incorporated AutoFixture as part of my daily unit testing workflow, I noticed how a consistent usage pattern had started to emerge. This pattern can be roughly summarized in three steps: Initialize an instance of the Fixture class. Configure the way different types of objects involved in the test should be created by [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=942&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When I first incorporated <a href="http://autofixture.codeplex.com">AutoFixture</a> as part of my daily unit testing workflow, I noticed how a consistent usage pattern had started to emerge.<br />
This pattern can be roughly summarized in three steps:</p>
<ol>
<li><strong>Initialize</strong> an instance of the <code>Fixture</code> class.</li>
<li><strong>Configure</strong> the way different types of objects involved in the test should be created by using the <code>Build&lt;T&gt;</code> method.</li>
<li><strong>Create</strong> the actual objects with the <code>CreateAnonymous&lt;T&gt;</code> or <code>CreateMany&lt;T&gt;</code> methods.</li>
</ol>
<p>As a result, my unit tests had started to look a lot like this:</p>
<p><pre class="brush: csharp; light: true;">
[Test]
public void WhenGettingAListOfPublishedPostsThenItShouldOnlyIncludeThose()
{
    // Step 1: Initialize the Fixture
    var fixture = new Fixture();

    // Step 2: Configure the object creation
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });

    // Step 3: Create the anonymous objects
    var posts = fixture.CreateMany&lt;Post&gt;();

   // Act and Assert...
}
</pre></p>
<p>In this particular configuration, AutoFixture will satisfy all requests for <code>IEnumerable&lt;Post&gt;</code> types by returning the same array with exactly two <code>Post</code> objects: one with the <code>IsDraft</code> property set to <code>True</code> and one with the same property set to <code>False</code>.</p>
<p>At that point I felt pretty satisfied with the way things were shaping up: I had managed to replace entire blocks of boring object initialization code with a couple of calls to the AutoFixture API, my unit tests were getting smaller and all was good.</p>
<h2>Duplication creeps in</h2>
<p>After a while though, the configuration lines created in <em>Step 2</em> started to repeat themselves across multiple unit tests. This was naturally due to the fact that <strong>different unit tests sometimes shared a common set of object states in their test scenario</strong>. Things weren&#8217;t so DRY anymore and suddenly it wasn&#8217;t uncommon to find code like this in the test suite:</p>
<p><pre class="brush: csharp; highlight: [2,18]; light: true;">
[Test]
public void WhenGettingAListOfPublishedPostsThenItShouldOnlyIncludeThose()
{
    var fixture = new Fixture();
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Act and Assert...
}

[Test]
public void WhenGettingAListOfDraftsThenItShouldOnlyIncludeThose()
{
    var fixture = new Fixture();
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Different Act and Assert...
}
</pre></p>
<p>See how these two tests share the same initial state even though they verify completely different behaviors? Such blatant duplication in the test code is a problem, since it inhibits the ability to make changes.<br />
Luckily a solution was just around the corner as I discovered <a href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx">customizations</a>.</p>
<h2>Customizing your way out</h2>
<p>A customization is a pretty general term. However, put in the context of AutoFixture it assumes a specific definition:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;">
A <strong>customization</strong> is a group of settings that, when applied to a given <code>Fixture</code>, control the way AutoFixture will create anonymous instances of the types requested through that <code>Fixture</code>.</div>
<p>What that means is that I could take all the boilerplate configuration code produced during <em>Step 2</em> and move it out of my unit tests into a single place, that is a customization. That allowed me to <strong>specify only once how different objects needed to be created for a given scenario</strong>, and reuse that across multiple tests.</p>
<p><pre class="brush: csharp; light: true;">
public class MixedDraftsAndPublishedPostsCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        var draft = fixture.Build&lt;Post&gt;()
            .With(a =&gt; a.IsDraft = true)
            .CreateAnonymous();
        var publishedPost = fixture.Build&lt;Post&gt;()
            .With(a =&gt; a.IsDraft = false)
            .CreateAnonymous();
        fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    }
}
</pre></p>
<p>As you can see, <code>ICustomization</code> is nothing more than a <a href="http://martinfowler.com/bliki/RoleInterface.html">role interface</a> that describes how a <code>Fixture</code> should be set up. In order to apply a customization to a specific <code>Fixture</code> instance, you&#8217;ll simply have to call the <code>Fixture.Customize(ICustomization)</code> method, like shown in the example below.<br />
This newly won encapsulation allowed me to rewrite my unit tests in a much more terse way:</p>
<p><pre class="brush: csharp; light: true;">
[Test]
public void WhenGettingAListOfDraftsThenItShouldOnlyIncludeThose()
{
    // Step 1: Initialize the Fixture
    var fixture = new Fixture();

    // Step 2: Apply the customization for the test scenario
    fixture.Customize(new MixedDraftsAndPublishedPostsCustomization());

    // Step 3: Create the anonymous objects
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Act and Assert...
}
</pre></p>
<p>The configuration logic now exists only in one place, namely a class whose name clearly describes the kind of test data it will produce.<br />If applied consistently, this approach will in time <strong>build up a library of customizations, each representative of a given situation or scenario</strong>. Assuming that they are created at the proper level of granularity, these customizations could even be composed to form more complex scenarios.</p>
<h2>Conclusion</h2>
<p>Customizations in <a href="http://autofixture.codeplex.com">AutoFixture</a> are a pretty powerful concept in of themselves, but they become even more effective when <strong>mapped directly to test scenarios</strong>. In fact, they represent a natural place to specify which objects are involved in a given scenario and the state they are supposed to be in. You can use them to remove duplication in your test code and, in time, build up a library of self-documenting modules, which describe the different contexts in which the system&#8217;s behavior is being verified.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/942/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=942&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	</item>
		<item>
		<title>Behavior changes in AutoFixture 2.2 &#8211; Anonymous numbers</title>
		<link>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/</link>
		<comments>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 15:40:34 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=892</guid>
		<description><![CDATA[Now that AutoFixture 2.2 is approaching on the horizon, it&#8217;s a good time to start talking about some of the changes that were made to the underlying behavior of some existing APIs. I&#8217;ll start off this series of posts by focusing on the new generation strategy for anonymous numbers. The good old fashioned way Before [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=892&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now that <a href="http://twitter.com/#!/ploeh/status/109005068581343232">AutoFixture 2.2 is approaching on the horizon</a>, it&#8217;s a good time to start talking about some of the changes that were made to the underlying behavior of some existing APIs. I&#8217;ll start off this series of posts by focusing on the new generation strategy for anonymous numbers.</p>
<h2>The good old fashioned way</h2>
<p>Before I jump into the details of what exactly has been changed and how, allow me to set up a little bit of stage:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;">A key part of AutoFixture&#8217;s mission statement is to make the process of authoring unit tests faster by providing an easy way of creating test values (or &#8220;<em>specimens</em>&#8220;) for the variables involved in the test. The goal of providing values that are as neutral as possible to the test scenario at hand is achieved by employing <a href="http://blog.ploeh.dk/2009/03/05/ConstrainedNonDeterminism.aspx">&#8220;constrained non-deterministic&#8221;</a> generation algorithms.</div>
<p>Put in simple terms, this essentially means that <strong>AutoFixture will come up with test values at run time that can be considered &#8220;random&#8221; within some predefined bounds</strong>. These bounds are imposed at the lowest level by the variable&#8217;s own data type: a string is a string, a number is a number and so on. More constraints, however, can be added at a higher level, based on any semantics the variable may have in the specific test scenario. For example a string can&#8217;t be longer than 20 characters or a number must be between 1 and 100.</p>
<p>AutoFixture comes with a set of built-in generation algorithms that can produce test values for all the primitive types included in the .NET Framework. The algorithm for numeric types has historically been based on individually incremented sequences, one for each numeric data type. Let&#8217;s look at an example that illustrates this:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
Console.WriteLine(&quot;Byte specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;byte&gt;(),
    fixture.CreateAnonymous&lt;byte&gt;());
Console.WriteLine(&quot;Int32 specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;int&gt;(),
    fixture.CreateAnonymous&lt;int&gt;());
Console.WriteLine(&quot;Single specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;float&gt;(),
    fixture.CreateAnonymous&lt;float&gt;());

// The output will be:
// Byte specimen is 1, 2
// Int32 specimen is 1, 2
// Single specimen is 1, 2
</pre></p>
<p>The key point here is that <strong>AutoFixture will only guarantee unique numeric specimens within the scope of a specific data type</strong>. Now, you may wonder how this would be a problem. Well, it certainly isn&#8217;t in itself, but if you asked AutoFixture to give you an anonymous instance of a class with multiple properties of different numeric types, you would get something like this:</p>
<p><pre class="brush: csharp; gutter: false;">
public class NumericBag
{
    public byte ByteValue { get; set; }
    public int Int32Value { get; set; }
    public float SingleValue { get; set; }
}

var fixture = new Fixture();
var specimen = fixture.CreateAnonymous&lt;NumericBag&gt;();
Console.WriteLine(&quot;ByteValue property is {0}&quot;, specimen.ByteValue);
Console.WriteLine(&quot;Int32Value property is {0}&quot;, specimen.Int32Value);
Console.WriteLine(&quot;SingleValue property is {0}&quot;, specimen.SingleValue);

// The output will be:
// ByteValue property is 1
// Int32Value property is 1
// SingleValue property is 1
</pre></p>
<p>We can agree that the end result doesn&#8217;t exactly live up to the expectation of anonymous values being &#8220;random&#8221;. Starting from version 2.2, however, this behavior is due to change.</p>
<h2>The fresh new way</h2>
<p>AutoFixture has taken a different approach to numeric specimen generation and <strong>will now by default return unique values across all numeric types</strong>. Running our first example in AutoFixture 2.2 will therefore yield a very different result:</p>
<p><pre class="brush: csharp; gutter: false; highlight: [13,14,15];">
var fixture = new Fixture();
Console.WriteLine(&quot;Byte specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;byte&gt;(),
    fixture.CreateAnonymous&lt;byte&gt;());
Console.WriteLine(&quot;Int32 specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;int&gt;(),
    fixture.CreateAnonymous&lt;int&gt;());
Console.WriteLine(&quot;Single specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;float&gt;(),
    fixture.CreateAnonymous&lt;float&gt;());

// The output will be:
// Byte specimen is 1, 2
// Int32 specimen is 3, 4
// Single specimen is 5, 6
</pre></p>
<p>In other words, AutoFixture is being a little more &#8220;non-deterministic&#8221; when it comes to numeric test values. Take for example the following scenario:</p>
<p><pre class="brush: csharp; gutter: false; highlight: [15,16,17];">
public class NumericBag
{
    public byte ByteValue { get; set; }
    public int Int32Value { get; set; }
    public float SingleValue { get; set; }
}

var fixture = new Fixture();
var specimen = fixture.CreateAnonymous&lt;NumericBag&gt;();
Console.WriteLine(&quot;ByteValue property is {0}&quot;, specimen.ByteValue);
Console.WriteLine(&quot;Int32Value property is {0}&quot;, specimen.Int32Value);
Console.WriteLine(&quot;SingleValue property is {0}&quot;, specimen.SingleValue);

// The output will be:
// ByteValue property is 1
// Int32Value property is 2
// SingleValue property is 3
</pre></p>
<p>See how all the numeric properties on the generated object have different values? That&#8217;s what I&#8217;m talking about.</p>
<p>Now, in theory, this shouldn&#8217;t be considered a breaking change. I say this because AutoFixture is all about <a href="http://blogs.msdn.com/b/ploeh/archive/2008/11/17/anonymous-variables.aspx">anonymous variables</a>, which, by definition, can&#8217;t be expected to have specific values during a test run. So, as long as you&#8217;ve played by this rule, the new behavior shouldn&#8217;t impact any of your existing tests.</p>
<p>However, if this does turn out to be a problem or you simply prefer the old way of doing things, you shouldn&#8217;t feel left out in the cold. The <strong>previous behavior is still in the box, packaged up in a nice customization</strong> unambiguously named <code>NumericSequencePerTypeCustomization</code>. The simple act of adding it to a Fixture instance will restore things the way they were:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
fixture.Customize(new NumericSequencePerTypeCustomization());
</pre></p>
<p>If you wish to try this out today, I encourage you to go head and grab the latest build off of <a href="http://teamcity.codebetter.com/project.html;jsessionid=C212815CFF41DFCD2E93DDDECABF1668?projectId=project129&amp;tab=projectOverview">AutoFixture&#8217;s project page on Team City</a>. Enjoy.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/892/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=892&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	</item>
		<item>
		<title>Anonymous delegates in AutoFixture</title>
		<link>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/</link>
		<comments>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 21:16:40 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">https://megakemp.wordpress.com/?p=720</guid>
		<description><![CDATA[I’m excited to announce that AutoFixture now officially supports delegates in the main trunk up on CodePlex. If you aren&#8217;t familiar with AutoFixture, let me give you the pitch: AutoFixture is an open source framework for .NET designed to minimize the &#8216;Arrange&#8217; phase of your unit tests. Its primary goal is to allow developers to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=720&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’m excited to announce that <a href="http://autofixture.codeplex.com">AutoFixture</a> now officially supports delegates in the <a href="http://autofixture.codeplex.com/SourceControl/changeset/changes/48b0ea5a7f15">main trunk</a> up on CodePlex.</p>
<p>If you aren&#8217;t familiar with AutoFixture, let me give you the pitch:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;"><strong>AutoFixture</strong> is an open source framework for .NET designed to minimize the &#8216;Arrange&#8217; phase of your unit tests. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.</div>
<p>Does this sound interesting to you? In that case head over to the <a href="http://autofixture.codeplex.com">AutoFixture CodePlex site</a> and find out more. You’ll be glad you did.</p>
<p>For those of you already familiar with AutoFixture, the newly added support for delegates means that every time AutoFixture is asked to create an anonymous instance of a delegate type (or more precisely a <em>delegate specimen</em>), it will actually return one, instead of throwing an exception.</p>
<p>So, you’ll be able to say things like:</p>
<p><pre class="brush: csharp; gutter: false;">
public delegate void MyDelegate();

var fixture = new Fixture();
var delegateSpecimen = fixture.CreateAnonymous&lt;MyDelegate&gt;();
</pre></p>
<p>and get back <strong>a delegate pointing to a dynamically generated method</strong>, whose signature matches the one of the requested delegate type. In other words AutoFixture will satisfy the requests for delegates by providing a <em>method specimen</em>.</p>
<p>That’s cool, but it may leave you wondering: what on Earth does a method specimen do when it gets invoked? Well, in order to answer that question, we need to look at the signature of the delegate that was requested in the first place. The rule basically says:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;">
<ul>
<li>If the signature of the requested delegate <strong>has a return value</strong> (i.e. it’s a <em>function</em>), the method specimen will always return an anonymous value of the return type.</li>
<li>If the signature of the requested delegate <strong>doesn’t have a return value</strong> (i.e. it’s an <em>action</em>) the returned method specimen will have an empty body.</li>
</ul>
</div>
<p>This principle is best illustrated by examples. Consider the following code snippet:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
var funcSpecimen = fixture.CreateAnonymous&lt;Func&lt;string&gt;&gt;();
var result = funcSpecimen();

// result = &quot;fd95320f-0a37-42be-bd49-3afbbe089d9d&quot;
</pre></p>
<p>In this example, since the signature of the requested delegate has a return value of type <a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a>, the <font face="Consolas">result</font> variable will contain an anonymous string value, which in AutoFixture usually translates into a GUID.<br />On the other hand, if requested delegate didn&#8217;t have a return value, invoking the anonymous delegate would do just about nothing:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
var actionSpecimen = fixture.CreateAnonymous&lt;Action&lt;string&gt;&gt;();
actionSpecimen(&quot;whatever&quot;); // no-op
</pre></p>
<p>Note that in both cases <strong>any input arguments passed to the anonymous delegate will be ignored</strong>, since they don&#8217;t have any impact on the generated method specimen.</p>
<p>Now, if you’re using AutoFixture from <a href="http://nuget.org/List/Packages/AutoFixture">its NuGet package</a> (which, by the way, you should) you’ll have to wait until the next release to get this feature. However, taking advantage of it with the current version of AutoFixture requires a minimal amount of effort. Just <a href="http://autofixture.codeplex.com/SourceControl/changeset/view/493eecec7784#Src%2fAutoFixture%2fKernel%2fDelegateGenerator.cs">grab the DelegateGenerator.cs class from AutoFixture&#8217;s main trunk</a> on CodePlex and include it in your project. You’ll then be able to add support for delegates to your Fixture instance by simply saying:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
fixture.Customizations.Add(new DelegateGenerator());
</pre></p>
<p>You can even <a href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx">wrap that up in a Customization</a> to make it more centralized and keep your test library <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>:</p>
<p><pre class="brush: csharp; gutter: false;">
public class DelegateCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        if (fixture == null)
        {
            throw new ArgumentNullException(&quot;fixture&quot;);
        }

        fixture.Customizations.Add(new DelegateGenerator());
    }
}
</pre></p>
<p>Before finishing this off, let me give you a more concrete example that shows how this is useful in a real world scenario. Keeping in mind that delegates offer a pretty terse way to implement the <a href="http://sourcemaking.com/design_patterns/strategy">Strategy Design Pattern</a> in .NET, consider this implementation of the <a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer&lt;T&gt; interface</a>:</p>
<p><pre class="brush: csharp; gutter: false;">
public class EqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;
{
    private readonly Func&lt;T, T, bool&gt; equalityStrategy;
    private readonly Func&lt;T, int&gt; hashCodeStrategy;

    public EqualityComparer(Func&lt;T, T, bool&gt; equalityStrategy, Func&lt;T, int&gt; hashCodeStrategy)
    {
        if (equalityStrategy == null)
        {
            throw new ArgumentNullException(&quot;equalityStrategy&quot;);
        }

        if (hashCodeStrategy == null)
        {
            throw new ArgumentNullException(&quot;hashCodeStrategy&quot;);
        }

        this.equalityStrategy = equalityStrategy;
        this.hashCodeStrategy = hashCodeStrategy;
    }

    public bool Equals(T x, T y)
    {
        return equalityStrategy(x, y);
    }

    public int GetHashCode(T obj)
    {
        return hashCodeStrategy(obj);
    }
}
</pre></p>
<p>That&#8217;s a nice flexible class that, by allowing to specify the comparison logic in the form of delegates, is suitable in different scenarios. Before the support for delegates was added, however, having AutoFixture play along with this class in the context of unit testing would be quite problematic. The tests would, in fact, fail consistently with a <a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx">NotSupportedException</a>, since the constructor of the <font face="Consolas">EqualityComparer</font> class requires the creation of two delegates.<br />Luckily, this is not a problem anymore.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/720/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=720&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	</item>
		<item>
		<title>Fixing a bug in ASP.NET Ajax and the pain of leaky abstractions</title>
		<link>http://megakemp.wordpress.com/2010/01/04/fixing-a-bug-in-asp-net-ajax-and-the-pain-of-leaky-abstractions/</link>
		<comments>http://megakemp.wordpress.com/2010/01/04/fixing-a-bug-in-asp-net-ajax-and-the-pain-of-leaky-abstractions/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 13:54:58 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web Forms]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=653</guid>
		<description><![CDATA[There was a time when all my energies and effort went into building web applications. In the beginning the platform I was on was Microsoft ASP 2.0, but since 2002 it became all about ASP.NET Web Forms. I still remember clearly the excitement there was around the programming model and architecture brought by Web Forms. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=653&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There was a time when all my energies and effort went into building web applications. In the beginning the platform I was on was Microsoft ASP 2.0, but since 2002 it became all about ASP.NET Web Forms.</p>
<p>I still remember clearly the excitement there was around the programming model and architecture brought by Web Forms. The new <strong>code-behind</strong> style allowed to finally separating a web page’s layout from its code logic. The <strong>server controls </strong>programming model were built so that developers could build web pages pretending they were Windows Forms.</p>
<p>The promise of Web Forms was that web developers would never have to touch HTML and JavaScript ever again. They could simply have to add a bunch of .NET controls to a class, set a couple of properties and web pages would magically appear in the browser.</p>
<p>Although ASP.NET Web Forms was designed with a noble goal in mind, it turned out the Forms/Controls metaphor never completely worked for the web.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:25px 10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />Sure, the Web Forms model boosted productivity compared to previous technologies like ASP. However it never succeeded in shielding developers from having to deal <strong>HTML</strong>, <strong>CSS</strong> and <strong>JavaScript</strong>. That essentially meant ignoring the very basic elements of the web. </div>
<p>This is a story of how I was painfully reminded of this reality.</p>
<p><span style="color:#515151;font-size:120%;"><strong>ASP.NET and the Ajax Control Toolkit</strong></span></p>
<p>At some point in time the Web became all about rich user interaction. One way to achieve this was through the power of asynchronous HTTP requests made through JavaScript, which returned XML data. This combination is commonly referred to as <strong><a href="http://en.wikipedia.org/wiki/Ajax_(programming)">Ajax</a></strong>.     <br />When Ajax got widespread popularity, Microsoft built upon the Web Forms model to enable developers to leverage this new programming paradigm. Once more with the promise of ever having to touch a line of JavaScript.<a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/"><img style="display:inline;border-width:0;margin:20px 0 20px 20px;" title="AspNetAjaxLogo" border="0" alt="AspNetAjaxLogo" align="right" src="http://megakemp.files.wordpress.com/2010/01/aspnetajaxlogo.png?w=164&#038;h=83" width="164" height="83" /></a> </p>
<p>This effort culminated in a new infrastructure made available in the .NET Framework 3.5 and a collection of <strong>Ajax-enabled server controls</strong>. Once dragged into a Web Forms page, these controls would instantly deliver rich functionality by emitting the required JavaScript code to make it happen.</p>
<p>Contrarily to what had been done in the past, the new Ajax controls were not made part of an official version of the .NET Framework, but only the underlying framework support they need in order to work. The control themselves were released as an open-source project called the <strong><a href="http://ajaxcontroltoolkit.codeplex.com/">ASP.NET Ajax Control Toolkit</a>&#160;</strong>hosted on the <strong><a href="http://www.codeplex.com/">Microsoft CodePlex site</a></strong>.</p>
<p><span style="color:#515151;font-size:120%;"><strong>The illusion</strong></span></p>
<p>After having been away from web development for almost three years, I&#8217;ve lately been involved in a project to build a web application. Of course the customer expected a modern and interactive web application, which meant we were going to be using Ajax on the frontend to some extent.</p>
<p>After having brought myself up to speed on the latest innovations around Ajax in ASP.NET 3.5, I was excited at the idea of be able to deliver that kind of functionality on a web page without having to handcraft (and debug) gobs of JavaScript. Or at least, so I thought.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Facing reality</strong></span></p>
<p>I have to admit that the Ajax support in ASP.NET 3.5 held up to my high expectations quite well. Up until the Web Forms metaphor leaked again and I was roughly brought back to earth.</p>
<p>It turns out the ComboBox control contained in the Ajax Control Toolkit has a nasty bug that manifested itself for me when I used it inside a TabPanel control (also part of the same library).</p>
<p>Here is what happens: the first screenshot shows a ComboBox control inside a TabPanel that is visible when the page loads for the first time. Below is another ComboBox control this time hosted in a second TabPanel that is initially hidden.</p>
<p><img src="http://megakemp.files.wordpress.com/2010/03/ajaxcomboboxbugworking.png?w=480" alt="ASP.NET Ajax ComboBox control working" /><br />
<img src="http://megakemp.files.wordpress.com/2010/03/ajaxcomboboxbugbroken.png?w=480" alt="ASP.NET Ajax ComboBox control broken" /></p>
<p>The second definitely doesn’t look right. After a quick check to <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ComboBox/ComboBox.aspx">the documentation available online</a> I couldn’t find anything I was doing wrong when using the controls. The only possible explanation was that there must be a bug in the JavaScript generated by the ComboBox. Let me just check. Yes, <a href="http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=25295">here it is</a>.</p>
<p>Apparently there is currently no plan from Microsoft to fix this issue anytime soon. That could mean only one thing: I had to dig in and debug the JavaScript myself. The Web Forms’ bubble had burst once again.</p>
<p><span style="color:#515151;font-size:120%;"><strong>The “pragmatic” workaround</strong></span></p>
<p>After having downloaded the AJAX Control Toolkit source code off CodePlex, I started to look around among the project files. I quickly indentified that the JavaScript code for the ComboBox control is all contained in a single file found in <strong>/AjaxControlToolkit/ComboBox/ComboBox.js</strong> (actually the <em>ComboBox.debug.js</em> file contains the original source code while its <em>ComboBox.js</em> counterpart contains the <strong><a href="http://en.wikipedia.org/wiki/Minification_(programming)">minified JavaScript</a></strong> optimized for production).</p>
<p>The general design of the client-side Ajax framework and controls built by Microsoft makes a lot of sense and the source code is well organized. This allowed me to quickly arrive at the root of the problem, which is:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:30px 10px 25px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2010/02/remove.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />The ComboBox control calculates its size (width and height) during initialization relatively to the size of its parent container. If <strong>the parent container is hidden when it gets measured</strong>, the returned size will be zero. That means <strong>the ComboBox has nothing to calculate its own site against</strong> and it ends up looking the way it does.</div>
<p><span style="color:#515151;font-size:120%;"><strong></strong></span></p>
<p>Without having to dig too much into the inner workings of the ComboBox, I came up with the simplest possible solution to the problem:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:25px 10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2010/02/accept.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />We need to make sure that the <strong>ComboBox&#8217;s parent container is visible during the control&#8217;s initialization</strong> phase. That way the ComboBox&#8217;s size can correctly be calculated and assigned. Afterwards we can restore the parent container to its original state.</div>
<p>In order to achieve this I added the following code (lines 9-16 and 30-40) to the <strong>ComboBox.debug.js</strong> file:</p>
<p><pre class="brush: jscript; highlight: [9,10,11,12,13,14,15,16,30,31,32,33,34,35,36,37,38,39,40];">
AjaxControlToolkit.ComboBox.prototype = {

    initialize: function() {

        AjaxControlToolkit.ComboBox.callBaseMethod(this, 'initialize');

        // Workaround for issue #24251
        // http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=24251
        var hiddenParent = this._findHiddenParent(this.get_comboTableControl());
        var hiddenParentDisplay;

        if (hiddenParent != null) {
            hiddenParentDisplay = hiddenParent.style.display;
            hiddenParent.style.visibility = &quot;visible&quot;;
            hiddenParent.style.display = &quot;block&quot;;
        }

        this.createDelegates();
        this.initializeTextBox();
        this.initializeButton();
        this.initializeOptionList();
        this.addHandlers();

        if (hiddenParent != null) {
            hiddenParent.style.visibility = &quot;hidden&quot;;
            hiddenParent.style.display = hiddenParentDisplay;
        }

    },
    _findHiddenParent: function(element) {

        var parent = element.parentElement;

        if (parent == null || parent.style.visibility == &quot;hidden&quot;) {
            return parent;
        }

        return this._findHiddenParent(parent);

    }
</pre></p>
<p>Yes I know this isn’t the most elegant solution, but it works. After all, I said it was going to be pragmatic.</p>
<p>Once I made sure the patch worked correctly, I used the freely available <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35893"><strong>Microsoft Ajax Minifier</strong></a><strong>&#160;</strong>to produce a new ultra-compact (or <strong><a href="http://en.wikipedia.org/wiki/Minify">minified</a></strong>) version of the <strong>ComboBox.js</strong> file.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Integrating the workaround into the solution</strong></span></p>
<p>The workaround itself may not be a piece of art. However the way it got integrated into the existing ASP.NET web application is quite elegant in my opinion. Let me give a quick background first.</p>
<p>With ASP.NET Web Forms 3.5 Microsoft introduced a new mechanism for delivering JavaScript content into web pages. This is done by a specialized server control called the <strong><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx">ScriptManager</a></strong>.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:15px 10px 25px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />All controls that need some piece of JavaScript code to in order to work, have to register the required scripts with the <strong>ScriptManager</strong>. Its responsibility is to make sure that the links to the appropriate resources are ultimately included in the page output.</div>
<p>The ScriptManager obviously plays a central role in the ASP.NET Ajax infrastructure. However it has some great features too. In this case&#160; I’m referring to the possibility to substitute a JavaScript resource required by a server control with a local resource. <a href="http://www.hanselman.com">Scott Hanselman</a> wrote a <a href="http://www.hanselman.com/blog/ASPNETAjaxScriptCombiningAndMovingScriptResourceaxdsToStaticScripts.aspx">great article explaining how to take advantage of this feature</a>, which served me well in this case. </p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:45px 10px 25px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2010/02/accept.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />Since all JavaScript files contained in the Ajax Control Toolkit are <strong>statically compiled in the AjaxControlToolkit.dll assembly</strong>, the only way to replace the original ComboBox.js file with the patched one without having to deploy a recompiled version of the library, was to <strong>substitute the original reference within the ScriptManager</strong> and have it point to a local version of the file.</div>
<p>Here is how it was done:</p>
<p><pre class="brush: xml;">
&lt;asp:scriptmanager id=&quot;scmScriptManager&quot; runat=&quot;server&quot;&gt;
    &lt;scripts&gt;
        &lt;asp:scriptreference path=&quot;~/UI/Scripts/ComboBox.js&quot; name=&quot;AjaxControlToolkit.ComboBox.ComboBox.js&quot; assembly=&quot;AjaxControlToolkit, Version=3.0.30512.20315, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e&quot; /&gt;
    &lt;/scripts&gt;
&lt;/asp:scriptmanager&gt;
</pre></p>
<p>What about the original <strong>ComboBox.debug.js</strong> file? Well, the ScriptManager is smart enough to deliver the appropriate version of the file whenever debugging is enabled in the web application&#8217;s configuration file. This will work automatically as long as both files are located in the same folder on the server and are named according to the following convention:</p>
<ul>
<li><strong>Original:</strong> filename<em>.debug.</em>js </li>
<li><strong>Optimized:</strong> filename.js </li>
</ul>
<p>You can download the modified JavaScript files from the link at the end of this page. Note that <strong>they are based on and will work with the <a href="http://ajaxcontroltoolkit.codeplex.com/releases/view/27326">Ajax Control Toolkit release 3.0.30512</a></strong>.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Conclusions</strong></span></p>
<p>The Ajax support built into <a href="http://www.asp.net/"><strong>ASP.NET 3.5 Web Forms</strong></a> together with the control freely available in the <a href="http://www.codeplex.com/AjaxControlToolkit"><strong>Ajax Control Toolkit</strong></a> is a powerful combination. When used wisely it will allow you to get quite far in creating rich and interactive web pages without having to worry about JavaScript.<br />
  <br />However we all know that <a href="http://en.wikipedia.org/wiki/Leaky_abstraction">software abstractions are leaky</a>, and this is especially true for the one that is ASP.NET Web Forms. That means that sooner or later you will have to take control of what’s being sent down to the browser, whether it be the HTML markup, CSS stylesheets or JavaScript code. And when that time comes, you’d better be prepared.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-left:5px;padding-right:5px;">
<p style="margin-top:0;">
<img src="http://megakemp.files.wordpress.com/2009/07/download.gif?w=480" alt="Download" style="margin:10px 5px 0 10px;" /> Download <a href="http://cid-3e060a4c9d48a446.skydrive.live.com/self.aspx/Public/AjaxControlToolkit-ComboBox.js-patched.zip"><strong>Ajax Control Toolkit ComboBox JavaScript files</strong></a></p>
</div>
<p>/Enrico</p>
<br />Posted in .NET, Software Development Tagged: .NET, Ajax, ASP.NET, JavaScript, Web Forms <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/653/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/653/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=653&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2010/01/04/fixing-a-bug-in-asp-net-ajax-and-the-pain-of-leaky-abstractions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/01/aspnetajaxlogo.png" medium="image">
			<media:title type="html">AspNetAjaxLogo</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/03/ajaxcomboboxbugworking.png" medium="image">
			<media:title type="html">ASP.NET Ajax ComboBox control working</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/03/ajaxcomboboxbugbroken.png" medium="image">
			<media:title type="html">ASP.NET Ajax ComboBox control broken</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/02/remove.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/02/accept.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2010/02/accept.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/07/download.gif" medium="image">
			<media:title type="html">Download</media:title>
		</media:content>
	</item>
		<item>
		<title>Speed up your queries in SQL Server by being declarative</title>
		<link>http://megakemp.wordpress.com/2009/11/10/speed-up-your-queries-in-sql-server-by-being-declarative/</link>
		<comments>http://megakemp.wordpress.com/2009/11/10/speed-up-your-queries-in-sql-server-by-being-declarative/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 16:12:29 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Declarative Programming]]></category>
		<category><![CDATA[Imperative Programming]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=635</guid>
		<description><![CDATA[It’s interesting how a lot of the work I’ve been doing lately has in some way involved a kind of performance tuning. Previously I’ve talked about how to increase the performance of .NET applications by using delegates instead of reflection in code that runs frequently. This time it is all about performance in database processing. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=635&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It’s interesting how a lot of the work I’ve been doing lately has in some way involved a kind of performance tuning. Previously I’ve talked about <a href="http://megakemp.wordpress.com/2009/09/04/improving-performance-with-generic-delegates-in-net/">how to increase the performance of .NET applications</a> by using delegates instead of reflection in code that runs frequently.</p>
<p>This time it is all about performance in database processing.</p>
<p><span style="color:#515151;font-size:120%;"><strong>The scenario</strong></span></p>
<p>Imagine an application that manages a <strong>wait list</strong>. Users of this application put themselves in line and wait for their turn to gain access to some kind of shared resource. Here are the basic rules of this system:</p>
<ul>
<li>The same user can appear in the wait list multiple times, once for every resource she is queuing for. </li>
<li>The users’ position in the wait list at any given time is decided by a score. </li>
<li>This score is calculated based on the number of credits each user has in the system compared to the amount required by the resource they wish to access. </li>
</ul>
<p>Let’s say that this wait list is modeled in a <a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx"><strong>Microsoft SQL Server</strong></a> database with the following schema:</p>
<p><a href="http://megakemp.files.wordpress.com/2009/11/waitlistschema.png"><img style="border-bottom:0;border-left:0;display:block;float:none;border-top:0;border-right:0;margin:25px auto;" title="WaitListSchema" border="0" alt="WaitListSchema" src="http://megakemp.files.wordpress.com/2009/11/waitlistschema_thumb1.png?w=500&#038;h=317" width="500" height="317" /></a></p>
<p>The position of the different users in the wait list is periodically updated by a <a href="http://en.wikipedia.org/wiki/Stored_procedure"><strong>Stored Procedure</strong></a> that calculates the current score for each and every row in the <em>WaitList</em> table.</p>
<p>So far so good. Now, imagine that this <em>WaitList</em> table contains somewhere around <strong>30 millions rows</strong>, and the Stored Procedure that updates all of the scores takes about <strong>9 hours</strong> to complete. And now we have problem.</p>
<p>&#160;<span style="color:#515151;font-size:120%;"><strong>The imperative SQL approach</strong></span></p>
<p><span style="color:#515151;font-size:120%;"><strong></strong></span>Before going into all kinds of general database optimization techniques, let’s start off by looking at how that Stored Procedure is implemented.     <br />Here is a slightly simplified version of it:</p>
<p>  <pre class="brush: sql;">CREATE PROCEDURE CalculateWaitListScores_Imperative
AS
BEGIN

DECLARE @rowsToCalculate INT

SELECT @rowsToCalcualte = COUNT(*)
FROM WaitList
AND Score IS NULL

WHILE ( @rowsToCalculate &gt; 0 )
BEGIN

  DECLARE @userID INT
  DECLARE @resourceID INT
  DECLARE @score INT

  SELECT TOP 1 @userID = UserID, @resourceID = ResourceID
  FROM WaitList
  AND Score IS NULL

  -- The actual calculation of the score is omitted for clarity.
  -- Let's just say that it involves a SELECT query that joins
  -- the [WaitList] table with the [User] and [Resource] tables
  -- and applies a formula that associates the values
  -- of the [Credit] columns in each of them.
  -- For the sake of this example we just set it to a constant value
  SET @score = 150

  UPDATE WaitList
  SET Score = @score
  WHERE UserID = @userID
  AND ResourceID = @resourceID
  AND Score IS NULL

  SELECT @rowsToCalcualte = COUNT(*)
  FROM WaitList
  AND Score IS NULL

END

END</pre></p>
<p>If you aren’t into the <a href="http://en.wikipedia.org/wiki/Transact-SQL"><strong>Transact-SQL</strong></a> language syntax, let me spell out the algorithm for you:</p>
<ol>
<li>Get the number of rows in the <em>WaitList</em> table where the score has never been calculated </li>
<li>If there are any such rows, get the user and the resource IDs for the first row in the <em>WaitList</em> table where the score has never been calculated </li>
<li>Calculate the score for that user and resource </li>
<li>Update the score with the newly calculated value </li>
<li>Go to Step 1 </li>
</ol>
<p>In the worst case, this set of operations will be repeated 30 millions times, that is once for every row in the <em>WaitList</em> table. Think about it for a moment.</p>
<p>While looking at this code, I immediately imagined this dialogue taking place between SQL Server and the developer(s) who wrote the Stored Procedure:</p>
<blockquote>
<p>Developer: <em>Listen up, SQL Server. I want you to calculate a new score and update all of those 3o millions rows, but <strong>do it one row at a time</strong>.</em></p>
<p>SQL Server: <em>That’s easy enough, but I’m pretty sure I can find a faster way to do this, if you’ll let me.</em></p>
<p>Developer: <em>No, no. I want you to do exactly what I said. That way it’s easier for me to understand what’s going on and debug if any problem occurs.</em></p>
<p>SQL Server: <em>Alright, you’re the boss.</em></p>
</blockquote>
<p>Jokes aside, the bottom line here is this:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:25px 10px 10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/09/warning.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />By implementing database operations in an <strong>imperative manner</strong>, you effectively tie up the hands of the query execution engine, thus preventing it from performing a number of optimizations at runtime in order to speed things up.</div>
<p>And that basically means trading performance and scalability for more fine-grained control.</p>
<p>&#160;<span style="color:#515151;font-size:120%;"><strong>The declarative SQL approach</strong></span></p>
<p>Let’s see if we can make this Stored Procedure run any faster, by changing our approach to the problem altogether.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:15px 10px 10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />This time, we’ll tell the database what we want done in a <strong>declarative manner</strong>, and we’ll let the query execution engine figure out the best way to get the job done.</div>
<p>Here is a rewritten version of the original Stored Procedure:</p>
<p><pre class="brush: sql;">CREATE PROCEDURE CalculateWaitListScores_Declarative
AS
BEGIN

UPDATE WaitList
SET Score = dbo.CalculateScore(UserID, ResourceID)
WHERE Score IS NULL
	
END</pre></p>
<p>What we did is basically removing the explicit loop and merging all operations into a <strong>single UPDATE statement</strong> executed on the <em>WaitList</em> table, which invokes a custom a <strong>scalar function</strong> (<em>CalculateScore</em>) to calculate the score with the value of the current row.</p>
<p>Now, let’s look at some performance comparison:</p>
<p><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="WaitListPerfChart" border="0" alt="WaitListPerfChart" src="http://megakemp.files.wordpress.com/2009/11/waitlistperfchart.png?w=499&#038;h=323" width="499" height="323" /></p>
<p>That’s a pretty significant leap in speed. How is that possible? A look at the CPU usage on the database server while running the two versions of the Stored Procedure pretty much explains it all:</p>
<p>CPU usage while executing <em>CalculateWaitListScores_Imperative</em>:</p>
<p><img style="display:inline;border-width:0;margin:5px 0;" title="CpuUsageWithImperativeSql" border="0" alt="CpuUsageWithImperativeSql" src="http://megakemp.files.wordpress.com/2009/11/cpuusagewithimperativesql.png?w=504&#038;h=129" width="504" height="129" /></p>
<p>CPU usage while executing <em>CalculateWaitListScores_Declarative</em>:</p>
<p><img style="display:inline;border-width:0;margin:5px 0;" title="CpuUsageWithDeclarativeSql" border="0" alt="CpuUsageWithDeclarativeSql" src="http://megakemp.files.wordpress.com/2009/11/cpuusagewithdeclarativesql.png?w=504&#038;h=129" width="504" height="129" />&#160;</p>
<p>As you see, in the first picture the CPU is steadily at 9-10% and is basically using only one out of four available cores. This is because SQL Server is forced to do its work sequentially and has to wait until the score for the current row has been calculated and updated before proceeding to the next.</p>
<p>In the second picture, we are simply telling SQL Server our intent, rather than dictating exactly how it should be done. This allows SQL Server to parallelize the workload than can now be executed on multiple CPU/Cores at once leveraging the full power of the hardware.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Lessons learned</strong></span></p>
<p>Here are a couple of getaways I learned from this exercise:</p>
<ol>
<li>SQL is a declarative language at its core, designed to work with sets of rows. That’s what it does best and that’s how you should use it. </li>
<li>Whenever possible, try to avoid applying an imperative programming mindset when implementing database operations, even if&#160; the constructs available in SQL-derived languages like T-SQL make it easy to do so </li>
<li>Don’t be afraid to give up some control over what happens at runtime when your database code runs. Let the database find out the best way to do things, and get ready to experience some great performance improvements. </li>
</ol>
<p>Hope this helps.</p>
<p>/Enrico</p>
<br />Posted in Databases, Software Development Tagged: Declarative Programming, Imperative Programming, Performance, SQL, SQL Server, T-SQL <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/635/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=635&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2009/11/10/speed-up-your-queries-in-sql-server-by-being-declarative/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/11/waitlistschema_thumb1.png" medium="image">
			<media:title type="html">WaitListSchema</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/09/warning.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/11/waitlistperfchart.png" medium="image">
			<media:title type="html">WaitListPerfChart</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/11/cpuusagewithimperativesql.png" medium="image">
			<media:title type="html">CpuUsageWithImperativeSql</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/11/cpuusagewithdeclarativesql.png" medium="image">
			<media:title type="html">CpuUsageWithDeclarativeSql</media:title>
		</media:content>
	</item>
		<item>
		<title>Improving performance with generic delegates in .NET</title>
		<link>http://megakemp.wordpress.com/2009/09/04/improving-performance-with-generic-delegates-in-net/</link>
		<comments>http://megakemp.wordpress.com/2009/09/04/improving-performance-with-generic-delegates-in-net/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 15:57:40 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=596</guid>
		<description><![CDATA[Lately I have been involved in the performance profiling work of a Windows client application, which customers had lamented to be way too slow for their taste. The application was originally developed a couple of years ago on top of the .NET Framework 2.0. Its user interface is built using Windows Forms and it retrieves [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=596&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately I have been involved in the performance profiling work of a Windows client application, which customers had lamented to be way too slow for their taste.</p>
<p>The application was originally developed a couple of years ago on top of the .NET Framework 2.0. Its user interface is built using <a href="http://windowsclient.net/">Windows Forms</a> and it retrieves its data from a remote remote server through Web Services using <a href="http://msdn.microsoft.com/en-us/library/ba0z6a33(lightweight).aspx">ASMX</a>.</p>
<p>Everything worked just fine from a functionality standpoint. However customers complained over long delays as data was being retrieved from the Web Services and slowly populated the widgets on the screen.   <br />Something had to be done to speed things up.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Reflection is a bottleneck</strong></span></p>
<p>A look with a .NET profiler tool such as <strong><a href="http://www.jetbrains.com/profiler/">JetBrains DotTrace</a></strong> revealed that a lot of time was spent sorting large collections of objects by the value of one of their properties. This would typically be done before binding them to various list controls in the UI.     <br />The code would typically look like this and was spread out all over the code base:</p>
<p><pre class="brush: csharp;">// Retrieves the entire list of customers from the DAL
List&lt;Customer&gt; customerList = CustomerDAO.GetAll();

// Sorts the list of 'Customer' objects
// by the value of the 'FullName' property
customerList.Sort(new PropertyComparer(&quot;FullName&quot;));

// Binds the list to a ComboBox control for display
cmbCustomers.DataSource = customerList;</pre></p>
<p>Apparently <strong>line 6</strong> was the one that takes forever to execute. Now, since the sorting algorithm used in the <a href="http://msdn.microsoft.com/en-us/library/234b841s(lightweight).aspx">IList.Sort</a> method can&#8217;t be changed from outside the class, the weak link here must be the <strong>PropertyComparer</strong>. But what is it doing? Well, here it is:</p>
<p><pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Reflection;

namespace Thoughtology.Samples.Collections
{
    public class PropertyComparer&lt;T&gt; : IComparer&lt;T&gt;
    {
        private string propertyName;
    
        public PropertyComparer(string propertyName)
        {
            this.propertyName = propertyName;
        }
    
        public int Compare(T x, T y)
        {
            Type targetType = x.GetType();

            PropertyInfo targetProperty = targetType.GetProperty(propertyName);
    
            string xValueText = targetProperty.GetValue(x, null).ToString();
            string yValueText = targetProperty.GetValue(y, null).ToString();
     
            int xValueNumeric = Int32.Parse(xValueText);
            int yValueNumeric = Int32.Parse(yValueText);
    
            if (xValueNumeric &lt; yValueNumeric)
            {
                return -1;
            }
            else if (xValueNumeric == yValueNumeric)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
    }
}</pre></p>
<p>Likely not the prettiest code you have ever seen. However, it’s pretty easy to see what it’s doing:</p>
<ol>
<li>Extracts the value of the specified property from the input objects using <strong><a href="http://msdn.microsoft.com/en-us/library/f7ykdhsy(lightweight).aspx">reflection</a>.</strong></li>
<li>Converts that value to a String.</li>
<li>Parses the converted value to an Integer.</li>
<li>Compares the numeric values to decide which one is bigger.</li>
</ol>
<p>That seems like a lot of extra work for a simple value comparison to me.<br />
  <br />I&#8217;m sure the method was built that way for a reason. This <a href="http://msdn.microsoft.com/en-us/library/8ehhxeaf(lightweight).aspx">IComparer</a> class is designed to be “<em>generic</em>” and work on any type of value on any object. However my guess is that it won&#8217;t work with anything but primitive types (numbers, strings and booleans). In fact the default implementation of the <a href="http://msdn.microsoft.com/en-us/library/system.object.tostring(lightweight).aspx">Object.ToString()</a> (used in <strong>lines 22-23</strong>) method returns the fully qualified name of the class, and that usually doesn’t isn’t much of a sorting criteria in most cases.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/09/warning.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />The real performance bottleneck here is caused by the use of <strong>reflection</strong> inside of a method that is called hundreds if not thousands of times from all over the application.</div>
<p><span style="color:#515151;font-size:120%;"><strong>Use delegates instead</strong></span></p>
<p>At this point it is clear that we need to <a href="http://en.wikipedia.org/wiki/Code_refactoring">refactor</a><strong> </strong>this class to improve its performance and still retain its original functionality, that is to provide a generic way to compare object by the value of one of their properties.</p>
<p>The key is to find a better way to retrieve the value of a property from any type of object without having to use reflection.</p>
<p>Well, since we do know the type of the objects we are comparing through the generic parameter T, we could let the caller specify which value to compare the objects with by. This can be done by having the caller pass a reference to a method, which would return that value when invoked inside of the <a href="http://msdn.microsoft.com/en-us/library/system.collections.icomparer.compare(lightweight).aspx">Compare</a><strong> </strong>method. Let&#8217;s try it and see how it works.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Implementing the solution in .NET 2.0</strong></span></p>
<p>Since the application was on .NET 2.0, we need to define our own delegate type that will allow callers to pass the reference to a method returning the comparable value . Here is the complete implementation of the refactored PropertyComparer class:</p>
<p><pre class="brush: csharp;">using System;
using System.Collections.Generic;

namespace Thoughtology.Samples.Collections
{
    public class PropertyComparer&lt;T&gt; : IComparer&lt;T&gt;
    {
        public delegate IComparable ComparableValue(T arg);

        public PropertyComparer(ComparableValue propertySelector)
        {
            this.PropertySelector = propertySelector;
        }

        public ComparableValue PropertySelector { get; set; }

        public int Compare(T x, T y)
        {
            if (this.PropertySelector == null)
            {
                throw new InvalidOperationException(&quot;PropertySelector cannot be null&quot;);
            }

            IComparable firstValue = this.PropertySelector(x);
            IComparable secondValue = this.PropertySelector(y);

            return firstValue.CompareTo(secondValue);
        }
    }
}</pre></p>
<p>Our delegate, called <strong>ComparableValue</strong>, takes an object of the generic type T as input and returns a value to compare that object by.</p>
<p>The comparison itself is than performed by the returned value itself, by invoking the <a href="http://msdn.microsoft.com/en-us/library/system.icomparable.compareto(lightweight).aspx">IComparable.CompareTo</a> method on it (see <strong>line 27</strong>).</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;padding-bottom:10px;background-color:#fffbcc;padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;"><img style="border-right-width:0;display:inline;margin:10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24&#038;h=24" width="24" height="24" />All primitive types in .NET implement the <a href="http://msdn.microsoft.com/en-us/library/system.icomparable(lightweight).aspx">IComparable</a> interface. Custom objects can easily be compared in a semantically meaningful way by manually implementing that same interface.</div>
<p>The caller can now invoke the Sort method by specifying the property to compare the items by with an <strong><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k(lightweight).aspx">anoymous delegate</a></strong>:</p>
<p><pre class="brush: csharp;">customerList.Sort(new PropertyComparer(delegate(Customer c)
    {
        return c.FullName;
    });</pre></p>
<p>Notice how the property name is no longer passed a a string. Instead it is actually invoked on the object providing compile-time type checking.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Alternative implementation in .NET 3.5</strong></span></p>
<p>This same solution can be implemented slightly differently in .NET 3.5 by taking advantage of the built in <strong><a href="http://msdn.microsoft.com/en-us/library/bb549151(lightweight).aspx">Func&lt;T,TResult&gt;</a> </strong>delegate type:</p>
<p><pre class="brush: csharp;">using System;
using System.Collections.Generic;

namespace Thoughtology.Samples.Collections
{
    public class PropertyComparer&lt;T&gt; : IComparer&lt;T&gt;
    {
        public PropertyComparer(Func&lt;T, IComparable&gt; propertySelector)
        {
            this.PropertySelector = propertySelector;
        }

        public Func&lt;T, IComparable&gt; PropertySelector { get; set; }

        public int Compare(T x, T y)
        {
            if (this.PropertySelector == null)
            {
                throw new InvalidOperationException(&quot;PropertySelector cannot be null&quot;);
            }

            IComparable firstValue = this.PropertySelector(x);
            IComparable secondValue = this.PropertySelector(y);

            return firstValue.CompareTo(secondValue);
        }
    }
}</pre></p>
<p>Great, this saved us exactly one line of code.<br />Don&#8217;t worry, things get much nicer on the caller’s side where the anonymous delegate is substituted by a much more compact <strong><a href="http://msdn.microsoft.com/en-us/library/bb397687(lightweight).aspx">lambda expression</a></strong>:</p>
<p><pre class="brush: csharp;">customerList.Sort(new PropertyComparer(c =&gt; c.FullName));</pre></p>
<p><span style="color:#515151;font-size:120%;"><strong>The results</strong></span></p>
<p>Now that we put reflection out of the picture, it is a good time to run a simple test harness to see how the new comparison strategy performs. For this purpose we will sort an increasingly large collection of objects with the two <strong>PropertyComparer</strong> implementations and compare how long it takes to complete the operation. Here are the results in a graph:</p>
<p><img style="display:inline;border-width:0;" title="SortingPerformanceChart" border="0" alt="SortingPerformanceChart" src="http://megakemp.files.wordpress.com/2009/09/sortingperformancechart.png?w=461&#038;h=310" width="461" height="310" /></p>
<p>As you see, by using delegates the sorting algorithm stays on the linear O(n). On the other hand with reflection it quickly jumps over in the exponential O(c<sup>n</sup>) space, where c is the time it takes to make a single comparison.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Lessons learned</strong></span></p>
<p>This exercise teaches three general guidelines that can be applied when programming in .NET:</p>
<ul>
<li><strong>Reflection is expensive</strong>. Use it sparingly and avoid it whenever possible in code that is executed very often, such as loops. </li>
<li><strong>Generic delegates allow to build flexible code in a fast and strongly-typed fashion</strong>. This can be achieved by letting callers &#8220;<em>inject</em>&#8221; custom code into an algorithm by passing a delegate as argument to a method. The code referred to by the delegate will then be executed at the appropriate stage in the algorithm inside the method.</li>
<li>When reflection is used to dynamically invoke members on a class, the same thing can be achieved by using generic delegates instead, like demonstrated in this article. This technique is widely used by modern isolation frameworks such as <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>, <a href="http://code.google.com/p/moq/">Moq</a> and <a href="http://learn.typemock.com/typemock-isolator/">TypeMock Isolator</a>.</li>
</ul>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-left:5px;padding-right:5px;">
<p style="margin-top:0;">
<img src="http://megakemp.files.wordpress.com/2009/07/download.gif?w=480" alt="Download" style="margin:10px 5px 0 10px;" /> Download <a href="https://cid-3e060a4c9d48a446.skydrive.live.com/self.aspx/Public/Thoughtology.Samples.SortTest.zip"><strong>Sort Test Harness Sample</strong></a></p>
</div>
<p>/Enrico</p>
<br />Posted in .NET, Software Development Tagged: .NET, C#, Performance <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/596/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/596/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/596/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=596&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2009/09/04/improving-performance-with-generic-delegates-in-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/09/warning.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#38;h=24" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/09/sortingperformancechart.png" medium="image">
			<media:title type="html">SortingPerformanceChart</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/07/download.gif" medium="image">
			<media:title type="html">Download</media:title>
		</media:content>
	</item>
		<item>
		<title>Building an HTPC</title>
		<link>http://megakemp.wordpress.com/2009/08/19/building-an-htpc/</link>
		<comments>http://megakemp.wordpress.com/2009/08/19/building-an-htpc/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 20:41:07 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[HTPC]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=571</guid>
		<description><![CDATA[Almost exactly one year ago, I seriously started considering the problem of having the digital content I care about, mostly made up of music and pictures, scattered around different computers. At home I often found myself thinking “I wish I could watch this movie on the TV instead of sitting in front of a tiny [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=571&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Almost exactly one year ago, I seriously started considering the problem of having the digital content I care about, mostly made up of music and pictures, scattered around different computers. <img style="display:inline;border-width:0;margin:10px 0 10px 15px;" title="htpc" border="0" alt="htpc" align="right" src="http://megakemp.files.wordpress.com/2009/08/htpc.jpg?w=200&#038;h=94" width="200" height="94" />     <br />At home I often found myself thinking “<em>I wish I could watch this movie on the TV instead of sitting in front of a tiny monitor”</em>. At a friend’s house I would sometimes say “<em>I can’t show you the pictures of our last trip right now because they are on my other laptop</em>”<em>.      <br /></em>On top of that I started to have the creepy feeling that that not everything was backed up properly and on a regular basis, since it resided on different machines. This had become both annoying and worrying.</p>
<p>That’s how I got interested in <strong>Home Theater PC </strong>or <strong>HTPC</strong> for short.</p>
<p>My goal was to be able collect and organize all of my digital content in the form of music, pictures and movies <strong>in one central place</strong>, more precisely the living room, and to make it available to other PCs in the house as well as enjoying it on the TV’s big screen.</p>
<p>After looking at a couple of commercial products in that category (particularly <strong><a href="http://www.apple.com/macmini/">Apple Mac mini</a></strong> and <strong><a href="http://www.apple.com/appletv/">Apple TV</a></strong>) I realized the most common thing to do for a geek like me was to go off and build my own HTPC. This way I could pick and choose the hardware parts to build a machine that matches my specific needs.</p>
<p> <span style="color:#515151;font-size:120%;"><strong>The requirements</strong></span>
<p>A computer that wishes to rightfully be called an HTPC must have the following basic characteristics:</p>
<ul>
<li>Silent </li>
<li>Low power consumption </li>
<li>TV connectivity </li>
<li>Large storage capacity </li>
</ul>
<p>On top of that, my personal requirements were:</p>
<ul>
<li>Be able to play High Definition (HD) movies at high resolution (1080p) </li>
<li>Be able to play some occasional 3D game </li>
<li>Do not look like a computer but rather like some Audio-Video piece of equipment </li>
</ul>
<p><span style="color:#515151;font-size:120%;"><strong>The hardware</strong></span></p>
<p>Based on these requirements and my budget, I came up with the following hardware configuration:</p>
<table border="0" cellspacing="0" cellpadding="4" width="430">
<tbody>
<tr style="background-color:#ebebeb;">
<td width="209"><strong>Motherboard</strong></td>
<td width="219"><a href="http://www.gigabyte.com.tw/Products/Motherboard/Products_Overview.aspx?ProductID=2579">Gigabyte GA-MA69GM-S2H</a></td>
</tr>
<tr>
<td width="210"><strong>CPU</strong></td>
<td width="219"><a href="http://products.amd.com/en-us/DesktopCPUDetail.aspx?id=426">AMD Athlon X2 Dual-Core 4850e 2.5GH</a></td>
</tr>
<tr style="background-color:#ebebeb;">
<td width="210"><strong>Cooling</strong></td>
<td valign="middle" width="219"><a href="http://www.scythe-usa.com/product/cpu/032/scmnj1000_detail.html">Scythe Ninja Mini CPU Cooler</a></td>
</tr>
<tr>
<td width="210"><strong>Memory</strong></td>
<td valign="top" width="219">Kingston DDR2 PC6400 2048MB </td>
</tr>
<tr style="background-color:#ebebeb;">
<td width="210"><strong>Storage</strong></td>
<td valign="top" width="219">Western Digital 500 GB SATA</td>
</tr>
<tr>
<td width="210"><strong>Graphics Card</strong></td>
<td valign="top" width="219"><a href="http://eu.msi.com/index.php?func=proddesc&amp;maincat_no=130&amp;cat2_no=136&amp;prod_no=1195#">MSI GeForce 8600GT 256MB DDR3</a></td>
</tr>
<tr style="background-color:#ebebeb;">
<td width="210"><strong>Sound Card</strong></td>
<td valign="top" width="219">Integrated</td>
</tr>
<tr>
<td width="210"><strong>Case</strong></td>
<td valign="top" width="219"><a href="http://www.antec.com/Believe_it/product1.php?Type=Mg==&amp;id=NDk=">Antec Fusion 430 Silver</a></td>
</tr>
</tbody>
</table>
<p>There are some key points here that lead my decisions I should probably explain.</p>
<p>First of all I decided to go with the cheaper <strong><a href="http://www.amd.com/us/products/desktop/processors/athlon-x2/Pages/amd-athlon-x2-dual-core-processors-desktop.aspx">AMD Athlon X2</a></strong> CPU over an <strong><a href="http://www.intel.com/cd/products/services/emea/eng/processors/core2duo/300131.htm">Intel Core 2 Duo</a></strong>, since the performance gain I would get from the Intel processor wasn’t really that important to me to justify the higher price.     <br />Moreover the <a href="http://products.amd.com/en-us/DesktopCPUDetail.aspx?id=426">4850e</a> uses just 45W of electricity, which contributes in keeping the CPU cool and the power consumption low.</p>
<p>My choice of motherboard was based on a couple of factors:</p>
<ul>
<li>The Antec Fusion V2 case (really slick by the way), has only room for a <strong>Mini-ATX</strong> size motherboard </li>
<li>It has integrated <strong>High Definition Audio</strong> sound chip with support for 7.1 channels and DTS (Digital Theater Systems), which basically means great audio for music and movies </li>
<li>It also has a decent <strong>ATI Radeon X1250</strong> graphics chip with HDMI and TV-out ports integrated, which is nice to have in case my graphics card fails </li>
</ul>
<p>I wanted this computer to be <strong>silent</strong>, and since I’m not a huge fan of <a href="http://www.youtube.com/watch?v=We9xGpP1RWw">water cooling</a>, I figured the best way to keep the volume down would be to keep as few fans as possible.     <br />For this reason I substituted the stock CPU cooler that comes with the AMD processor with a <a href="http://www.scythe-usa.com/product/cpu/032/scmnj1000_detail.html"><strong>Scythe Ninja Mini</strong></a> heat sink (shown in the picture below). This would allow me to cool the CPU without needing a fan. Moreover its low profile fits well in the Antec Fusion case.</p>
<p><a href="http://megakemp.files.wordpress.com/2009/08/htpccpucooler.jpg"><img style="display:inline;border-width:0;margin:10px 5px 10px 8px;" title="HtpcCpuCooler" border="0" alt="HtpcCpuCooler" src="http://megakemp.files.wordpress.com/2009/08/htpccpucooler_thumb.jpg?w=384&#038;h=308" width="384" height="308" /></a></p>
<p>As a matter of personal preference, the graphics card had to be an <a href="http://www.nvidia.com/object/geforce_family.html">NVIDIA GeForce</a>. This particular <a href="http://megakemp.files.wordpress.com/2009/08/msigeforce8600gtheatpipe.jpg"><img style="display:inline;border-width:0;margin:10px 0 10px 15px;" title="MsiGeForce8600GTHeatpipe" border="0" alt="MsiGeForce8600GTHeatpipe" align="right" src="http://megakemp.files.wordpress.com/2009/08/msigeforce8600gtheatpipe_thumb.jpg?w=200&#038;h=133" width="200" height="133" /></a> model not only provides a nice price/performance balance, but is also extremely silent thanks to its <strong>fan-less passive cooling</strong> through a <strong><a href="http://en.wikipedia.org/wiki/Heat_pipe">heat pipe</a></strong>.     <br />The downside is that once installed in the case it takes up the equivalent space of two cards, due to the large heat sink on the backside.</p>
<p>The case was the most important (and expensive) piece of the whole configuration. I have to say the <strong><a href="http://www.antec.com/Believe_it/product1.php?Type=Mg==&amp;id=NDk=">Antect Fusion 430</a></strong> is a great case for an HTPC.<a href="http://megakemp.files.wordpress.com/2009/08/antecfusion430.jpg"><img style="display:inline;border-width:0;margin:5px 0 5px 15px;" title="AntecFusion430" border="0" alt="AntecFusion430" align="right" src="http://megakemp.files.wordpress.com/2009/08/antecfusion430_thumb.jpg?w=250&#038;h=91" width="250" height="91" /></a>&#160;&#160; <br />As far as aesthetics go, it makes a computer look like a fancy hi-fi amplifier with a shiny aluminum front panel. Moreover it has some nice features like an LCD screen with support for IR remotes and even a volume nod, contributing to the overall experience.</p>
<p>On the inside, it is designed to keep the hardware cool without being loud. It has two big fans positioned on one side of the case blowing cool air from the outside on the CPU and the graphics card, which are the hottest components in the system. </p>
<p><a href="http://megakemp.files.wordpress.com/2009/08/htpccpugpu.jpg"><img style="display:inline;border-width:0;margin:10px 5px 10px 8px;" title="HtpcCpuGpu" border="0" alt="HtpcCpuGpu" src="http://megakemp.files.wordpress.com/2009/08/htpccpugpu_thumb.jpg?w=404&#038;h=277" width="404" height="277" /></a></p>
<p>In this picture you can see the two fans on the left side directing the air flow towards the two giants heat sinks mounted on the CPU and GPU.</p>
<p><span style="color:#515151;font-size:120%;"><strong>The software</strong></span></p>
<p>After the build was done, I immediately installed Windows Vista Home Premium and the required device drivers on it to see how it performed.</p>
<p>Here is how Vista rates the system:</p>
<p><a href="http://megakemp.files.wordpress.com/2009/08/vistarating.png"><img style="display:inline;border-width:0;margin:5px;" title="VistaRating" border="0" alt="VistaRating" src="http://megakemp.files.wordpress.com/2009/08/vistarating_thumb.png?w=454&#038;h=242" width="454" height="242" /></a> </p>
<p>Playing HD movies encoded with the H.264 codec at 1080p on to a 40’’ flat HDTV is no problem at all. I use <a href="http://www.cyberlink.com/products/powerdvd/overview_en_US.html"><strong>Cyberlink PowerDVD 9</strong></a> which supports the <a href="http://www.nvidia.com/page/purevideo.html"><strong>NVIDIA PureVideo®</strong></a> feature to offload part of the rendering off to the GPU.</p>
<p>I have to admit I was a little worried that the two fans mounted in the Antec case weren’t enough to keep the system from overheating, especially when HTPC is inside of a closet under the TV.</p>
<p>So I decided to run the excellent <strong><a href="http://www.mersenne.org/freesoft/">Prime95</a></strong> tool to stress test the system and watch the CPU and GPU temperature with <strong><a href="http://www.cpuid.com/cpuz.php">CPU-Z</a></strong> and <strong><a href="http://www.techpowerup.com/gpuz/">GPU-Z</a></strong> respectively. The screenshots below show the temperature measured at the two CPU cores when the system is idle (on top) and when running under load (below):</p>
<p><a href="http://megakemp.files.wordpress.com/2009/08/coretempidle.png"><img style="display:inline;border-width:0;margin:8px 5px 8px 8px;" title="CoreTempIdle" border="0" alt="CoreTempIdle" src="http://megakemp.files.wordpress.com/2009/08/coretempidle_thumb.png?w=384&#038;h=379" width="384" height="379" /></a> <a href="http://megakemp.files.wordpress.com/2009/08/coretempload.png"><img style="display:inline;border-width:0;margin:20px 5px 8px 8px;" title="CoreTempLoad" border="0" alt="CoreTempLoad" src="http://megakemp.files.wordpress.com/2009/08/coretempload_thumb.png?w=384&#038;h=381" width="384" height="381" /></a> </p>
<p>It seems that the passive cooling is doing a pretty good job at keeping the CPU and GPU at low temperatures, even when the system is put under heavy load.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Conclusion</strong></span></p>
<p>So far I&#8217;ve been pretty satisfied with the HTPC I&#8217;ve built. It fits well into the living room thanks to its specially designed case and it’s silent enough that I can’t even tell when it’s turned on or off (OK, I can always look at the power led on the front panel). Also it does everything I need it to without issues.</p>
<p>Having a PC working as media center instead of a proprietary custom device such as the Apple TV, definitely is the most flexible choice in terms of what software you can run. It also allows you to tweak the system to your preference, which is a requirement in itself for anyone with a passion for technology.</p>
<p>/Enrico</p>
<br />Posted in Technology Tagged: Hardware, HTPC <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/571/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/571/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/571/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=571&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2009/08/19/building-an-htpc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/htpc.jpg" medium="image">
			<media:title type="html">htpc</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/htpccpucooler_thumb.jpg" medium="image">
			<media:title type="html">HtpcCpuCooler</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/msigeforce8600gtheatpipe_thumb.jpg" medium="image">
			<media:title type="html">MsiGeForce8600GTHeatpipe</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/antecfusion430_thumb.jpg" medium="image">
			<media:title type="html">AntecFusion430</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/htpccpugpu_thumb.jpg" medium="image">
			<media:title type="html">HtpcCpuGpu</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/vistarating_thumb.png" medium="image">
			<media:title type="html">VistaRating</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/coretempidle_thumb.png" medium="image">
			<media:title type="html">CoreTempIdle</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/08/coretempload_thumb.png" medium="image">
			<media:title type="html">CoreTempLoad</media:title>
		</media:content>
	</item>
		<item>
		<title>Isolating WCF through Dependency Injection &#8211; Part II</title>
		<link>http://megakemp.wordpress.com/2009/07/02/isolating-wcf-through-dependency-injection-part-ii/</link>
		<comments>http://megakemp.wordpress.com/2009/07/02/isolating-wcf-through-dependency-injection-part-ii/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 09:02:27 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Unit testing]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=479</guid>
		<description><![CDATA[In my previous post, I talked about how to design a class that uses a WCF client proxy in such a way to make it testable in unit tests, without having to spin up a real service to answer the requests. The technique I illustrated uses a particular Inversion of Control (IoC) principle called Dependency [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=479&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://megakemp.wordpress.com/2009/06/25/isolating-wcf-through-dependency-injection-part-i/">my previous post</a>, I talked about how to design a class that uses a WCF client proxy in such a way to make it <strong>testable in unit tests, without having to spin up a real service to answer the requests</strong>.     <br />The technique I illustrated uses a particular <strong>Inversion of Control</strong> (IoC) principle called <strong>Dependency Injection</strong> (DI), in which objects that a given class depends on get pushed into it from the outside rather than being created internally.</p>
<p>In this particular case, the external dependency is represented by a WCF client proxy targeting a particular service. This approach enables me to swap the real proxy objects used in production with <a href="http://www.martinfowler.com/bliki/TestDouble.html">test doubles</a> while running unit tests, making it possible to assert the class&#8217;s behavior in a completely isolated and controlled environment.</p>
<p>  <span style="color:#515151;font-size:120%;"><strong>Moving from concrete classes to interfaces</strong></span>
<p>Last time we left off with a <em>MailClient</em> class that takes an instance of <em>ChannelFactory&lt;MailServiceClientChannel&gt;</em> in the constructor and uses it internally every time it needs to download Email messages by following three steps:</p>
<ol>
<li>Creating a new proxy instance configured to communicate with the remote <em>MailService</em> service </li>
<li>Invoking the <em>GetMessages</em> operation on the service </li>
<li>Disposing the proxy </li>
</ol>
<p>However, as I pointed out before, being the <a href="http://msdn.microsoft.com/en-us/library/ms576132.aspx">ChannelFactory&lt;TChannel&gt;</a> a concrete class, creating a <a href="http://www.martinfowler.com/bliki/TestDouble.html">test double</a> for it isn’t very convenient. A much better approach would be having the MailClient class<strong> interact with an interface instead</strong>. This way it would be easy to create a <strong>fake factory object</strong> in unit tests and have the class use that instead of the real one.</p>
<p>After a quick look in the online MSDN Documentation I found that the <a href="http://msdn.microsoft.com/en-us/library/ms576132.aspx">ChannelFactory&lt;TChannel&gt;</a> class indeed implements the <a href="http://msdn.microsoft.com/en-us/library/ms405876.aspx">IChannelFactory&lt;TChannel&gt;</a> interface. “<em>Sweet, I can use that!</em>” I thought. But there’s a catch:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-right:10px;padding-bottom:10px;"><img style="border-right-width:0;display:inline;margin:25px 10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24" width="24" height="24" /><br />
The <a href="http://msdn.microsoft.com/en-us/library/ms195571.aspx">IChannelFactory&lt;TChannel&gt;.CreateChannel</a> factory method requires the caller to pass along an <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.endpointaddress.aspx">EndpointAddress</a> object, which contains information about <strong>where</strong> and <strong>how</strong> to reach the service, like the URI and the <a href="http://msdn.microsoft.com/en-us/magazine/cc163394.aspx">Binding</a>.</div>
<p>This isn’t really what I wanted, since it forced the MailClient class to have knowledge of where the remote service is located or at the very least how to obtain that piece of information. This doesn’t really conform to the Dependency Injection principle, since these details naturally belong to the dependent object, and should therefore be handled outside the scope of the class.</p>
<p> <span style="color:#515151;font-size:120%;"><strong>The ChannelFactory adapter</strong></span>
<p>The solution I came up with is to create an <a href="http://sourcemaking.com/design_patterns/adapter">adapter interface</a> to hide these details from my class. The implementation of this interface would then wrap a properly configured instance of <a href="http://msdn.microsoft.com/en-us/library/ms576132.aspx">ChannelFactory&lt;TChannel&gt;</a> and delegate all the calls it receives to it. </p>
<p>Here is the definition of the adapter interface:</p>
<p><pre class="brush: csharp;">
using System.ServiceModel;

public interface IClientChannelFactory&lt;TChannel&gt;
    where TChannel : IClientChannel 
{ 
    void Open(); 

    void Close(); 

    void Abort(); 

    TChannel CreateChannel(); 
}
</pre> </p>
<p>And here is the default implementation:</p>
<p><pre class="brush: csharp;"> 
using System; 
using System.ServiceModel; 

public class ClientChannelFactory&lt;TChannel&gt; : IClientChannelFactory&lt;TChannel&gt;
    where TChannel : IClientChannel 
{ 
    private ChannelFactory&lt;TChannel&gt; factory; 

    public ClientChannelFactory(string endpointConfigurationName) 
    { 
        this.factory = new ChannelFactory&lt;TChannel&gt;(endpointConfigurationName); 
    } 

    public void Open() 
    { 
        this.factory.Open(); 
    } 

    public void Close() 
    { 
        this.factory.Close(); 
    } 

    public void Abort() 
    { 
        this.factory.Abort(); 
    } 

    public TChannel CreateChannel() 
    { 
        return this.factory.CreateChannel(); 
    } 
}
</pre> </p>
<p>As you can see by using generics we are able to create an implementation that works for different types of proxies.<br />
  <br />Notice also that the class requires the callers to specify the name of the configuration element used to describe the service endpoint in the constructor. This way the MailClient class&#160; is completely isolated from having to know about WCF configuration details, and can instead concentrate on its core responsibility, that is to invoke operations on the service and work with the results.</p>
<p>Here is the final MailClient implementation:</p>
<p><pre class="brush: csharp;">
public class MailClient 
{ 
    private IClientChannelFactory&lt;IMailServiceClientChannel&gt; proxyFactory; 

    public MailClient(IClientChannelFactory&lt;IMailServiceClientChannel&gt; proxyFactory) 
    { 
        this.proxyFactory = proxyFactory; 
    } 

    public EmailMessage[] DownloadMessages(string smtpAddress) 
    { 
        // Validate the specified Email address 
        
        IMailServiceClientChannel proxy; 
        
        try 
        { 
            proxy = proxyFactory.CreateChannel(); 

            Mailbox request = new Mailbox(smtpAddress); 
            EmailMessage[] response = proxy.GetMessages(request) 

            // Do some processing on the results 

            proxy.Close(); 
            
            return response; 
        } 
        catch(Exception e) 
        { 
            proxy.Abort(); 

            throw new MailClientException(&amp;quot;Failed to download Email messages&amp;quot;, e); 
        } 
    } 
}
</pre></p>
<p>The only modification is in the type of the argument declared in the constructor, which is now an interface.</p>
<p><span style="color:#515151;font-size:120%;"><strong>Finally unit testing</strong></span></p>
<p>We are now able to test our class in isolation by creating fake objects that implement the <i>IClientChannelFactory</i> and <i>IMailServiceClientChannel</i> interfaces respectively, and inject them into our object under test.</p>
<p>In this particular example I am using <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a> as an isolation framework to create and manage test doubles, but I could as well used just about any other isolation framework out there, such as <a href="http://www.typemock.com/">Typemock Isolator</a>, with the same result.</p>
<p><pre class="brush: csharp;">
using Microsoft.VisualStudio.TestTools.UnitTesting; 
using Rhino.Mocks; 

[TestClass] 
public class MailClientTest 
{ 
    [TestMethod] 
    public void DownloadMessages_WithValidEmailAddress_ReturnsOneMessage() 
    { 
        // Fakes out the WCF proxy
        var stubProxy = MockRepository.CreateStub&lt;IMailServiceClientChannel&gt;(); 

        // Stubs the service operation invoked by the class under test
        stubProxy
            .Stub(m =&gt; m.GetMessages(Arg&lt;string&gt;.Is.Anything))
            .Returns(new EmailMessage[0]);

        // Fakes out the WCF proxy factory
        var stubProxyFactory = MockRepository.CreateStub&lt;IClientChannelFactory&lt;IMailServiceClientChannel&gt;&gt;();

        // Stubs the factory method to return the mocked proxy
        stubProxyFactory 
            .Stub(s =&gt; s.CreateChannel()) 
            .Return(stubProxy);
 
        var testObject = new MailClient(stubProxyFactory); 

        EmailMessage[] results = testObject.DownloadMessages(&quot;test@test.com&quot;); 

        Assert.AreEqual(0, results.Length, &quot;The method was not supposed to return any results&quot;);
    } 
}
</pre> </p>
<p>This concludes this short series of posts on how to apply Dependency Injection to classes that consume WCF services in order to easily test them in isolation with unit tests. I hope this helps.</p>
<p>/Enrico</p>
<br />Posted in .NET, Software Development Tagged: .NET, Best Practices, IoC, Unit testing, WCF <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/479/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/479/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/479/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=479&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2009/07/02/isolating-wcf-through-dependency-injection-part-ii/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png" medium="image">
			<media:title type="html">info</media:title>
		</media:content>
	</item>
		<item>
		<title>Isolating WCF through Dependency Injection &#8211; Part I</title>
		<link>http://megakemp.wordpress.com/2009/06/25/isolating-wcf-through-dependency-injection-part-i/</link>
		<comments>http://megakemp.wordpress.com/2009/06/25/isolating-wcf-through-dependency-injection-part-i/#comments</comments>
		<pubDate>Thu, 25 Jun 2009 20:59:54 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Unit testing]]></category>
		<category><![CDATA[Unity]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=460</guid>
		<description><![CDATA[I have to admit that in the beginning I didn’t think Inversion of Control (IoC) Containers were that big of a deal. The idea of relying on an external agent to manage all the associations between objects in an application, sounded like it would bring more problems than advantages. Overkill. But I was wrong. Since [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=460&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have to admit that in the beginning I didn’t think <strong>Inversion of Control (IoC) Containers</strong> were that big of a deal. The idea of relying on an external agent to manage all the associations between objects in an application, sounded like it would bring more problems than advantages. Overkill. But I was wrong.</p>
<p>Since I began using IoC containers in my projects, I found that it naturally leads to loosely-coupled structures in the software.&#160; <br />This is due to two key design principles that an IoC container will enforce you to follow:</p>
<ul>
<li>Classes must explicitly <strong>state their dependencies</strong> with other classes as part of their public interface. </li>
<li>Classes never interact with each other directly, but only <strong>through interfaces</strong> that describe a set of capabilities in an abstract manner. </li>
</ul>
<p>This decoupling contributes in making the software easily testable and ready for evolution.</p>
<p><span style="font-size:120%;color:#515151;"><strong>Giving up control of WCF clients</strong></span></p>
<p>In my last project I was designing classes that would need to interact with different Web Services through WCF client proxies.<br />I needed to test those classes in isolation in my unit tests, without having to have my WCF service host process running in the background, so I figured I would let an instance of a WCF proxy be pushed from outside the classes through an interface, as a <strong>dependency</strong>, instead of creating it internally, like I would normally do.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;padding-right:10px;padding-bottom:10px;"><img style="border-right-width:0;display:inline;margin:10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24" width="24" height="24" /> This idea fits well with the way tools like <strong>svcutil</strong> and <strong>Visual Studio 2008</strong> work when generating WCF client proxies, since they create a class as well as interfaces exposing the operations that can be invoked through the proxy.</div>
<p>So here is my first implementation:</p>
<p><pre class="brush: csharp;">
public class MailClient
{
    private IMailServiceClientChannel proxy;

    public MailClient(IMailServiceClientChannel proxy)
    {
        this.proxy = proxy;
    }

    public EmailMessage[] DownloadMessages(string smtpAddress)
    {
        // Validate the specified Email address

        Mailbox request = new Mailbox(smtpAddress);
        EmailMessage[] response = proxy.GetMessages(request)

        // Do some processing on the results

        return response;
    }
}
</pre></p>
<p>Here I am using the <strong>IMailServiceClientChannel</strong> interface that is automatically generated by Visual Studio when adding a service proxy with the <a href="http://msdn.microsoft.com/en-us/library/bb386382.aspx"><strong>Add Service Reference</strong></a> dialog. This interface contains the signatures of all the operations that are part of the service contract, as well as WCF-specific infrastructure methods to manage the proxy, like <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.iclientchannel.open.aspx">Open</a> and <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.iclientchannel.close.aspx">Close</a>.</p>
<p><span style="font-size:120%;color:#515151;"><strong>Something is missing</strong></span></p>
<p>This didn&#8217;t feel quite right. I was not treating the WCF proxy like I should since I was not closing it properly after being done with it, and not having any sort of error handling code.</p>
<p>However, at a second thought, I realized this wasn’t really the responsibility of my class. Since <strong>I wasn’t creating the proxy instance myself but was instead receiving from the outside, I couldn’t really dispose it inside my method</strong>, because it could still be needed by the caller. So here is an alternative implementation:</p>
<p><pre class="brush: csharp;">
public class MailClient
{
    private ChannelFactory&lt;IMailServiceClientChannel&gt; proxyFactory;

    public MailClient(ChannelFactory&lt;IMailServiceClientChannel&gt; proxyFactory)
    {
        this.proxyFactory = proxyFactory;
    }

    public EmailMessage[] DownloadMessages(string smtpAddress)
    {
        // Validate the specified Email address
        
        IMailServiceClientChannel proxy;
        
        try
        {
            proxy = proxyFactory.CreateChannel();

            Mailbox request = new Mailbox(smtpAddress);
            EmailMessage[] response = proxy.GetMessages(request)

            // Do some processing on the results

            proxy.Close();
            
            return response;
        }
        catch(Exception e)
        {
            proxy.Abort();

            throw new MailClientException(&quot;Failed to download Email messages&quot;, e);
        }
    }
}
</pre></p>
<p>This time instead of using a proxy instance, the class receives a <strong><a href="http://msdn.microsoft.com/en-us/library/ms576132.aspx">ChannelFactory instance</a></strong> as an external dependency through the constructor.</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:#fffbcc;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding-top:10px;padding-right:10px;padding-bottom:10px;"><img style="border-right-width:0;display:inline;margin:10px;" title="info" border="0" alt="info" align="left" src="http://megakemp.files.wordpress.com/2009/06/info.png?w=24&#038;h=24" width="24" height="24" />Channel factories in WCF are the facilities used to create the pipelines, through which incoming and outgoing messages pass before being dispatched to the receiver or sent out over the wire.</div>
<p>This approach allows me to create a new proxy instances by invoking the <a href="http://msdn.microsoft.com/en-us/library/ms575250.aspx">ChannelFactory.CreateChannel</a> method ad-hoc inside the class and to properly dispose them as soon as I no longer need them.</p>
<p>According to <a href="http://blogs.msdn.com/wenlong/default.aspx">sources inside the WCF team at Microsoft</a>, it is <a href="http://blogs.msdn.com/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx">a best practice to create proxies by reusing the same ChannelFactory object</a>, instead of creating a new proxy objects from the class generated by Visual Studio, since the cost of initializing the factory is paid only once.</p>
<p>This turns out to be a much better approach to assign WCF proxies to classes through <strong>Dependency Injection (DI)</strong> because now I can create instances of the <strong>MailClient</strong> class using my IoC of choice, which happens to be <a href="http://www.codeplex.com/unity">Microsoft Unity</a>, with a couple of lines of code:</p>
<p><pre class="brush: csharp;">
// Registers the ChannelFactory class with Unity
// and specifies the name of the endpoint to use
// as stated in the configuration file
var container = new UnityContainer();
container
    .RegisterType&lt;ChannelFactory&lt;IMailServiceClientChannel&gt;&gt;()
        .Configure&lt;InjectedMembers&gt;()
            .ConfigureInjectionFor&lt;ChannelFactory&lt;IMailServiceClientChannel&gt;&gt;(new InjectionConstructor(&quot;localMailServiceEndpoint&quot;));

var client = container.Resolve&lt;MailClient&gt;();

// The object has now its dependencies already setup
// and is ready to be used
client.DownloadMessages(&quot;enrico@somedomain.com&quot;);
</pre></p>
<p>Here I&#8217;m registering the <strong>ChannelFactory</strong> class with the IoC container, telling it to pass the string <em>&#8220;localMailServiceEndpoint&#8221;</em> in the constructor whenever a new instance is created.<br />The ChannelFactory will use that value to look up in the <strong>configuration file</strong> the URL where the service is located and the protocol it should use to communicate with it, like in this sample WCF configuration:</p>
<p><pre class="brush: xml;">
&lt;configuration&gt;
    &lt;system.serviceModel&gt;
        &lt;client&gt;
            &lt;endpoint
                name=&quot;localMailServiceEndpoint&quot;
                address=&quot;http://localhost/mailservice&quot;
                binding=&quot;wsHttpBinding&quot;
                contract=&quot;IMailServiceClient&quot; /&gt;
        &lt;/client&gt;
    &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre></p>
<p>With this information in place, I&#8217;m now able to ask the container to construct an instance of the <strong>MailClient</strong> class, and it will automatically resolve the dependency on the WCF ChannelFactory for me.</p>
<p><span style="font-size:120%;color:#515151;"><strong>What about testability?</strong></span></p>
<p>Well, the <a href="http://msdn.microsoft.com/en-us/library/ms576132.aspx">ChannelFactory</a> is a concrete class and, although certanly possible, <strong>can’t easily be faked out (through mocks or stubs)</strong> by using one of the common <del datetime="2009-07-06T07:39:13+00:00">mocking</del> isolation frameworks available out there, since it requires the presence of a configuration file with the proper WCF-specific settings in order to work correctly. This makes the MailClient class still hard to test in isolation.</p>
<p>In my <a href="http://megakemp.wordpress.com/2009/07/02/isolating-wcf-through-dependency-injection-part-ii/">next post</a> I will explain a way to modify this sample to be able to write unit test for classes that use WCF proxies.</p>
<p>/Enrico</p>
<br />Posted in .NET, Software Development Tagged: .NET, Best Practices, IoC, Unit testing, Unity, WCF <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/460/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=460&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2009/06/25/isolating-wcf-through-dependency-injection-part-i/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png" medium="image">
			<media:title type="html">info</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2009/06/info.png" medium="image">
			<media:title type="html">info</media:title>
		</media:content>
	</item>
	</channel>
</rss>
