<?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; .Net</title>
	<atom:link href="http://quickduck.com/blog/tag/net/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>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>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 [...]]]></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>Using a generic base class control in WPF</title>
		<link>http://quickduck.com/blog/2009/06/26/using-a-generic-base-class-control-in-wpf/</link>
		<comments>http://quickduck.com/blog/2009/06/26/using-a-generic-base-class-control-in-wpf/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 10:28:18 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.Net]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=100</guid>
		<description><![CDATA[One thing that I find myself doing all the time is creating some type of base class for my windows/controls in WPF: namespace Editors { public class EntityEditorControlBase&#60;TModel&#62; : UserControl where TModel : class, IEntityEditorModel { public TModel Model { get { return DataContext as TModel; } protected set { DataContext = value; } } [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that I find myself doing all the time is creating some type of base class for my windows/controls in WPF:</p>
<pre><code style="font-size:125%">
namespace Editors {
    public class EntityEditorControlBase&lt;TModel&gt; : UserControl
        where TModel : class, IEntityEditorModel {

        public TModel Model {
            get { return DataContext as TModel; }
            protected set { DataContext = value; }
        }
    }
}
</code></pre>
<p>Since this is a generic control you need to specify the concrete type arguments when you subclass it. You can do this in your WPF markup via the <strong>x:TypeArguments</strong> attribute:</p>
<pre><code style="font-size:125%">
&lt;Editors:EntityEditorControlBase
    x:Class="ConcreteEntityEditorControl"
    <strong>x:TypeArguments="Models:ConcreteEntityEditorControlModel"</strong>
    xmlns:Editors="clr-namespace:Editors"&gt;

    &lt;UserControl.Resources&gt;
        &lt;ResourceDictionary Source="../Resources/EditorResources.xaml" /&gt;
    &lt;/UserControl.Resources&gt;

    &lt;!-- control content here --&gt;

&lt;/Editors:EntityEditorControlBase&gt;
</code></pre>
<p>Two important things to note:</p>
<ul>
<li>When you want to attach a resource dictionary to the class, you need to do so using the <strong>&lt;UserControl.Resources&gt;</strong> tag</li>
<li>In your base class control, make sure you include the [ContentProperty("Content")] and [DefaultProperty("Content")] tags on your class to avoid the horrible &#8220;<a href="http://msdn.microsoft.com/en-us/library/bb514660.aspx">The type &#8216;{0}&#8217; does not support direct content</a>&#8221; error.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/06/26/using-a-generic-base-class-control-in-wpf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selecting an item in a TreeView in WPF</title>
		<link>http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/</link>
		<comments>http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 09:56:17 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/</guid>
		<description><![CDATA[I have to admit that I much prefer WPF over Windows Forms (but prefer ASP.Net to either). However, the programming model is still a bit immature (in my opinion), and sometimes things that you wish were simple just aren&#8217;t. Case and point: trying to programmatically select an item in a TreeView control; it just ain&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I have to admit that I <i>much</i> prefer WPF over Windows Forms (but prefer ASP.Net to either). However, the programming model is still a bit immature (in my opinion), and sometimes things that you wish were simple just aren&#8217;t. Case and point: trying to programmatically select an item in a TreeView control; it just ain&#8217;t easy!</p>
<p>Anyway, after scrubbing the web and finding a few solutions that really didn&#8217;t appeal (e.g. using reflection; surely it&#8217;s not <i>that</i> hard!) I came up with this extension method which does the trick quite nicely.</p>
<pre class="brush: csharp;">
/// &lt;summary&gt;
/// Walks the tree items to find the node corresponding with
/// the given item, then sets it to be selected.
/// &lt;/summary&gt;
/// &lt;param name=&quot;treeView&quot;&gt;The tree view to set the selected
/// item on&lt;/param&gt;
/// &lt;param name=&quot;item&quot;&gt;The item to be selected&lt;/param&gt;
/// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if the item was found and set to be
/// selected&lt;/returns&gt;
static public bool SetSelectedItem(
    this TreeView treeView, object item) {

    return SetSelected(treeView, item);
}

static private bool SetSelected(ItemsControl parent,
    object child) {

    if (parent == null || child == null) {
        return false;
    }

    TreeViewItem childNode = parent.ItemContainerGenerator
        .ContainerFromItem(child) as TreeViewItem;

    if (childNode != null) {
        childNode.Focus();
        return childNode.IsSelected = true;
    }

    if (parent.Items.Count &amp;gt; 0) {
        foreach (object childItem in parent.Items) {
            ItemsControl childControl = parent
                .ItemContainerGenerator
                .ContainerFromItem(childItem)
                as ItemsControl;

            if (SetSelected(childControl, child)) {
                return true;
            }
        }
    }

    return false;
}
</pre>
<p>(Forgive formatting; the code window is only so-wide.)</p>
<p>The trick, you see, is to use the ItemContainerGenerator on the ItemsControl &#8211; which TreeView and TreeViewNode both inherit from &#8211; to try to find the container for the item you are selecting. This will only work for the <i>immediate</i> children of the control that you&#8217;re calling it on &#8211; so asking your root node for the container for an item which is three nodes deep is fruitless; hence, you have to walk down the tree asking each branch node if it contains the item.</p>
<p>It&#8217;s possibly not the fastest executing code in the world &#8211; walking a tree rarely is &#8211; but you could speed things up if you knew where the parent node was; then you could just call the recursive method directly.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>StaticResource vs DynamicResource</title>
		<link>http://quickduck.com/blog/2008/06/17/staticresource-vs-dynamicresource/</link>
		<comments>http://quickduck.com/blog/2008/06/17/staticresource-vs-dynamicresource/#comments</comments>
		<pubDate>Tue, 17 Jun 2008 15:35:45 +0000</pubDate>
		<dc:creator>Gerrod</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/06/17/staticresource-vs-dynamicresource/</guid>
		<description><![CDATA[I&#8217;ve been focusing a lot (read: &#8220;learning&#8221;) on WPF lately, and one thing that crops up all the time is StaticResource and DynamicResource. I had tried to infer their usage/differences from the context of where I&#8217;d seen them used, but I could never quite get it right. Anyway, I just read a nice definition which [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been focusing a lot (read: &#8220;learning&#8221;) on WPF lately, and one thing that crops up all the time is StaticResource and DynamicResource. I had tried to infer their usage/differences from the context of where I&#8217;d seen them used, but I could never quite get it right. Anyway, I just read a nice definition which makes it all rather clear:</p>
<blockquote><p>
Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime.</p>
<p>Use DynamicResources when the value of the resource could change during the lifetime of the Application.</p>
<p>Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/06/17/staticresource-vs-dynamicresource/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
