<?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>Mon, 09 Jan 2012 02:29:30 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>MVC 3 XML Sitemap</title><link>http://quickduck.com/blog/2012/01/08/mvc-3-xml-sitemap/</link> <comments>http://quickduck.com/blog/2012/01/08/mvc-3-xml-sitemap/#comments</comments> <pubDate>Sun, 08 Jan 2012 01:24:36 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[Xml]]></category> <category><![CDATA[seo]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=425</guid> <description><![CDATA[Ok, so you&#8217;ve got your shiny new mvc3 app up and running. Now, it&#8217;s time to bake in some of that SEO goodness. Here&#8217;s how you can easily add a sitemap.xml to your new mvc application. The solution specified below not only pumps out the xml file to submit to the search engines, but it [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2012/01/08/mvc-3-xml-sitemap/"></g:plusone></div><p>Ok, so you&#8217;ve got your shiny new mvc3 app up and running. Now, it&#8217;s time to bake in some of that SEO goodness. Here&#8217;s how you can easily add a sitemap.xml to your new mvc application. The solution specified below not only pumps out the xml file to submit to the search engines, but it is also a System.Web.SiteMapProvider, so you can use it for menus and wherever else you want to use your sitemap.</p><p>I&#8217;m a big fan of NuGet, so bring up the Package Manager Console and grab MvcSiteMapProvider (or download it from <a title="MvcSiteMapProvider" href="https://github.com/maartenba/MvcSiteMapProvider" target="_blank">github</a>).</p><pre class="brush: plain; title: ; notranslate">Install-Package MvcSiteMapProvider</pre><p>Once it is installed there will be a new Mvc.sitemap file added with the following to your solution:</p><pre class="brush: xml; title: ; notranslate">&lt;mvcSiteMapNode title=&quot;Home&quot; controller=&quot;Home&quot; action=&quot;Index&quot;&gt;
    &lt;mvcSiteMapNode title=&quot;About&quot; controller=&quot;Home&quot; action=&quot;About&quot;/&gt;
&lt;/mvcSiteMapNode&gt;</pre><p>Now for the easy bit: to get a ~/sitemap.xml to auto-generate for us based on our controller actions we specified in the sitemap file above. All you need to do is simply add the following to your route registration (generally Global.Application_Start()):</p><pre class="brush: csharp; title: ; notranslate">
XmlSiteMapController.RegisterRoutes(RouteTable.Routes);
</pre><p>Now, like a lot of other people out there my next question was, what about my dynamically generated content from the database (such as Product/Details/1)?  Easy &#8211; MvcSiteMapProvider comes with dynamic node support. Just create a class like the following:</p><pre class="brush: csharp; title: ; notranslate">

public class ProductDetailsDynamicNodeProvider : DynamicNodeProviderBase
 {
     public override IEnumerable&lt;DynamicNode&gt; GetDynamicNodeCollection()
     {
         // Create a node for each product
         foreach (Product product in productService.GetAllProducts())
         {
             var node = new DynamicNode();
             node.Title = product.Name;
             node.RouteValues.Add(&quot;id&quot;, product.Id);

             yield return node;
         }
     }
     public override CacheDescription GetCacheDescription()
     {
        return new CacheDescription(&quot;ProductDetailsDynamicNodeProvider&quot;)
        {
            SlidingExpiration = TimeSpan.FromMinutes(60);
        };
    }
 }
</pre><p>Things to note with the above code: you don&#8217;t have to override the cachedescription method, but this does allow us to specify how long all our products will be cached for in the sitemap. Then, you can add your dynamic node to the mvc.sitemap files as follows:</p><pre class="brush: xml; title: ; notranslate">
&lt;mvcSiteMapNode title=&quot;Details&quot; action=&quot;Details&quot;
dynamicNodeProvider=&quot;Website.ProductDetailsDynamicNodeProvider, Website&quot;/&gt;
</pre><p>Now you are done and have a working auto-generated mvc sitemap. For those of us who are using it to generate breadcrumbs, check out the awesome example of <a href="https://github.com/maartenba/MvcSiteMapProvider/wiki/HtmlHelper-functions" target="_blank">html helpers in the documentation</a>.</p><p>Next time, I&#8217;ll be looking at creating SEO friendly URLs in MVC.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2012/01/08/mvc-3-xml-sitemap/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>IList and Covariance</title><link>http://quickduck.com/blog/2011/04/21/ilist-and-covariance/</link> <comments>http://quickduck.com/blog/2011/04/21/ilist-and-covariance/#comments</comments> <pubDate>Wed, 20 Apr 2011 21:03:14 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[Contravariance]]></category> <category><![CDATA[Contravariant]]></category> <category><![CDATA[Covariance]]></category> <category><![CDATA[Covariant]]></category> <category><![CDATA[Generics]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=357</guid> <description><![CDATA[Now that I&#8217;m developing in .NET 4.0 I thought all my covariance problems were behind me. This was until I tried to use the following: Turns out, IEnumerable&#60;T&#62; has support for covariance, IList&#60;T&#62; does not. I&#8217;d like to thank Marc Gravell for his excellent writeup on this. One way around this (instead of dogsToAttack.Cast&#60;Animal&#62;().ToList()) is [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2011/04/21/ilist-and-covariance/"></g:plusone></div><link rel="me" type="text/html" href="https://profiles.google.com/drew.freyling?rel=me"><p>Now that I&#8217;m developing in .NET 4.0 I thought all my <a title="C# 3.0 – Variance Explained" href="http://quickduck.com/blog/2009/07/30/c-3-0-variance-explained/" target="_blank">covariance</a> problems were behind me. This was until I tried to use the following:</p><pre class="brush: csharp; title: ; notranslate">

