<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Arrange Act Assert</title>
	<atom:link href="http://www.arrangeactassert.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arrangeactassert.com</link>
	<description>Jag Reehal on Agile Development, ASP.NET MVC and all manner of good stuff</description>
	<lastBuildDate>Wed, 10 Mar 2010 22:00:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How NBuilder Could Help You Write Better .Net Unit Tests</title>
		<link>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/</link>
		<comments>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 22:00:51 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[NBuilder]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=618</guid>
		<description><![CDATA[One of the biggest challenges when creating unit tests is to come up test data.  It makes sense having someone other than you test your code, so how about having someone other than you generate the test input for your .Net unit tests.
Data generation tools aren’t new concept and they come in many different [...]]]></description>
			<content:encoded><![CDATA[<p>One of the biggest challenges when creating unit tests is to come up test data.  It makes sense having someone other than you test your code, so how about having someone other than you generate the test input for your .Net unit tests.</p>
<p>Data generation tools aren’t new concept and they come in many different forms.  When I first saw <a href="http://www.red-gate.com/products/sql_data_generator/index.htm">Red Gate Sql Data Generator</a> a couple of years ago, I thought to myself it&#8217;s a shame you need a database because this would have been great for unit and integration tests.</p>
<p>In this blog post I want to show you how <a href="http://nbuilder.org">NBuilder</a> can be used when unit testing with .Net objects.  The NBuilder assembly can be downloaded here <a href="http://code.google.com/p/nbuilder/">http://code.google.com/p/nbuilder/</a>.</p>
<p>In this blog post we will be using the product and category classes below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class Product
{
    public Product()
    {
        Categories = new List&lt;Category&gt;();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public int Rating { get; set; }
    public decimal Price { get; set; }
    public bool InStock { get; set; }
    public List&lt;Category&gt; Categories { get; set; }

    public override string ToString()
    {
        return String.Format(&quot;Id:{0}, Name:{1}, Rating:{2}, Price:{3}, InStock:{4}, Categories:{5}&quot;, Id, Name, Rating, Price, InStock, Categories.Count);
    }
}

public class Category
{
    public string Name { get; set; }
}
</pre>
<h3 class="subheading">NBuilder default values</h3>
<p>The product class contains a variety of types.  When you run the following code to create 10 products</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Should_Create_Ten_Products()
{
    var products = Builder&lt;Product&gt;.CreateListOfSize(10).Build();
    products.Count().ShouldEqual(10);
}
</pre>
<p>this is the output</p>
<table border=1>
<tr align="center"  bgcolor="grey">
<td>Id</td>
<td>Name</td>
<td>Rating</td>
<td>Price</td>
<td>InStock</td>
<td>Categories Count</td>
</tr>
<tr align="center">
<td>00000000-0000-0000-0000-000000000001</td>
<td>Name1</td>
<td>1</td>
<td>1</td>
<td>False</td>
<td>0</td>
</tr>
<tr align="center"  bgcolor="#F1EDED">
<td>00000000-0000-0000-0000-000000000002</td>
<td>Name2</td>
<td>2</td>
<td>2</td>
<td>True</td>
<td>0</td>
</tr>
<tr align="center">
<td>00000000-0000-0000-0000-000000000003</td>
<td>Name3</td>
<td>3</td>
<td>3</td>
<td>False</td>
<td>0</td>
</tr>
<tr align="center"  bgcolor="#F1EDED">
<td>00000000-0000-0000-0000-000000000004</td>
<td>Name4</td>
<td>4</td>
<td>4</td>
<td>True</td>
<td>0</td>
</tr>
<tr align="center">
<td>00000000-0000-0000-0000-000000000005</td>
<td>Name5</td>
<td>5</td>
<td>5</td>
<td>False</td>
<td>0</td>
</tr>
<tr align="center"  bgcolor="#F1EDED">
<td>00000000-0000-0000-0000-000000000006</td>
<td>Name6</td>
<td>6</td>
<td>6</td>
<td>True</td>
<td>0</td>
</tr>
<tr align="center">
<td>00000000-0000-0000-0000-000000000007</td>
<td>Name7</td>
<td>7</td>
<td>7</td>
<td>False</td>
<td>0</td>
</tr>
<tr align="center"  bgcolor="#F1EDED">
<td>00000000-0000-0000-0000-000000000008</td>
<td>Name8</td>
<td>8</td>
<td>8</td>
<td>True</td>
<td>0</td>
</tr>
<tr align="center">
<td>00000000-0000-0000-0000-000000000009</td>
<td>Name9</td>
<td>9</td>
<td>9</td>
<td>False</td>
<td>0</td>
</tr>
<tr align="center"  bgcolor="#F1EDED">
<td>00000000-0000-0000-0000-00000000000a</td>
<td>Name10</td>
<td>10</td>
<td>10</td>
<td>True</td>
<td>0</td>
</tr>
</table>
<p><br/></p>
<ul>
<li>For strings NBuilder suffixes the index number to the name of the property e.g. Name1</li>
<li>For numeric values such as int and decimal the default value is the index number</li>
<li>For guids a hexadecimal range is used</li>
<li>Boolean values alternate between true and false for each product</li>
<li>The categories collection is left empty.  This would have been null if we didn&#8217;t create a new collection in the constructor of the product class</li>
</ul>
<h3 class="subheading">Changing how NBuilder default values are created</h3>
<p>I really like how you can customize NBuilder and use your own convention for creating default values.</p>
<p>For example what if we wanted to change how guids are created.</p>
<p>One way to do this is to inherit from the RandomValuePropertyNamer class and override the GetGuid method as shown below.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class JagsRandomValuePropertyNamer : RandomValuePropertyNamer
{
    protected override Guid GetGuid(System.Reflection.MemberInfo memberInfo)
    {
        return Guid.NewGuid();
    }
}
</pre>
<p>After setting the default property namer, all guids are created by calling Guid.NewGuid()</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Product_Should_Have_Guid_Assigned()
{
    BuilderSetup.SetDefaultPropertyNamer(new JagsRandomValuePropertyNamer());

    var product = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p =&gt; p.Id = Guid.NewGuid())
        .Build();

    product[0].Id.ToString().ShouldNotEqual(&quot;00000000-0000-0000-0000-000000000001&quot;);
}
</pre>
<h3 class="subheading">Using the WhereAll method to set the InStock to always be true</h3>
<p>What if we wanted to change the InStock value to true for all the products in the collection.  This can be done using the WhereAll method as shown in the code below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void All_Products_Should_Be_In_Stock()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .Have(p =&gt; p.InStock = true)
        .Build();

    products.All(p =&gt; p.InStock).ShouldBeTrue();
}
</pre>
<h3 class="subheading">Using NBuilder to set parts of a collection</h3>
<p>There are two ways you can use Nbuilder to set values in parts of a collection.  The first is by using the first or last methods like so</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void First_Two_Products_Should_Be_In_Stock()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereTheFirst(2)
            .Have(p =&gt; p.InStock = true)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[1].InStock.ShouldBeTrue();
}
</pre>
<p>the other is to use sections</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Mixture_Of_Products_In_Stock_Using_Sections()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereSection(0, 1)
            .Have(p =&gt; p.InStock = true)
        .WhereSection(2, 9)
            .Have(p =&gt; p.InStock = false)
        .Build();

    products[0].InStock.ShouldBeTrue();
    products[2].InStock.ShouldBeFalse();
}
</pre>
<h3 class="subheading">Using the UniqueRandomList to create unique random lists&#8230;</h3>
<p>So far we haven&#8217;t done anything with the category property.</p>
<p>What if you wanted to build a product collection with each product having a random number of categories?</p>
<p>By calling the HaveDoneToThem and the UniqueRandomList methods we can create a set of products with having different categories to one another</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Products_With_Random_Categories()
{
    var categories = Builder&lt;Category&gt;
        .CreateListOfSize(100)
        .Build();

    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
        .HaveDoneToThem(p =&gt; p.Categories.AddRange(Pick&lt;Category&gt;.UniqueRandomList(2).From(categories)))
        .Build();

    var productCategoryOne = products[0].Categories[0].Name;
    var productCategoryTwo = products[1].Categories[0].Name;

    productCategoryOne.ShouldNotBeTheSameAs(productCategoryTwo);
}
</pre>
<h3 class="subheading">Extending NBuilder with a Lorem Ipsum string generator</h3>
<p>One thing I really like about NBuilder is the ability to extend it. </p>
<p>The code below shows how easy it is to have product names randomly using Lorem Ipsum just by creating a extension method like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public static class StringExtensions
{
    public const string LoremIpsum = &quot;Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;;

    public static IOperable&lt;Product&gt; HavingRandomLoremIpsumProductName(this IOperable&lt;Product&gt; operable)
    {
        ((IDeclaration&lt;Product&gt;)operable).ObjectBuilder.With(x =&gt; x.Name = LoremIpsum.Substring(0, new Random().Next(446)));
        return operable;
    }
}
</pre>
<p>this can be used to generate products with random names like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void Products_With_Random_LoremIpsum_Names()
{
    var products = Builder&lt;Product&gt;
        .CreateListOfSize(10)
        .WhereAll()
            .HavingRandomLoremIpsumProductName()
        .Build();

    var nameOfProductOne = products[0].Name;
    var nameOfProductTwo = products[1].Name;

    nameOfProductOne.ShouldNotBeTheSameAs(nameOfProductTwo);
}
</pre>
<h3 class="subheading">Jag Reehal’s Final Thought on &#8216;How NBuilder Could Help You Write Better .Net Unit Tests’</h3>
<p>I think frameworks like NBehave could really have a big impact on how you go about having to create test data.  The fluent interface is fantastic and it&#8217;s so easy to customize. </p>
<p>NBuilder contains a lot more features than I have covered in this post so if you like what you&#8217;ve seen make sure you check out the <a href="http://nbuilder.org/Documentation">NBuilder documentation</a>.</p>
<p>For the future I’m hoping <a href="http://fluentnhibernate.org/">Fluent NHibernate</a> and NBuilder could work together.  For example when you define class maps in Fluent NHibernate you can specify the length of string column.  If NBuilder could use information like this when generating data that would really be something special.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-nbuilder-could-help-you-write-better-net-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Create Heat Maps In Sql Server Reporting Services</title>
		<link>http://www.arrangeactassert.com/how-to-create-heat-maps-in-sql-server-reporting-services/</link>
		<comments>http://www.arrangeactassert.com/how-to-create-heat-maps-in-sql-server-reporting-services/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 21:04:34 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[SQL Server Reporting Services]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=577</guid>
		<description><![CDATA[Recently I&#8217;ve been doing some work with Microsoft Sql Server Reporting Services.  One of the tasks I was given was to create a report with a heat map, which means you transform a report that looks like this

to something that looks like this

As you can see the a heat map is excellent way to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve been doing some work with <a href="http://www.microsoft.com/sqlserver/2008/en/us/reporting.aspx">Microsoft Sql Server Reporting Services</a>.  One of the tasks I was given was to create a report with a heat map, which means you transform a report that looks like this</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/PlainReport.PNG" alt="Plain Report" width=700 height=57 align=left /></p>
<p>to something that looks like this</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/BobsHeatmapReport.PNG" alt="Bobs Heat Map Report"  width=700 height=57 align=left  /></p>
<p>As you can see the a heat map is excellent way to visualize data.</p>
<p>This was done without the use of any plugins.  I implemented the heat map in Reporting Services by following <a href="http://blogs.msdn.com/bobmeyers/">Bob Meyers</a> excellent solution in his &#8216;<a href="http://blogs.msdn.com/bobmeyers/archive/2009/07/31/add-excel-like-color-scale-conditional-formatting-to-your-reports.aspx">Add Excel-like &#8220;color scale&#8221; conditional formatting to your reports</a>&#8216; blog post. </p>
<h3 class="subheading">Exporting to Excel</h3>
<p>One of the requirements for my work was for users to be able to export the report into Microsoft Excel.  Unfortunately it was at this point Bob&#8217;s solution didn&#8217;t work out for me.  The problem was I was getting cells with a black background color as shown below.  </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ErrorsExportingToExcel.PNG" alt="Errors Exporting To Excel" width=700 height=298 align=left /></p>
<p>So I came up with an alternative solution.</p>
<h3 class="subheading">An Alternative Sql Server Reporting Services Heat Map Generator</h3>
<p>So instead of using hex codes for the color like Bob does, I wanted to play it safe and use Microsoft colors i.e. those in the System.Drawing library.</p>
<p>The code below shows the GetHeatmapColor function which takes in three arguments and returns a string for the color</p>
<pre class="brush: vb; gutter: false; toolbar: true;">
Public Class SqlReportingServicesHeatMapGenerator
    Public Function GetHeatmapColor(ByVal textBoxValue, ByVal minDataSetValue, ByVal maxDataSetValue) As String
        Dim colours As String() = New String() {&quot;Green&quot;, &quot;LimeGreen&quot;, &quot;Yellow&quot;, &quot;Orange&quot;, &quot;OrangeRed&quot;, &quot;Red&quot;}

        If textBoxValue = 0 Then
            Return colours(0)
        End If

        If minDataSetValue = maxDataSetValue Then
            Return colours(0)
        End If

        If textBoxValue &gt; maxDataSetValue Then
            Return colours(colours.Length - 1)
        End If

        Dim divider As Integer = (maxDataSetValue - minDataSetValue + 1) / 5
        Dim index As Integer = textBoxValue / divider
        GetHeatmapColor = colours(index)

    End Function
End Class
</pre>
<p>This function can be unit tested like this.  Yes I know this falls a long way from 100% test coverage, but this is just an example  <img src='http://www.arrangeactassert.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<pre class="brush: vb; gutter: false; toolbar: true;">
Imports NUnit.Framework

&lt;TestFixture()&gt; _
Public Class When_Getting_The_Fill_Color
    Private _heatMapGenerator As New SqlReportingServicesHeatMapGenerator()
    &lt;Test()&gt; _
    Public Sub Should_Return_Green_For_Zero()
        Dim result = _heatMapGenerator.GetHeatmapColor(0, 1, 100)
        Assert.AreEqual(&quot;Green&quot;, result)
    End Sub

    &lt;Test()&gt; _
    Public Sub Should_Return_Green_For_Lowest_Value()
        Dim result = _heatMapGenerator.GetHeatmapColor(1, 1, 100)
        Assert.AreEqual(&quot;Green&quot;, result)
    End Sub

    &lt;Test()&gt; _
    Public Sub Should_Return_Red_For_Highest_Value()
        Dim result = _heatMapGenerator.GetHeatmapColor(100, 1, 100)
        Assert.AreEqual(&quot;Red&quot;, result)
    End Sub

    &lt;Test()&gt; _
    Public Sub Should_Return_Green_If_All_Values_Are_The_Same()
        Dim result = _heatMapGenerator.GetHeatmapColor(1, 1, 1)
        Assert.AreEqual(&quot;Green&quot;, result)
    End Sub

    &lt;Test()&gt; _
    Public Sub Should_Return_Red_Even_If_Cell_Value_Is_Greater_Than_The_Maximum()
        Dim result = _heatMapGenerator.GetHeatmapColor(1164, 1, 896)
        Assert.AreEqual(&quot;Red&quot;, result)
    End Sub
End Class
</pre>
<h3 class="subheading">Implementing The Solution</h3>
<p>The colors on the report are shown using the fill property of a text box and an expression to determine what the fill color should be.  Follow the steps below to create a heat map in Reporting Services using either Report Builder or Visual Studio. </p>
<p>First create a data source and dataset (we will not be connecting to any databases).  Right click on the dataset and select query</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/RightClickQuery.PNG" alt="Right click on the dataset and select query" align=left /></p>
<p>In the query for the dataset paste in the sql below </p>
<pre class="brush: sql; gutter: false; toolbar: true;">
DECLARE @LogTable TABLE (WebServer VARCHAR(10),[Hour] TINYINT, NumberOfUsers INT)
INSERT INTO @LogTable VALUES ('WebServer1',0,0)
INSERT INTO @LogTable VALUES ('WebServer1',1,2)
INSERT INTO @LogTable VALUES ('WebServer1',2,4)
INSERT INTO @LogTable VALUES ('WebServer1',3,6)
INSERT INTO @LogTable VALUES ('WebServer1',4,8)
INSERT INTO @LogTable VALUES ('WebServer1',5,10)
INSERT INTO @LogTable VALUES ('WebServer1',6,12)
INSERT INTO @LogTable VALUES ('WebServer1',7,14)
INSERT INTO @LogTable VALUES ('WebServer1',8,16)
INSERT INTO @LogTable VALUES ('WebServer1',9,18)
INSERT INTO @LogTable VALUES ('WebServer1',10,20)
INSERT INTO @LogTable VALUES ('WebServer1',11,22)
INSERT INTO @LogTable VALUES ('WebServer1',12,24)
INSERT INTO @LogTable VALUES ('WebServer1',13,22)
INSERT INTO @LogTable VALUES ('WebServer1',14,21)
INSERT INTO @LogTable VALUES ('WebServer1',15,20)
INSERT INTO @LogTable VALUES ('WebServer1',16,18)
INSERT INTO @LogTable VALUES ('WebServer1',17,16)
INSERT INTO @LogTable VALUES ('WebServer1',18,14)
INSERT INTO @LogTable VALUES ('WebServer1',19,12)
INSERT INTO @LogTable VALUES ('WebServer1',20,10)
INSERT INTO @LogTable VALUES ('WebServer1',21,8)
INSERT INTO @LogTable VALUES ('WebServer1',22,6)
INSERT INTO @LogTable VALUES ('WebServer1',23,4) 

SELECT WebServer, [Hour], NumberOfUsers FROM @LogTable
</pre>
<p>Next create a table, using hour as the column and the number of users as the data field</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/Report.PNG" alt="Creating the table" align=left /></p>
<p>Now in right click on the report designer and select the &#8220;Report Properties&#8221; option, and then the &#8220;Code&#8221; tab.  Copy the GetHeatmapColor function (NOT the SqlReportingServicesHeatMapGenerator class) and paste it into the window</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/EnteringCode.PNG" alt="Entering the VBA code into the report"  /></p>
<p>Right click in the text box that you want to generate the heat map for and select &#8220;Text Box Properties&#8221; (or use the properties window)</p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/TextBoxProperties.PNG" alt="Text Box Properties"  /></p>
<p>Then choose the &#8220;Fill&#8221; tab and click the Expression button. </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/EnteringTheExpression.PNG" alt="Entering the Expression"  /></p>
<p>In the expression window enter the line below</p>
<pre class="brush: vb; gutter: false; toolbar: true;">
=Code.GetHeatmapColor(Sum(Fields!NumberOfUsers.Value), Min(Fields!NumberOfUsers.Value, &quot;DataSet1&quot;), Max(Fields!NumberOfUsers.Value, &quot;DataSet1&quot;))
</pre>
<p>As Bob says his post &#8220;The argument &#8216;Dataset1&#8242; defines the scope in which the min or max value is calculated, which must be a parent scope of the current scope.&#8221;</p>
<p>If you preview the report you should see the following </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/JagsHeatmapReport.PNG" alt="Jags Heat Map Report" width=700 height=57 align=left /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-to-create-heat-maps-in-sql-server-reporting-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pimp Up Your Unit Test Assertions</title>
		<link>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/</link>
		<comments>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 14:21:35 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=574</guid>
		<description><![CDATA[In this post I’m going to show you how you can write your unit test assertions to read more fluently and allow you to be more productive. 
The Plain Jane Unit Test Assertion

[Test]
public void The_Plain_Jane_Assertion()
{
    const string firstString = &#34;Hello World&#34;;
    const string secondString = &#34;Hello World&#34;;

   [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I’m going to show you how you can write your unit test assertions to read more fluently and allow you to be more productive. </p>
<h3 class="subheading">The Plain Jane Unit Test Assertion</h3>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void The_Plain_Jane_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.AreEqual(firstString, secondString);

    // Greater Than
    Assert.Greater(bigNumber,smallNumber);

    // Less Than
    Assert.Less(smallNumber,bigNumber);
}
</pre>
<p>This is what most developers will start off using.  No problem with the equals assertion it easy enough to read and use.  </p>
<p>However when using the greater or less than assertions, it’s not clear if the first argument should be the lower or the higher value as shown in the screen shot below.  </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/NUnitAssertConfusion.png" alt="NUnit Assert Confusion" style="border: solid #000000 1px;"/></p>
<p>This distraction can easily stop your flow.</p>
<h3 class="subheading">The More Fluent NUnit Test Assertion</h3>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void The_More_Fluent_Nunit_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.That(firstString, Is.EqualTo(secondString));

    // Greater Than
    Assert.That(bigNumber, Is.GreaterThan(smallNumber));

    // Less Than
    Assert.That(smallNumber, Is.LessThan(bigNumber));
}
</pre>
<p>The unit test assertions read a lot more fluently, we no longer have to be concerned about the order of arguments. </p>
<p>If you don’t want to use another third party library, this is for you.  </p>
<h3 class="subheading">The Super Fluent NBehave Spec Assertion</h3>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void The_Super_Fluent_NBehave_Spec_Assertion()
{
    const string firstString = &quot;Hello World&quot;;
    const string secondString = &quot;Hello World&quot;;

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    firstString.ShouldEqual(secondString);

    // Greater Than
    bigNumber.ShouldBeGreaterThan(smallNumber);

    // Less Than
    smallNumber.ShouldBeLessThan(bigNumber);
}
</pre>
<p>This example uses the NBehave Spec Framework which you can download from the <a href="http://nbehave.org/">NBehave</a> site.  In addition to being very easy to understand, the use of extension methods means there is a lot less noise. </p>
<p>Some developers will be concerned by losing the word ‘Assert’ in the line that does the assertion.  If you arrange your tests using the <strong>Arrange, Act, Assert</strong> pattern this should not be a problem.  See the example below.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
[Test]
public void The_NBehave_Spec_Assertion_Using_Arrange_Act_Assert()
{
    // Arrange
    const int inputValue = 1;

    // Act
    var result = inputValue + 1;

    // Assert
    result.ShouldBeGreaterThan(inputValue);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/pimp-up-your-unit-test-assertions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ever Thought About Changing How You Name Unit Tests?</title>
		<link>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/</link>
		<comments>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 12:40:04 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=556</guid>
		<description><![CDATA[In the last couple of months I’ve seen a new convention of how developers are naming their unit test classes.  
Traditionally the naming convention most developers use is to append the word ‘Tests’ to the class name as shown below.

public class UserValidation
{
}

[TestFixture]
public class UserValidationTests
{
}

There is absolutely nothing wrong with it, but this can lead [...]]]></description>
			<content:encoded><![CDATA[<p>In the last couple of months I’ve seen a new convention of how developers are naming their unit test classes.  </p>
<p>Traditionally the naming convention most developers use is to append the word ‘Tests’ to the class name as shown below.</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
public class UserValidation
{
}

[TestFixture]
public class UserValidationTests
{
}
</pre>
<p>There is absolutely nothing wrong with it, but this can lead to problems because a test class can become unwieldy and difficult to maintain either because it’s too long, testing a lot of different concerns or both.  </p>
<p>In some cases it would make more sense to take different approach and adopt an alternative naming convention.  Sticking with the example above instead of having tests for validating a user in one class, a new class could be created for each concern.  So instead of </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class UserValidationTests
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid(&quot;123456&quot;);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}
</pre>
<h3 class="subheading">we create two test classes</h3>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class When_Validating_A_Users_Username
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }
    }

    [TestFixture]
    public class When_Validating_A_Users_Password
    {
        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid(&quot;123456&quot;);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}
</pre>
<p>I think this behavior driven development type naming convention will help focus on the problem you are solving and nothing more.  This is very useful when doing test driven development.  </p>
<p>When I first saw tests written like this my first thought was how am I going to find the all the tests for User Validation because they are no longer in a single class?  If this is a problem for you think about using namespaces, folders or test attributes to organise your tests.  Don’t forget if you use tools like <a href="http://www.jetbrains.com/resharper/index.html">ReSharper</a> help you find where a class is being used very easily.   </p>
<p>Remember this is about renaming your tests classes and not your methods. So even if you follow the <a href="http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx">MethodName_StateUnderTest_ExpectedBehavior</a> pattern for test methods this could still work.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/ever-thought-about-changing-how-you-name-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Congratulations Chris Alcock on 500 Morning Brew Posts</title>
		<link>http://www.arrangeactassert.com/congratulations-chris-alcock-on-500-morning-brew-posts/</link>
		<comments>http://www.arrangeactassert.com/congratulations-chris-alcock-on-500-morning-brew-posts/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 08:36:43 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=547</guid>
		<description><![CDATA[My iGoogle page helps me keep up to date with the latest .Net news, podcasts and blogs with many RSS feeds I have subscribed to.    
Unfortunately I don&#8217;t have the time to check out all of them and so it can be difficult to decide what is worth reading.   
It&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>My iGoogle page helps me keep up to date with the latest .Net news, podcasts and blogs with many RSS feeds I have subscribed to.    </p>
<p>Unfortunately I don&#8217;t have the time to check out all of them and so it can be difficult to decide what is worth reading.   </p>
<p>It&#8217;s lucky for me then Chris Alcock does a really good job of giving a summary for each of the blog posts he thinks are worth reading on his <a href="http://www.themorningbrew.net/">Morning Brew posts</a>.</p>
<p>I reckon his <a href="http://blog.cwa.me.uk/">Reflective Perspective blog</a> must be the most underrated .Net blog.</p>
<p>Well done Chris, keep up the great work.</p>
<p>If you&#8217;re ever in Cambridge, I&#8217;ll buy you a beer.</p>
<p><a href="http://www.themorningbrew.net/linkhere/contribute.php"><img src="http://www.themorningbrew.net/linkhere/contributeimg.php" alt="I've contributed to The Morning Brew - Daily .NET News and Views" title="I've contributed to The Morning Brew - Daily .NET News and Views" border="0" /></a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/congratulations-chris-alcock-on-500-morning-brew-posts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pair Programming Is Not a Silver Bullet</title>
		<link>http://www.arrangeactassert.com/pair-programming-is-not-a-silver-bullet/</link>
		<comments>http://www.arrangeactassert.com/pair-programming-is-not-a-silver-bullet/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 08:09:37 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Extreme Programming (XP)]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=501</guid>
		<description><![CDATA[Over the past four weeks I have been working with a new start up company where the owners (who are developers themselves) want to use pair programming to do everything. 
In this blog post I want to share my experiences and opinions on pair programming.
This is not the first time I have done pair programming [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past four weeks I have been working with a new start up company where the owners (who are developers themselves) want to use pair programming to do everything. </p>
<p>In this blog post I want to share my experiences and opinions on pair programming.</p>
<p>This is not the first time I have done pair programming and it won’t be the last.  I chose the title because when you read about pair programming in extreme programming books, the ideas look great on paper but can be difficult to implement and don’t work in the real word.</p>
<h3 class="subheading">Two heads are better than one</h3>
<p>Developers who have had positive pair programming experiences write about</p>
<ul>
<li>how much more focused they were</li>
<li>increased productivity</li>
<li>better code quality</li>
<li>shared knowledge/less dependency on a single developer</li>
<li>how it helps new developers learn the ropes</li>
<li>quicker investigation and resolution of bugs</li>
<li>on the job training</li>
<li>why it’s so much better than doing code reviews</li>
</ul>
<p>On that last point Theodore Nguyen-Cao has made an excellent observation in his blog post <a href="http://www.theodorenguyen-cao.com/2008/10/29/pair-programming-greater-than-code-reviews/">Pair Programming > Code Reviews</a></p>
<blockquote><p>In code reviews, people sit down to review someone’s code. Everyone has an opinion but not everyone is going to be working with the code on a daily basis. At the time, everyone seems to be involved in the process but there is no vested interest. They are just looking at some code and asking themselves &#8220;does this code look good and is it correct?&#8221;. It’s a very passive standpoint. On the other hand, pair programmers are completely invested (committed?) in the task at hand. They immediately are using the code they are writing together and collaborating their thoughts on design, code layout, etc. Both programmers are taking on an active role and are emotionally invested in the task at hand because they are attacking the same problem together.</p></blockquote>
<h3 class="subheading">Shared Code Ownership</h3>
<p>Have you ever been in a situation where a ‘friend’ has become so attached to their code, they find it difficult to accept it doesn’t do what it’s supposed to or is no longer required?  </p>
<p>My best experience of pair programming has been taking over the lead development of a project where the previous developer had been working alone.  </p>
<p>When a colleague and I came to conclusion what had be done did not have anything to do with the problem domain, we decided to delete the code and pair together to ensure the same mistake did not happen again.  We continued to pair until we had a solid foundation to build upon.       </p>
<p>When code is written by a single developer, they will inevitably end up owning it.  No doubt you’ve heard something like “that’s Bobs login controller”.  If there’s a bug or issue with that code the developer can become very defensive.  </p>
<p>When a pair is told the same thing I think it’s a lot easier to deal with because no one person owns the code.  In addition developers working in a pair find it easier to accept the path they had followed has come to a dead end a lot quicker than a developer working alone.  </p>
<h3 class="subheading">Sounds great.  Where do I sign?</h3>
<p>Hold on comrade not so fast. </p>
<blockquote><p>Pair programming can be a bit like communism, too good to be true.</p></blockquote>
<p>One of the most difficult things in pair programming is finding a good pairing partner.  The general consensus is that developers need be at similar skill levels, understand the domain and offer something their partner other can’t.  </p>
<h3 class="subheading">All good relationships are about give and take</h3>
<p>Unless you’re a total idiot and couldn’t care what your pairing partner thinks, you will be conscious how your partner is feeling.  </p>
<p>If you hog the keyboard too much your partner will become a chicken, involved but not committed.  They will play with their phone, think about what to have for dinner, or even fall asleep.  </p>
<p>If you’re too passive, not wanting to ‘rock the boat’ you will be putting your name against something you don’t necessarily agree with.  This can even be an issue even when you have the keyboard, because all you’re doing is typing what the other is saying.   Lets hope your secretarial skills are up to the job.     </p>
<p>Some of you will be quick to point out the solution to this problem is to swap the driver/observer roles every 30 minutes or by adopting the <a href="http://en.wikipedia.org/wiki/Pair_programming#Ping_pong_pair_programming">ping pong pair programming pattern</a>. </p>
<p>However this doesn’t always solve the issue especially if you’re working with a control freak who says something like “why don’t <strong>you</strong> try this?” before taking back the keyboard.</p>
<p>In addition to changing roles within a pair, the developers in the pair should be rotated.</p>
<p>In the <a href="http://www.infoq.com/presentations/turning-on-a-sixpence">Turning on a sixpence &#8211; No excuses: Concept To Cash Every Week</a> video, developers working on a project for a broadcasting company changed pair in morning and afternoons.  This means over a course of two days five different developers would have been involved.</p>
<p>For example in the morning developer A would be ‘driving’, and developer B would be the ‘observer’.  In the afternoon developer A, would move onto something else, developer B would be ‘driving’ and developer C would be ‘observer’.</p>
<p>I know this is cynical but I can’t imagine that the first few minutes of a new pair starting aren&#8217;t spent bitching about the developer who has moved on, followed another half an hour taking out what they think is wrong and doing what they wanted to do.</p>
<h3 class="subheading">Developer Values</h3>
<p>There’s no doubt a developer has to make sacrifices when pairing.  What if you like doing test driven development, but your partner doesn’t?  You could</p>
<ul>
<li>suggest to try it out &#8211; and then try to look pleased when they don’t.</li>
<li>raise the issue &#8211; because that’s really going to help you build a relationship.</li>
<li>do nothing &#8211; it’s the easiest thing to do and you simply can’t face another day at work wasting time fighting your corner.
<li>
</ul>
<p>A good developer in a pair can’t argue with everything they don’t agree with, they have to bite their lip and let things slide. After all how much value is there in arguing if underscores should be used for private member variables.</p>
<h3 class="subheading">Thanks But No Thanks</h3>
<p>Many developers have said that pair programming is that it’s not for them.    </p>
<p><a href="http://www.guardian.co.uk/football/2009/dec/01/lionel-messi-ballon-dor-barcelona">Lionel Messi</a> European and soon to be crowned World footballer of the year is fantastic when he plays for Barcelona.  But when he plays for Argentina things don’t go so well.  The problem is the system he has to fit into.</p>
<blockquote><p>Why should a developer who is able to write good quality code on time be forced to fit into a process?  After all that isn’t agile about &#8216;Individuals and interactions over processes and tools&#8217;.</p></blockquote>
<p>And if you believe ‘people work harder when there is someone looking over their<br />
shoulder’ (see Mendelt Siebenga&#8217;s post <a href="http://agilesoftwaredevelopment.com/blog/mendelt/dirty-secret-pair-programming">The dirty secret of pair programming</a>), well that fits in with the Tayloristic view that workers are stupid, can&#8217;t be trusted because they don’t care about things and only managers know better. </p>
<p>When I’m working alone and have to solve a problem I can look on <del datetime="2009-12-08T22:51:18+00:00">the internet</del> Stack Overflow or ask a colleague.  </p>
<p>Sometimes when you&#8217;re pair programming trying to find a solution is like having a back seat driver on board, you&#8217;re unable to concentrate and have to speed read because your partner wanted to click on a different link or search for something else.    This clip sums up what I mean.</p>
<p><embed src="http://www.metacafe.com/fplayer/773285/harry_enfield_television_programme_you_didnt_wanna.swf" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" name="Metacafe_773285" align="center"> </embed><br /><font size = 1><a href="http://www.metacafe.com/watch/773285/harry_enfield_television_programme_you_didnt_wanna/">Harry Enfield Television Programme &#8211; You Didn&#8217;t Wanna</a> &#8211; <a href="http://www.metacafe.com/">A funny movie is a click away</a></font></p>
<p>On a lighter note some developers have pointed out they don’t like pair programming because to hygiene issues.  Sharing a keyboard and mouse with someone who doesn’t wash their hands, or having to sit in close proximity with someone who smells, is not a pleasant experience. </p>
<h3 class="subheading">Jag Reehal’s Final Thought on &#8216;Pair Programming Is Not a Silver Bullet&#8217;</h3>
<p>Should developers do pair programming all of the time? No.</p>
<blockquote><p>Developers should be trusted and left to their own deceives.  They should pair when they think it’s the right thing to do.</p></blockquote>
<p>When pair programming works it’s very good, not only for the project but for individuals as well.  The amount of keyboard shortcuts and tips and tricks I’ve picked up when pairing is amazing.  Check out <a href="http://weblogs.asp.net/rosherove/archive/2007/06/03/train-to-be-a-keyboard-master-with-keyboard-jedi.aspx">Keyboard Jedi</a> when you are pairing, it shows a visual list of shortcuts as they are being typed.  </p>
<p>It’s important that developers are able to read blogs, explore and experiment, which pair programming doesn’t really allow for because your partner has to agree with everything you want to do.  In his <a href="http://www.hanselman.com/blog/PDC09ASPNETMVC2NinjasStillOnFireBlackBeltTips.aspx">PDC 09 ASP.NET MVC 2: Ninjas Still on Fire Black Belt Tips talk Scott Hanselman</a> said &#8216;you can spot a good dev if their recent project list contains projects where they are just trying out stuff&#8217;.</p>
<p>For me code reviews come too late in the development process.  Pair programming should seriously be considered if code reviews are of paramount importance to you.  </p>
<p>As for the arguments about productivity and focus etc, yes it can help.  But I also believe developers working alone and using <a href="http://www.pomodorotechnique.com/">the pomodoro technique</a> could achieve similar results.  </p>
<p>I will never dictate my team have to do pair programming.  But I would be disappointed if they never tried.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/pair-programming-is-not-a-silver-bullet/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating the animals game using Asp.Net MVC, jQuery and jQueryUI</title>
		<link>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/</link>
		<comments>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 09:36:50 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[Unit tests]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery UI]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=483</guid>
		<description><![CDATA[A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the ‘Having fun with jQuery UI’ blog post. 
In this post we will go through how to create the game using ASP.NET MVC, jQuery and jQuery UI. 
The screenshot below shows the game [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the <a href="http://www.arrangeactassert.com/having-fun-with-jquery-ui/">‘Having fun with jQuery UI</a>’ blog post. </p>
<p>In this post we will go through how to create the game using <a href="http://www.asp.net/mvc/">ASP.NET MVC</a>, <a href="http://jquery.com/">jQuery</a> and <a href="http://jqueryui.com/">jQuery UI</a>. </p>
<p>The screenshot below shows the game running.  </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ScreenshotOfGameUsingASP.NET-MVC-jQueryAndjQueryUI.png" alt="Screenshot of Game using Asp.Net MVC, jQuery and jQueryUI" /></p>
<p>The code used for creating the game in ASP.NET MVC, jQuery and jQuery UI can be downloaded <a href="http://cid-8a29bf85dc9538dc.skydrive.live.com/self.aspx/.Public/GameUsingAspNetMVCandJQueryUI.zip">here</a>.  </p>
<h3 class="subheading">Getting Started</h3>
<p>Instead of three animals used in the demo, the game now contains fourteen.   I’ve created a repository which returns the animals.  To keep things simple there’s no database here, instead the animals are hard coded.  </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;

namespace GameUsingAspNetMVCandJQueryUI.Core.Repository
{
    public class AnimalsRepository : IAnimalsRepository
    {
        public IQueryable&lt;Animal&gt; GetAll()
        {
            return new Animal[]
                       {
                           new Animal(){Name = &quot;Cow&quot;},
                           new Animal(){Name = &quot;Cat&quot;},
                           new Animal(){Name = &quot;Chicken&quot;},
                           new Animal(){Name = &quot;Dog&quot;},
                           new Animal(){Name = &quot;Elephant&quot;},
                           new Animal(){Name = &quot;Giraffe&quot;},
                           new Animal(){Name = &quot;Hippo&quot;},
                           new Animal(){Name = &quot;Lion&quot;},
                           new Animal(){Name = &quot;Monkey&quot;},
                           new Animal(){Name = &quot;Mouse&quot;},
                           new Animal(){Name = &quot;Owl&quot;},
                           new Animal(){Name = &quot;Penguin&quot;},
                           new Animal(){Name = &quot;Pig&quot;},
                           new Animal(){Name = &quot;Sheep&quot;},
                       }
                .AsQueryable();
        }
    }
}
</pre>
<h3 class="subheading">Command Query Separation</h3>
<p>One of the features I have added is to ensure a correct answer for the current game could not be the correct answer in the next.  As the repository class was responsible for getting animals, having it contain any logic would violate good design principles.  </p>
<p>So the logic goes into the service layer which returns a data transfer object for animals and the correct answer.   </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.ExtensionMethods;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;

namespace GameUsingAspNetMVCandJQueryUI.Core.Service
{
    public class AnimalsService : IAnimalsService
    {
        private readonly IAnimalsRepository _animalsRepository;

        public AnimalsService(IAnimalsRepository animalsRepository)
        {
            _animalsRepository = animalsRepository;
        }

        public AnimalsDto GetAnimalsForGameWithCorrectAnswer(int numberOfAnimals, string previousAnimal)
        {
            AnimalsDto animalsDto = new AnimalsDto();
            animalsDto.Animals = _animalsRepository
                .GetAll()
                .Where(a =&gt; a.Name != previousAnimal)
                .Shuffle()
                .Take(numberOfAnimals);

            animalsDto.CorrectAnswer = animalsDto.Animals.Shuffle().First().Name;

            return animalsDto;
        }
    }
}
</pre>
<p>This also makes testing easier because the tests can focus on making sure the service is doing what it should like this</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
using NBehave.Spec.NUnit;
using NUnit.Framework;
using Rhino.Mocks;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class AnimalsServiceTests
    {
        private IAnimalsService _animalsService;
        private IAnimalsRepository _animalsRepository;

        private readonly IQueryable&lt;Animal&gt; _animalsStub = new Animal[]
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           }.AsQueryable();

        [SetUp]
        public void SetUp()
        {
            _animalsRepository = MockRepository.GenerateStub&lt;IAnimalsRepository&gt;();
            _animalsService = new AnimalsService(_animalsRepository);
        }

        [Test]
        public void Should_Exclude_Previous_Animal_When_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            var previousAnimal = _animalsStub.First();

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal.Name);

            // Assert
            result.Animals.Count(a =&gt; a.Name == previousAnimal.Name).ShouldEqual(0);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = String.Empty;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result..Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Null()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);
            string previousAnimal = null;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result.Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Correct_Answer_Should_Not_Be_Empty()
        {
            // Arrange
            _animalsRepository.Stub(a =&gt; a.GetAll()).Return(_animalsStub);            

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, null);

            // Assert
            result.CorrectAnswer.ShouldNotBeEmpty();
        }
    }
}
</pre>
<h3 class="subheading">The LINQ Shuffle</h3>
<p>Even though we have removed the previous answer, if the animals were returned as they are the answer would just be the next one in the list.  So to keep the game exciting, a shuffle extension method is used to shuffle the answers.  </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System;
using System.Collections.Generic;
using System.Linq;

namespace GameUsingAspNetMVCandJQueryUI
{
    public static class GameExtensions
    {
        public static IEnumerable&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; items)
        {
            var rnd = new Random();
            IEnumerable&lt;int&gt; numbers = Enumerable.Range(0, items.Count()).OrderBy(r =&gt; rnd.Next());
            var randomItems = new List&lt;T&gt;();
            foreach (int number in numbers)
            {
                randomItems.Add(items.Skip(number).First());
            }
            return randomItems;
        }
    }
}
</pre>
<p>This can be unit tested as shown below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System.Collections.Generic;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using NUnit.Framework;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class GameExtensionsTests
    {
        [Test]
        public void Can_Shuffle_Animals()
        {
            List&lt;Animal&gt; animals = new List&lt;Animal&gt;()
                           {
                               new Animal(){Name = &quot;Cow&quot;},
                               new Animal(){Name = &quot;Pig&quot;},
                               new Animal(){Name = &quot;Sheep&quot;},
                           };
            IList&lt;Animal&gt; result = animals.Shuffle().ToList();
            Assert.IsFalse(
                animals[0].Equals(result[0]) &amp;&amp;
                animals[1].Equals(result[1]) &amp;&amp;
                animals[2].Equals(result[2]),
                &quot;Animals should have been shuffled&quot;);
        }
    }
}
</pre>
<h3 class="subheading">What happens when a player opens the game in their browser?</h3>
<p>When the page loads an Ajax call is made using jQuery to an Asp.Net MVC action method which returns a JsonResult.  </p>
<pre class="brush: jscript; gutter: false; toolbar: true;">
   $.getJSON(&quot;/Game/GetAnimals&quot;,
            { numberOfAnimals: numberOfItemsToGet, previousAnimal: correctAnswer.text() },
            function(data) {
                addItems(data);
                $(&quot;#droppable&quot;).droppable(droppableOptions);
                assignDraggables();
                hideItemsForLevel();
                setUpSlider();
                setTimeout(function() {
                    instructions.text(instructionsText);
                    items.show();
                }, 1000);
            });
</pre>
<p>Two parameters are passed to the action method, one for the previous answer and the other for the number of animals required.  The reason for this is because we don’t want to transfer more data over the wire than required, why return fourteen animals when only six are required?  </p>
<p>The ‘GetAnimals’ Asp.Net MVC action method shown below serializes the view model returned by the service layer into JSON. </p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
using System.Web.Mvc;
using GameUsingAspNetMVCandJQueryUI.Core.Service;

namespace GameUsingAspNetMVCandJQueryUI.Controllers
{
    [HandleError]
    public class GameController : Controller
    {
        private readonly IAnimalsService _animalsService;

        public GameController(IAnimalsService animalsService)
        {
            _animalsService = animalsService;
        }

        public ActionResult Index()
        {
            return View(&quot;Index&quot;);
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = &quot;*&quot;)]
        public JsonResult GetAnimals(int numberOfAnimals, string previousAnimal)
        {
            return Json(_animalsService.GetAnimalsForGameWithCorrectAnswer(numberOfAnimals,previousAnimal));
        }
    }
}
</pre>
<blockquote><p>Notice how I have to be explicit about how I do NOT want the JsonResult to be cached.  If you don&#8217;t add this Internet Explorer will cache the result and you will get the same animals. </p></blockquote>
<h3 class="subheading">Using the jQuery and jQuery UI in the ASP.NET MVC View</h3>
<p>The JavaScript used the demo was good enough to perform the dragging and dropping of pictures so the good news is we can use it again here.  </p>
<p>An additional feature I have added is to allow the player to change the difficulty of the game by choosing how many animals are shown on the screen. </p>
<p>To do this I used the jQuery UI slider and jQuery fade functionality.  The reason I used fade rather show/hide in jQuery was because I didn’t want the animals to move position when a user changed the difficulty as this would have resulted in a poor user experience by confusing the player.</p>
<p>Currently the message which tells the player if they have selected an incorrect answer is shown when the user stops dragging the animal.  This is a problem because if the user drags a correct animal but doesn’t drop it on the droppable a message isn’t shown.  If I find a fix for this I’ll update the code and this post.</p>
<h3 class="subheading">Jag Reehal’s Final Thought on ‘Creating the animals game using Asp.Net MVC, jQuery and jQueryUI’ </h3>
<p>I’ve been using jQuery for a while now and I still love it.  </p>
<p>The jQuery UI library is very good and the <a href="http://jqueryui.com/about">jQuery UI team</a> have done a fantastic job creating demos and documentation.  </p>
<p>I really like how you can create your own custom javascript file which only contains the features you require from the library.  </p>
<p>No doubt some people will question why the service is returning a data transfer object.  I could have returned a collection of animals to the ASP.NET MVC controller and have it create an object to pass to the view.  The reason I didn’t do this is because I know the data transfer object will be used by another user interface layer (Silverlight) and because this would have bloated the controller and that’s not good.  A <a href="http://www.arrangeactassert.com/asp-net-mvc-controller-best-practices-%E2%80%93-skinny-controllers/">best practice for ASP.NET MVC is to have skinny controllers</a>.     </p>
<p>The images for the animals used in the game are from <a href="http://www.openclipart.org">http://www.openclipart.org</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/creating-the-animals-game-using-asp-net-mvc-jquery-and-jqueryui/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A solution for the Resharper Test Runner not picking up your latest changes</title>
		<link>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/</link>
		<comments>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 00:19:12 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Resharper]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=463</guid>
		<description><![CDATA[For a while now I thought there was a bug when using Resharper to run my unit tests.
Because my latest changes were not being picked up, I always had to build my solution first and then run the unit tests.
Not anymore.
Today a colleague showed me this &#8216;Build Settings&#8217; option 


Selecting ‘Always Build’ makes sure the [...]]]></description>
			<content:encoded><![CDATA[<p>For a while now I thought there was a bug when using <a href="http://www.jetbrains.com/resharper/">Resharper</a> to run my unit tests.</p>
<p>Because my latest changes were not being picked up, I always had to build my solution first and then run the unit tests.</p>
<p><strong>Not anymore.</strong></p>
<p>Today a colleague showed me this &#8216;Build Settings&#8217; option </p>
<p><img src="http://www.arrangeactassert.com/wp-content/themes/resources/images/ResharperUnitTestRunnerWindow.png" alt="Resharper Unit Test Runner Window" /></p>
<p><br/><br />
Selecting ‘Always Build’ makes sure the latest changes (even to config files) are used when running unit tests. The default is &#8216;Automatic&#8217; as shown above.</p>
<p>Just be aware of the size of your solution will have an impact on how long the tests will take to run.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/a-solution-for-the-resharper-test-runner-not-picking-up-your-latest-changes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Having fun with jQuery UI</title>
		<link>http://www.arrangeactassert.com/having-fun-with-jquery-ui/</link>
		<comments>http://www.arrangeactassert.com/having-fun-with-jquery-ui/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 23:32:30 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery UI]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=412</guid>
		<description><![CDATA[As my nephew is coming round to visit in a couple of weeks, I want to create a game he could play.  
The aim of the game is to match pictures to a word.  The demo shown below uses the jQuery UI library which makes the dragging and dropping possible.  If you [...]]]></description>
			<content:encoded><![CDATA[<p>As my nephew is coming round to visit in a couple of weeks, I want to create a game he could play.  </p>
<p>The aim of the game is to match pictures to a word.  The demo shown below uses the <a href="http://jqueryui.com/home">jQuery UI</a> library which makes the dragging and dropping possible.  If you want to know more check out the excellent <a href="http://jqueryui.com/demos/draggable/">draggable</a> and <a href="http://jqueryui.com/demos/droppable/">droppable</a> demos.<br />
<em><br />
 As this is just a demo the animals are hard coded so if you hit play again you will see the same animals.</em><br />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><br />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script><br />
<script src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/gameScript.js" type="text/javascript"></script>	</p>
<link href="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/gameStyles.css" rel="stylesheet" type="text/css" />
<div id="gameContainer">
<div id="gameTitle">Can you match the picture to the word?</div>
<p id="instructions">Drag the picture to the box on the right</p>
<div id="items">
	            <img class="draggable correct" id="Cow" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/cow.png" /><br />
	            <img class="draggable" id="Pig" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/pig.png" /><br />
	            <img class="draggable" id="Sheep" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/sheep.png" />
    </div>
<div id="droppable">
<p id="itemName">Cow</p>
</p></div>
<div id="results">
<div id="correctResult">
<input id="playAgain" type="button" value="Click here to play again"/></div>
<div id="incorrectResult"></div>
</p></div>
</div>
<p><br/><br />
The demo uses the <a href="http://jquery.com/">jQuery</a> and <a href="http://jqueryui.com/home">jQuery UI</a> libraries (hosted by Google) and the javascript shown below</p>
<pre class="brush: jscript; gutter: false; toolbar: true;">
$(function() {
    var result = $('#incorrectResult');
    var correctResult = $('#correctResult');

    $(&quot;.draggable&quot;).draggable({
        containment: '#gameContainer',
        revert: 'invalid',
        start: function(event, ui) {
            result.fadeOut(1000);
        },
        stop: function(event, ui) {
            if (!$(this).hasClass('correct')) {
                result.html(&quot;Try again that's a &quot; + $(this).attr(&quot;id&quot;));
                result.fadeIn(1000);
            }
        }
    });

    $(&quot;#droppable&quot;).droppable({
        accept: '.correct',
        drop: function(event, ui) {
            $(&quot;.draggable&quot;).draggable('disable');
            correctResult.fadeIn(1000);
            correctResult.prepend('Well done! You found the ' + ui.draggable.attr('id') + ' ');
        }
    });

    $(&quot;#playAgain&quot;).click(function() {
        location.reload(true);
    });
});
</pre>
<p>The html used to create the game looks like this</p>
<pre class="brush: xml; gutter: false; toolbar: true;">
&lt;div id=&quot;gameContainer&quot;&gt;
    &lt;div id=&quot;gameTitle&quot;&gt;Can you match the picture to the word?&lt;/div&gt;
    &lt;p id=&quot;instructions&quot;&gt;Drag the picture to the box on the right&lt;/p&gt;
    &lt;div id=&quot;items&quot;&gt;
        &lt;img class=&quot;draggable correct&quot; id=&quot;Cow&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/cow.png&quot; /&gt;&lt;br /&gt;
        &lt;img class=&quot;draggable&quot; id=&quot;Pig&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/pig.png&quot; /&gt;&lt;br /&gt;
        &lt;img class=&quot;draggable&quot; id=&quot;Sheep&quot; src=&quot;http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/sheep.png&quot; /&gt;
    &lt;/div&gt;
    &lt;div id=&quot;droppable&quot;&gt;
        &lt;p id=&quot;itemName&quot;&gt;Cow&lt;/p&gt;
    &lt;/div&gt;
    &lt;div id=&quot;results&quot;&gt;
        &lt;div id=&quot;correctResult&quot;&gt;
            &lt;input id=&quot;playAgain&quot; type=&quot;button&quot; value=&quot;Click here to play again&quot; /&gt;
        &lt;/div&gt;
        &lt;div id=&quot;incorrectResult&quot; /&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p><em>Yes the html and javascript won’t win any awards, the fact it works in a blog post is good enough for me <img src='http://www.arrangeactassert.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </em></p>
<h3 class="subheading">What’s next?</h3>
<p>To begin with I will create a version of the game using ASP.NET MVC, jQuery and jQuery UI.  This will look like demo shown in this post with additional functionality to randomise the pictures.  </p>
<p>Then I will create a version of the game using Silverlight. </p>
<p>Once this is complete I will refactor both solutions to share as much code as possible.  I’m assuming <a href="http://code.msdn.microsoft.com/RiaServices">RIA services</a> is the tool of choice but we will see.  </p>
<p>After that maybe (way in the future) I might attempt to write this game for the Android platform and take advantage of touch screen mobile phones.  I have never developed an application before so this should be an interesting challenge.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/having-fun-with-jquery-ui/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Excellent FREE resource for learning Domain Driven Design</title>
		<link>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/</link>
		<comments>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 11:09:35 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Extreme Programming (XP)]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=407</guid>
		<description><![CDATA[If you asked developers what books they should read, most would (or should) include Domain Driven Design by Eric Evans.
Why is it important?
The patterns and practices outlined in this book will help you develop more successful software solutions.  
How?
Eric Evans shows how you can improve communication with your customer (by doing things like developing [...]]]></description>
			<content:encoded><![CDATA[<p>If you asked developers what books they should read, most would (or should) include <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven Design by Eric Evans</a>.</p>
<p><strong>Why is it important?</strong></p>
<p>The patterns and practices outlined in this book will help you develop more successful software solutions.  </p>
<p><strong>How?</strong></p>
<p>Eric Evans shows how you can improve communication with your customer (by doing things like developing a ubiquitous language), implement agile practices and create maintainable solutions which follow good software development principles.  </p>
<p><em>One of common criticisms of the book is that ‘it does go on a bit’.</em></p>
<p>The good news is that the folks over at <a href="http://www.infoq.com">InfoQ</a> have come up with ‘<a href="http://www.infoq.com/minibooks/domain-driven-design-quickly">Domain Driven Design Quickly</a>’ which summarizes what Domain Driven Design is about.</p>
<p>The even better news is that it’s FREE if you register with <a href="http://www.infoq.com">InfoQ</a>, which is no bad thing because it&#8217;s a fantastic resource with videos, presentations and some very good articles. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
