<?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 &#187; C#</title>
	<atom:link href="http://quickduck.com/blog/category/development/net/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://quickduck.com/blog</link>
	<description>Straight from the mind of geniuseseses....</description>
	<lastBuildDate>Wed, 30 Jun 2010 10:52:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>DateTime Localization in ASP .NET</title>
		<link>http://quickduck.com/blog/2010/06/18/datetime-localization-in-asp-net/</link>
		<comments>http://quickduck.com/blog/2010/06/18/datetime-localization-in-asp-net/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 08:11:25 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=298</guid>
		<description><![CDATA[You&#8217;ve got an ASP .NET app and you need to display a date. Normally that just involves the old DateTime.ToShortDateString() or DateTime.ToString(&#8220;d&#8221;) and you continue coding on your merry little way. But what happens when your users are from different countries and expect different date formats.  Between Australia, USA and Japan there are 3 different [...]]]></description>
			<content:encoded><![CDATA[<p>You&#8217;ve got an ASP .NET app and you need to display a date. Normally that just involves the old DateTime.ToShortDateString() or DateTime.ToString(&#8220;d&#8221;) and you continue coding on your merry little way. But what happens when your users are from different countries and expect different date formats.  Between Australia, USA and Japan there are 3 different date formats.</p>
<p>Then answer? The HttpRequest&#8217;s UserLanguages. This string array basically maps to the following languages that you can setup in your browser:</p>
<p><a href="http://quickduck.com/blog/wp-content/uploads/2010/06/screenshot.png"><img class="alignnone size-full wp-image-301" title="languages" src="http://quickduck.com/blog/wp-content/uploads/2010/06/screenshot.png" alt="" width="592" height="465" /></a></p>
<p>Now for the code:</p>
<pre class="brush: csharp;">

CultureInfo culture = Request.UserLanguages != null
? CultureInfo.CreateSpecificCulture(Request.UserLanguages[0])
: CultureInfo.CurrentCulture;
myLabel.Text = DateTimeOffset.Now.ToLocalTime().ToString(&quot;d&quot;, culture);
</pre>
<div>Don&#8217;t forget to check if the UserLanguages is not null since you can remove all the values from the list if you like.</div>
<div>Also, if you are looking at ways to do this client side, ScottGu&#8217;s Blog has a nice <a title="jQuery Globalization Plugin from Microsoft" href="http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx" target="_blank">post on a new jquery plugin</a> for this.</div>
<p><strong>* Update *</strong><br />
Just realised that you don&#8217;t need to any of this if you use the following in your web.config:</p>
<pre class="brush: xml;">
&lt;globalization uiCulture=&quot;auto&quot; culture=&quot;auto&quot; /&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2010/06/18/datetime-localization-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parsing comma separated values with regular expressions</title>
		<link>http://quickduck.com/blog/2010/05/15/parsing-comma-separated-values-with-regular-expressions/</link>
		<comments>http://quickduck.com/blog/2010/05/15/parsing-comma-separated-values-with-regular-expressions/#comments</comments>
		<pubDate>Fri, 14 May 2010 21:22:01 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[RegEx]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=282</guid>
		<description><![CDATA[We&#8217;ve all had to write code to parse comma separated values before; it sounds simple, but it can actually be quite tricky! Sure, if our lists were always nicely defined like this: &#8220;one&#8221;,&#8221;two&#8221;,&#8221;three&#8221;,&#8221;four&#8221; five,six,seven,eight Then we could simply use String.Split. But life is never that kind! When your input strings may be a bit more [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve all had to write code to parse comma separated values before; it sounds simple, but it can actually be quite tricky! Sure, if our lists were always nicely defined like this:</p>
<ul>
<li>&#8220;one&#8221;,&#8221;two&#8221;,&#8221;three&#8221;,&#8221;four&#8221;</li>
<li>five,six,seven,eight</li>
</ul>
<p>Then we could simply use String.Split. But life is never that kind! When your input strings may be a bit more loosely defined, like this:</p>
<ul>
<li>one,&#8221;two,three&#8221;,four,,six,&#8221;seven&#8221;</li>
<li>,two,&#8221;three,four,five&#8221;,,</li>
</ul>
<p>It gets a little tougher.</p>
<p>So can you do it using a single regular expression? Yes, you most certainly can! It&#8217;s simply a matter of breaking down the possibilities, then catering for the <em>best case scenario</em> (quoted values), down to the <em>worse case scenario</em> (zero-length values), and finally, catering for the delimiters (either a comma, or the end of the string). Lets look at them one step at a time.</p>
<p>Firstly, quoted values. This is by far the easiest of all the conditions &#8211; find any length of text between two quotes. We&#8217;ll use a non-greedy expression (the question mark after the star) to ensure we don&#8217;t over-extend the length of text that we match:</p>
<pre class="brush: csharp;">
private const string
    Template_QuotedValues = @&quot;&quot;&quot;(?&lt;content&gt;.*?)&quot;&quot;&quot;;
</pre>
<p>The next easiest type of match to capture are non-quoted, non-zero length values. To do this, we&#8217;ll simply look for one or more characters which are <em>not</em> a comma. Again, we&#8217;re using a non-greedy match:</p>
<pre class="brush: csharp;">
private const string
    Template_UnquotedValues = @&quot;(?&lt;content&gt;[^,]+?)&quot;;
</pre>
<p>Notice also that that for both templates, we&#8217;re creating a named group called &#8220;content&#8221; &#8211; this allows us to easily extract the contents the match, no matter what conditions were matched under.</p>
<p>The last type of match we need to cater for is non-quoted, zero-length matches. This is the trickiest of the three situations, since there&#8217;s &#8220;nothing&#8221; to actually match on! So instead, we look <em>zero repetitions</em> of any character, immediately after a delimiter. Since the <em>first</em> value in the list may be empty, the possible values for our delimiter are either the start of string (specified by the hat &#8211; ^), or a comma:</p>
<pre class="brush: csharp;">
private const string
    Template_EmptyValues = @&quot;(?&lt;=(?:,|^))(?&lt;content&gt;.{0})&quot;,
</pre>
<p>The final piece of the puzzle is the delimiters. Since we&#8217;re matching from left-to-right, we can assume that every match will be followed either by a comma, or the end of the string. We&#8217;ll use a <em>non-capturing group</em> since we don&#8217;t want the delimiter to be explicitly captured in a group.</p>
<pre class="brush: csharp;">
private const string
    Template_Delimiter = @&quot;(?=(?:,|$))&quot;;
</pre>
<p>Now, to put it all together. We have our three types of matches that we&#8217;re expecting, and our delimiter, so all we need to do is create a single RegEx for it all. Here goes:</p>
<pre class="brush: csharp;">
private const string
    // Any length value within quotes...
    Template_QuotedValues = @&quot;&quot;&quot;(?&lt;content&gt;.*?)&quot;&quot;&quot;,

    // ... or values with at least 1 character, not in quotes...
    Template_UnquotedValues = @&quot;(?&lt;content&gt;[^,]+?)&quot;,

    // ...or zero-length matches, not in quotes...
    Template_EmptyValues = @&quot;(?&lt;=(?:,|^))(?&lt;content&gt;.{0})&quot;,

    // ... followed either a comma, or end of string
    Template_Delimiter = @&quot;(?=(?:,|$))&quot;;

// Now join as one Template - notice the OR condition (pipe)
// between the three match types
readonly static private string
    Template = String.Format(&quot;({0}|{1}|{2}){3}&quot;,
        Template_QuotedValues,
        Template_UnquotedValues,
        Template_EmptyValues,
        Template_Delimiter);

// Finally, our RegEx!
readonly static private Regex CsvSplitterRegex
    = new Regex(Template, RegexOptions.Compiled);
</pre>
<p>Was that so bad? ;-) Iterating through the list of values in our comma separated list is now a piece of cake.</p>
<pre class="brush: csharp;">
// Assume CSV is in &quot;record&quot; field
foreach (Match match in CsvSplitterRegex.Matches(record))
{
    Console.WriteLine(&quot;Match value: {0}&quot;,
        match.Groups[&quot;content&quot;].Value);
}
</pre>
<p>Simple, eh?</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2010/05/15/parsing-comma-separated-values-with-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Handling of Nulls in Entity Framework</title>
		<link>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/</link>
		<comments>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 05:44:21 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Data Access]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=270</guid>
		<description><![CDATA[I think most of you can agree that we are advocates of Entity Framework here. But sometimes things can get a little hairy (as with all ORM solutions). So I just thought I&#8217;d post a quick solution to a problem that had me tearing my hair out at work to solve the other day. Given the following [...]]]></description>
			<content:encoded><![CDATA[<p>I think most of you can agree that we are <a href="http://quickduck.com/blog/2009/05/18/abstracting-the-data-access-layer/">advocates of Entity Framework here</a>. But sometimes things can get a little hairy (as with all ORM solutions). So I just thought I&#8217;d post a quick solution to a problem that had me tearing my hair out at work to solve the other day.</p>
<p>Given the following two queries using Entity Framework one would assume the generated sql would the same?</p>
<pre class="brush: csharp;">
string country = null;
var query = context.Orders.Where(o =&gt; o.Customer.Address.Country == country);
var query2 = context.Orders.Where(o =&gt; o.Customer.Address.Country == null);
</pre>
<div>Wrong. Thanks to this <a href="https://connect.microsoft.com/data/feedback/details/545491/incorrect-handling-of-null-variables-in-where-clause" target="_blank">bug </a>and this <a href="http://msdn.microsoft.com/en-us/library/bb738687.aspx" target="_blank">Microsoft article</a>, I found out that not only will Entity Framwork will not honour what I have specified for ANSI NULLs, it will result in two inconsistent sql queries as the first query will do a &#8220;@country = null&#8221; comparison while the second query will do a &#8220;Country IS NULL&#8221; comparison.</div>
<div>Now, while I get that just because two objects are null it doesn&#8217;t mean they are equal, the workaround here can result in some ugly looking linq queries! Thank you ever so much Microsoft :)</div>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<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>5</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 [...]]]></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>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 code: Frequency myFrequency = (Frequency) 104; System.Console.WriteLine(&#34;My frequency is: {0}&#34;, myFrequency.ToString()); bool is100Defined = Enum.IsDefined(typeof(Frequency), [...]]]></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>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; [...]]]></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>
		<item>
		<title>C# 3.0 &#8211; Variance Explained</title>
		<link>http://quickduck.com/blog/2009/07/30/c-3-0-variance-explained/</link>
		<comments>http://quickduck.com/blog/2009/07/30/c-3-0-variance-explained/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 00:20:13 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contravariance]]></category>
		<category><![CDATA[Contravariant]]></category>
		<category><![CDATA[Covariance]]></category>
		<category><![CDATA[Covariant]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Invariance]]></category>
		<category><![CDATA[Invariant]]></category>
		<category><![CDATA[Subclass]]></category>
		<category><![CDATA[Variance]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=121</guid>
		<description><![CDATA[The problem: Why can’t I create a List of type Dog and assign it to a List of type Animal? IList&#60;Animal&#62; animals = new List&#60;Dog&#62;(); // no good Theory: There are 3 terms relating to variance: Covariance – allows more specific types to be assigned to more general types. (i.e. sub-types (classes, interfaces) can be [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The problem:</strong></p>
<p>Why can’t I create a List of type Dog and assign it to a List of type Animal?</p>
<pre><code>IList&lt;Animal&gt; animals = new List&lt;Dog&gt;(); // no good</code></pre>
<p><strong>Theory:</strong></p>
<p>There are 3 terms relating to variance:</p>
<p><strong>Covariance</strong> – allows more specific types to be assigned to more general types. (i.e. sub-types (classes, interfaces) can be assigned to any types (classes, interfaces) that they inherit from).</p>
<p><em>C# Example:</em> Method Return types are Covariant. We can return a sub-type of the method’s declaring return type.</p>
<pre>
<code>
IAnimal GetAnimal(string animalName) {...};

GetAnimal("dog") {return new Dog();} // the dog is more specific and returned as the general type IAnimal
GetAnimal("cat") {return new Cat();} // the cat is more specific and returned as the general type IAnimal
</code>
</pre>
<p><strong>Contravariance</strong> – allows general types to accept more specific types – i.e. The reverse of covariance.</p>
<p><em>C# Example:</em> Method parameters are Contravariant. We can call a method with a parameter that is a sub-type of the parameters declaring type.</p>
<pre>
<code>
IAnimal GetAnimal(IAnimal animal) {...};
GetAnimal(new Dog()); // the method takes a general type IAnimal but is called with the more specific type Dog
GetAnimal(new Cat()); // the method takes a general type IAnimal but is called with the more specific type Dog
</code>
</pre>
<p><strong>Invariance</strong> – occurs when neither of these conditions are met.</p>
<p><em>C# Example:</em> In C# 3.0 Generics are invariant. C# 4.0 allows the variance of generics to be defined (with restrictions).</p>
<pre>
<code>
IList&lt;Animal&gt; animals = new IList&lt;Animal&gt;();
animals.Add(new Dog());
animals.Add(new Cat()); 

IList&lt;Animal&gt; animals = new List&lt;Dog&gt;();
animals.Add(new Dog());
animals.Add(new Cat()); // no dice. You can’t assign a cat to a list of dogs.
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/07/30/c-3-0-variance-explained/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Two nice string extensions</title>
		<link>http://quickduck.com/blog/2009/07/09/two-nice-string-extensions/</link>
		<comments>http://quickduck.com/blog/2009/07/09/two-nice-string-extensions/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 09:04:49 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=113</guid>
		<description><![CDATA[Here&#8217;s a couple (well, one is an overload of the other) of string extension methods I wrote today which I&#8217;m quite fond of: /// &#60;summary&#62; /// Determines if any of the given matches are a case sensitive match for the /// nominated string value /// &#60;/summary&#62; /// &#60;param name="text"&#62;The string value to be checked&#60;/param&#62; /// [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a couple (well, one is an overload of the other) of string extension methods I wrote today which I&#8217;m quite fond of:</p>
<pre><code>
/// &lt;summary&gt;
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// &lt;/summary&gt;
/// &lt;param name="text"&gt;The string value to be checked&lt;/param&gt;
/// &lt;param name="matches"&gt;The list of potential matches&lt;/param&gt;
static public bool IsIn(this string text, params string[] matches)
{
    return IsIn(text, true, matches);
}

/// &lt;summary&gt;
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// &lt;/summary&gt;
/// &lt;param name="text"&gt;The string value to be checked&lt;/param&gt;
/// &lt;param name="caseSensitive"&gt;&lt;c&gt;true&lt;/c&gt; to perform a case
/// sensitive match&lt;/param&gt;
/// &lt;param name="matches"&gt;The list of potential matches&lt;/param&gt;
static public bool IsIn(this string text, bool caseSensitive, params string[] matches)
{
    StringComparison comparer = caseSensitive
        ? StringComparison.CurrentCulture
        : StringComparison.CurrentCultureIgnoreCase;

    return matches.Any(value =&gt; text.Equals(value, comparer));
}
</pre>
<p></code><br />
So instead of writing this:</p>
<pre><code>
if (name == "James" || name == "Peter" || name == "Sally")
    Console.WriteLine("Your name is too generic!");
</code></pre>
<p>You can simply write this:</p>
<pre><code>
if (name.IsIn("James", "Peter", "Sally")
    Console.WriteLine("Your name is too generic!");
</code></pre>
<p>No offence to the James, Peters, and Sallys of the world.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/07/09/two-nice-string-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