public class  Animal {
    public void AttackOtherAnimals(IList&lt;Animal&gt; animals) { }
}

public class Dog : Animal { }

Dog angryDog = new Dog();
List dogsToAttack = new List&lt;Dog&gt;();
angryDog.AttackOtherAnimals(dogsToAttack);
</pre><p>Turns out, IEnumerable&lt;T&gt; has support for covariance, IList&lt;T&gt; does not. I&#8217;d like to thank Marc Gravell for his excellent <a href="http://marcgravell.blogspot.com/2009/02/what-c-40-covariance-doesn-do.html" target="_blank">writeup</a> on this.</p><p>One way around this (instead of dogsToAttack.Cast&lt;Animal&gt;().ToList()) is to use generics to accept any IList&lt;T&gt; where T is of type Animal.</p><pre class="brush: csharp; title: ; notranslate">
public void AttackOtherAnimals(IList&lt;T&gt; animals) where T : Animal { }
</pre>]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2011/04/21/ilist-and-covariance/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>jQuery Intellisense Support in Content Pages</title><link>http://quickduck.com/blog/2011/02/03/jquery-intellisense-support-in-content-pages/</link> <comments>http://quickduck.com/blog/2011/02/03/jquery-intellisense-support-in-content-pages/#comments</comments> <pubDate>Wed, 02 Feb 2011 21:27:17 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[.Net]]></category> <category><![CDATA[jQuery]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=335</guid> <description><![CDATA[I was trying my hand at whipping up some jQuery today and realising the awesome intellisense that is provided, couldn&#8217;t wait to get stuck in. Since I do enjoy adhering to the DRY principle wherever possible I decided I needed to use master pages first before I create my example content. I then set out [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2011/02/03/jquery-intellisense-support-in-content-pages/"></g:plusone></div><p>I was trying my hand at whipping up some jQuery today and realising the awesome <a href="http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx">intellisense</a> that is provided, couldn&#8217;t wait to get stuck in. Since I do enjoy adhering to the DRY principle wherever possible I decided I needed to use master pages first before I create my example content. I then set out to try and do a basic hello world example but realized my intellisense wasn&#8217;t working with jQuery. It was working with vanilla ASP .NET pages, just not content pages.</p><p>It turns out, that VS uses -vsdocs javascript files to provide this support. It requires it to be sitting next to your jquery file that you are referencing. Which it was thanks to the MVC Internet Application project template. It seems that ASP .NET doesn&#8217;t know at design time that I&#8217;m referencing jQuery in the master page.</p><p>After asking Professor Google, I stumbled upon a <a href="http://stackoverflow.com/questions/770810/how-do-you-get-jquery-intellisense-working-if-youve-implemented-a-url-helper-ext" target="_blank">solution</a>. I decided to slap the following bit of code into any content page that I have created and want some good ol&#8217; intellisense.</p><pre class="brush: xml; title: ; notranslate">
&lt;% #if (false) %&gt;
&lt;script src=&quot;~/scripts/jquery-1.4.4.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;% #endif %&gt;
</pre><p>Yes, this is a bit of hack to get it working and yes, I would like Microsoft to fix it. In the mean time, I will be egarly awaiting the <a href="http://appendto.com/community/jquery-vsdoc">intellisense support to be released</a> for the latest 1.5 version.</p><p><strong>UPDATE:</strong> I&#8217;ve just found that somebody has generated a <a href="http://encosia.com/2011/02/04/a-vsdoc-for-jquery-1-5/">new vsdoc for jQuery 1.5</a></p><p><strong>UPDATE 2</strong>: If you reference your jQuery from the Microsoft CDN, you get intellisense since they also host the vsdoc files. Sadly, the Google CDN does not.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2011/02/03/jquery-intellisense-support-in-content-pages/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 Freyling</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[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/"></g:plusone></div><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; title: ; notranslate">
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 Freyling</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: I&#8217;m sure this can [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2009/09/15/get-a-treeviewitems-parent-item/"></g:plusone></div><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; title: ; notranslate">

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 Freyling</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: Unless you are one of one of those fancy pants with TypeMock and the ability to [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/"></g:plusone></div><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; title: ; notranslate">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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
 /// &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; title: ; notranslate">
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>1</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[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2009/06/26/using-a-generic-base-class-control-in-wpf/"></g:plusone></div><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[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/12/11/selecting-an-item-in-a-treeview-in-wpf/"></g:plusone></div><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; title: ; notranslate">
/// &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>19</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[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/06/17/staticresource-vs-dynamicresource/"></g:plusone></div><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>5</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: quickduck.com @ 2012-02-05 16:28:37 -->
