<?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>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>Overriding the default serialization behavior in Json.NET</title><link>http://quickduck.com/blog/2011/08/08/overriding-the-default-serialization-behavior-in-json-net/</link> <comments>http://quickduck.com/blog/2011/08/08/overriding-the-default-serialization-behavior-in-json-net/#comments</comments> <pubDate>Mon, 08 Aug 2011 06:19:11 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=412</guid> <description><![CDATA[We use Newtonsoft Json.NET heavily in our project to control our JSON serialization. For the most part, it works absolutely perfectly out-of-the-box, but every now and then, we need to customize the way that serialization works for a particular object. Such an occasion occurred today. Basically, I have a list of EmployeeActivity objects &#8211; where [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2011/08/08/overriding-the-default-serialization-behavior-in-json-net/"></g:plusone></div><p>We use <a href="http://json.codeplex.com/">Newtonsoft Json.NET</a> heavily in our project to control our JSON serialization. For the most part, it works absolutely perfectly out-of-the-box, but every now and then, we need to customize the way that serialization works for a particular object.</p><p>Such an occasion occurred today. Basically, I have a list of <code>EmployeeActivity</code> objects &#8211; where each instance is a <em>subclass</em> of <code>EmployeeActivity</code>. So, for example:</p><pre class="brush: csharp; title: ; notranslate">
public abstract class EmployeeActivity
{
    public TimeSpan Start { get; set; }
    public TimeSpan Stop { get; set; }

    public virtual bool IsAvailable
    {
        get { return false; }
    }
}

public class AbsenceActivity : EmployeeActivity
{
    public string Reason { get; set; }
}

public class BreakActivity : EmployeeActivity
{
    public string BreakName { get; set; }
}
</pre><p>json.NET does a perfect job of serializing my objects, and they rebuild perfectly when I&#8217;m back in javascript land &#8211; however, I have no way of knowing the actual <em>type</em> of each activity in my array! To alleviate this, I wanted to create my own serializer which also injected the type name into each of the serialized objects &#8211; or at least, that&#8217;s what I <em>thought</em> I wanted to do!</p><p>As it turns out, there&#8217;s a bit of an easier option. <code>JsonConvert</code> uses a <a href="http://james.newtonking.com/projects/json/help/ContractResolver.html"><code>ContractResolver</code></a> in order to work out how to Serialize/Deserialize each class, and you can override the default contract resolver when running serialization:</p><pre class="brush: csharp; title: ; notranslate">
// This class contains the activity list
ActivityViewModel = new ActivityViewModel(DateTime.Today);

// Serialize using a custom contract resolver
string jsonViewModel = JsonConvert.SerializeObject(viewModel,
    Formatting.None, new JsonSerializerSettings
    {
        ContractResolver = new ActivityJsonContractResolver()
    });
</pre><p>The contract resolver&#8217;s job is to return a <a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Serialization_JsonContract.htm"><code>JsonContract</code></a> which describes the object to be returned. For a POCO, this would typically be an instance of <a href="http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_Serialization_JsonObjectContract.htm"><code>JsonObjectContract</code></a>, which (amongst other things) describes the properties of the class which should be serialized.</p><p>So, all I needed to do was to extend the contract for subclasses of <code>EmployeeActivity</code>, such that it inherited a new Property to be serialized:</p><pre class="brush: csharp; title: ; notranslate">
public class DiaryActivityJsonContractResolver : DefaultContractResolver
{
    protected override JsonObjectContract CreateObjectContract(Type objectType)
    {
        JsonObjectContract contract = base.CreateObjectContract(objectType);

        if (typeof(EmployeeActivity).IsAssignableFrom(objectType))
        {
            contract.Properties.Add(new JsonProperty
            {
                Readable = true,
                ShouldSerialize = value =&gt; true,
                PropertyName = &quot;Type&quot;,
                PropertyType = typeof(string),
                Converter = ResolveContractConverter(typeof(string)),
                ValueProvider = new StaticValueProvider(objectType.Name)
            });
        }

        return contract;
    }
}
</pre><p>Truth be told, I&#8217;m not 100% sure if I need to implement as many of the properties on the <code>JsonProperty</code> that I&#8217;m creating. But you can see what&#8217;s going on here &#8211; I&#8217;m effectively telling the object contract that there&#8217;s an additional property called <code>Type</code> which needs to be serialized, that it&#8217;s a string, and that it should return whatever value is resolved by the <code>StaticValueProvider</code>. Speaking of which, here&#8217;s the last piece of the puzzle &#8211; a simple value resolver that always returns the same value:</p><pre class="brush: csharp; title: ; notranslate">
/// &lt;summary&gt;
/// JSON value provider that always returns a static value
/// &lt;/summary&gt;
public class StaticValueProvider : IValueProvider
{
    private readonly object _staticValue;

