<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns: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/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Thoughtology</title>
	
	<link>http://megakemp.com</link>
	<description>The art of thinking about technology</description>
	<lastBuildDate>Thu, 16 May 2013 13:02:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain="megakemp.com" port="80" path="/?rsscloud=notify" registerProcedure="" protocol="http-post" />
<image>
		<url>http://1.gravatar.com/blavatar/3c23d5ca864e4cdac09348530fb3a7c6?s=96&amp;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Thoughtology</title>
		<link>http://megakemp.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://megakemp.com/osd.xml" title="Thoughtology" />
	
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Thoughtology" /><feedburner:info uri="thoughtology" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://megakemp.com/?pushpress=hub" /><creativeCommons:license>http://creativecommons.org/licenses/by-sa/3.0/</creativeCommons:license><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FThoughtology" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2FThoughtology" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><item>
		<title>General-purpose customizations with AutoFixture</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/7KsmwgzT2uY/</link>
		<comments>http://megakemp.com/2013/04/16/general-purpose-customizations-with-autofixture/#comments</comments>
		<pubDate>Tue, 16 Apr 2013 21:10:05 +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[TDD]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://megakemp.com/?p=1310</guid>
		<description><![CDATA[If you&#8217;ve been using AutoFixture in your tests for more than a while, chances are you&#8217;ve already come across the concept of customizations. If you&#8217;re not familiar with it, let me give you a quick introduction: A customization is a group of settings that, when applied to a given Fixture object, control the way AutoFixture [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1310&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;ve been using <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a> in your tests for more than a while, chances are you&#8217;ve already come across the concept of customizations. If you&#8217;re not familiar with it, let me give you a quick introduction:</p>
<div style="background-color:#fffbcc;padding:10px;border:#e6db55 1px solid;">A <strong>customization</strong> is a group of settings that, when applied to a given <code>Fixture</code> object, control the way AutoFixture will create instances for the types requested through that <code>Fixture</code>.</div>
<p>At this point you might find yourself feeling an irresistible urge to know everything there&#8217;s to know about customizations. If that&#8217;s the case, don&#8217;t worry. There are <a href="http://www.google.com/search?q=AutoFixture+customizations">a few resources</a> online where you learn more about them. For example, I wrote about <a href="http://megakemp.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations">how to take advantage of customizations</a> to group together test data related to specific scenarios.</p>
<p>In this post I&#8217;m going to talk about something different which, in a sense, is quite the opposite of that: how to write <em>general-purpose customizations</em>.</p>
<h2>A (user) story about cooking</h2>
<p>It&#8217;s hard to talk about test data without a bit of context. So, for the sake of this post, I thought we would pretend to be working on a somewhat realistic project. The system we&#8217;re going to build is an online catalogue of food recipies. The domain, at the very basic level, consists of three concepts:</p>
<ul>
<li><strong>Cookbook</strong></li>
<li><strong>Recipes</strong></li>
<li><strong>Ingredients</strong></li>
</ul>
<div id="domainmodel" class="wp-caption aligncenter" style="width: 490px"><a href="http://megakemp.files.wordpress.com/2013/04/domain.png"><img src="http://megakemp.files.wordpress.com/2013/04/domain.png?w=480&#038;h=56" alt="Basic domain model for a recipe catalogue." width="480" height="56" class="size-large wp-image-1312" /></a><p class="wp-caption-text">Basic domain model for a recipe catalogue.</p></div>
<p>Now, let&#8217;s imagine that in our backlog of requirements we have one where the user wishes to be able to search for recepies that contain a specific set of ingredients. Or in other words:</p>
<div style="background-color:#c7edaf;border:#548e2e 1px solid;border-radius:12.5px;margin-bottom:25px;padding:12px;text-align:left;">
<em>As a foodie, I want to know which recipes I can prepare with the ingredients I have,<br />
so that I can get the best value for my groceries.</em>
</div>
<h2>From the tests&#8230;</h2>
<p>As usual, we start out by translating the requirement at hand into a set of acceptance tests. In order do that, we need to tell AutoFixture how we&#8217;d like the test data for our domain model to be generated.</p>
<p>For this particular scenario, we need every <code>Ingredient</code> created in the test fixture to be <em>randomly chosen from a fixed pool of objects</em>. That way we can ensure that all recepies in the cookbook will be made up of the <em>same set of ingredients</em>.</p>
<p>Here&#8217;s how such a customization would look like:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class RandomIngredientsFromFixedSequence : ICustomization
{
    private readonly Random randomizer = new Random();
    private IEnumerable&lt;Ingredient&gt; sequence;

    public void Customize(IFixture fixture)
    {
        InitializeIngredientSequence(fixture);
        fixture.Register(PickRandomIngredientFromSequence);
    }

    private void InitializeIngredientSequence(IFixture fixture)
    {
        this.sequence = fixture.CreateMany&lt;Ingredient&gt;();
    }

    private Ingredient PickRandomIngredientFromSequence()
    {
        var randomIndex = this.randomizer.Next(0, sequence.Count() - 1);
        return sequence.ElementAt(randomIndex);
    }
}
</pre>
<p>Here we&#8217;re creating a pool of ingredients and telling AutoFixture to randomly pick one of those every time it needs to create an <code>Ingredient</code> object by using the <code>Fixture.Register&lt;T&gt;</code> method.</p>
<p>Since we&#8217;ll be using <a href="https://xunit.codeplex.com">Xunit</a> as our test runner, you can take advantage of the <a href="http://blog.ploeh.dk/2010/10/08/AutoDataTheorieswithAutoFixture">AutoFixture Data Theories</a> to keep our tests succinct by using AutoFixture in a declarative fashion. In order to do so, we need to write an <a href="http://stackoverflow.com/a/9110623/26396">xUnit Data Theory</a> attribute that tells AutoFixture to use our new customization:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class CookbookAutoDataAttribute : AutoDataAttribute
{
    public CookbookAutoDataAttribute()
        : base(new Fixture().Customize(
                   new RandomIngredientsFromFixedSequence())))
    {
    }
}
</pre>
<p>If you prefer to use AutoFixture directly in your tests, the imperative equivalent of the above is:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
var fixture = new Fixture();
fixture.Customize(new RandomIngredientsFromFixedSequence());
</pre>
<p>At this point, we can finally start writing the acceptance tests to satisfy our original requirement:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class When_searching_for_recipies_by_ingredients
{
    [Theory, CookbookAutoData]
    public void Should_only_return_recipes_with_a_specific_ingredient(
        Cookbook sut,
        Ingredient ingredient)
    {
        // When
        var recipes = sut.FindRecipies(ingredient);
        // Then
        Assert.True(recipes.All(r =&gt; r.Ingredients.Contains(ingredient)));
    }

    [Theory, CookbookAutoData]
    public void Should_include_new_recipes_with_a_specific_ingredient(
        Cookbook sut,
        Ingredient ingredient,
        Recipe recipeWithIngredient)
    {
        // Given
        sut.AddRecipe(recipeWithIngredient);
        // When
        var recipes = sut.FindRecipies(ingredient);
        // Then
        Assert.Contains(recipeWithIngredient, recipes);
    }
}
</pre>
<p>Notice that during these tests AutoFixture will have to create <code>Ingredient</code> objects in a couple of different ways:</p>
<ul>
<li><strong>indirectly</strong> when constructing <code>Recipe</code> objects associated to a <code>Cookbook</code></li>
<li><strong>directly</strong> when providing arguments for the test parameters</li>
</ul>
<p>As far as AutoFixture is concerned, it doesn&#8217;t really matter which code path leads to the creation of ingredients. The algorithm provided by the <code>RandomIngredientsFromFixedSequence</code> customization will apply in all situations.</p>
<h2>&#8230;to the implementation</h2>
<p>After a couple of <a href="http://www.jamesshore.com/Blog/Red-Green-Refactor.html">Red-Green-Refactor</a> cycles spawned from the above tests, it&#8217;s not completely unlikely that we might end up with some production code similar to this:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
// Cookbook.cs
public class Cookbook
{
    private readonly ICollection&lt;Recipe&gt; recipes;

    public Cookbook(IEnumerable&lt;Recipe&gt; recipes)
    {
        this.recipes = new List&lt;Recipe&gt;(recipes);
    }

    public IEnumerable&lt;Recipe&gt; FindRecipies(params Ingredient[] ingredients)
    {
        return recipes.Where(r =&gt; r.Ingredients.Intersect(ingredients).Any());
    }

    public void AddRecipe(Recipe recipe)
    {
        this.recipes.Add(recipe);
    }
}

// Recipe.cs
public class Recipe
{
    public readonly IEnumerable&lt;Ingredient&gt; Ingredients;

    public Recipe(IEnumerable&lt;Ingredient&gt; ingredients)
    {
        this.Ingredients = ingredients;
    }
}

// Ingredient.cs
public class Ingredient
{
    public readonly string Name;

    public Ingredient(string name)
    {
        this.Name = name;
    }
}
</pre>
<p>Nice and simple. But let&#8217;s not stop here. It&#8217;s time to take it a bit further.</p>
<h2>An opportunity for generalization</h2>
<p>Given the fact that we started working from a very concrete requirement, it&#8217;s only natural that the <code>RandomIngredientsFromFixedSequence</code> customization we came up at with encapsulates a behavior that is specific to the scenario at hand. However, if we take a closer look we might notice the following:</p>
<div style="background-color:#fffbcc;padding:10px;border:#e6db55 1px solid;">
The only part of the algorithm that is specific to the original scenario is the <em>type of the objects being created</em>. The rest can easily be applied whenever you want to create objects that are picked at random from a predefined pool.</div>
<p>An opportunity for writing a <strong>general-purpose customization</strong> has just presented itself. We can&#8217;t let it slip.</p>
<p>Let&#8217;s see what happens if we extract the <code>Ingredient</code> type into a generic argument and remove all references to the word <em>&#8220;ingredient&#8221;</em>:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class RandomFromFixedSequence&lt;T&gt; : ICustomization
{
    private readonly Random randomizer = new Random();
    private IEnumerable&lt;T&gt; sequence;

    public void Customize(IFixture fixture)
    {
        InitializeSequence(fixture);
        fixture.Register(PickRandomItemFromSequence);
    }

    private void InitializeSequence(IFixture fixture)
    {
        this.sequence = fixture.CreateMany&lt;T&gt;();
    }

    private T PickRandomItemFromSequence()
    {
        var randomIndex = this.randomizer.Next(0, sequence.Count() - 1);
        return sequence.ElementAt(randomIndex);
    }
}
</pre>
<p>Voilà. We just turned our scenario-specific customization into a pluggable algorithm that changes the way objects of <strong>any type</strong> are going to be generated by AutoFixture. In this case the algorithm will create items by <em>picking them at random from a fixed sequence of T</em>.</p>
<p>The <code>CookbookAutoDataAttribute</code> can easily changed to use the general-purpose version of the customization by closing the generic argument with the <code>Ingredient</code> type:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class CookbookAutoDataAttribute : AutoDataAttribute
{
    public CookbookAutoDataAttribute()
        : base(new Fixture().Customize(
                   new RandomFromFixedSequence&lt;Ingredient&gt;())))
    {
    }
}
</pre>
<p>The same is true if you&#8217;re using AutoFixture imperatively:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
var fixture = new Fixture();
fixture.Customize(new RandomFromFixedSequence&lt;Ingredient&gt;());
</pre>
<h2>Wrapping up</h2>
<p>As I said before, customizations are a great way to set up test data for a specific scenario. Sometimes these configurations turn out to be useful in <a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/AutoFixture/FreezingCustomization.cs#L8-11">more than just one situation</a>.</p>
<p>When such opportunity arises, it&#8217;s often a good idea to separate out the parts that are specific to a particular context and turn them into parameters. This allows the customization to become a <em>reusable strategy</em> for controlling AutoFixture&#8217;s behavior across entire test suites.</p>
<br />Filed under: <a href='http://megakemp.com/category/net/'>.NET</a>, <a href='http://megakemp.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.com/tag/c/'>C#</a>, <a href='http://megakemp.com/tag/tdd/'>TDD</a>, <a href='http://megakemp.com/tag/unit-testing/'>Unit testing</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1310&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=7KsmwgzT2uY:QAaXQ5ZRzKc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=7KsmwgzT2uY:QAaXQ5ZRzKc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=7KsmwgzT2uY:QAaXQ5ZRzKc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=7KsmwgzT2uY:QAaXQ5ZRzKc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=7KsmwgzT2uY:QAaXQ5ZRzKc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=7KsmwgzT2uY:QAaXQ5ZRzKc:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/7KsmwgzT2uY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2013/04/16/general-purpose-customizations-with-autofixture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2013/04/domain.png?w=480" medium="image">
			<media:title type="html">Basic domain model for a recipe catalogue.</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2013/04/16/general-purpose-customizations-with-autofixture/</feedburner:origLink></item>
		<item>
		<title>Adventures in overclocking a Raspberry Pi</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/ahyH3yNLLS4/</link>
		<comments>http://megakemp.com/2013/02/26/adventures-in-overclocking-a-raspberry-pi/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 00:01:49 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Overclocking]]></category>
		<category><![CDATA[Raspberry Pi]]></category>

		<guid isPermaLink="false">http://megakemp.com/?p=1156</guid>
		<description><![CDATA[This article sums up my experience when overclocking a Raspberry Pi computer. It doesn&#8217;t provide a step-by-step guide on how to do the actual overclocking, since that kind of resources can easily be found elsewhere on the Internet. Instead, it gathers the pieces of information that I found most interesting during my research, while diving [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1156&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p class="abstract" style="font-style:italic;text-align:justify;margin-left:2%;margin-right:2%;">This article sums up my experience when overclocking a Raspberry Pi computer. It doesn&#8217;t provide a step-by-step guide on how to do the actual overclocking, since that kind of resources can easily be found <a href="http://lifehacker.com/5971395/overclock-your-raspberry-pi">elsewhere on the Internet</a>. Instead, it gathers the pieces of information that I found most interesting during my research, while diving deeper on some exquisitely geeky details on the way.</p>
<h2>A little background</h2>
<p>For the past couple of months I’ve been running a <a href="https://en.wikipedia.org/wiki/Raspberry_pi">Raspberry Pi</a> as my primary NAS at home. It wasn&#8217;t something that I had planned. On the contrary, it all started by chance when I received a Raspberry Pi as a conference gift at last year&#8217;s <a href="http://leetspeak.se">Leetspeak</a>.<br />
But why using it as a NAS when there are <a href="http://www.synology.com/products">much better products</a> on the market, you might ask. Well, because I happen to have a small network closet at home and the Pi is a pretty good fit for a device that&#8217;s capable of acting like a NAS while at the same time taking <em>very</em> little space.</p>
<div id="attachment_1168" class="wp-caption alignright" style="width: 260px"><a href="http://megakemp.files.wordpress.com/2013/02/raspberrypi-closet.jpg"><img class="size-medium wp-image-1168" alt="My Raspberry Pi in the network closet." src="http://megakemp.files.wordpress.com/2013/02/raspberrypi-closet.jpg?w=250&#038;h=250" width="250" height="250" style="padding-left:15px;" /></a><p class="wp-caption-text">My Raspberry Pi in a tiny network closet.</p></div>
<p>Much like the size, the setup itself also strikes with its simplicity: I plugged in an external <a href="http://www.wdc.com/en/products/products.aspx?id=470">1 TB WD Element USB drive</a> that I had lying around (the black box sitting above the Pi in the picture on the right), installed <a href="http://www.raspbian.org">Raspbian</a> on a SD memory card and went to town. Once booted, the little Pi exposes the storage space on the local network through 2 channels:</p>
<ul>
<li>As a Windows file share on top of the <strong>SMB</strong> protocol, through <a href="http://www.samba.org">Samba</a></li>
<li>As an Apple file share on top of the <strong>AFP</strong> protocol, through <a href="http://netatalk.sourceforge.net">Nettalk</a></li>
</ul>
<p>On top of that it also runs a <a href="https://twitter.com/ecampidoglio/status/273913939996332032">headless version</a> of the <a href="http://www.crashplan.com/consumer/download.html?os=Linux">CrashPlan Linux client</a> to backup the contents of the external drive to the cloud. So, the Pi not only works as a central storage for all my files, but it also manages to <a href="https://twitter.com/ecampidoglio/status/265176614315380736">fool Mac OS X into thinking that it’s a Time Capsule</a>. Not too bad for a tiny ARM11 700 MHz processor and 256 MB of RAM.</p>
<h2>The need for (more) speed</h2>
<p>A Raspberry Pi needs 5 volts of electricity to function. On top of that, depending on the number and kind of devices that you connect to it, it&#8217;ll draw approximately between 700 and 1400 milliamperes (mA) of current. This gives an average consumption of roughly 5 watts, which makes it ideal to work as an appliance that’s on 24/7. However, as impressive as all of this might be, it’s not all sunshine and rainbows. In fact, as the expectations get higher, the Pi’s limited hardware resources quickly become a frustrating bottleneck.</p>
<p>Luckily for us, the folks at the <a href="http://www.raspberrypi.org/about">Raspberry Pi Foundation</a> have made it fairly easy to squeeze more power out of the little piece of silicon by officially allowing overcloking. Now, there are a few different <a href="http://www.elinux.org/RPiconfig#Overclocking">combinations of frequencies</a> that you can use to boost the CPU and GPU in your Raspberry Pi.</p>
<div style="background-color:#fffbcc;padding:10px;border:#e6db55 1px solid;">The amount of <em>stable</em> overclocking that you&#8217;ll be able to achieve, however, depends on a number of physical factors, such as the quality of the soldering on the board and the amount of output that&#8217;s supported by the power supply in use. In other words, <a href="http://www.urbandictionary.com/define.php?term=YMMV">YMMV</a>.</div>
<p>There are also at least a couple of <a href="http://www.jeremymorgan.com/tutorials/raspberry-pi/how-to-overclock-raspberry-pi/">different ways</a> to go about overclocking a Raspberry Pi. I found that the most suitable one for me is to manually edit the <a href="http://www.elinux.org/RPiconfig">configuration file</a> found at <strong>/boot/config.txt</strong>. This will not only give you fine-grained control on what parts of the board to overclock, but it will also allow you to change other aspects of the process such as voltage, temperature thresholds and so on.</p>
<p>In my case, I managed to work my way up from the stock 700 MHz to 1 GHz through a number of small incremental steps. Here&#8217;s the final configuration I ended up with:</p>
<p><code>arm_freq=1000<br />
core_freq=500<br />
sdram_freq=500<br />
over_voltage=6<br />
force_turbo=0</code></p>
<p>One thing to notice is the <code class="inline">force_turbo</code> option that’s currently turned off. It&#8217;s there because, until September of last year, modifying the CPU frequencies of the Raspberry Pi would set a permanent bit inside the <a href="https://en.wikipedia.org/wiki/System_on_chip">chip</a> that voided the warranty.</p>
<p>However, having recognized the widespread interest in overclocking, the Raspberry Foundation decided to give it their blessing by building a feature into their own version of the Linux kernel called <a href="http://www.raspberrypi.org/archives/2008">Turbo Mode</a>. This allows the operating system to automatically increase and decrease the speed and voltage of the CPU based on much load is put on the system, thus reducing the impact on the hardware&#8217;s lifetime to <a href="http://www.raspberrypi.org/archives/2008">effectively zero</a>.</p>
<p>Setting the <code>force_turbo</code> option to <code>1</code> will cause the CPU to run at its full speed all the time and will apparently also contribute to setting the dreaded warranty bit in <a href="http://www.raspberrypi.org/phpBB3/viewtopic.php?p=176865#p176865">some configurations</a>.</p>
<h2>Entering Turbo Mode</h2>
<p>When Turbo Mode is enabled, the CPU speed and voltage will switch between two values, a <strong>minimum</strong> one and a <strong>maximum</strong> one, both of which are configurable. When it comes to speed, the default minimum is the stock <strong>700 MHz</strong>. The default voltage is <strong>1.20 V</strong>. During my overclocking experiments I wanted to keep a close eye on these parameters, so I wrote <a href="https://gist.github.com/ecampidoglio/5009512">a simple Bash script</a> that fetches the current state of the CPU from different sources within the system and displays a brief summary. Here&#8217;s how it looks like when the system is idle:</p>
<div id="attachment_1184" class="wp-caption aligncenter" style="width: 310px"><a href="http://megakemp.files.wordpress.com/2013/02/cpustatus-idle.png"><img class="size-medium wp-image-1184" alt="Output of my cpustatus script  when the CPU is idle." src="http://megakemp.files.wordpress.com/2013/02/cpustatus-idle.png?w=300&#038;h=113" width="300" height="113" /></a><p class="wp-caption-text">Output of my cpustatus script when the CPU is idle.</p></div>
<p>See how the current speed is equal to the minimum one? Now, take a look at how things change on full blast with the Turbo mode kicked in:</p>
<div id="attachment_1193" class="wp-caption aligncenter" style="width: 310px"><a href="http://megakemp.files.wordpress.com/2013/02/cpustatus-load.png"><img class="size-medium wp-image-1193" alt="Output of my cpustatus script with Turbo Mode enabled." src="http://megakemp.files.wordpress.com/2013/02/cpustatus-load.png?w=300&#038;h=113" width="300" height="113" /></a><p class="wp-caption-text">Output of my cpustatus script with Turbo Mode enabled.</p></div>
<p>As you can see, the CPU is running hot at the maximum speed of <strong>1 GHz</strong> fed with <strong>0,15 extra volts</strong>.</p>
<p>The last line shows the <strong>governor</strong>, which is a piece of the Linux kernel driver called <a href="https://wiki.archlinux.org/index.php/CPU_Frequency_Scaling">cpufreq</a> that&#8217;s responsible for adjusting the speed of the processor. The governor is the <a href="http://sourcemaking.com/design_patterns/strategy"><em>strategy</em></a> that regulates exactly when and how much the CPU frequency will be scaled up and down. The one that’s currently in use is called <code>ondemand</code> and it’s the foundation upon which the entire Turbo Mode is built.</p>
<p>It&#8217;s interesting to notice that the choice of governor, contrary to what you would expect, isn&#8217;t fixed. The cpufreq driver can, in fact, be configured to use a different governor during boot simply by modifying a file on disk. For example, changing from the <code>ondemand</code> governor to the one called <code>powersave</code> would block the CPU speed to its minimum value, effectively disabling Turbo Mode:</p>
<pre class="brush: bash; title: ; notranslate">
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
# Prints ondemand

&quot;powersave&quot; | /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
# Prints powersave
</pre>
<p>Here’s a list of available governors as seen in <a href="http://www.raspbian.org">Raspbian</a>:</p>
<pre class="brush: bash; title: ; notranslate">
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors
# Prints conservative ondemand userspace powersave performance
</pre>
<p>If you&#8217;re interested in seeing how they work, I encourage you to check out the <a href="https://github.com/raspberrypi/linux/tree/rpi-3.6.y/drivers/cpufreq">cpufreq source code</a> on GitHub. It&#8217;s very well written.</p>
<h2>Fine tuning</h2>
<p>I’ve managed to get a pretty decent performance boost out of my Raspberry Pi just by applying the settings shown above. However, there are still a couple of nods left to tweak before we can settle.</p>
<p>The <code>ondemand</code> governor used in the Raspberry Pi will increase the CPU speed to the maximum configured value whenever it finds it to be busy more than <strong>95%</strong> of the time. That sounds fair enough for most cases, but if you&#8217;d like that extra speed bump even when the system is performing somewhat lighter tasks, you’ll have to lower the load threshold. This is also easily done by writing an integer value to a file:</p>
<pre class="brush: bash; title: ; notranslate">
60 &gt; /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
</pre>
<p>Here we’re saying that we&#8217;d like to have the Turbo Mode kick in when the CPU is busy at least <strong>60%</strong> of the time. That is enough to make the Pi feel a little snappier during general use.</p>
<h2>Wrap up</h2>
<p>I have to say that I&#8217;ve been positively surprised by the capabilities of the Raspberry Pi. Its exceptional form factor and low power consumption makes it ideal to work as a NAS in very restricted spaces, like my network closet. Add to that the flexibility that comes from running Linux and the possibilities become <a href="http://www.raspberrypi.org/phpBB3/viewtopic.php?f=36&amp;t=14804"> truly endless</a>. In fact, the more stuff I add to my Raspberry Pi, the more I&#8217;d like it to do. What will be next, a <a href="http://jeelabs.org/2013/01/06/node-js-on-raspberry-pi">Node.js server</a>?</p>
<div style="background-color:#fffbcc;padding-left:5px;padding-right:5px;margin-top:20px;margin-bottom:20px;border:#e6db55 1px solid;">
<p style="margin-top:0;"><img style="margin:10px 5px 0 10px;" alt="Download" src="http://megakemp.files.wordpress.com/2009/07/download.gif?w=480" /> Download <a href="https://gist.github.com/ecampidoglio/5009512"><strong>cpustatus.sh</strong></a> from <a href="http://github.com/">GitHub</a></p>
</div>
<br />Filed under: <a href='http://megakemp.com/category/hardware/'>Hardware</a>, <a href='http://megakemp.com/category/technology/'>Technology</a>, <a href='http://megakemp.com/category/tools/'>Tools</a> Tagged: <a href='http://megakemp.com/tag/bash/'>Bash</a>, <a href='http://megakemp.com/tag/linux/'>Linux</a>, <a href='http://megakemp.com/tag/overclocking/'>Overclocking</a>, <a href='http://megakemp.com/tag/raspberry-pi/'>Raspberry Pi</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1156&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=ahyH3yNLLS4:luFxwMLXZsE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=ahyH3yNLLS4:luFxwMLXZsE:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=ahyH3yNLLS4:luFxwMLXZsE:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=ahyH3yNLLS4:luFxwMLXZsE:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=ahyH3yNLLS4:luFxwMLXZsE:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=ahyH3yNLLS4:luFxwMLXZsE:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/ahyH3yNLLS4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2013/02/26/adventures-in-overclocking-a-raspberry-pi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2013/02/raspberrypi-closet.jpg?w=250" medium="image">
			<media:title type="html">My Raspberry Pi in the network closet.</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2013/02/cpustatus-idle.png?w=300" medium="image">
			<media:title type="html">Output of my cpustatus script  when the CPU is idle.</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2013/02/cpustatus-load.png?w=300" medium="image">
			<media:title type="html">Output of my cpustatus script with Turbo Mode enabled.</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>
	<feedburner:origLink>http://megakemp.com/2013/02/26/adventures-in-overclocking-a-raspberry-pi/</feedburner:origLink></item>
		<item>
		<title>Grokking Git by seeing it</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/nBdKXFnVEe4/</link>
		<comments>http://megakemp.com/2013/01/22/grokking-git-by-seeing-it/#comments</comments>
		<pubDate>Tue, 22 Jan 2013 00:19:28 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Speaking]]></category>

		<guid isPermaLink="false">http://megakemp.com/?p=1108</guid>
		<description><![CDATA[When I first started getting into Git a couple of years ago, one of the things I found most frustrating about the learning experience was the complete lack of guidance on how to interpret the myriad of commands and switches found in the documentation. On second thought, calling it frustrating is actually an understatement. Utterly [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1108&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>When I first started getting into <a href="http://git-scm.com">Git</a> a couple of years ago, one of the things I found most frustrating about the learning experience was the complete lack of guidance on how to interpret the myriad of commands and switches found in the documentation. On second thought, calling it <em>frustrating</em> is actually an understatement. Utterly painful would be a better way to describe it.<br />
What I was looking for, was a way to <strong>represent the state of a Git repository in some sort of graphical format</strong>. In my mind, if only I could have visualized how the different combinations of commands and switches impacted my repo, I would have had a much better shot at actually understand their meaning.</p>
<p>After a bit of research on the Git forums, I noticed that many people was using a simple text-based notation to describe the state of their repo. The actual symbols varied a bit, but they all essentially came down to something like this:</p>
<pre><code style="font-size:120%;">
               C4--C5 (feature)
              / 
C1--C2--C3--C4'--C5'--C6 (master)
                       ^
</code></pre>
<p>where the symbols mean:</p>
<ul>
<li><strong>Cn</strong> represents a single commit</li>
<li><strong>Cn&#8217;</strong> represents a commit that has been moved from another location in history, i.e. it has been <em>rebased</em></li>
<li><strong>(branch)</strong> represents a branch name</li>
<li><strong>^</strong> indicates the commit referenced by HEAD</li>
</ul>
<p>This form of <a href="http://ayende.com/blog/2966/graphical-domain-specific-languages">graphical DSL</a> proved itself to be extremely useful not only as a learning tool but also as a universal Git language, useful for documentation as well as for communication during problem solving.</p>
<p>Now, keeping this idea in mind, imagine having a tool that is able to draw a similar diagram automatically. Sounds interesting? Well, let me introduce <a href="https://github.com/Haacked/SeeGit">SeeGit</a>.</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 href="https://github.com/Haacked/SeeGit">SeeGit</a> is Windows application that, given the path to a Git repository on disk, will generate a diagram of its commits and references. Once done, it will keep watching that directory for changes and automatically update the diagram accordingly.</div>
<p>This is where the idea for my <em>Grokking Git by seeing it</em> session came from. The goal is to <strong>illustrate the meaning behind different Git operations</strong> by going through a series of demos, while having the command line running on one half of the screen and SeeGit on the other. As I type away in the console you can see the Git history unfold in front of you, giving you an insight in how things work under the covers.</p>
<p>In other words, something like this:</p>
<p><a href="http://megakemp.files.wordpress.com/2013/01/seegitsession-original.png"><br />
<img src="http://megakemp.files.wordpress.com/2013/01/seegitsession.png?w=480" alt="SeeGit session in progress." class="aligncenter" style="margin-top:-15px;" /></a></p>
<p>So, this is just to give you a little background. Here you&#8217;ll find the session&#8217;s abstract, slides and demos. There&#8217;s also a recording from when I presented this talk at <a href="http://leetspeak.se">LeetSpeak</a> in Malmö, Sweden back in October 2012. I hope you find it useful.</p>
<h2>Abstract</h2>
<blockquote>
<p>In this session I’ll teach you the Git zen from the inside out. Working out of real world scenarios, I’ll walk you through Git’s fundamental building blocks and common use cases, working our way up to more advanced features. And I’ll do it by showing you graphically what happens under the covers, as we fire different Git commands.</p>
<p>You may already have been using Git for a while to collaborate on some open source project or even at work. You know how to commit files, create branches and merge your work with others. If that’s the case, believe me, you’ve only scratched the surface. I firmly believe that a deep understanding of Git’s inner workings is the key to unlock its true power allowing you, as a developer, to take full control of your codebase’s history.</p>
</blockquote>
<h2>Recording from LeetSpeak</h2>
<p></p>
<div class="embed-vimeo"><iframe src="http://player.vimeo.com/video/52633764" width="480" height="270" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>
<p></p>
<h2>Resources</h2>
<ul>
<li><a href="http://megakemp.files.wordpress.com/2013/01/grokkinggitbyseeingit-slides.pdf">Slides <img src="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif?w=480" alt="Download PDF file"   class="alignnone size-full wp-image-1091" style="vertical-align:bottom;margin-left:2px;margin-top:0;" /></a></li>
<li><a href="http://megakemp.files.wordpress.com/2013/01/grokkinggitbyseeingit-demos.pdf">Demos <img src="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif?w=480" alt="Download PDF file"   class="alignnone size-full wp-image-1091" style="vertical-align:bottom;margin-left:2px;margin-top:0;" /></a></li>
</ul>
<br />Filed under: <a href='http://megakemp.com/category/software-development/'>Software Development</a>, <a href='http://megakemp.com/category/tools/'>Tools</a> Tagged: <a href='http://megakemp.com/tag/git/'>Git</a>, <a href='http://megakemp.com/tag/presentations/'>Presentations</a>, <a href='http://megakemp.com/tag/speaking/'>Speaking</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1108&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=nBdKXFnVEe4:YkVrucn2hGg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=nBdKXFnVEe4:YkVrucn2hGg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=nBdKXFnVEe4:YkVrucn2hGg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=nBdKXFnVEe4:YkVrucn2hGg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=nBdKXFnVEe4:YkVrucn2hGg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=nBdKXFnVEe4:YkVrucn2hGg:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/nBdKXFnVEe4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2013/01/22/grokking-git-by-seeing-it/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2013/01/seegitsession.png" medium="image">
			<media:title type="html">SeeGit session in progress.</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif" medium="image">
			<media:title type="html">Download PDF file</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif" medium="image">
			<media:title type="html">Download PDF file</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2013/01/22/grokking-git-by-seeing-it/</feedburner:origLink></item>
		<item>
		<title>Make your system administrator friendly with PowerShell</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/X_V2mXnpxi0/</link>
		<comments>http://megakemp.com/2012/08/30/make-your-system-administrator-friendly-with-powershell/#comments</comments>
		<pubDate>Thu, 30 Aug 2012 09:13:51 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Speaking]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=1051</guid>
		<description><![CDATA[I know I’ve said it before, but I love the command line. And being a command line junkie, I’m naturally attracted to all kinds of tools the involve a bright blinking square on a black canvas. Historically, I’ve always been a huge fan of the mighty Bash. PowerShell, however, came to change that. Since PowerShell [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1051&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I know I’ve said it before, but I love the command line. And being a command line junkie, I’m naturally attracted to all kinds of tools the involve a bright blinking square on a black canvas. Historically, I’ve always been a huge fan of the mighty <a href="http://www.bash.org">Bash</a>. PowerShell, however, came to change that.</p>
<p><img src="http://megakemp.files.wordpress.com/2012/08/powershell-cropped-small.png?w=480" alt="PowerShell logo" title="PowerShell logo"   class="alignright size-full wp-image-1068" style="margin-top:-4px;" /></p>
<p>Since PowerShell made its first appearance under the <a href="http://blogs.msdn.com/b/monad/archive/2005/08/25/456590.aspx">codename “<em>Monad</em>”</a> back in 2005, it proposed itself as more than just a regular command prompt. It brought, in fact, something completely new to the table: <em>it combined the flexibility of a Unix-style console, such as Bash, with the richness of the .NET Framework and an <a href="http://powershell.com/cs/blogs/ebookv2/archive/2012/03/05/chapter-5-the-powershell-pipeline.aspx#object-oriented-pipeline">object-oriented pipeline</a></em>, which in itself was totally unheard of. <br />With such a compelling story, it soon became apparent that PowerShell was aiming to become the official command line tool for Windows, replacing both the ancient <a href="http://en.wikipedia.org/wiki/Command_Prompt">Command Prompt</a> and the often criticized <a href="http://en.wikipedia.org/wiki/Windows_Script_Host">Windows Script Host</a>. And so it has been.</p>
<p>Seven years has passed since “<em>Monad</em>” <a href="http://blogs.msdn.com/b/monad/archive/2006/04/25/583333.aspx">was officially released as PowerShell</a>, and its presence is as pervasive as ever. Nowadays you can expect to find PowerShell in just about all of Microsoft’s major server products, from <a href="http://social.technet.microsoft.com/wiki/contents/articles/1823.exchange-2010-powershell-scripting-resources-en-us.aspx">Exchange</a> to <a href="http://msdn.microsoft.com/en-us/library/cc281954(v=sql.105)">SQL Server</a>. It’s even become part of Visual Studio thorugh the <a href="http://docs.nuget.org/docs/start-here/using-the-package-manager-console">NuGet Package Manager Console</a>. Not only that, but tools such as <a href="https://github.com/dahlbyk/posh-git">posh-git</a>, make PowerShell a very nice, and arguably more natural, alternative to <a href="http://code.google.com/p/msysgit">Git Bash</a> when using Git on Windows.</p>
<p>Following up on my interest for PowerShell, I’ve found myself talking a fair deal about it both at conferences and user groups. In particular, during the last year or so, I’ve been giving a presentation about how to integrate PowerShell into your own applications.</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;">
The idea is to leverage the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms714469(v=vs.85).aspx">PowerShell programming model</a> to provide <strong>a rich set of administrative tools</strong> that will (hopefully) improve the often stormy relationship between devs and admins.</div>
<p>Since I’m often asked about where to get the slides and the code samples from the talk, I thought I would make them all <strong>available here</strong> in one place for future reference.</p>
<p>So here it goes, I hope you find it useful.</p>
<h3 id="abstract">Abstract</h3>
<blockquote><p>Have you ever been in a software project where the IT staff who would run the system in production, was accounted for right from the start? My guess is not very often. In fact, it’s far too rare to see functionality being built into software systems specifically to make the job of the IT administrator <em>easier</em>. It’s a pity, because pulling that off doesn’t require as much time and effort as you might think with tools like PowerShell.</p>
<p>In this session I’ll show you how to enhance an existing .NET web application with a set of administrative tools, built using the PowerShell programming model. Once that is in place, I’ll demonstrate how common maintenance tasks can either be performed manually using a traditional GUI or be fully automated through PowerShell scripts using the same code base.</p>
<p>Since the last few years, Microsoft itself has committed to making all of its major server products fully administrable both through traditional GUI based tools <em>as well as</em> PowerShell. If you’re building a server application on the .NET platform, you will soon be expected to do the same.</p></blockquote>
<h3 id="resources">Resources</h3>
<ul>
<li><a href='http://megakemp.files.wordpress.com/2012/08/sysadminfriendlywithpowershell-slides.pdf'>Slides <img src="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif?w=480" alt="Download PDF file"   class="alignnone size-full wp-image-1091" style="vertical-align:bottom;margin-left:2px;margin-top:0;" /></a></li>
<li><a href='http://megakemp.files.wordpress.com/2012/08/sysadminfriendlywithpowershell-codesamples.pdf'>Code samples <img src="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif?w=480" alt="Download PDF file"   class="alignnone size-full wp-image-1091" style="vertical-align:bottom;margin-left:2px;margin-top:0;" /></a></li>
<li><a href="https://github.com/ecampidoglio/Expresso">Expresso on GitHub</a></li>
</ul>
<br />Filed under: <a href='http://megakemp.com/category/net/'>.NET</a>, <a href='http://megakemp.com/category/software-development/'>Software Development</a>, <a href='http://megakemp.com/category/tools/'>Tools</a> Tagged: <a href='http://megakemp.com/tag/powershell/'>PowerShell</a>, <a href='http://megakemp.com/tag/presentations/'>Presentations</a>, <a href='http://megakemp.com/tag/speaking/'>Speaking</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1051&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=X_V2mXnpxi0:HPkHrHyXQwk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=X_V2mXnpxi0:HPkHrHyXQwk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=X_V2mXnpxi0:HPkHrHyXQwk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=X_V2mXnpxi0:HPkHrHyXQwk:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=X_V2mXnpxi0:HPkHrHyXQwk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=X_V2mXnpxi0:HPkHrHyXQwk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/X_V2mXnpxi0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2012/08/30/make-your-system-administrator-friendly-with-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/08/powershell-cropped-small.png" medium="image">
			<media:title type="html">PowerShell logo</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif" medium="image">
			<media:title type="html">Download PDF file</media:title>
		</media:content>

		<media:content url="http://megakemp.files.wordpress.com/2012/08/pdf_small.gif" medium="image">
			<media:title type="html">Download PDF file</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2012/08/30/make-your-system-administrator-friendly-with-powershell/</feedburner:origLink></item>
		<item>
		<title>Better DIFFs with PowerShell</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/yo0j6O5hr3Y/</link>
		<comments>http://megakemp.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 [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1005&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: diff; gutter: false; title: ; notranslate">
--- 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>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>
<pre class="brush: diff; light: true; title: ; notranslate">
@@ -6,12 +6,10 @@
</pre>
<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>
<pre class="brush: powershell; gutter: false; title: ; notranslate">
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>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>
<pre class="brush: powershell; light: true; title: ; notranslate">
. .\Out-Diff.ps1
git diff | Out-Diff
</pre>
<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.com/category/software-development/'>Software Development</a>, <a href='http://megakemp.com/category/tools/'>Tools</a> Tagged: <a href='http://megakemp.com/tag/diff/'>Diff</a>, <a href='http://megakemp.com/tag/git/'>Git</a>, <a href='http://megakemp.com/tag/powershell/'>PowerShell</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=1005&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=yo0j6O5hr3Y:Rbz4bhQuJXg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=yo0j6O5hr3Y:Rbz4bhQuJXg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=yo0j6O5hr3Y:Rbz4bhQuJXg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=yo0j6O5hr3Y:Rbz4bhQuJXg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=yo0j6O5hr3Y:Rbz4bhQuJXg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=yo0j6O5hr3Y:Rbz4bhQuJXg:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/yo0j6O5hr3Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2012/01/19/better-diffs-with-powershell/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;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>
	<feedburner:origLink>http://megakemp.com/2012/01/19/better-diffs-with-powershell/</feedburner:origLink></item>
		<item>
		<title>Keep your unit tests DRY with AutoFixture Customizations</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/EvHXFRZixvk/</link>
		<comments>http://megakemp.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 [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=942&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: csharp; light: true; title: ; notranslate">
[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>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>
<pre class="brush: csharp; highlight: [2,18]; light: true; title: ; notranslate">
[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>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>
<pre class="brush: csharp; light: true; title: ; notranslate">
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>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>
<pre class="brush: csharp; light: true; title: ; notranslate">
[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>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.com/category/net/'>.NET</a>, <a href='http://megakemp.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.com/tag/net/'>.NET</a>, <a href='http://megakemp.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.com/tag/c/'>C#</a>, <a href='http://megakemp.com/tag/unit-testing/'>Unit testing</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=942&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=EvHXFRZixvk:r9E5YWqAZIU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=EvHXFRZixvk:r9E5YWqAZIU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=EvHXFRZixvk:r9E5YWqAZIU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=EvHXFRZixvk:r9E5YWqAZIU:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=EvHXFRZixvk:r9E5YWqAZIU:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=EvHXFRZixvk:r9E5YWqAZIU:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/EvHXFRZixvk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/</feedburner:origLink></item>
		<item>
		<title>Behavior changes in AutoFixture 2.2 – Anonymous numbers</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/MqOhMx2HDtU/</link>
		<comments>http://megakemp.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 [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=892&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; highlight: [13,14,15]; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; highlight: [15,16,17]; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
var fixture = new Fixture();
fixture.Customize(new NumericSequencePerTypeCustomization());
</pre>
<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.com/category/net/'>.NET</a>, <a href='http://megakemp.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.com/tag/net/'>.NET</a>, <a href='http://megakemp.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.com/tag/c/'>C#</a>, <a href='http://megakemp.com/tag/unit-testing/'>Unit testing</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=892&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqOhMx2HDtU:aJGbJzSvvBk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqOhMx2HDtU:aJGbJzSvvBk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=MqOhMx2HDtU:aJGbJzSvvBk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqOhMx2HDtU:aJGbJzSvvBk:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqOhMx2HDtU:aJGbJzSvvBk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=MqOhMx2HDtU:aJGbJzSvvBk:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/MqOhMx2HDtU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/</feedburner:origLink></item>
		<item>
		<title>Anonymous delegates in AutoFixture</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/9yrv7RfEjmA/</link>
		<comments>http://megakemp.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 [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=720&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public delegate void MyDelegate();

var fixture = new Fixture();
var delegateSpecimen = fixture.CreateAnonymous&lt;MyDelegate&gt;();
</pre>
<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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
var fixture = new Fixture();
var actionSpecimen = fixture.CreateAnonymous&lt;Action&lt;string&gt;&gt;();
actionSpecimen(&quot;whatever&quot;); // no-op
</pre>
<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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
var fixture = new Fixture();
fixture.Customizations.Add(new DelegateGenerator());
</pre>
<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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
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>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>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
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>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.com/category/net/'>.NET</a>, <a href='http://megakemp.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.com/tag/net/'>.NET</a>, <a href='http://megakemp.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.com/tag/c/'>C#</a>, <a href='http://megakemp.com/tag/unit-testing/'>Unit testing</a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=720&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=9yrv7RfEjmA:KmjArD8X7_Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=9yrv7RfEjmA:KmjArD8X7_Q:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=9yrv7RfEjmA:KmjArD8X7_Q:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=9yrv7RfEjmA:KmjArD8X7_Q:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=9yrv7RfEjmA:KmjArD8X7_Q:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=9yrv7RfEjmA:KmjArD8X7_Q:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/9yrv7RfEjmA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2011/08/01/anonymous-delegates-in-autofixture/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.com/2011/08/01/anonymous-delegates-in-autofixture/</feedburner:origLink></item>
		<item>
		<title>Fixing a bug in ASP.NET Ajax and the pain of leaky abstractions</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/MqfR7GSXL5U/</link>
		<comments>http://megakemp.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. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=653&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: jscript; highlight: [9,10,11,12,13,14,15,16,30,31,32,33,34,35,36,37,38,39,40]; title: ; notranslate">
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>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>
<pre class="brush: xml; title: ; notranslate">
&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>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 <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=653&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqfR7GSXL5U:Nmuj9LMGzpM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqfR7GSXL5U:Nmuj9LMGzpM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=MqfR7GSXL5U:Nmuj9LMGzpM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqfR7GSXL5U:Nmuj9LMGzpM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=MqfR7GSXL5U:Nmuj9LMGzpM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=MqfR7GSXL5U:Nmuj9LMGzpM:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/MqfR7GSXL5U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.com/2010/01/04/fixing-a-bug-in-asp-net-ajax-and-the-pain-of-leaky-abstractions/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;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&amp;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&amp;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&amp;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&amp;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&amp;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>
	<feedburner:origLink>http://megakemp.com/2010/01/04/fixing-a-bug-in-asp-net-ajax-and-the-pain-of-leaky-abstractions/</feedburner:origLink></item>
		<item>
		<title>Speed up your queries in SQL Server by being declarative</title>
		<link>http://feedproxy.google.com/~r/Thoughtology/~3/i1K1-5x9A5Y/</link>
		<comments>http://megakemp.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. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=635&#038;subd=megakemp&#038;ref=&#038;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>
<pre class="brush: sql; title: ; notranslate">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>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>
<pre class="brush: sql; title: ; notranslate">CREATE PROCEDURE CalculateWaitListScores_Declarative
AS
BEGIN

UPDATE WaitList
SET Score = dbo.CalculateScore(UserID, ResourceID)
WHERE Score IS NULL
	
END</pre>
<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 <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.com&#038;blog=4633671&#038;post=635&#038;subd=megakemp&#038;ref=&#038;feed=1" width="1" height="1" /><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/Thoughtology?a=i1K1-5x9A5Y:Tz3UQbx5v20:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=i1K1-5x9A5Y:Tz3UQbx5v20:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=i1K1-5x9A5Y:Tz3UQbx5v20:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=i1K1-5x9A5Y:Tz3UQbx5v20:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/Thoughtology?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/Thoughtology?a=i1K1-5x9A5Y:Tz3UQbx5v20:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Thoughtology?i=i1K1-5x9A5Y:Tz3UQbx5v20:F7zBnMyn0Lo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Thoughtology/~4/i1K1-5x9A5Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.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://2.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;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&amp;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&amp;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>
	<feedburner:origLink>http://megakemp.com/2009/11/10/speed-up-your-queries-in-sql-server-by-being-declarative/</feedburner:origLink></item>
	</channel>
</rss>
