<?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>Quickduck</title>
	<atom:link href="http://quickduck.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://quickduck.com/blog</link>
	<description>Straight from the mind of geniuseseses....</description>
	<lastBuildDate>Wed, 20 Jan 2010 07:52:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Path resolution in ASP.NET</title>
		<link>http://quickduck.com/blog/2010/01/14/path-resolution-in-asp-net/</link>
		<comments>http://quickduck.com/blog/2010/01/14/path-resolution-in-asp-net/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 14:15:20 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=249</guid>
		<description><![CDATA[One thing I&#8217;ve always thought that ASP.NET doesn&#8217;t do a great job of is handling resource paths. For example, lets say on your development box, you have a website hosted under the virtual directory &#8220;MyProject&#8221;, such that you browse to http://localhost/MyProject/ to go to the home page. Lets also say that when you deploy the [...]]]></description>
			<content:encoded><![CDATA[<p>One thing I&#8217;ve always thought that ASP.NET doesn&#8217;t do a great job of is handling resource paths. For example, lets say on your development box, you have a website hosted under the virtual directory &#8220;MyProject&#8221;, such that you browse to <span style="font-family:courier">http://localhost/MyProject/</span> to go to the home page. Lets also say that when you deploy the website to an external domain, it falls into the domain root, so instead you go to <span style="font-family:courier">http://myproject.com/</span> to see your home page.</p>
<p>Sound familiar? The real problem then comes when you try and define a resource (e.g. a javascript file) using a relative path:</p>
<pre class="brush: xml;">
&lt;script
    type=&quot;text/javascript&quot;
    src=&quot;/Scripts/jquery.js&quot;&gt;
</pre>
<p>This will work fine and dandy when you deploy the website, however on your local machine it will be looking for jquery at the path <span style="font-family:courier">http://localhost/Scripts/jquery.js&#8221;</span> &#8211; which more than likely isn&#8217;t going to work.</p>
<p>To get around this problem, I wrote a quick helper method called &#8220;Locate&#8221;, which I find myself reusing time and time again between websites. More often than not, I put it into a static class called &#8220;SiteManager&#8221; which basically just contains a bunch of helper functions relevant to the current website. Here&#8217;s the method:</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// Resolves the path to a URL
/// &lt;/summary&gt;
/// &lt;param name=&quot;url&quot;&gt;The path to be resolved, relative to the
/// application root&lt;/param&gt;
/// &lt;param name=&quot;formatArgs&quot;&gt;String formatting arguments&lt;/param&gt;
/// &lt;returns&gt;The URL&lt;/returns&gt;
static public string Locate(string url, params object[] formatArgs)
{
    if (String.IsNullOrEmpty(url))
        url = &quot;/&quot;;

    if (formatArgs != null &amp;&amp; formatArgs.Length &gt; 0)
        url = String.Format(url, formatArgs);

    HttpContext context = HttpContext.Current;
    return String.Concat(
        context.Request.ApplicationPath,
        !url.StartsWith(&quot;/&quot;) ? &quot;/&quot; : String.Empty,
        url);
}
</pre>
<p>To use the method, you simply change your script declaration (or whatever resource you&#8217;re trying to find) as follows:</p>
<pre class="brush: csharp; html-script: true;">
&lt;script
    type=&quot;text/javascript&quot;
    src=&quot;&lt;%= SiteManager.Locate(&quot;/Scripts/jquery.js&quot;) %&gt;&quot;&gt;
&lt;/script&gt;
</pre>
<p>You&#8217;ll also notice that it supports string formatting &#8211; so even though it would be pointless in this particular example, you could, if you preferred, do something like this:</p>
<pre class="brush: csharp; html-script: true;">
&lt;script
    type=&quot;text/javascript&quot;
    src=&quot;&lt;%= SiteManager.Locate(&quot;/Scripts/{0}.js&quot;, &quot;jquery&quot;) %&gt;&quot;&gt;
&lt;/script&gt;
</pre>
<p>In both instances, this will resolve the URL in your output document using the current application path &#8211; </p>
<ul>
<li><span style="font-family:courier">http://localhost/MyProject/Scripts/jquery.js</span> on your local machine; and</li>
<li><span style="font-family:courier">http://myproject.com/Scripts/jquery.js</span> on the web server.</li>
</ul>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2010/01/14/path-resolution-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Creating your own ContentTemplates in WPF</title>
		<link>http://quickduck.com/blog/2009/12/23/creating-your-own-contenttemplates-in-wpf/</link>
		<comments>http://quickduck.com/blog/2009/12/23/creating-your-own-contenttemplates-in-wpf/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 12:00:36 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=244</guid>
		<description><![CDATA[This isn&#8217;t something that I do often, but rolling your own look-and-feel by starting a ContentTemplate from scratch can be a right pain in the botty. Today I found this excellent sample project from Microsoft, which contains custom ContentTemplates for most UI controls in the framework. It provides an excellent starting point for creating your [...]]]></description>
			<content:encoded><![CDATA[<p>This isn&#8217;t something that I do often, but rolling your own look-and-feel by starting a ContentTemplate from scratch can be a right pain in the botty. Today I found <a href="http://msdn.microsoft.com/en-us/library/ms771597.aspx">this excellent sample project from Microsoft</a>, which contains custom ContentTemplates for most UI controls in the framework. It provides an excellent starting point for creating your own customized controls.</p>
<p>Check it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/12/23/creating-your-own-contenttemplates-in-wpf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Quick WPF Performance Statistics</title>
		<link>http://quickduck.com/blog/2009/12/23/quick-wpf-performance-statistics/</link>
		<comments>http://quickduck.com/blog/2009/12/23/quick-wpf-performance-statistics/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 01:15:56 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=239</guid>
		<description><![CDATA[Just thought I&#8217;d put out some quick WPF performance statistics thanks to Microsoft. You can download the entire slideshow here.

DependencyProperty is x3 faster than INotifyPropertyChanged
ObservableCollection accesses single items 90 times faster than List
ObjectDataProvider is x20 smaller than XmlDataProvider

Microsoft also have some other good tips over here too.
I&#8217;d like to see some real world statistics on the differences [...]]]></description>
			<content:encoded><![CDATA[<div>Just thought I&#8217;d put out some quick WPF performance statistics thanks to Microsoft. You can download the entire slideshow <a title="WPF Performance Best Practices" href="http://download.microsoft.com/download/B/8/8/B8813050-D289-4A78-9A27-AA4ED49BCC65/2009-03-11_TechDays_MSDN_012.pptx" target="_blank">here</a>.</div>
<ul>
<li>DependencyProperty is x3 faster than INotifyPropertyChanged</li>
<li>ObservableCollection accesses single items 90 times faster than List</li>
<li>ObjectDataProvider is x20 smaller than XmlDataProvider</li>
</ul>
<p>Microsoft also have some other good tips over <a title="WPF Performance Best Practices" href="http://msdn.microsoft.com/en-us/library/aa970683.aspx">here</a> too.<br />
I&#8217;d like to see some real world statistics on the differences between using static vs dynamic resources too. Anybody know of any?</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/12/23/quick-wpf-performance-statistics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Containing floats in HTML</title>
		<link>http://quickduck.com/blog/2009/11/27/containing-floats-in-html/</link>
		<comments>http://quickduck.com/blog/2009/11/27/containing-floats-in-html/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 14:46:30 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[Asp.Net]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=219</guid>
		<description><![CDATA[Have you ever created a block-level element (e.g. a div), whose only contents are floating elements &#8211; only to find that your block-level element doesn&#8217;t stretch down to contain it&#8217;s children? Well, I have, and it&#8217;s a problem that always annoys me because I can never bring to mind the easiest way of fixing it.
The [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever created a block-level element (e.g. a div), whose only contents are floating elements &#8211; only to find that your block-level element doesn&#8217;t stretch down to contain it&#8217;s children? Well, I have, and it&#8217;s a problem that always annoys me because I can never bring to mind the easiest way of fixing it.</p>
<p>The simplest solution is to use &#8220;overflow:hidden&#8221; in the style of your parent element, however this doesn&#8217;t work for all browsers scenarios. So, for a much more comprehensive description of the problem, as well as a number of approaches you can use to solve it, check out <a href="http://www.ejeliot.com/blog/59">this post</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/11/27/containing-floats-in-html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AutoMapper</title>
		<link>http://quickduck.com/blog/2009/11/15/automapper/</link>
		<comments>http://quickduck.com/blog/2009/11/15/automapper/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 04:24:20 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=203</guid>
		<description><![CDATA[Ever had those mundane tasks of mapping your entities to Data Transfer Objects for use in your service layer? While browsing the web the other day I found this great tool called AutoMapper which does a superb job in filling this void.
Writing mapping code is painful, creates more work and means you have more tests [...]]]></description>
			<content:encoded><![CDATA[<p>Ever had those mundane tasks of mapping your entities to Data Transfer Objects for use in your service layer? While browsing the web the other day I found this great tool called <a title="AutoMapper" href="http://www.codeplex.com/AutoMapper" target="_blank">AutoMapper</a> which does a superb job in filling this void.</p>
<p>Writing mapping code is painful, creates more work and means you have more tests to write. This is where AutoMapper fits in.</p>
<p>Given the following entities:</p>
<pre class="brush: csharp;">
public class Bank {
public string Name{ get; set; }
}

public class Customer {
public string Name { get; set; }
public Bank BankDetails{ get; set; }
}

public class CustomerDTO {
public string Name { get; set; }
public string BankName{ get; set; }
}
</pre>
<p>Now all we need to do is use the mapper in code like so:</p>
<pre class="brush: csharp;">
AutoMapper.CreateMap&lt;Customer, CustomerDTO&gt;(); //setup the mappings
Customer newCustomer = new Customer() {Name = &quot;test&quot; };
CustomerDTO transformedCustomer = AutoMapper.Map&lt;Customer, CustomerDTO&gt;(newCustomer);
</pre>
<p>Brilliant! We now have a working CustomerDTO object and it even mapped our BankName for us without even setting up any custom mapping. Here is what AutoMapper can do for you:</p>
<ul>
<li>Matching property names</li>
<li>Methods starting with the word &#8220;Get&#8221; automatically get mapped. e.g. GetAccountBalance() maps to AccountBalance</li>
<li>Nested property names (Bank.Name maps to BankName, pretty sure this only works with PascalCase)</li>
</ul>
<p>AutoMapper can also <a title="Mapping Collections" href="http://automapper.codeplex.com/wikipage?title=Lists%20and%20Arrays&amp;referringTitle=Home">map collections</a> for you too. One of the things to remember here is you don&#8217;t need to create a mapping for collections, just the element types.</p>
<p>For the testers amongst us I hear you say that you now can&#8217;t test your mappings like you could before with custom mapping code. Well there is an answer to this.</p>
<pre class="brush: csharp;">
Mapper.AssertConfigurationIsValid();
</pre>
<p>This method will assert that all properties from the source will be mapped to something on the destination object. Mapping objects is now no longer painful!</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/11/15/automapper/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Question of the day: Enums</title>
		<link>http://quickduck.com/blog/2009/10/07/question-of-the-day-enums/</link>
		<comments>http://quickduck.com/blog/2009/10/07/question-of-the-day-enums/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 10:20:41 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Daily Question]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=198</guid>
		<description><![CDATA[Some fun with enums! Assume you have an enum defined as follows:

enum Frequency {
    None = 0,
    Annual = 1,
    SemiAnnual = 2,
    Quarterly = 4,
    Monthly = 12,
    Weekly = 52
}

Now, given the following block of [...]]]></description>
			<content:encoded><![CDATA[<p>Some fun with enums! Assume you have an enum defined as follows:</p>
<pre class="brush: csharp;">
enum Frequency {
    None = 0,
    Annual = 1,
    SemiAnnual = 2,
    Quarterly = 4,
    Monthly = 12,
    Weekly = 52
}
</pre>
<p>Now, given the following block of code:</p>
<pre class="brush: csharp;">
Frequency myFrequency = (Frequency) 104;
System.Console.WriteLine(&quot;My frequency is: {0}&quot;, myFrequency.ToString());
bool is100Defined = Enum.IsDefined(typeof(Frequency), 100);
bool is52Defined  = Enum.IsDefined(typeof(Frequency), 52);
</pre>
<ol>
<li>What is written to the console?</li>
<li>What is the value of is100Defined?</li>
<li>What is the value of is52Defined?</li>
</ol>
<p>First correct answer gets absolutely nothing (but think how great you&#8217;ll feel!)</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/10/07/question-of-the-day-enums/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What Is a Race Condition?</title>
		<link>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/</link>
		<comments>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 09:13:44 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=188</guid>
		<description><![CDATA[Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A race condition is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below:

function ValidateInput() {
//some slow running code here...
}

function [...]]]></description>
			<content:encoded><![CDATA[<p>Just thought I would put a post out on something I learnt today that can occur when using ajax- a race condition. A <a href="http://en.wikipedia.org/wiki/Race_condition" target="_blank">race condition</a> is is where the output or result of something is dependent on the timing of other events/code. A good example of this is below:</p>
<pre class="brush: jscript;">
function ValidateInput() {
//some slow running code here...
}

function SaveForm() {
//save the form
}
</pre>
<pre class="brush: xml;">

&lt;form&gt;
&lt;input type=&quot;text&quot; onchange=&quot;ValidateInput()&quot; /&gt;
&lt;input type=&quot;button&quot; onclick=&quot;SaveForm();&quot; value=&quot;Submit&quot; /&gt;
&lt;/form&gt;
</pre>
<p>The problem here can occur when the user hits the Submit button before the validation method can finish. One way to overcome this is use a <a title="Semaphore" href="http://en.wikipedia.org/wiki/Semaphore_%28programming%29" target="_blank">semaphore</a> to indicate whether the form still needs validating on the SaveForm method.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/10/06/what-is-a-race-condition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get a TreeViewItem&#8217;s Parent item</title>
		<link>http://quickduck.com/blog/2009/09/15/get-a-treeviewitems-parent-item/</link>
		<comments>http://quickduck.com/blog/2009/09/15/get-a-treeviewitems-parent-item/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 22:06:31 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=170</guid>
		<description><![CDATA[Further to Gerrod&#8217;s post on selecting an item in a treeview, I found myself scratching my head on how to find a treeviewitem&#8217;s parent item. Here I was expecting a TreeViewItem.Parent property. Unfortunately after scouring the dark depths of the internet, I found that using the VisualTreeHelper class was the answer:


private static TreeViewItem GetParentTreeViewItem(DependencyObject item)

{
if [...]]]></description>
			<content:encoded><![CDATA[<p>Further to Gerrod&#8217;s post on <a href="http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/" target="_self">selecting an item in a treeview</a>, I found myself scratching my head on how to find a treeviewitem&#8217;s parent item. Here I was expecting a TreeViewItem.Parent property. Unfortunately after scouring the dark depths of the internet, I found that using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.aspx">VisualTreeHelper</a> class was the answer:</p>
<pre class="brush: csharp;">

private static TreeViewItem GetParentTreeViewItem(DependencyObject item)

{
if (item != null)
{
  DependencyObject parent = VisualTreeHelper.GetParent(item);
  TreeViewItem parentTreeViewItem = parent as TreeViewItem;
  return parentTreeViewItem ?? GetParentTreeViewItem(parent);
}

return null;
}
</pre>
<p>I&#8217;m sure this can be easily converted into an extension method for those of you expecting the Parent property like I was.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/09/15/get-a-treeviewitems-parent-item/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unit Testing DateTime.Now</title>
		<link>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/</link>
		<comments>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 11:54:45 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=138</guid>
		<description><![CDATA[I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it.
Consider the follow code:
public class MyEntity
 {
   public DateTime Created { get; set; }
 }

 public class MyRepository
 {
 [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it.</p>
<p>Consider the follow code:</p>
<pre class="brush: csharp;">public class MyEntity
 {
   public DateTime Created { get; set; }
 }

 public class MyRepository
 {
   public void UpdateMyEntity(MyEntity entity)
   {
     entity.Created = DateTime.Now;
   }
 }</pre>
<p>Unless you are one of one of those fancy pants with <a title="TypeMock" href="http://www.typemock.com/" target="_blank">TypeMock</a> and the ability to <a title="Typemock Isolator 5.3.1 can fake DateTime.Now" href="http://bloggingabout.net/blogs/dennis/archive/2009/06/03/typemock-isolator-5-3-1-can-fake-datetime-now.aspx" target="_blank">fake DateTime.Now</a>, the rest of use must look elsewhere for a solution. Here are three different ways to solve this.</p>
<p><strong>1. Wrap your DateTime calls with another class</strong></p>
<p><a title="Dealing with time in tests" href="http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" target="_blank">Some people</a> prefer using a static &#8220;Clock&#8221; class to handle this which can be easily faked out during your unit testing.</p>
<pre class="brush: csharp;">
public static class Clock
{
    public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;
}
</pre>
<p>This approach, while decoupling your dependency on System.DateTime is a bit of overkill and requires all developers on the project to be aware of it and to use it.</p>
<p><strong>2.Use an Interface and your favourite Isolation Framework</strong><span> </span></p>
<pre class="brush: csharp;">
public interface IClock
{
  DateTime Now {get;}
}

public class SystemClock : IClock
{
  public DateTime Now { get { return DateTime.Now; } }
}
</pre>
<p>You can now use an isolation framework such as <a title="Rhino Mocks" href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino.Mocks</a> to fake the call to Now();</p>
<p><strong>3. Use a DateTime Comparer that accepts a range</strong></p>
<p>While not 100% accurate to the millisecond, this approach is my prefered approach as you don&#8217;t have to change to your code just to unit test it. No littering your code with IClock dependencies or using a delegate to return the current DateTime.Now (although one could argue that DateTime.Now <a title="Properties vs Methods" href="http://msdn.microsoft.com/en-us/library/bzwdh01d%28VS.71%29.aspx#cpconpropertyusageguidelinesanchor1" target="_blank">shouldn&#8217;t be a property</a> to begin with). This approach asserts that the Created property that is set in MyRepository.Update is within a certain range.</p>
<pre class="brush: csharp;">
 /// &lt;summary&gt;
 /// Helper class to compare 2 values are within a certain range.
 /// &lt;/summary&gt;
 public class DateComparer : IComparer&lt;DateTime&gt;
 {
 public TimeSpan MarginOfError { get; private set; }

 public DateComparer(TimeSpan marginOfError)
 {
   MarginOfError = marginOfError;
 }

  public int Compare(DateTime x, DateTime y)  // x = expected, y = actual
   {
     var margin = x - y;
     if (margin &lt;= MarginOfError)
       return 0;
     return new Comparer(CultureInfo.CurrentUICulture).Compare(x, y);
   }
 }
</pre>
<p>You can now write the follow test:</p>
<pre class="brush: csharp;">
public void MyRepository_UpdateTest()
 {
   var repository = new MyRepository();
   var entity = new MyEntity();
   repository.UpdateMyEntity(entity);
   var comparer = new DateComparer(new TimeSpan(0, 0, 0, 5));
   Assert.IsTrue(comparer.Compare(entity.Created, DateTime.Now) == 0);
 }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Expression Tree Equality</title>
		<link>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/</link>
		<comments>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 03:31:02 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Comparison]]></category>
		<category><![CDATA[Equality]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=131</guid>
		<description><![CDATA[Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.
This method will fail

[TestMethod]
public void TestDoesNotWork()
{
  Expression&#60;Func&#60;int, int&#62;&#62; expressionA = x =&#62; x + 1;
  Expression&#60;Func&#60;int, int&#62;&#62; expressionB = x =&#62; x + [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.</p>
<p><strong>This method will fail</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesNotWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA, expressionB);
}
</pre>
<p>This looks like it should work however it doesn&#8217;t. This is because when using anonymous expressions/delegates the CLR does some magic behind the scene to add a method on the fly, creating a new instance for every anonymous expression/delegate.</p>
<p>So if you have two expressions that are syntactically the same but not the same reference the easiest way to ensure they are the same is to compile the expression and invoke it comparing the resultant value.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA.Compile().Invoke(3), expressionB.Compile().Invoke(3));
}
</pre>
<p>An alternate approach would be to de-construct each constituent part of the expression trees comparing each part as you go. This however is far more complex.</p>
<p>For a more real world example that involves using Rhino mocks and Expect calls please read on:</p>
<p><span id="more-131"></span></p>
<p>When using Rhino Mocks and setting up an Expect call on a method that takes an expression you will most likely find that the Expect assertion always fails.</p>
<p><strong> The class that will be mocked out.</strong><br />
This class will have the method on it that takes an expression.</p>
<pre class="brush: csharp;">
public class Repository
{
  public virtual void Get&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition)
  {
        // Actual logic.
   }
}
</pre>
<p><strong>The class we are unit testing</strong></p>
<pre class="brush: csharp;">
public class UserManager
{
  public Repository Repo { get; set; }

  public void GetUserById(int id)
  {
    Repo.Get&lt;User&gt;(x =&gt; x.Id == id);
  }
}
</pre>
<p><strong>Supporting classes</strong></p>
<pre class="brush: csharp;">
public class User
{
  public int Id { get; set;  }
  public int Name { get; set; }
}
</pre>
<p>For our unit test we want to test that when we call the GetUserById() method on the UserManager class that we Expect the Repository.Get<TEntity>() method will be called with an expected expression value.</p>
<p><strong>Unit Test</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void Test()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };
  manager.Repo.Expect(r =&gt; r.Get&lt;User&gt;(x =&gt; x.Id == 3));

  // Act
  manager.GetUserById(3);

  // Assert
  manager.Repo.VerifyAllExpectations();
}
</pre>
<p>This looks like it should work however it won&#8217;t.</p>
<p>So using the approach listed earlier we can test that the method with an expression is called with the correct value by compiling and invoking the expected expression and the actual expression that was called and comparing their values.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestExpressionCalled()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };

  // Act
  manager.GetUserById(3);

  // Assert
  Expression&lt;Func&lt;User, bool&gt;&gt; expected = x =&gt; x.Id == 3;
  Expression&lt;Func&lt;User, bool&gt;&gt; actual = (Expression&lt;Func&lt;User, bool&gt;&gt;)manager.Repo.GetArgumentsForCallsMadeOn(r =&gt; r.Get&lt;User&gt;(null))[0][0];

  User user = new User { Id = 3 };
  Assert.AreEqual(expected.Compile().Invoke(user), actual.Compile().Invoke(user));
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