    public StaticValueProvider(object staticValue)
    {
        _staticValue = staticValue;
    }

    public void SetValue(object target, object value)
    {
        throw new NotSupportedException();
    }

    public object GetValue(object target)
    {
        return _staticValue;
    }
}
</pre><p>json.NET is fantastic, and it&#8217;s very extensible, but finding out where to start and what to do can be a little bit tricky. I managed to figure this out only by downloading the source files and poking through the code myself; hopefully this will be helpful to someone else in the same situation!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2011/08/08/overriding-the-default-serialization-behavior-in-json-net/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Extension methods for base/derived types</title><link>http://quickduck.com/blog/2011/07/25/extension-methods-for-base-derived-types/</link> <comments>http://quickduck.com/blog/2011/07/25/extension-methods-for-base-derived-types/#comments</comments> <pubDate>Mon, 25 Jul 2011 07:32:31 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=402</guid> <description><![CDATA[I had a situation today which I thought was prime for writing some extension methods: I wasn&#8217;t allowed to modify the original type, and I also couldn&#8217;t subclass it, either. Extension methods to the rescue! One thing which made the situation slightly interesting though, was that the original type also had a whole bunch of [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2011/07/25/extension-methods-for-base-derived-types/"></g:plusone></div><p>I had a situation today which I thought was prime for writing some extension methods: I wasn&#8217;t allowed to modify the original type, and I also couldn&#8217;t subclass it, either. Extension methods to the rescue!</p><p>One thing which made the situation slightly interesting though, was that the original type also had a whole bunch of <em>derived</em> types &#8211; and for each of them, I wanted to customise the relevant extension method! Well, that&#8217;s all well and good, but what I <em>really</em> wanted to know was: lets say I was operating on a collection of the base types (where each individual item was an instance of a derived type), which extension method would get invoked?</p><p>Only one way to find out &#8211; write some code! For simplicity, I used the base class <code>Animal</code>, and added two derived types: <code>Dog</code> and <code>Elephant</code>.</p><pre class="brush: csharp; title: ; notranslate">
    public abstract class Animal
    {
        public string Name { get; set; }
        public bool HasBoyBits { get; set; }
        public abstract string Type { get; }
    }

    public class Dog : Animal
    {
        public string Breed { get; set; }

        public override string Type
        {
            get { return &quot;Dog&quot;; }
        }
    }

    public class Elephant : Animal
    {
        public bool HasTusks { get; set; }

        public override string Type
        {
            get { return &quot;Elephant&quot;; }
        }
    }
</pre><p>Now for the extension method: <code>CanBreed</code>. For the base type <code>Animal</code>, the rule was simple &#8211; the animals had to be of the same type, and of the opposite sex:</p><pre class="brush: csharp; title: ; notranslate">
    public static class AnimalExtensions
    {
        public static bool CanBreedWith(this Animal animal, Animal other)
        {
            return animal.Type == other.Type
                &amp;&amp; animal.HasBoyBits != other.HasBoyBits;
        }
    }
</pre><p>For dogs, we only want to breed with dogs that are already of the same pedigree; and for elephants, we only want to breed with other elephants that have the same tusk status (yes, it&#8217;s pretty ambiguous, but whatever):</p><pre class="brush: csharp; title: ; notranslate">
    public static class DogExtensions
    {
        public static bool CanBreedWith(this Dog dog, Animal other)
        {
            return AnimalExtensions.CanBreedWith(dog, other)
                &amp;&amp; ((Dog) other).Breed == dog.Breed;
        }
    }

    public static class ElephantExtensions
    {
        public static bool CanBreedWith(this Elephant elephant, Animal other)
        {
            return AnimalExtensions.CanBreedWith(elephant, other)
                &amp;&amp; ((Elephant) other).HasTusks == elephant.HasTusks;
        }
    }
</pre><p>Finally, the test data: two lists of animals, separated by gender:</p><pre class="brush: csharp; title: ; notranslate">
    var baxter = new Dog { Name = &quot;Baxter&quot;, HasBoyBits = true, Breed = &quot;Jack Russell&quot; };
    var missy = new Dog { Name = &quot;Missy&quot;, HasBoyBits = false, Breed = &quot;Jack Russell&quot; };
    var jazzy = new Dog { Name = &quot;Jazzy&quot;, HasBoyBits = false, Breed = &quot;Poodle&quot; };

    List&lt;Animal&gt; boys = new List&lt;Animal&gt;
    {
        baxter,
        new Elephant { Name = &quot;Lance&quot;, HasBoyBits = true, HasTusks = true }
    };

    List&lt;Animal&gt; girls = new List&lt;Animal&gt;
    {
        missy,
        jazzy,
        new Elephant { Name = &quot;Renee&quot;, HasBoyBits = false, HasTusks = true },
        new Elephant { Name = &quot;Hephalump&quot;, HasBoyBits = false, HasTusks = false }
    };
</pre><p>Now, what I had to test was if .NET would use the <em>Runtime</em> type of each animal to work out which extension method to invoke. I was pretty confident that both of these would pass:</p><pre class="brush: csharp; title: ; notranslate">
    Assert.IsTrue(baxter.CanBreedWith(missy));
    Assert.IsFalse(baxter.CanBreedWith(jazzy));
</pre><p>And sure enough, the unit test succeeds with flying colours. However, to make things slightly trickier, what if we do this?</p><pre class="brush: csharp; title: ; notranslate">
    foreach (var boy in boys)
    {
        foreach (var girl in girls)
        {
            bool canBreed = boy.CanBreedWith(girl);

            Console.WriteLine(&quot;{0} can{2} breed with {1}&quot;,
                boy.Name, girl.Name, canBreed ? String.Empty : &quot;'t&quot;);
        }
    }
</pre><p>Unfortunately, here&#8217;s what the output looks like:</p><blockquote><p> Baxter can breed with Missy<br /> Baxter can breed with Jazzy<br /> Baxter can&#8217;t breed with Renee<br /> Baxter can&#8217;t breed with Hephalump<br /> Lance can&#8217;t breed with Missy<br /> Lance can&#8217;t breed with Jazzy<br /> Lance can breed with Renee<br /> Lance can breed with Hephalump</p></blockquote><p>So we can see that the animals aren&#8217;t allowed to breed when they&#8217;re of differing types (hence <code>AnimalExtensions.CanBreedWith</code> is being invoked); however, each type of animal is allowed to breed with <em>any other animal of the same type</em>. No joy! (Well, joy for the animals I suppose&#8230;)</p><p>On retrospect, this is pretty much the behavior that I expected, but I was still disappointed to find out that I had been right. Worse still, once the sample code was up and running, I thought, &#8220;Hey, I should have used Rabbits instead of Elephants, and then always returned <code>false</code> in the CanBreed method, because that would have been funnier&#8221;. Ahh, hindsight, where were you before?</p><p>Oh well. Time for some refactoring!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2011/07/25/extension-methods-for-base-derived-types/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Fixing debugging displays with ToString()</title><link>http://quickduck.com/blog/2011/07/19/fixing-debugging-displays-with-tostring/</link> <comments>http://quickduck.com/blog/2011/07/19/fixing-debugging-displays-with-tostring/#comments</comments> <pubDate>Tue, 19 Jul 2011 03:30:00 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[C#]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=389</guid> <description><![CDATA[Debugging can be tricky when you&#8217;re trying to inspect a collection of objects that superficially all look the same! But there&#8217;s a few things you can do to alleviate that problem, and a few gotchas to try and avoid, too. Lets say you have a simple class called TimeRange, which defines a start time and [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2011/07/19/fixing-debugging-displays-with-tostring/"></g:plusone></div><p>Debugging can be tricky when you&#8217;re trying to inspect a collection of objects that superficially all look the same! But there&#8217;s a few things you can do to alleviate that problem, and a few gotchas to try and avoid, too.</p><p>Lets say you have a simple class called <code>TimeRange</code>, which defines a start time and an end time, and also has a calculated property for the length of time it represents. Your class might look something like this:</p><pre class="brush: csharp; title: ; notranslate">
public class TimeRange
{
    public TimeSpan Start { get; set; }
    public TimeSpan End { get; set; }

    public TimeSpan Length
    {
        get { return End.Subtract(Start); }
    }
}
</pre><p>Now, lets say you create a list of these Time Ranges. When you debug your file, inspecting the list will give you a picture like this:</p><p><a href="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges1.png"><img src="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges1-300x109.png" alt="Unhelpful time ranges" title="Unhelpful time ranges" width="300" height="109" class="aligncenter size-medium wp-image-394" /></a></p><p>That&#8217;s not very helpful now, is it?! It would be much easier to work out what was going on if the debugger showed us a little bit about each time range, rather than simply the object type&#8217;s full name.</p><p>Thankfully, it&#8217;s actually pretty easy to customise what the debugger displays during object inspection using one of two methods:</p><ul><li><strong>The &#8220;hard&#8221; way:</strong> Decorate your class with the <code>DebuggerDisplayAttribute</code> (which you can <a href="http://msdn.microsoft.com/en-us/library/ms228992.aspx">read about here</a>). Essentially, this allows you to write custom text, and/or an expression which will be evaluated by the debugger when inspecting an object.</li><li><strong>The &#8220;easy&#8221; way:</strong> Override the <code>ToString()</code> method! This is what the debugger uses by default to display information about your object.</li></ul><p><em>(Note: If you override the <code>ToString()</code> method as well as decorate your class with the <code>DebuggerDisplayAttribute</code>, the attribute will take precedence.)</em></p><p>So, with that in mind, lets override <code>ToString()</code> to fix our debugging display:</p><pre class="brush: csharp; title: ; notranslate">
override public string ToString()
{
    return String.Format(&quot;{0:hh:mm} - {1:hh:mm} (Length: {2:h}h {2:mm}m)&quot;,
        Start, End, Length);
}
</pre><p>And now lets run our debugger and check out&#8230; hey, wait a minute! Our debugging display hasn&#8217;t changed! What&#8217;s going on? I thought overriding <code>ToString()</code> would change what the debugger shows when inspecting our objects! Lets use a hammer to crack a nut, and add in the <code>DebuggerDisplayAttribute</code> as well:</p><pre class="brush: csharp; title: ; notranslate">
[DebuggerDisplay(&quot;{ToString()}&quot;)]
public class TimeRange
</pre><p>And now lets see what we get:</p><p><a href="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges2.png"><img src="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges2-300x74.png" alt="Slightly more helpful..." title="Slightly more helpful..." width="300" height="74" class="aligncenter size-medium wp-image-397" /></a></p><p>Ah ha! We have a problem with our <code>String.Format()</code> statement &#8211; it turns out the formatting strings that we&#8217;ve used for the <code>TimeSpan</code> instances are incorrect. So, lets fix our formatting string, and remove the DebuggerDisplay attribute. Here&#8217;s how our class looks now:</p><pre class="brush: csharp; title: ; notranslate">
public class TimeRange
{
    public TimeSpan Start { get; set; }
    public TimeSpan End { get; set; }

    public TimeSpan Length
    {
        get { return End.Subtract(Start); }
    }

    override public string ToString()
    {
        return String.Format(@&quot;{0:hh\:mm} - {1:hh\:mm} (Length: {2:%h}h {2:mm}m)&quot;,
            Start, End, Length);
    }
}
</pre><p>And here&#8217;s what we see when we inspect a list of Time Ranges in the debugger:</p><p><a href="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges3.png"><img src="http://quickduck.com/blog/wp-content/uploads/2011/07/TimeRanges3-300x111.png" alt="Much better!" title="Much better!" width="300" height="111" class="aligncenter size-medium wp-image-398" /></a></p><p>Much better!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2011/07/19/fixing-debugging-displays-with-tostring/feed/</wfw:commentRss> <slash:comments>1</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>CSS Case Sensitivity</title><link>http://quickduck.com/blog/2010/12/02/css-case-sensitivity/</link> <comments>http://quickduck.com/blog/2010/12/02/css-case-sensitivity/#comments</comments> <pubDate>Thu, 02 Dec 2010 05:08:48 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[css]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=324</guid> <description><![CDATA[Your learn something new everyday. Today I learnt that CSS is case sensitive. No big deal. What I do find perplexing though is the fact that a) html attribute selection is case insensitive and b) alot of older browsers (or those running in quirks mode) implement CSS class selection as case insensitive. It is probably [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/12/02/css-case-sensitivity/"></g:plusone></div><p>Your learn something new everyday. Today I learnt that CSS is case sensitive. No big deal. What I do find perplexing though is the fact that a) html attribute selection is case insensitive and b) alot of older browsers (or those running in quirks mode) implement CSS class selection as case insensitive. It is probably easiest to just use lowercase to avoid any potential issues with your stylesheets!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/12/02/css-case-sensitivity/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Varchar, Nvarchar and Entity Framework</title><link>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/</link> <comments>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/#comments</comments> <pubDate>Thu, 23 Sep 2010 01:41:29 +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> <category><![CDATA[Performance]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=322</guid> <description><![CDATA[Further to my previous post about a bug with Entity Framework 1.0, I&#8217;ve have discovered another bug but this time due to its handling of varchars. Let&#8217;s assume we&#8217;re using the following query: If our Country column is a varchar Entity Framework will pass through our &#8220;Australia&#8221; string as an nvarchar parameter regardless of what [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/"></g:plusone></div><p>Further to my <a href="http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/">previous post</a> about a bug with Entity Framework 1.0, I&#8217;ve have discovered another bug but this time due to its handling of varchars.</p><p>Let&#8217;s assume we&#8217;re using the following query:</p><pre class="brush: plain; title: ; notranslate">
var query = context.Orders.Where(o =&gt; o.Customer.Address.Country == &quot;Australia&quot;);
</pre><p>If our Country column is a varchar  Entity Framework will pass through our &#8220;Australia&#8221; string as an nvarchar parameter regardless of what we define in our SSDL!<br /> Now has is this a bad thing you may ask? Well what this means is that even if we have an index on our country column, SQL Server will have to do an index scan rather than an index seek because it has to convert the nvarchar &#8220;Australia&#8221; down to a varchar and do the comparison across every row in the table.</p><p>Thankfully there is a <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/d8577454-ebca-4697-80ef-73b7620e87a4">workaround</a> .</p><p>This problem has also been <a href="http://blogs.msdn.com/b/adonet/archive/2010/05/10/improvements-to-generated-sql-in-net-4-0.aspx">addressed</a> in EF 4.0 as well.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Question of the day: Threading</title><link>http://quickduck.com/blog/2010/06/30/question-of-the-day-threading/</link> <comments>http://quickduck.com/blog/2010/06/30/question-of-the-day-threading/#comments</comments> <pubDate>Wed, 30 Jun 2010 10:52:18 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Daily Question]]></category> <category><![CDATA[Threading]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=313</guid> <description><![CDATA[Here&#8217;s a little question about Threading &#8211; this would be a great interview question, in my opinion! Given the code below: What will happen when you create a new instance of the Consumer class?]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/06/30/question-of-the-day-threading/"></g:plusone></div><p>Here&#8217;s a little question about Threading &#8211; this would be a great interview question, in my opinion!</p><p>Given the code below:</p><pre class="brush: csharp; title: ; notranslate">
public class Producer
{
    [ThreadStatic]
    readonly static private Producer _instance = new Producer();

    static private int _instanceCount;
    readonly private int _instanceId;

    private Producer()
    {
        _instanceId = ++_instanceCount;
    }

    static public Producer Instance
    {
        get { return _instance; }
    }

    public string Name
    {
        get
        {
            return String.Format(&quot;Instance {0} of {1}&quot;,
                _instanceId, _instanceCount);
        }
    }
}

public class Consumer
{
    public Consumer()
    {
        Thread t1 = new Thread(IdentifyProducer);
        t1.Start();

        Thread t2 = new Thread(IdentifyProducer);
        t2.Start();

        t1.Join();
        t2.Join();
    }

    public void IdentifyProducer()
    {
        Console.WriteLine(Producer.Instance.Name);
    }
}
</pre><p>What will happen when you create a new instance of the Consumer class?</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/06/30/question-of-the-day-threading/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Star Sizing and Grid Size Sharing in WPF</title><link>http://quickduck.com/blog/2010/06/22/star-sizing-and-grid-size-sharing-in-wpf/</link> <comments>http://quickduck.com/blog/2010/06/22/star-sizing-and-grid-size-sharing-in-wpf/#comments</comments> <pubDate>Tue, 22 Jun 2010 09:04:55 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[WPF]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=296</guid> <description><![CDATA[They don&#8217;t work together. Full stop. Thank you Microsoft. The only way around this is to manually bind your columns/rows of one grid to another instead of using star sizing. Thanks to this article we can use this:]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/06/22/star-sizing-and-grid-size-sharing-in-wpf/"></g:plusone></div><p>They don&#8217;t work together. Full stop. Thank you Microsoft. The only way around this is to manually bind your columns/rows of one grid to another instead of using star sizing. Thanks to <a href="http://blogs.interknowlogy.com/johnbowen/archive/2007/08/27/21132.aspx">this</a> article we can use this:</p><pre class="brush: xml; title: ; notranslate">
&lt;Grid.ColumnDefinitions&gt;
&lt;ColumnDefinition Width=&quot;{Binding ElementName=OtherGrid}, Path=ColumnDefinitions[0].Width}&quot; /&gt;
&lt;/Grid.ColumnDefinitions&gt;
</pre>]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/06/22/star-sizing-and-grid-size-sharing-in-wpf/feed/</wfw:commentRss> <slash:comments>0</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:07:49 -->
