<?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>Thomas Levesque&#039;s .NET blog</title>
	<atom:link href="http://www.thomaslevesque.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.thomaslevesque.com</link>
	<description>Tips, tricks and thoughts about .NET development</description>
	<lastBuildDate>Sat, 25 May 2013 23:10:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>An easy and secure way to store a password using Data Protection API</title>
		<link>http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/</link>
		<comments>http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/#comments</comments>
		<pubDate>Mon, 20 May 2013 22:59:50 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[dpapi]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[protect]]></category>

		<guid isPermaLink="false">http://www.thomaslevesque.com/?p=520</guid>
		<description><![CDATA[If you&#8217;re writing a client application that needs to store user credentials, it&#8217;s usually not a good idea to store the password as plain text, for obvious security reasons. So you need to encrypt it, but as soon as you start to think about encryption, it raises all kinds of issues&#8230; Which algorithm should you [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re writing a client application that needs to store user credentials, it&#8217;s usually not a good idea to store the password as plain text, for obvious security reasons. So you need to encrypt it, but as soon as you start to think about encryption, it raises all kinds of issues&#8230; Which algorithm should you use? Which encryption key? Obviously you will need the key to decrypt the password, so it needs to be either in the executable or in the configuration. But then it will be pretty easy to find&#8230;</p>
<p>Well, the good news is that you don&#8217;t really need to solve this problem, because Windows already solved it for you! The solution is called <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx">Data Protection API</a>. The documentation is lengthy and boring, but actually it&#8217;s pretty easy to use from .NET, because the framework provides a <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx"><code>ProtectedData</code></a> class that wraps the low-level API calls for you.</p>
<p>This class has two methods, with pretty self-explanatory names: <code>Protect</code> and <code>Unprotect</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope);
public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope);
</pre>
<p>The <code>userData</code> parameter is the plain, unencrypted binary data. The <code>scope</code> is a value that indicates whether to protect the data for the current user (only that user will be able to decrypt it) or for the local machine (any user on the same machine will be able to decrypt it). What about the <code>optionalEntropy</code> parameter? Well, I&#8217;m not an expert in cryptography, but as far as I understand, it&#8217;s a kind of &#8220;salt&#8221;: according to the documentation, it is used to &#8220;increase the complexity of the encryption&#8221;. Obviously, you&#8217;ll need to provide the same entropy to decrypt the data later.</p>
<p>So, this API is quite simple, but not directly usable for our goal: the input and output of <code>Protect</code> are byte arrays, but we want to encrypt a password, which is a string; also, it&#8217;s usually more convenient to store a string than a byte array. To get a byte array from the password string, it&#8217;s pretty easy: we just need to use a text encoding, like UTF-8. But we can&#8217;t use the same approach to get a string from the encrypted binary data, because it will probably not contain printable text; instead we can encode the result in Base64, which gives a clean text representation of binary data. So, basically we&#8217;re going to do this:</p>
<pre>
                      clear text
(encode to UTF8)   => clear bytes
(Protect)          => encrypted bytes
(encode to base64) => encrypted text
</pre>
<p>And for decryption, we just need to reverse the steps:</p>
<pre>
                        encrypted text
(decode from base64) => encrypted bytes
(Unprotect)          => clear bytes
(decode from UTF8)   => clear text
</pre>
<p>I omitted the entropy in the description above; in most cases it will probably be more convenient to have it as a string, too, so we can just encode the string to UTF-8 to get the corresponding bytes.</p>
<p>Eventually, we can wrap all this in two simple extension methods:</p>
<pre class="brush: csharp; title: ; notranslate">
public static class DataProtectionExtensions
{
    public static string Protect(
        this string clearText,
        string optionalEntropy = null,
        DataProtectionScope scope = DataProtectionScope.CurrentUser)
    {
        if (clearText == null)
            throw new ArgumentNullException(&quot;clearText&quot;);
        byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
        byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
            ? null
            : Encoding.UTF8.GetBytes(optionalEntropy);
        byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
        return Convert.ToBase64String(encryptedBytes);
    }

    public static string Unprotect(
        this string encryptedText,
        string optionalEntropy = null,
        DataProtectionScope scope = DataProtectionScope.CurrentUser)
    {
        if (encryptedText == null)
            throw new ArgumentNullException(&quot;encryptedText&quot;);
        byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
        byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
            ? null
            : Encoding.UTF8.GetBytes(optionalEntropy);
        byte[] clearBytes = ProtectedData.Unprotect(encryptedBytes, entropyBytes, scope);
        return Encoding.UTF8.GetString(clearBytes);
    }
}
</pre>
<p>Encryption example:</p>
<pre class="brush: csharp; title: ; notranslate">
string encryptedPassword = password.Protect();
</pre>
<p>Decryption example:</p>
<pre class="brush: csharp; title: ; notranslate">
try
{
    string password = encryptedPassword.Unprotect();
}
catch(CryptographicException)
{
    // Possible causes:
    // - the entropy is not the one used for encryption
    // - the data was encrypted by another user (for scope == CurrentUser)
    // - the data was encrypted on another machine (for scope == LocalMachine)
    // In this case, the stored password is not usable; just prompt the user to enter it again.
}
</pre>
<p>What I love with this technique is that it Just Works™: you don&#8217;t need to worry about how the data is encrypted, where the key is stored, or anything, Windows takes care of everything.</p>
<p>The code above works on the full .NET framework, but the Data Protection API is also available:</p>
<ul>
<li>for Windows Phone: same methods, but without the scope parameter</li>
<li>for Windows Store apps, using the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.dataprotection.dataprotectionprovider">DataProtectionProvider</a> class. The API is quite different and a bit more complex, but achieves the same result.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Detecting dependency property changes in WinRT</title>
		<link>http://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/</link>
		<comments>http://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/#comments</comments>
		<pubDate>Sun, 21 Apr 2013 17:05:53 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dependency property]]></category>
		<category><![CDATA[winrt]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://www.thomaslevesque.com/?p=505</guid>
		<description><![CDATA[Today I’d like to share a trick I used while developing my first Windows Store application. I’m very new to this technology and it’s my first article about it, so I hope I won’t make a fool of myself… It’s often useful to be notified when the value of a dependency property changes; many controls [...]]]></description>
			<content:encoded><![CDATA[<p>Today I’d like to share a trick I used while developing my first Windows Store application. I’m very new to this technology and it’s my first article about it, so I hope I won’t make a fool of myself…</p>
<p>It’s often useful to be notified when the value of a dependency property changes; many controls expose events for that purpose, but it’s not always the case. For instance, recently I was trying to detect when the <code>Content</code> property of a <code>ContentControl</code> changed. In WPF, I would have used the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.aspx"><code>DependencyPropertyDescriptor</code></a> class, but it’s not available in WinRT.</p>
<p>Fortunately, there is a mechanism which is available on all XAML platforms, and can solve this problem: binding. So, the solution is just to create a class with a dummy property that is bound to the property we want to watch, and call a handler when the value of the dummy property changes. To make it cleaner and hide the actual implementation, I wrapped it as an extension method that returns an <code>IDisposable</code>:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:552616e7-d43e-4386-8c36-0604400759f1" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
    public static class DependencyObjectExtensions
    {
        public static IDisposable WatchProperty(this DependencyObject target,
                                                string propertyPath,
                                                DependencyPropertyChangedEventHandler handler)
        {
            return new DependencyPropertyWatcher(target, propertyPath, handler);
        }

        class DependencyPropertyWatcher : DependencyObject, IDisposable
        {
            private DependencyPropertyChangedEventHandler _handler;

            public DependencyPropertyWatcher(DependencyObject target,
                                             string propertyPath,
                                             DependencyPropertyChangedEventHandler handler)
            {
                if (target == null) throw new ArgumentNullException(&quot;target&quot;);
                if (propertyPath == null) throw new ArgumentNullException(&quot;propertyPath&quot;);
                if (handler == null) throw new ArgumentNullException(&quot;handler&quot;);

                _handler = handler;

                var binding = new Binding
                {
                    Source = target,
                    Path = new PropertyPath(propertyPath),
                    Mode = BindingMode.OneWay
                };
                BindingOperations.SetBinding(this, ValueProperty, binding);
            }

            private static readonly DependencyProperty ValueProperty =
                DependencyProperty.Register(
                    &quot;Value&quot;,
                    typeof(object),
                    typeof(DependencyPropertyWatcher),
                    new PropertyMetadata(null, ValuePropertyChanged));

            private static void ValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                var watcher = d as DependencyPropertyWatcher;
                if (watcher == null)
                    return;

                watcher.OnValueChanged(e);
            }

            private void OnValueChanged(DependencyPropertyChangedEventArgs e)
            {
                var handler = _handler;
                if (handler != null)
                    handler(this, e);
            }

            public void Dispose()
            {
                _handler = null;
                // There is no ClearBinding method, so set a dummy binding instead
                BindingOperations.SetBinding(this, ValueProperty, new Binding());
            }
        }
    }
</pre>
</pre>
</div>
<p>It can be used like this:</p>
<div id="scid:C89E2BDB-ADD3-4f7a-9810-1B7EACF446C1:871fd7da-96b9-4c2d-b2cc-c5f409381843" class="wlWriterEditableSmartContent" style="float: none; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px">
<pre style=white-space:normal>
<pre class="brush: csharp; title: ; notranslate">
// Subscribe
watcher = myControl.WatchProperty(&quot;Content&quot;, myControl_ContentChanged);

// Unsubscribe
watcher.Dispose();
</pre>
</pre>
</div>
<p>I hope you will find this useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2013/04/21/detecting-dependency-property-changes-in-winrt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using C# 5 caller info attributes when targeting earlier versions of the .NET framework</title>
		<link>http://www.thomaslevesque.com/2012/06/13/using-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework/</link>
		<comments>http://www.thomaslevesque.com/2012/06/13/using-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 15:32:05 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[c# 5]]></category>
		<category><![CDATA[caller info]]></category>

		<guid isPermaLink="false">http://www.thomaslevesque.com/?p=475</guid>
		<description><![CDATA[Caller info attributes are one of the new features of C# 5. They&#8217;re attributes applied to optional method parameters that enable you to pass caller information implicitly to a method. I&#8217;m not sure that description is very clear, so an example will help you understand: The method above takes several parameters intended to pass information [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/hh534540%28v=vs.110%29.aspx">Caller info attributes</a> are one of the new features of C# 5. They&#8217;re attributes applied to optional method parameters that enable you to pass caller information implicitly to a method. I&#8217;m not sure that description is very clear, so an example will help you understand:</p>
<pre class="brush: csharp; first-line: 25; title: ; notranslate">
        static void Log(
            string message,
            [CallerMemberName] string memberName = null,
            [CallerFilePath] string filePath = null,
            [CallerLineNumber] int lineNumber = 0)
        {
            Console.WriteLine(
                &quot;[{0:g} - {1} - {2} - line {3}] {4}&quot;,
                DateTime.UtcNow,
                memberName,
                filePath,
                lineNumber,
                message);
        }
</pre>
<p>The method above takes several parameters intended to pass information about the caller: calling member name, source file path and line number. The <code>Caller*</code> attributes make the compiler pass the appropriate values automatically, so you don&#8217;t have to specify the values for these parameters:</p>
<pre class="brush: csharp; first-line: 16; title: ; notranslate">
        static void Foo()
        {
            Log(&quot;Hello world&quot;);
            // Equivalent to:
            // Log(&quot;Hello world&quot;, &quot;Foo&quot;, @&quot;C:\x\y\z\Program.cs&quot;, 18);
        }
</pre>
<p>This is of course especially useful for logging methods&#8230;</p>
<p>Notice that the <code>Caller*</code> attributes are defined in the .NET Framework 4.5. Now, suppose we use Visual Studio 2012 to target an earlier framework version (e.g. 4.0): the caller info attributes don&#8217;t exist in 4.0, so we can&#8217;t use them&#8230; But wait! What if we could trick the compiler into thinking the attributes exist? Let&#8217;s define our own attributes, taking care to put them in the namespace where the compiler expects them:</p>
<pre class="brush: csharp; title: ; notranslate">
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerMemberNameAttribute : Attribute
    {
    }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerFilePathAttribute : Attribute
    {
    }

    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public class CallerLineNumberAttribute : Attribute
    {
    }
}
</pre>
<p>If we compile and run the program, we can see that our custom attributes are taken into account by the compiler. So they don&#8217;t have to be defined in mscorlib.dll like the &#8220;real&#8221; ones, they just have to be in the right namespace, and the compiler accepts them. This enables us to use this cool feature when targeting .NET 4.0, 3.5 or even 2.0!</p>
<p>Note that a similar trick enabled the creation of extension methods when targeting .NET 2.0 with the C# 3 compiler: you just had to create an <code>ExtensionAttribute</code> class in the <code>System.Runtime.CompilerServices</code> namespace, and the compiler would pick it up. This is also what enabled <a href="http://www.albahari.com/nutshell/linqbridge.aspx">LinqBridge</a> to work.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.thomaslevesque.com%2f2012%2f06%2f13%2fusing-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.thomaslevesque.com%2f2012%2f06%2f13%2fusing-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2012/06/13/using-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Little known new features in Visual Studio 2012</title>
		<link>http://www.thomaslevesque.com/2012/06/02/little-known-new-features-in-visual-studio-2012/</link>
		<comments>http://www.thomaslevesque.com/2012/06/02/little-known-new-features-in-visual-studio-2012/#comments</comments>
		<pubDate>Sat, 02 Jun 2012 16:00:31 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[edit and continue]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[Visual Studio 2012]]></category>

		<guid isPermaLink="false">http://www.thomaslevesque.com/?p=431</guid>
		<description><![CDATA[Visual Studio 2012 RC is out since last week, and even though I didn’t have much time to play with it yet, I think I like it so far. Lots of things have already been said about the design, and about the most important new features, but there are also many smaller and less remarkable [...]]]></description>
			<content:encoded><![CDATA[<p>Visual Studio 2012 RC is out since last week, and even though I didn’t have much time to play with it yet, I think I like it so far. Lots of things have already been said about the design, and about the most important new features, but there are also many smaller and less remarkable improvements that make life easier for us. Since I have seen little or nothing written about those, I thought I would make a list of what I noticed so far.</p>
<h3>Better <em>Edit and Continue</em>: improved debug experience with anonymous methods</h3>
<p><em>Edit and continue</em> is a very useful feature that has been present in Visual Studio for a long time. It’s great when you need to fix some code in the middle of a step-by-step debugging session without restarting the application completely. This feature has always had a limitation: you couldn’t use it in a method that contained an anonymous method:</p>
<blockquote><p>Modifying a ’method’ which contains a lambda expression will prevent the debug session from continuing while Edit and Continue is enabled.</p>
</blockquote>
<p>Before .NET 3.5, it wasn’t really a problem since anonymous methods were not very common, but since Linq was introduced and lambda expressions became more widely used, this limitation began to grow more and more annoying.</p>
<p>Well, good news: Visual Studio 2012 fixed that! You can now use <em>Edit and Continue</em> in a method that contains lambda expressions or Linq queries. Note that the limitation hasn’t completely disappeared: you still can’t modify a <em>statement</em> that contains an anonymous method. Note the slightly different error message:</p>
<blockquote><p>Modifying a statement which contains a lambda expression will prevent the debug session from continuing while Edit and Continue is enabled.</p>
</blockquote>
<p>But you can modify everything else in the method body, which is a great improvement. Note that editing a method that contains anonymous types is also supported, as long as you don’t modify the anonymous type itself.</p>
<h3>Optimized event handler autocompletion</h3>
<p>Visual Studio has a nice autocompletion feature that allow you to generate an event handler automatically when you type <code>+=</code> and <kbd>Tab</kbd> after an event name :</p>
<p><a href="http://www.thomaslevesque.com/files/2012/06/image3.png"><img style="background-image: none; border-right-width: 0px; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.thomaslevesque.com/files/2012/06/image_thumb3.png" width="404" height="75" /></a></p>
<p>But the <code>new EventHandler(…)</code> part is redundant, because since C# 2, method groups are implicitly convertible to compatible delegate types. Visual Studio 2012 fixes this and generates the shorter form:</p>
<p><a href="http://www.thomaslevesque.com/files/2012/06/image31.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://www.thomaslevesque.com/files/2012/06/image3_thumb.png" width="405" height="74" /></a></p>
<p>OK, this is a very small change, but the previous behavior was really annoying me… I had actually <a href="http://connect.microsoft.com/VisualStudio/feedback/details/632300/auto-generated-event-handlers-should-use-implicit-conversion-of-method-group-to-delegate">suggested this improvement on Connect</a>, so I’m glad to see that it was implemented.</p>
<h3>Improved <em>Find/Replace</em></h3>
<p>The <em>Find</em> dialog in Visual Studio had not seen any improvement for as long as I can remember (probably since VS2003 or VS2005), so it was time for a change… In VS2012, it has been replaced with the Quick Find feature from the <a href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef">Productivity Power Tools extension</a>. It appears as a small panel in the top right corner of the text editor, much less obtrusive than the old dialog:</p>
<p><a href="http://www.thomaslevesque.com/files/2012/06/image4.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://www.thomaslevesque.com/files/2012/06/image_thumb4.png" width="620" height="260" /></a></p>
<p>It provides the following features:</p>
<ul>
<li>incremental search (matches are highlighted as you type in the search box) </li>
<li>quick access to options such as match case, match whole word, or regex through the search field dropdown </li>
<li>support for .NET regular expressions (the old <em>Find</em> dialog was using a different kind of regex, not fully compatible with the .NET regex syntax) </li>
</ul>
<p>If for some reason you need the full <em>Find</em> dialog, it’s still there: there’s a menu item to access it in the search field dropdown.</p>
<h3>Quick launch</h3>
<blockquote><p>Where’s that command again? In the Debug menu or the Project menu? I can’t remember, and I don’t know the keyboard shortcut…</p>
</blockquote>
<p>Sounds familiar? For me it does… Visual Studio has so many features that sometimes it can be hard to find what you’re looking for. That’s why the new <em>Quick Access</em> feature is a very welcome addition; it appears as a search box in the top right corner of the IDE, and allows you to type what you want to do:</p>
<p><a href="http://www.thomaslevesque.com/files/2012/06/image5.png"><img style="background-image: none; border-right-width: 0px; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://www.thomaslevesque.com/files/2012/06/image_thumb5.png" width="561" height="304" /></a></p>
<p>Again, this feature comes from the Productivity Power Tools extension, and has been included in Visual Studio itself. It has also been given a more prominent place in the IDE (in VS2010 it was only accessible through the <kbd>Ctrl+Q</kbd> shortcut).</p>
<h3>Smarter Solution Explorer</h3>
<p>The Solution Explorer used to show only the files in your project, but nothing about what was in the files; If you want to see the classes and members, you had to switch to the Class View. Visual Studio 2012 changes that: now you can see what is declared in a file, just by expanding the node in the Solution Explorer:</p>
<p><a href="http://www.thomaslevesque.com/files/2012/06/image6.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px" title="image" border="0" alt="image" src="http://www.thomaslevesque.com/files/2012/06/image_thumb6.png" width="310" height="414" /></a></p>
<p>This feature had been in Eclipse for a long time, so it was time for Visual Studio to catch up <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Clignement d&#39;œil" src="http://www.thomaslevesque.com/files/2012/06/wlEmoticon-winkingsmile.png" />.</p>
<p>A few other interesting features of the new Solution Explorer:</p>
<ul>
<li>Scope to This: allows to re-root the tree to a specific node (e.g. if you want to see only the content of a folder). The re-rooted tree can be viewed in a separate view. </li>
<li>Pending Changes Filter: show only pending changes (if source control is active for the current project) </li>
<li>Open Files Filter: show only open files </li>
<li>Sync With Active Document: quickly locate the current document in the Solution Explorer (<em>very</em> useful for large solutions) </li>
</ul>
<p>And yes, that’s yet another feature that comes from Productivity Power Tools (it was known as the <em>Solution Navigator</em>), with a few improvements.</p>
<h3>ALL CAPS MENUS</h3>
<p>Menus in VS2012 are in ALL CAPS, and it’s not exactly the most popular change… there has been tons of negative feedback about this! Frankly, I’m a bit surprised that people pay so much importance to such an insignificant detail, when there are so many more important things to discuss. Personally, I found it a bit unsettling when I saw the first screenshots, but when I got my hands on the RC I found that it didn’t bother me at all. I guess most people will just get used to it in the end…</p>
<p>Anyway, the reason I mention this is to say that if you really don’t like the ALL CAPS menus, you can get the normal casing back with a simple registry tweak. Just open regedit, go to the <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General</code> key, create a DWORD value named <code>SuppressUppercaseConversion</code> and set it to 1.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.thomaslevesque.com%2f2012%2f06%2f02%2flittle-known-new-features-in-visual-studio-2012%2f"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://www.thomaslevesque.com/2012/06/02/little-known-new-features-in-visual-studio-2012/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2012/06/02/little-known-new-features-in-visual-studio-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[WPF] Using Linq to shape data in a CollectionView</title>
		<link>http://www.thomaslevesque.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/</link>
		<comments>http://www.thomaslevesque.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 13:09:45 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[collectionview]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=381</guid>
		<description><![CDATA[WPF provides a simple mechanism for shaping collections of data, via the ICollectionView interface and its Filter, SortDescriptions and GroupDescriptions properties: Even though this technique is not difficult to use, it has a few drawbacks: The syntax is a bit clumsy and unnatural: the fact that the filter parameter is an object whereas we know [...]]]></description>
			<content:encoded><![CDATA[<p>WPF provides a simple mechanism for shaping collections of data, via the <code>ICollectionView</code> interface and its <code>Filter</code>, <code>SortDescriptions</code> and <code>GroupDescriptions</code> properties:</p>
<pre class="brush: csharp; title: ; notranslate">
// Collection to which the view is bound
public ObservableCollection People { get; private set; }
...

// Default view of the People collection
ICollectionView view = CollectionViewSource.GetDefaultView(People);

// Show only adults
view.Filter = o =&gt; ((Person)o).Age &gt;= 18;

// Sort by last name and first name
view.SortDescriptions.Add(new SortDescription(&quot;LastName&quot;, ListSortDirection.Ascending));
view.SortDescriptions.Add(new SortDescription(&quot;FirstName&quot;, ListSortDirection.Ascending));

// Group by country
view.GroupDescriptions.Add(new PropertyGroupDescription(&quot;Country&quot;));
</pre>
<p>Even though this technique is not difficult to use, it has a few drawbacks:</p>
<ul>
<li>The syntax is a bit clumsy and unnatural: the fact that the filter parameter is an <code>object</code> whereas we know it&#8217;s actually of type <code>Person</code> makes the code less readable because of the cast, and the specification of the sort and group descriptions is a little repetitive</li>
<li>Specifying the property names as strings introduces a risk of error, since they&#8217;re not verified by the compiler</li>
</ul>
<p>In the last few years, we got used to use Linq to do this kind of things… it would be nice to be able to do the same for the shaping of an <code>ICollectionView</code>.</p>
<p>Let&#8217;s see what syntax we could use to do it with Linq… something like this perhaps?</p>
<pre class="brush: csharp; title: ; notranslate">
People.Where(p =&gt; p.Age &gt;= 18)
      .OrderBy(p =&gt; p.LastName)
      .ThenBy(p =&gt; p.FirstName)
      .GroupBy(p =&gt; p.Country);
</pre>
<p>Or, with the Linq query comprehension syntax:</p>
<pre class="brush: csharp; title: ; notranslate">
from p in People
where p.Age &gt;= 18
orderby p.LastName, p.FirstName
group p by p.Country;
</pre>
<p>Obviously, this is not enough: this code only creates a  query on the collection, it doesn&#8217;t modify the <code>CollectionView</code>… but with just a little extra work, we can get the desired result:</p>
<pre class="brush: csharp; title: ; notranslate">
var query =
    from p in People.ShapeView()
    where p.Age &gt;= 18
    orderby p.LastName, p.FirstName
    group p by p.Country;

query.Apply();
</pre>
<p>The <code>ShapeView</code> method returns a wrapper which encapsulates the default view of the collection, and exposes <code>Where</code>, <code>OrderBy</code> and <code>GroupBy</code> methods with appropriate signatures to specify the shaping of the <code>CollectionView</code>. Creating the query has no direct effect, the changes are only applied to the view when  <code>Apply</code> is called: that&#8217;s because it&#8217;s better to apply all changes at the same time, using <code>ICollectionView.DeferRefresh</code>, to avoid causing a refresh of the view for each clause of the query. When <code>Apply</code> is called, we can see that the view is correctly updated to reflect the query.</p>
<p>This solution allows to define the filter, sort and grouping in a strongly-typed way, which implies that the code is verified by the compiler. It&#8217;s also more concise and readable than the original code… Just be careful with one thing: some queries that are correct from the compiler&#8217;s point of view won&#8217;t be applicable to a <code>CollectionView</code>. For instance, if you try to group the data by the first letter of the last name (<code>p.LastName.Substring(0, 1)</code>), the <code>GroupBy</code> method will fail because only properties are supported by <code>PropertyGroupDescription</code>.</p>
<p>Note that the wrapper won&#8217;t overwrite the shaping properties of the <code>CollectionView</code> if you don&#8217;t specify the corresponding Linq clause, so you can just modify the current view without specifying everything again. If you need to clear the properties, you can use the <code>ClearFilter</code>, <code>ClearSort</code> and <code>ClearGrouping</code> methods:</p>
<pre class="brush: csharp; title: ; notranslate">
// Remove the grouping and add a sort criteria
People.ShapeView()
      .ClearGrouping()
      .OrderBy(p =&gt; p.LastName);
      .Apply();
</pre>
<p>Note that as for a normal Linq query, it&#8217;s possible to use either the query comprehension syntax or to call the methods directly, since the former is just syntactic sugar for the latter.</p>
<p>Finally, here&#8217;s the complete code of the wrapper and the associated extension methods:</p>
<pre class="brush: csharp; title: ; notranslate">
    public static class CollectionViewShaper
    {
        public static CollectionViewShaper&lt;TSource&gt; ShapeView&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)
        {
            var view = CollectionViewSource.GetDefaultView(source);
            return new CollectionViewShaper&lt;TSource&gt;(view);
        }

        public static CollectionViewShaper&lt;TSource&gt; Shape&lt;TSource&gt;(this ICollectionView view)
        {
            return new CollectionViewShaper&lt;TSource&gt;(view);
        }
    }

    public class CollectionViewShaper&lt;TSource&gt;
    {
        private readonly ICollectionView _view;
        private Predicate&lt;object&gt; _filter;
        private readonly List&lt;SortDescription&gt; _sortDescriptions = new List&lt;SortDescription&gt;();
        private readonly List&lt;GroupDescription&gt; _groupDescriptions = new List&lt;GroupDescription&gt;();

        public CollectionViewShaper(ICollectionView view)
        {
            if (view == null)
                throw new ArgumentNullException(&quot;view&quot;);
            _view = view;
            _filter = view.Filter;
            _sortDescriptions = view.SortDescriptions.ToList();
            _groupDescriptions = view.GroupDescriptions.ToList();
        }

        public void Apply()
        {
            using (_view.DeferRefresh())
            {
                _view.Filter = _filter;
                _view.SortDescriptions.Clear();
                foreach (var s in _sortDescriptions)
                {
                    _view.SortDescriptions.Add(s);
                }
                _view.GroupDescriptions.Clear();
                foreach (var g in _groupDescriptions)
                {
                    _view.GroupDescriptions.Add(g);
                }
            }
        }

        public CollectionViewShaper&lt;TSource&gt; ClearGrouping()
        {
            _groupDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearSort()
        {
            _sortDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearFilter()
        {
            _filter = null;
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; ClearAll()
        {
            _filter = null;
            _sortDescriptions.Clear();
            _groupDescriptions.Clear();
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; Where(Func&lt;TSource, bool&gt; predicate)
        {
            _filter = o =&gt; predicate((TSource)o);
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; OrderBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, true, ListSortDirection.Ascending);
        }

        public CollectionViewShaper&lt;TSource&gt; OrderByDescending&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, true, ListSortDirection.Descending);
        }

        public CollectionViewShaper&lt;TSource&gt; ThenBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, false, ListSortDirection.Ascending);
        }

        public CollectionViewShaper&lt;TSource&gt; ThenByDescending&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            return OrderBy(keySelector, false, ListSortDirection.Descending);
        }

        private CollectionViewShaper&lt;TSource&gt; OrderBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector, bool clear, ListSortDirection direction)
        {
            string path = GetPropertyPath(keySelector.Body);
            if (clear)
                _sortDescriptions.Clear();
            _sortDescriptions.Add(new SortDescription(path, direction));
            return this;
        }

        public CollectionViewShaper&lt;TSource&gt; GroupBy&lt;TKey&gt;(Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
        {
            string path = GetPropertyPath(keySelector.Body);
            _groupDescriptions.Add(new PropertyGroupDescription(path));
            return this;
        }

        private static string GetPropertyPath(Expression expression)
        {
            var names = new Stack&lt;string&gt;();
            var expr = expression;
            while (expr != null &amp;&amp; !(expr is ParameterExpression) &amp;&amp; !(expr is ConstantExpression))
            {
                var memberExpr = expr as MemberExpression;
                if (memberExpr == null)
                    throw new ArgumentException(&quot;The selector body must contain only property or field access expressions&quot;);
                names.Push(memberExpr.Member.Name);
                expr = memberExpr.Expression;
            }
            return String.Join(&quot;.&quot;, names.ToArray());
        }
    }
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f11%2f30%2fwpf-using-linq-to-shape-data-in-a-collectionview%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f11%2f30%2fwpf-using-linq-to-shape-data-in-a-collectionview%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/11/30/wpf-using-linq-to-shape-data-in-a-collectionview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[WPF] Creating parameterized styles with attached properties</title>
		<link>http://www.thomaslevesque.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/</link>
		<comments>http://www.thomaslevesque.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 00:37:15 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[attached property]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=371</guid>
		<description><![CDATA[2012-05-10 22:40:19]]></description>
			<content:encoded><![CDATA[<p>Today I&#8217;d like to share a trick that I used quite often in the past few months. Let&#8217;s assume that in order to improve the look of your application, you created custom styles for the standard controls:</p>
<p><a href="/files/2012/05/parameterized_styles11.png"><img src="/files/2012/05/parameterized_styles11.png" alt="" width="200" height="200" class="aligncenter size-full wp-image-468" /></a></p>
<p>OK, I&#8217;m not a designer&#8230; but it will serve the purpose well enough to illustrate my point <img src='http://www.thomaslevesque.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . These styles are very simple, they&#8217;re just the default styles of <code>CheckBox</code> and <code>RadioButton</code> in which I only changed the templates to replace the <code>BulletChrome</code>s with these awesome blue tick marks. Here&#8217;s the code:</p>
<pre class="brush: xml; title: ; notranslate">
        &lt;Style x:Key=&quot;{x:Type CheckBox}&quot; TargetType=&quot;{x:Type CheckBox}&quot;&gt;
            &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}&quot;/&gt;
            &lt;Setter Property=&quot;Background&quot; Value=&quot;{StaticResource CheckBoxFillNormal}&quot;/&gt;
            &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource CheckBoxStroke}&quot;/&gt;
            &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;1&quot;/&gt;
            &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource EmptyCheckBoxFocusVisual}&quot;/&gt;
            &lt;Setter Property=&quot;Template&quot;&gt;
                &lt;Setter.Value&gt;
                    &lt;ControlTemplate TargetType=&quot;{x:Type CheckBox}&quot;&gt;
                        &lt;BulletDecorator Background=&quot;Transparent&quot;
                                         SnapsToDevicePixels=&quot;true&quot;&gt;
                            &lt;BulletDecorator.Bullet&gt;
                                &lt;Border BorderBrush=&quot;{TemplateBinding BorderBrush}&quot;
                                        Background=&quot;{TemplateBinding Background}&quot;
                                        BorderThickness=&quot;1&quot;
                                        Width=&quot;11&quot; Height=&quot;11&quot; Margin=&quot;0,1,0,0&quot;&gt;
                                    &lt;Grid&gt;
                                        &lt;Path Name=&quot;TickMark&quot;
                                              Fill=&quot;Blue&quot;
                                              Data=&quot;M0,4 5,9 9,0 4,5&quot;
                                              Visibility=&quot;Hidden&quot; /&gt;
                                        &lt;Rectangle Name=&quot;IndeterminateMark&quot;
                                                   Fill=&quot;Blue&quot;
                                                   Width=&quot;7&quot; Height=&quot;7&quot;
                                                   HorizontalAlignment=&quot;Center&quot;
                                                   VerticalAlignment=&quot;Center&quot;
                                                   Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;/Grid&gt;
                                &lt;/Border&gt;
                            &lt;/BulletDecorator.Bullet&gt;
                            &lt;ContentPresenter HorizontalAlignment=&quot;{TemplateBinding HorizontalContentAlignment}&quot;
                                              Margin=&quot;{TemplateBinding Padding}&quot;
                                              RecognizesAccessKey=&quot;True&quot;
                                              SnapsToDevicePixels=&quot;{TemplateBinding SnapsToDevicePixels}&quot;
                                              VerticalAlignment=&quot;{TemplateBinding VerticalContentAlignment}&quot;/&gt;
                        &lt;/BulletDecorator&gt;
                        &lt;ControlTemplate.Triggers&gt;
                            &lt;Trigger Property=&quot;HasContent&quot; Value=&quot;true&quot;&gt;
                                &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource CheckRadioFocusVisual}&quot;/&gt;
                                &lt;Setter Property=&quot;Padding&quot; Value=&quot;4,0,0,0&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsEnabled&quot; Value=&quot;false&quot;&gt;
                                &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;True&quot;&gt;
                                &lt;Setter TargetName=&quot;TickMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;{x:Null}&quot;&gt;
                                &lt;Setter TargetName=&quot;IndeterminateMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                        &lt;/ControlTemplate.Triggers&gt;
                    &lt;/ControlTemplate&gt;
                &lt;/Setter.Value&gt;
            &lt;/Setter&gt;
        &lt;/Style&gt;
        &lt;Style x:Key=&quot;{x:Type RadioButton}&quot; TargetType=&quot;{x:Type RadioButton}&quot;&gt;
            &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}&quot;/&gt;
            &lt;Setter Property=&quot;Background&quot; Value=&quot;#F4F4F4&quot;/&gt;
            &lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource CheckBoxStroke}&quot;/&gt;
            &lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;1&quot;/&gt;
            &lt;Setter Property=&quot;Template&quot;&gt;
                &lt;Setter.Value&gt;
                    &lt;ControlTemplate TargetType=&quot;{x:Type RadioButton}&quot;&gt;
                        &lt;BulletDecorator Background=&quot;Transparent&quot;&gt;
                            &lt;BulletDecorator.Bullet&gt;
                                &lt;Grid VerticalAlignment=&quot;Center&quot; Margin=&quot;0,1,0,0&quot;&gt;
                                    &lt;Ellipse Width=&quot;11&quot; Height=&quot;11&quot;
                                             Stroke=&quot;{TemplateBinding BorderBrush}&quot;
                                             StrokeThickness=&quot;1&quot;
                                             Fill=&quot;{TemplateBinding Background}&quot; /&gt;
                                    &lt;Ellipse Name=&quot;TickMark&quot;
                                             Width=&quot;7&quot; Height=&quot;7&quot;
                                             Fill=&quot;Blue&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;Ellipse Name=&quot;IndeterminateMark&quot;
                                             Width=&quot;3&quot; Height=&quot;3&quot;
                                             Fill=&quot;Blue&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                &lt;/Grid&gt;
                            &lt;/BulletDecorator.Bullet&gt;
                            &lt;ContentPresenter HorizontalAlignment=&quot;{TemplateBinding HorizontalContentAlignment}&quot;
                                              Margin=&quot;{TemplateBinding Padding}&quot;
                                              RecognizesAccessKey=&quot;True&quot;
                                              VerticalAlignment=&quot;{TemplateBinding VerticalContentAlignment}&quot;/&gt;
                        &lt;/BulletDecorator&gt;
                        &lt;ControlTemplate.Triggers&gt;
                            &lt;Trigger Property=&quot;HasContent&quot; Value=&quot;true&quot;&gt;
                                &lt;Setter Property=&quot;FocusVisualStyle&quot; Value=&quot;{StaticResource CheckRadioFocusVisual}&quot;/&gt;
                                &lt;Setter Property=&quot;Padding&quot; Value=&quot;4,0,0,0&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsEnabled&quot; Value=&quot;false&quot;&gt;
                                &lt;Setter Property=&quot;Foreground&quot; Value=&quot;{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}&quot;/&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;True&quot;&gt;
                                &lt;Setter TargetName=&quot;TickMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                            &lt;Trigger Property=&quot;IsChecked&quot; Value=&quot;{x:Null}&quot;&gt;
                                &lt;Setter TargetName=&quot;IndeterminateMark&quot; Property=&quot;Visibility&quot; Value=&quot;Visible&quot; /&gt;
                            &lt;/Trigger&gt;
                        &lt;/ControlTemplate.Triggers&gt;
                    &lt;/ControlTemplate&gt;
                &lt;/Setter.Value&gt;
            &lt;/Setter&gt;
        &lt;/Style&gt;
</pre>
<p>OK, so you now have beautiful controls that are going to make the app a big success, management is happy, everything is for the best&#8230; until you realize that in another view of the application, the controls need to have the same style, but with green tick marks!</p>
<p>The first solution that comes to mind is to duplicate the style, and replace blue with green in the copy. But since you&#8217;re a good developer who cares about best practices, you know that duplicate code is evil: if you ever need to make changes to the style of the blue <code>CheckBox</code>, you will also have to modify the green one&#8230; and perhaps the red one, and the black one, etc. Clearly it would soon become unmanageable. So we need to refactor, but how? Ideally we would pass parameters to the style, but a style is not a method that you can call with various parameters&#8230;</p>
<p>What we need is an extra property that controls the color of the tick marks, so we can bind to this property in the template. A possible approach is to create custom controls that inherit <code>CheckBox</code> and <code>RadioButton</code>, with an extra <code>TickBrush</code> property&#8230; but personnally I don&#8217;t really like this approach, I always prefer to use the built-in controls when they can fit the bill.</p>
<p>Anyway, there is an easier solution: we just need to create a <code>ThemeProperties</code> class with an attached property of type <code>Brush</code>:</p>
<pre class="brush: csharp; title: ; notranslate">
    public static class ThemeProperties
    {
        public static Brush GetTickBrush(DependencyObject obj)
        {
            return (Brush)obj.GetValue(TickBrushProperty);
        }

        public static void SetTickBrush(DependencyObject obj, Brush value)
        {
            obj.SetValue(TickBrushProperty, value);
        }

        public static readonly DependencyProperty TickBrushProperty =
            DependencyProperty.RegisterAttached(
                &quot;TickBrush&quot;,
                typeof(Brush),
                typeof(ThemeProperties),
                new FrameworkPropertyMetadata(Brushes.Black));
    }
</pre>
<p>We change the templates a bit to replace the hard-coded color with a binding to this property:</p>
<pre class="brush: xml; title: ; notranslate">
                                ...

                                &lt;!-- CheckBox --&gt;
                                        &lt;Path Name=&quot;TickMark&quot;
                                              Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                              Data=&quot;M0,4 5,9 9,0 4,5&quot;
                                              Visibility=&quot;Hidden&quot; /&gt;
                                        &lt;Rectangle Name=&quot;IndeterminateMark&quot;
                                                   Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                                   Width=&quot;7&quot; Height=&quot;7&quot;
                                                   HorizontalAlignment=&quot;Center&quot;
                                                   VerticalAlignment=&quot;Center&quot;
                                                   Visibility=&quot;Hidden&quot; /&gt;

                                ...

                                &lt;!-- RadioButton --&gt;
                                    &lt;Ellipse Name=&quot;TickMark&quot;
                                             Width=&quot;7&quot; Height=&quot;7&quot;
                                             Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
                                    &lt;Ellipse Name=&quot;IndeterminateMark&quot;
                                             Width=&quot;3&quot; Height=&quot;3&quot;
                                             Fill=&quot;{TemplateBinding my:ThemeProperties.TickBrush}&quot;
                                             Visibility=&quot;Hidden&quot; /&gt;
</pre>
<p>And when we use the controls, we set the property to the desired tick color:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;CheckBox Content=&quot;Checked&quot; IsChecked=&quot;True&quot; my:ThemeProperties.TickBrush=&quot;Blue&quot; /&gt;
</pre>
<p>So we can now have controls that share the same style, but have different colors for the tick mark:</p>
<p><a href="/files/2012/05/parameterized_styles42.png"><img src="/files/2012/05/parameterized_styles42.png" alt="" width="410" height="200" class="aligncenter size-full wp-image-475" /></a></p>
<p>Isn&#8217;t it great? However there is a small problem left: since controls on the same view all use the same tick color, it&#8217;s not very convenient to repeat the color on each one. It would be nice to be able to specify the color just once, on the root of the view&#8230; Well, as it happens, dependency properties have a nice feature that allows to do exactly that: value inheritance. We just need to specify the <code>Inherits</code> flag in the declaration of the <code>TickBrush</code> property:</p>
<pre class="brush: csharp; title: ; notranslate">
        public static readonly DependencyProperty TickBrushProperty =
            DependencyProperty.RegisterAttached(
                &quot;TickBrush&quot;,
                typeof(Brush),
                typeof(ThemeProperties),
                new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.Inherits));
</pre>
<p>With this flag, the property becomes &#8220;ambient&#8221;: we only need to specify its value on a parent control, and all descendant controls will automatically inherit the value. So if you need a view where all the checkboxes and radiobuttons are red, just set the <code>TickBrush</code> property to <code>Red</code> on the root element of the view.</p>
<p>Obviously this concept can be extended to other cases: actually, every time an element of the template must change based on arbitrary criteria, this technique can be used. It can be a good alternative to duplicating a template when you only need to change a small part of it.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f10%2f01%2fwpf-creating-parameterized-styles-with-attached-properties%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f10%2f01%2fwpf-creating-parameterized-styles-with-attached-properties%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[WPF 4.5] Subscribing to an event using a markup extension</title>
		<link>http://www.thomaslevesque.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/</link>
		<comments>http://www.thomaslevesque.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 11:32:07 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[markup extension]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=364</guid>
		<description><![CDATA[It&#8217;s been a while since I last wrote about markup extensions&#8230; The release of Visual Studio 11 Developer Preview, which introduces a number of new features to WPF, just gave me a reason to play with them again. The feature I&#8217;m going to discuss here is perhaps not the most impressive, but it fills in [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since I last wrote about markup extensions&#8230; The release of <a href="http://msdn.microsoft.com/en-us/vstudio/hh127353">Visual Studio 11 Developer Preview</a>, which introduces a number of <a href="http://msdn.microsoft.com/en-us/library/bb613588%28v=VS.110%29.aspx">new features</a> to WPF, just gave me a reason to play with them again. The feature I&#8217;m going to discuss here is perhaps not the most impressive, but it fills in a gap of the previous versions: the support of markup extensions for events.</p>
<p>Until now, it was possible to use a markup extension in XAML to assign a value to a property, but we couldn&#8217;t do the same to subscribe to an event. In WPF 4.5, it is now possible. So here is a small example of the kind we can do with it&#8230;</p>
<p>When using the MVVM pattern, we often associate commands of the ViewModel with controls of the view, via the binding mechanism. This approach usually works well, but it has some downsides:</p>
<ul>
<li>it introduces a lot of boilerplate code in the ViewModel</li>
<li>not all controls have a <code>Command</code> property (actually, most don&#8217;t), and when this property exists, it corresponds only to one event of the control (e.g. the click on a button). There is no really easy way to &#8220;bind&#8221; the other events to commands of the ViewModel</li>
</ul>
<p>It would be nice to be able to bind events directly to ViewModel methods, like this:</p>
<pre class="brush: xml; title: ; notranslate">
        &lt;Button Content=&quot;Click me&quot;
                Click=&quot;{my:EventBinding OnClick}&quot; /&gt;
</pre>
<p>With the <code>OnClick</code> method defined in the ViewModel:</p>
<pre class="brush: csharp; title: ; notranslate">
        public void OnClick(object sender, EventArgs e)
        {
            MessageBox.Show(&quot;Hello world!&quot;);
        }
</pre>
<p>Well, this is now possible! Here&#8217;s a proof of concept&#8230; The <code>EventBindingExtension</code> class shown below first gets the <code>DataContext</code> of the control, then looks for the specified method on the <code>DataContext</code>, and eventually returns a delegate for this method:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;

    public class EventBindingExtension : MarkupExtension
    {
        public EventBindingExtension() { }

        public EventBindingExtension(string eventHandlerName)
        {
            this.EventHandlerName = eventHandlerName;
        }

        [ConstructorArgument(&quot;eventHandlerName&quot;)]
        public string EventHandlerName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(EventHandlerName))
                throw new ArgumentException(&quot;The EventHandlerName property is not set&quot;, &quot;EventHandlerName&quot;);

            var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

            EventInfo eventInfo = target.TargetProperty as EventInfo;
            if (eventInfo == null)
                throw new InvalidOperationException(&quot;The target property must be an event&quot;);

            object dataContext = GetDataContext(target.TargetObject);
            if (dataContext == null)
                throw new InvalidOperationException(&quot;No DataContext found&quot;);

            var handler = GetHandler(dataContext, eventInfo, EventHandlerName);
            if (handler == null)
                throw new ArgumentException(&quot;No valid event handler was found&quot;, &quot;EventHandlerName&quot;);

            return handler;
        }

        #region Helper methods

        static object GetHandler(object dataContext, EventInfo eventInfo, string eventHandlerName)
        {
            Type dcType = dataContext.GetType();

            var method = dcType.GetMethod(
                eventHandlerName,
                GetParameterTypes(eventInfo));
            if (method != null)
            {
                if (method.IsStatic)
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, method);
                else
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, dataContext, method);
            }

            return null;
        }

        static Type[] GetParameterTypes(EventInfo eventInfo)
        {
            var invokeMethod = eventInfo.EventHandlerType.GetMethod(&quot;Invoke&quot;);
            return invokeMethod.GetParameters().Select(p =&gt; p.ParameterType).ToArray();
        }

        static object GetDataContext(object target)
        {
            var depObj = target as DependencyObject;
            if (depObj == null)
                return null;

            return depObj.GetValue(FrameworkElement.DataContextProperty)
                ?? depObj.GetValue(FrameworkContentElement.DataContextProperty);
        }

        #endregion
    }
</pre>
<p>This class can be used as shown in the example above.</p>
<p>As it is now, this markup extension has an annoying limitation: the <code>DataContext</code> must be set before the call to <code>ProvideValue</code>, otherwise it won&#8217;t be possible to find the event handler method. A solution could be to subscribe to the <code>DataContextChanged</code> event to look for the method after the <code>DataContext</code> is set, but in the meantime we still need to return something&#8230; and we can&#8217;t return null, because it would cause an exception (since you can&#8217;t subscribe to an event with a null handler). So we need to return a dummy handler generated dynamically from the event signature. It makes things a bit harder&#8230; but it&#8217;s still feasible.</p>
<p>Here&#8217;s a second version that implements this improvement :</p>
<pre class="brush: csharp; collapse: true; light: false; title: ; toolbar: true; notranslate">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Windows;
using System.Windows.Markup;

    public class EventBindingExtension : MarkupExtension
    {
        private EventInfo _eventInfo;

        public EventBindingExtension() { }

        public EventBindingExtension(string eventHandlerName)
        {
            this.EventHandlerName = eventHandlerName;
        }

        [ConstructorArgument(&quot;eventHandlerName&quot;)]
        public string EventHandlerName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(EventHandlerName))
                throw new ArgumentException(&quot;The EventHandlerName property is not set&quot;, &quot;EventHandlerName&quot;);

            var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

            var targetObj = target.TargetObject as DependencyObject;
            if (targetObj == null)
                throw new InvalidOperationException(&quot;The target object must be a DependencyObject&quot;);

            _eventInfo = target.TargetProperty as EventInfo;
            if (_eventInfo == null)
                throw new InvalidOperationException(&quot;The target property must be an event&quot;);

            object dataContext = GetDataContext(targetObj);
            if (dataContext == null)
            {
                SubscribeToDataContextChanged(targetObj);
                return GetDummyHandler(_eventInfo.EventHandlerType);
            }

            var handler = GetHandler(dataContext, _eventInfo, EventHandlerName);
            if (handler == null)
            {
                Trace.TraceError(
                    &quot;EventBinding: no suitable method named '{0}' found in type '{1}' to handle event '{2'}&quot;,
                    EventHandlerName,
                    dataContext.GetType(),
                    _eventInfo);
                return GetDummyHandler(_eventInfo.EventHandlerType);
            }

            return handler;

        }

        #region Helper methods

        static Delegate GetHandler(object dataContext, EventInfo eventInfo, string eventHandlerName)
        {
            Type dcType = dataContext.GetType();

            var method = dcType.GetMethod(
                eventHandlerName,
                GetParameterTypes(eventInfo.EventHandlerType));
            if (method != null)
            {
                if (method.IsStatic)
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, method);
                else
                    return Delegate.CreateDelegate(eventInfo.EventHandlerType, dataContext, method);
            }

            return null;
        }

        static Type[] GetParameterTypes(Type delegateType)
        {
            var invokeMethod = delegateType.GetMethod(&quot;Invoke&quot;);
            return invokeMethod.GetParameters().Select(p =&gt; p.ParameterType).ToArray();
        }

        static object GetDataContext(DependencyObject target)
        {
            return target.GetValue(FrameworkElement.DataContextProperty)
                ?? target.GetValue(FrameworkContentElement.DataContextProperty);
        }

        static readonly Dictionary&lt;Type, Delegate&gt; _dummyHandlers = new Dictionary&lt;Type, Delegate&gt;();

        static Delegate GetDummyHandler(Type eventHandlerType)
        {
            Delegate handler;
            if (!_dummyHandlers.TryGetValue(eventHandlerType, out handler))
            {
                handler = CreateDummyHandler(eventHandlerType);
                _dummyHandlers[eventHandlerType] = handler;
            }
            return handler;
        }

        static Delegate CreateDummyHandler(Type eventHandlerType)
        {
            var parameterTypes = GetParameterTypes(eventHandlerType);
            var returnType = eventHandlerType.GetMethod(&quot;Invoke&quot;).ReturnType;
            var dm = new DynamicMethod(&quot;DummyHandler&quot;, returnType, parameterTypes);
            var il = dm.GetILGenerator();
            if (returnType != typeof(void))
            {
                if (returnType.IsValueType)
                {
                    var local = il.DeclareLocal(returnType);
                    il.Emit(OpCodes.Ldloca_S, local);
                    il.Emit(OpCodes.Initobj, returnType);
                    il.Emit(OpCodes.Ldloc_0);
                }
                else
                {
                    il.Emit(OpCodes.Ldnull);
                }
            }
            il.Emit(OpCodes.Ret);
            return dm.CreateDelegate(eventHandlerType);
        }

        private void SubscribeToDataContextChanged(DependencyObject targetObj)
        {
            DependencyPropertyDescriptor
                .FromProperty(FrameworkElement.DataContextProperty, targetObj.GetType())
                .AddValueChanged(targetObj, TargetObject_DataContextChanged);
        }

        private void UnsubscribeFromDataContextChanged(DependencyObject targetObj)
        {
            DependencyPropertyDescriptor
                .FromProperty(FrameworkElement.DataContextProperty, targetObj.GetType())
                .RemoveValueChanged(targetObj, TargetObject_DataContextChanged);
        }

        private void TargetObject_DataContextChanged(object sender, EventArgs e)
        {
            DependencyObject targetObj = sender as DependencyObject;
            if (targetObj == null)
                return;

            object dataContext = GetDataContext(targetObj);
            if (dataContext == null)
                return;

            var handler = GetHandler(dataContext, _eventInfo, EventHandlerName);
            if (handler != null)
            {
                _eventInfo.AddEventHandler(targetObj, handler);
            }
            UnsubscribeFromDataContextChanged(targetObj);
        }

        #endregion
    }
</pre>
<p>So this is the kind of things we can do thanks to this new WPF feature. We could also imagine a behavior system similar to what we can do with attached properties, e.g. to execute a standard action when an event occurs. There are lots of possible applications for this, I leave it to you to find them <img src='http://www.thomaslevesque.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f23%2fwpf-4-5-subscribing-to-an-event-using-a-markup-extension%2f"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/09/23/wpf-4-5-subscribing-to-an-event-using-a-markup-extension/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Tail recursion in C#</title>
		<link>http://www.thomaslevesque.com/2011/09/02/tail-recursion-in-c/</link>
		<comments>http://www.thomaslevesque.com/2011/09/02/tail-recursion-in-c/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 22:16:52 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Code sample]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[tail recursion]]></category>
		<category><![CDATA[trampoline]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=348</guid>
		<description><![CDATA[Regardless of the programming language you&#8217;re using, there are tasks for which the most natural implementation uses a recursive algorithm (even if it&#8217;s not always the optimal solution). The trouble with the recursive approach is that it can use a lot of space on the stack: when you reach a certain recursion depth, the memory [...]]]></description>
			<content:encoded><![CDATA[<p>Regardless of the programming language you&#8217;re using, there are tasks for which the most natural implementation uses a recursive algorithm (even if it&#8217;s not always the optimal solution). The trouble with the recursive approach is that it can use a lot of space on the stack: when you reach a certain recursion depth, the memory allocated for the thread stack runs out, and you get a stack overflow error that usually terminates the process (<code>StackOverflowException</code> in .NET).</p>
<h6><strong>Terminal recursion? What&#8217;s that?</strong></h6>
<p>Some languages, more particularly functional languages, have native support for an optimization technique called <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion</a>. The idea is that if the recursive call is the last instruction in a recursive function, there is no need to keep the current call context on the stack, since we won&#8217;t have to go back there: we only need to replace the parameters with their new values, and jump back to the beginning of the function. So the recursion is transformed into an iteration, so it can’t cause a stack overflow. This notion being quite new to me, I won’t try to give a full course about tail recursion… much smarter people already took care of it! I suggest you follow the Wikipedia link above, which is a good starting point to understand tail recursion.</p>
<p>Unfortunately, the C# compiler doesn’t support tail recursion, which is a pity, since <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall.aspx">the CLR supports it</a>. However, all is not lost! Some people had a very clever idea to work around this issue: a technique called “trampoline” (because it makes the function “bounce”) that allows to easily transform a recursive algorithm into an iterative algorithm. Samuel Jack has a good explanation of this concept <a href="http://blog.functionalfun.net/2008/04/bouncing-on-your-tail.html">on his blog</a>. In the rest of this article, we will see how to apply this technique to a simple algorithm, using the class from Samuel Jack’s article; then I’ll present another implementation of the trampoline, which I find more flexible.</p>
<h6><strong>A simple use case in C#</strong></h6>
<p>Let’s see how we can transform a simple recursive algorithm, like the computation of the factorial of a number, into an algorithm that uses tail recursion (incidentally, the factorial can be computed much more efficiently with a non-recursive algorithm, but let’s assume we don’t know that…). Here’s a basic implementation that results directly from the definition:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; pad-line-numbers: true; title: ; notranslate">
BigInteger Factorial(int n)
{
    if (n &lt; 2)
        return 1;
    return n * Factorial(n - 1);
}
</pre>
</pre>
</div>
<p>(Note the use of <code>BigInteger</code>: if we are to make the recursion deep enough to observe the effects of tail recursion, the result will be far beyond the capacity of an int or even a <code>long</code>…)</p>
<p>If we call this method with a large value (around 20000 on my machine), we get an error which was quite predictable: <code>StackOverflowException</code>. We made so many nested call to the <code>Factorial</code> method that we exhausted the capacity of the stack. So we’re going to modify this code so that it can benefit from tail recursion…</p>
<p>As mentioned above, the key requirement for tail recursion is that the method calls itself as the last instruction. It <em>seems</em> to be the case here… but it’s not: the last operation is actually the multiplication, which can’t be executed until we know the result of <code>Factorial(n-1)</code>. So we need to redesign this method so that it ends with a call to itself, with different arguments. To do that, we can add a new parameter named <code>product</code>, which will act as an accumulator:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
BigInteger Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return product;
    return Factorial(n - 1, n * product);
}
</pre>
</pre>
</div>
<p>For the first call, we’ll just have to pass 1 for the initial value of the accumulator.</p>
<p>We now have a method that meets the requirements for tail recursion: the recursive call to <code>Factorial</code> really is the last instruction. Now that we have put the algorithm in this form, the final transformation to enable tail recursion using Samuel Jack’s trampoline is trivial:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
Bounce&lt;int, BigInteger, BigInteger&gt; Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return Trampoline.ReturnResult&lt;int, BigInteger, BigInteger&gt;(product);
    return Trampoline.Recurse&lt;int, BigInteger, BigInteger&gt;(n - 1, n * product);
}
</pre>
</pre>
</div>
<ul>
<li>Instead of returning the final result directly, we call <code>Trampoline.ReturnResult</code> to tell the trampoline that we now have a result </li>
<li>The recursive call to <code>Factorial</code> is replaced with a call to <code>Trampoline.Recurse</code>, which tells the trampoline that the method needs to be called again with different parameters </li>
</ul>
<p>This method can’t be used directly: it returns a <code>Bounce</code> object, and we don&#8217;t really know what to do with this… To execute it, we use the <code>Trampoline.MakeTrampoline</code> method, which returns a new function on which tail recursion is applied. We can then use this new function directly:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
Func&lt;int, BigInteger, BigInteger&gt; fact = Trampoline.MakeTrampoline&lt;int, BigInteger, BigInteger&gt;(Factorial);
BigInteger result = fact(50000, 1);
</pre>
</pre>
</div>
<p>We can now compute the factorial of large numbers, with no risk of causing a stack overflow… Admittedly, it’s not very efficient: as mentioned before, there are better ways of computing a factorial, and furthermore, computations involving <code>BigInteger</code>s are much slower than with <code>int</code>s or <code>long</code>s.</p>
<h6><strong>Can we make it better?</strong></h6>
<p>Well, you can guess that I wouldn’t be asking the question unless the answer was yes… The trampoline implementation demonstrated above does its job well enough, but I think it could be made more flexible and easier to use:</p>
<ul>
<li>It only works if you have 2 parameters (of course we can adapt it for a different number of parameters, but then we need to create new methods with adequate signatures for each different arity) </li>
<li>The syntax is quite unwieldy: there are 3 type arguments, and we need to specify them every time because the compiler doesn’t have enough information to infer them automatically </li>
<li>Having to use <code>MakeTrampoline</code> just to create a new function that we can then call isn’t very convenient; it would be more intuitive to have an <code>Execute</code> method that returns the result directly </li>
</ul>
<p>And finally, I think the terminology isn’t very explicit… Names like <code>Trampoline</code> and <code>Bounce</code> sound like fun, but they don’t really reveal the intent.</p>
<p>So I tried to improve the system to make it more convenient. My solution is based on lambda expressions. There is only one type argument (the return type), and the parameters are passed trough a closure, so there is no need for multiple methods to handle different numbers of parameters. Here’s what the <code>Factorial</code> method looks like with my implementation:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
RecursionResult&lt;BigInteger&gt; Factorial(int n, BigInteger product)
{
    if (n &lt; 2)
        return TailRecursion.Return(product);
    return TailRecursion.Next(() =&gt; Factorial(n - 1, n * product));
}
</pre>
</pre>
</div>
<p>It can be used as follows:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
BigInteger result = TailRecursion.Execute(() =&gt; Factorial(50000, 1));
</pre>
</pre>
</div>
<p>It’s more flexible, more concise, and more readable…in my opinion at least<img style="border-style:none" class="wlEmoticon wlEmoticon-smile" alt="Sourire" src="http://blog.thomaslevesque.net/en/files/2011/09/wlemoticon-smile.png" />. The downside is that performance is slightly worse than before (it takes about 20% longer to compute the factorial of 50000), probably because of the delegate creation at each level of recursion.</p>
<p>Here’s the full code for the <code>TailRecursion</code> class:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
public static class TailRecursion
{
    public static T Execute&lt;T&gt;(Func&lt;RecursionResult&lt;T&gt;&gt; func)
    {
        do
        {
            var recursionResult = func();
            if (recursionResult.IsFinalResult)
                return recursionResult.Result;
            func = recursionResult.NextStep;
        } while (true);
    }

    public static RecursionResult&lt;T&gt; Return&lt;T&gt;(T result)
    {
        return new RecursionResult&lt;T&gt;(true, result, null);
    }

    public static RecursionResult&lt;T&gt; Next&lt;T&gt;(Func&lt;RecursionResult&lt;T&gt;&gt; nextStep)
    {
        return new RecursionResult&lt;T&gt;(false, default(T), nextStep);
    }

}

public class RecursionResult&lt;T&gt;
{
    private readonly bool _isFinalResult;
    private readonly T _result;
    private readonly Func&lt;RecursionResult&lt;T&gt;&gt; _nextStep;
    internal RecursionResult(bool isFinalResult, T result, Func&lt;RecursionResult&lt;T&gt;&gt; nextStep)
    {
        _isFinalResult = isFinalResult;
        _result = result;
        _nextStep = nextStep;
    }

    public bool IsFinalResult { get { return _isFinalResult; } }
    public T Result { get { return _result; } }
    public Func&lt;RecursionResult&lt;T&gt;&gt; NextStep { get { return _nextStep; } }
}
</pre>
</pre>
</div>
<h6><strong>Is there a better way to accomplish tail recursion in C#?</strong></h6>
<p>Sure! But it gets a little tricky, and it’s not pure C#. As I mentioned before, the CLR supports tail recursion, through the <code>tail</code> instruction. Ideally, the C# compiler would automatically generate this instruction for methods that are eligible to tail recursion, but unfortunately it’s not the case, and I don’t think this will ever be supported given the low demand for this feature.</p>
<p>Anyway, we can cheat a little by helping the compiler to do its job: the .NET Framework SDK provides tools named <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx">ildasm</a> (IL disassembler) and <a href="http://msdn.microsoft.com/en-us/library/496e4ekx.aspx">ilasm</a> (IL assembler), which can help to fill the gap between C# and the CLR… Let’s go back to the classical recursive implementation of <code>Factorial</code>, which doesn’t yet use tail recursion:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: csharp; title: ; notranslate">
static BigInteger Factorial(int n, BigInteger product)
{
	if (n &lt; 2)
		return product;
	return Factorial(n - 1, n * product);
}
</pre>
</pre>
</div>
<p>If we compile this code and disassemble it with ilasm, we get the following IL code:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: plain; title: ; wrap-lines: false; notranslate">
.method private hidebysig static valuetype [System.Numerics]System.Numerics.BigInteger
        Factorial(int32 n,
                  valuetype [System.Numerics]System.Numerics.BigInteger product) cil managed
{
  // Code size       41 (0x29)
  .maxstack  3
  .locals init (valuetype [System.Numerics]System.Numerics.BigInteger V_0,
           bool V_1)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldc.i4.2
  IL_0003:  clt
  IL_0005:  ldc.i4.0
  IL_0006:  ceq
  IL_0008:  stloc.1
  IL_0009:  ldloc.1
  IL_000a:  brtrue.s   IL_0010

  IL_000c:  ldarg.1
  IL_000d:  stloc.0
  IL_000e:  br.s       IL_0027

  IL_0010:  ldarg.0
  IL_0011:  ldc.i4.1
  IL_0012:  sub
  IL_0013:  ldarg.0
  IL_0014:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Implicit(int32)
  IL_0019:  ldarg.1
  IL_001a:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Multiply(valuetype [System.Numerics]System.Numerics.BigInteger,
                                                                                                                                      valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_001f:  call       valuetype [System.Numerics]System.Numerics.BigInteger Program::Factorial(int32,
                                                                                                valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_0024:  stloc.0
  IL_0025:  br.s       IL_0027

  IL_0027:  ldloc.0
  IL_0028:  ret
} // end of method Program::Factorial
</pre>
</pre>
</div>
<p>It’s a bit hard on the eye if you’re not used to read IL code, but we can see roughly what’s going on… The recursive call is at offset <code>IL_001f;</code> this is where we’re going to fiddle with the generated code to introduce tail recursion. If we look at the documentation for the <code>tail</code> instruction, we see that it must immediately precede a <code>call</code> instruction, and that the instruction following the <code>call</code> must be <code>ret</code> (return). Right now, we have several instructions following the recursive call, because the compiler introduced a local variable to store the return value. We just need to modify the code so that it doesn’t use this variable, and add the <code>tail</code> instruction in the right place:</p>
<div style="float:none;margin:0;padding:0" class="wlWriterEditableSmartContent">
<pre>
<pre class="brush: plain; title: ; wrap-lines: false; notranslate">
.method private hidebysig static valuetype [System.Numerics]System.Numerics.BigInteger
        Factorial(int32 n,
                  valuetype [System.Numerics]System.Numerics.BigInteger product) cil managed
{
  // Code size       41 (0x29)
  .maxstack  3
  .locals init (valuetype [System.Numerics]System.Numerics.BigInteger V_0,
           bool V_1)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldc.i4.2
  IL_0003:  clt
  IL_0005:  ldc.i4.0
  IL_0006:  ceq
  IL_0008:  stloc.1
  IL_0009:  ldloc.1
  IL_000a:  brtrue.s   IL_0010

  IL_000c:  ldarg.1
  IL_000d:  ret		// Return directly instead of storing the result in V_0
  IL_000e:  nop

  IL_0010:  ldarg.0
  IL_0011:  ldc.i4.1
  IL_0012:  sub
  IL_0013:  ldarg.0
  IL_0014:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Implicit(int32)
  IL_0019:  ldarg.1
  IL_001a:  call       valuetype [System.Numerics]System.Numerics.BigInteger [System.Numerics]System.Numerics.BigInteger::op_Multiply(valuetype [System.Numerics]System.Numerics.BigInteger,
                                                                                                                                      valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_001f:  tail.
  IL_0020:  call       valuetype [System.Numerics]System.Numerics.BigInteger Program::Factorial(int32,
                                                                                                valuetype [System.Numerics]System.Numerics.BigInteger)
  IL_0025:  ret		// Return directly instead of storing the result in V_0

} // end of method Program::Factorial
</pre>
</pre>
</div>
<p>If we reassemble this code with ilasm, we get a new executable, which runs without issues even for large values which made the old code crash<img style="border-style:none" class="wlEmoticon wlEmoticon-smile" alt="Sourire" src="http://blog.thomaslevesque.net/en/files/2011/09/wlemoticon-smile.png" />. Performance is also pretty good: about 3 times as fast than the version using the <code>Trampoline</code> class. If we compare the performance for smaller values (so that the old code doesn’t crash), we can see that it’s also 3 times as fast as the recursive version with no tail recursion.</p>
<p>Of course, this is just a proof of concept… it doesn’t seem very realistic to perform this transformation manually in a “real” project. However, it might be possible to create a tool that rewrites assemblies automatically after the compilation to introduce tail recursion.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f02%2ftail-recursion-in-c%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f09%2f02%2ftail-recursion-in-c%2f" border="0" alt="kick it on DotNetKicks.com" /></a> <a rev="vote-for" href="http://dotnetshoutout.com/Tail-recursion-in-C-Thomas-Levesques-NET-blog"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Ftomlev2.wordpress.com%2F2011%2F09%2F02%2Ftail-recursion-in-c%2F" style="border:0" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/09/02/tail-recursion-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[WPF] Display an animated GIF image</title>
		<link>http://www.thomaslevesque.com/2011/03/27/wpf-display-an-animated-gif-image/</link>
		<comments>http://www.thomaslevesque.com/2011/03/27/wpf-display-an-animated-gif-image/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 22:25:18 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[WPF]]></category>
		<category><![CDATA[animated]]></category>
		<category><![CDATA[gif]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=336</guid>
		<description><![CDATA[WPF is a great technology, but sometimes it seems to be missing some really basic features&#8230; A frequently mentioned example is the lack of support for animated GIF images. Actually, the GIF format itself is supported by the imaging API, but the Image control only shows the first frame of the animation. Many solutions to [...]]]></description>
			<content:encoded><![CDATA[<p>WPF is a great technology, but sometimes it seems to be missing some really basic features&#8230; A frequently mentioned example is the lack of support for animated GIF images. Actually, the GIF format itself is supported by the imaging API, but the <code>Image</code> control only shows the first frame of the animation.</p>
<p>Many solutions to this problem have been proposed on technical forums and blogs, usually variations of the following approaches:</p>
<ul>
<li>Use the <code>MediaElement</code> control: unfortunately this control only supports URI like <code>file://</code> or <code>http://</code>, not the <code>pack://</code> URI schema used for WPF resources; this means the image can&#8217;t be included in the resources, it has to be in a separate file. Furthermore, transparency for GIF images isn&#8217;t supported in <code>MediaElement</code>, which makes the final result quite ugly</li>
<li>Use the <code>PictureBox</code> control from Windows Forms, via a <code>WindowsFormsHost</code>: I personnally dislike using WinForms controls in WPF, it really looks like a hack&#8230;</li>
<li>Create a custom control that inherits <code>Image</code> and handles the animation. Some solutions take advantage of the <code>ImageAnimator</code> class from <code>System.Drawing</code> (GDI), others use a WPF animation to change the current frame. It&#8217;s a rather &#8220;clean&#8221; approach, but it forces you to use a specific control for GIF images. Also, the solution using <code>ImageAnimator</code> turns out not to be very smooth, the animation is quite jerky.</li>
</ul>
<p>As you might have guessed, I don&#8217;t find any of these solutions really satisfying&#8230; Furthermore, none of the implementations I&#8217;ve seen of the third approach handles the duration of each frame properly, they only assume that all frames last 100ms (which is almost always true, but <em>almost</em> isn&#8217;t good enough IMHO&#8230;). So I kept the best ideas from each approach I&#8217;ve seen, and I came up with my own solution. Here are the goals I set to attain:</p>
<ul>
<li>No dependency on Windows Forms or GDI</li>
<li>Display the animated image in a standard <code>Image</code> control</li>
<li>Use the same XAML code for normal and animated images</li>
<li>Support for transparency</li>
<li>Correct handling of frame duration</li>
</ul>
<p>To achieve this result, I started from a very simple, even obvious idea: to animate the image, all you have to do is apply an animation to the <code>Source</code> property of the <code>Image</code> control. WPF provides all the necessary tools to do that; in this case, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.animation.objectanimationusingkeyframes.aspx"><code>ObjectAnimationUsingKeyFrames</code></a> class fits the bill perfectly: it allows to specify at what exact time a given value should be assigned to the property, which makes it easy to take the frame duration into account.</p>
<p>The next problem is to extract the frames from the image: fortunately WPF supports this natively, and the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapdecoder.aspx"><code>BitmapDecoder</code></a> class provides a <code>Frames</code> property to do exactly that. So, no big difficulty so far&#8230;</p>
<p>Finally, last obstacle: extract the duration of each frame. It&#8217;s the part that took me the longest, because I needed to do some research&#8230; I first thought I would need to read the file manually and decode the binary data myself. But eventually the solution is quite simple, and takes advantage of the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapmetadata.aspx"><code>BitmapMetadata</code></a> class. The only difficulty has been to find the &#8220;path&#8221; of the metadata that contains the delay, but after a few minutes of trial and error, here it is: <code>/grctlext/Delay</code>.</p>
<p>The final solution is implemented as an attached property named <code>AnimatedSource</code>, that applies to the <code>Image</code> control, and can be used instead of <code>Source</code>:</p>
<pre class="brush: xml; title: ; notranslate">&lt;Image Stretch=&quot;None&quot; my:ImageBehavior.AnimatedSource=&quot;/Images/animation.gif&quot; /&gt;</pre>
<p>This property can also be assigned a normal (not animated) image, it will be displayed normally; therefore this property can be used without worrying about whether the image to display will be animated or not.</p>
<p>So in the end, all the goals have been achieved, and we even get some icing on the cake: this solution also works in the designer (at least in Visual Studio 2010), so the animation is immediately visible when you set the <code>AnimatedSource</code> property <img src='http://www.thomaslevesque.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Without further ado, here&#8217;s the complete code:</p>
<pre class="brush: csharp; collapse: true; light: false; title: ; toolbar: true; notranslate">
    public static class ImageBehavior
    {
        #region AnimatedSource

        [AttachedPropertyBrowsableForType(typeof(Image))]
        public static ImageSource GetAnimatedSource(Image obj)
        {
            return (ImageSource)obj.GetValue(AnimatedSourceProperty);
        }

        public static void SetAnimatedSource(Image obj, ImageSource value)
        {
            obj.SetValue(AnimatedSourceProperty, value);
        }

        public static readonly DependencyProperty AnimatedSourceProperty =
            DependencyProperty.RegisterAttached(
              &quot;AnimatedSource&quot;,
              typeof(ImageSource),
              typeof(ImageBehavior),
              new UIPropertyMetadata(
                null,
                AnimatedSourceChanged));

        private static void AnimatedSourceChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            Image imageControl = o as Image;
            if (imageControl == null)
                return;

            var oldValue = e.OldValue as ImageSource;
            var newValue = e.NewValue as ImageSource;
            if (oldValue != null)
            {
                imageControl.BeginAnimation(Image.SourceProperty, null);
            }
            if (newValue != null)
            {
                imageControl.DoWhenLoaded(InitAnimationOrImage);
            }
        }

        private static void InitAnimationOrImage(Image imageControl)
        {
            BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource;
            if (source != null)
            {
                var decoder = GetDecoder(source) as GifBitmapDecoder;
                if (decoder != null &amp;&amp; decoder.Frames.Count &gt; 1)
                {
                    var animation = new ObjectAnimationUsingKeyFrames();
                    var totalDuration = TimeSpan.Zero;
                    BitmapSource prevFrame = null;
                    FrameInfo prevInfo = null;
                    foreach (var rawFrame in decoder.Frames)
                    {
                        var info = GetFrameInfo(rawFrame);
                        var frame = MakeFrame(
                            source,
                            rawFrame, info,
                            prevFrame, prevInfo);

                        var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration);
                        animation.KeyFrames.Add(keyFrame);

                        totalDuration += info.Delay;
                        prevFrame = frame;
                        prevInfo = info;
                    }
                    animation.Duration = totalDuration;
                    animation.RepeatBehavior = RepeatBehavior.Forever;
                    if (animation.KeyFrames.Count &gt; 0)
                        imageControl.Source = (ImageSource)animation.KeyFrames[0].Value;
                    else
                        imageControl.Source = decoder.Frames[0];
                    imageControl.BeginAnimation(Image.SourceProperty, animation);
                    return;
                }
            }
            imageControl.Source = source;
            return;
        }

        private static BitmapDecoder GetDecoder(BitmapSource image)
        {
            BitmapDecoder decoder = null;
            var frame = image as BitmapFrame;
            if (frame != null)
                decoder = frame.Decoder;

            if (decoder == null)
            {
                var bmp = image as BitmapImage;
                if (bmp != null)
                {
                    if (bmp.StreamSource != null)
                    {
                        bmp.StreamSource.Position = 0;
                        decoder = BitmapDecoder.Create(bmp.StreamSource, bmp.CreateOptions, bmp.CacheOption);
                    }
                    else if (bmp.UriSource != null)
                    {
                        Uri uri = bmp.UriSource;
                        if (bmp.BaseUri != null &amp;&amp; !uri.IsAbsoluteUri)
                            uri = new Uri(bmp.BaseUri, uri);
                        decoder = BitmapDecoder.Create(uri, bmp.CreateOptions, bmp.CacheOption);
                    }
                }
            }

            return decoder;
        }

        private static BitmapSource MakeFrame(
            BitmapSource fullImage,
            BitmapSource rawFrame, FrameInfo frameInfo,
            BitmapSource previousFrame, FrameInfo previousFrameInfo)
        {
            DrawingVisual visual = new DrawingVisual();
            using (var context = visual.RenderOpen())
            {
                if (previousFrameInfo != null &amp;&amp; previousFrame != null &amp;&amp;
                    previousFrameInfo.DisposalMethod == FrameDisposalMethod.Combine)
                {
                    var fullRect = new Rect(0, 0, fullImage.PixelWidth, fullImage.PixelHeight);
                    context.DrawImage(previousFrame, fullRect);
                }

                context.DrawImage(rawFrame, frameInfo.Rect);
            }
            var bitmap = new RenderTargetBitmap(
                fullImage.PixelWidth, fullImage.PixelHeight,
                fullImage.DpiX, fullImage.DpiY,
                PixelFormats.Pbgra32);
            bitmap.Render(visual);
            return bitmap;
        }

        private class FrameInfo
        {
            public TimeSpan Delay { get; set; }
            public FrameDisposalMethod DisposalMethod { get; set; }
            public double Width { get; set; }
            public double Height { get; set; }
            public double Left { get; set; }
            public double Top { get; set; }

            public Rect Rect
            {
                get { return new Rect(Left, Top, Width, Height); }
            }
        }

        private enum FrameDisposalMethod
        {
            Replace = 0,
            Combine = 1,
            RestoreBackground = 2,
            RestorePrevious = 3
        }

        private static FrameInfo GetFrameInfo(BitmapFrame frame)
        {
            var frameInfo = new FrameInfo
            {
                Delay = TimeSpan.FromMilliseconds(100),
                DisposalMethod = FrameDisposalMethod.Replace,
                Width = frame.PixelWidth,
                Height = frame.PixelHeight,
                Left = 0,
                Top = 0
            };

            BitmapMetadata metadata;
            try
            {
                metadata = frame.Metadata as BitmapMetadata;
                if (metadata != null)
                {
                    const string delayQuery = &quot;/grctlext/Delay&quot;;
                    const string disposalQuery = &quot;/grctlext/Disposal&quot;;
                    const string widthQuery = &quot;/imgdesc/Width&quot;;
                    const string heightQuery = &quot;/imgdesc/Height&quot;;
                    const string leftQuery = &quot;/imgdesc/Left&quot;;
                    const string topQuery = &quot;/imgdesc/Top&quot;;

                    var delay = metadata.GetQueryOrNull&lt;ushort&gt;(delayQuery);
                    if (delay.HasValue)
                        frameInfo.Delay = TimeSpan.FromMilliseconds(10 * delay.Value);

                    var disposal = metadata.GetQueryOrNull&lt;byte&gt;(disposalQuery);
                    if (disposal.HasValue)
                        frameInfo.DisposalMethod = (FrameDisposalMethod) disposal.Value;

                    var width = metadata.GetQueryOrNull&lt;ushort&gt;(widthQuery);
                    if (width.HasValue)
                        frameInfo.Width = width.Value;

                    var height = metadata.GetQueryOrNull&lt;ushort&gt;(heightQuery);
                    if (height.HasValue)
                        frameInfo.Height = height.Value;

                    var left = metadata.GetQueryOrNull&lt;ushort&gt;(leftQuery);
                    if (left.HasValue)
                        frameInfo.Left = left.Value;

                    var top = metadata.GetQueryOrNull&lt;ushort&gt;(topQuery);
                    if (top.HasValue)
                        frameInfo.Top = top.Value;
                }
            }
            catch (NotSupportedException)
            {
            }

            return frameInfo;
        }

        private static T? GetQueryOrNull&lt;T&gt;(this BitmapMetadata metadata, string query)
            where T : struct
        {
            if (metadata.ContainsQuery(query))
            {
                object value = metadata.GetQuery(query);
                if (value != null)
                    return (T) value;
            }
            return null;
        }

        #endregion
    }
</pre>
<p>And here&#8217;s the <code>DoWhenLoaded</code> extension method used in the code above:</p>
<pre class="brush: csharp; title: ; notranslate">
public static void DoWhenLoaded&lt;T&gt;(this T element, Action&lt;T&gt; action)
    where T : FrameworkElement
{
    if (element.IsLoaded)
    {
        action(element);
    }
    else
    {
        RoutedEventHandler handler = null;
        handler = (sender, e) =&gt;
        {
            element.Loaded -= handler;
            action(element);
        };
        element.Loaded += handler;
    }
}
</pre>
<p>Enjoy <img src='http://www.thomaslevesque.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Update</strong>: the code that retrieves the frame duration only works on Windows Seven, and on Windows Vista if the <a href="http://support.microsoft.com/kb/971644/en-us">Platform Update</a> is installed (untested). The default duration (100ms) will be used instead on other versions of Windows. I will update the article if I find a solution that works on all operating systems (I know I could use <code>System.Drawing.Bitmap</code>, but I&#8217;d rather not depend on this&#8230;)</p>
<p><strong>Update 2</strong>: as pointed out by Klaus in the comments, the <code>ImageBehavior</code> class didn&#8217;t handle some important attributes of the frames: the diposal method (whether a frame should entirely replace the previous one, or be combined with it), and the frame position (Left/Top/Width/Height). I updated the code to handle these attributes properly. Thank you Klaus!</p>
<p><strong>Update 3</strong>: a commenter on the French version of my blog pointed out a problem when the AnimatedSource is an image in a resource dictionary; the UriSource wasn&#8217;t correctly interpreted when it was a relative URI. This problem is now fixed. Thank you, &#8220;anonymous&#8221;!</p>
<p><strong>Update 4</strong>: uploaded an <a href="http://www.thomaslevesque.com/files/2012/06/AnimatedGif.zip">example project</a> to demonstrate the code.</p>
<p><strong>Update 5</strong>: yet another bug fix, for when you use a <code>BitmapImage</code> initialized from a stream. Thanks to Mizutama for spotting this one!</p>
<p><strong>Update 6</strong>: rather than posting improvements to this blog post, I eventually created <a href="http://wpfanimatedgif.codeplex.com/">a project on CodePlex</a> where this class will be maintained. You can also install it using NuGet, the package id is <a href="https://nuget.org/packages/WpfAnimatedGif">WpfAnimatedGif</a>. Thanks to Diego Mijelshon for the suggestion!</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2ftomlev2.wordpress.com%2f2011%2f03%2f27%2fwpf-display-an-animated-gif-image%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/27/wpf-display-an-animated-gif-image/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/03/27/wpf-display-an-animated-gif-image/feed/</wfw:commentRss>
		<slash:comments>51</slash:comments>
		</item>
		<item>
		<title>[WPF] How to bind to data when the DataContext is not inherited</title>
		<link>http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/</link>
		<comments>http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 16:15:29 +0000</pubDate>
		<dc:creator>Thomas Levesque</dc:creator>
				<category><![CDATA[Tricks]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[datacontext]]></category>
		<category><![CDATA[freezable]]></category>

		<guid isPermaLink="false">http://tomlev2.wordpress.com/?p=327</guid>
		<description><![CDATA[The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don&#8217;t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part [...]]]></description>
			<content:encoded><![CDATA[<p>The <code>DataContext</code> property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don&#8217;t need to set it again on each element you want to bind. However, in some cases the <code>DataContext</code> is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements&#8230;</p>
<p>Let&#8217;s illustrate with a simple example: we want to display a list of products in a <code>DataGrid</code>. In the grid, we want to be able to show or hide the Price column, based on the value of a <code>ShowPrice</code> property exposed by the ViewModel. The obvious approach is to bind the <code>Visibility</code> of the column to the <code>ShowPrice</code> property:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding ShowPrice,
                        Converter={StaticResource visibilityConverter}}&quot;/&gt;
</pre>
<p>Unfortunately, changing the value of <code>ShowPrice</code> has no effect, and the column is always visible&#8230; why? If we look at the Output window in Visual Studio, we notice the following line:</p>
<blockquote><p>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is &#8216;DataGridTextColumn&#8217; (HashCode=32685253); target property is &#8216;Visibility&#8217; (type &#8216;Visibility&#8217;)</p></blockquote>
<p>The message is rather cryptic, but the meaning is actually quite simple: WPF doesn&#8217;t know which <code>FrameworkElement</code> to use to get the <code>DataContext</code>, because the column doesn&#8217;t belong to the visual or logical tree of the <code>DataGrid</code>.</p>
<p>We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the <code>DataGrid</code> itself:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding DataContext.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}&quot;/&gt;
</pre>
<p>Or we can add a <code>CheckBox</code> bound to <code>ShowPrice</code>, and try to bind the column visibility to the <code>IsChecked</code> property by specifying the element name:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding IsChecked,
                        Converter={StaticResource visibilityConverter},
                        ElementName=chkShowPrice}&quot;/&gt;
</pre>
<p>But none of these workarounds seems to work, we always get the same result&#8230;</p>
<p>At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern&#8230; But I&#8217;m not going to give up so soon, at least not while there are other options to consider <img src='http://www.thomaslevesque.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>The solution to our problem is actually quite simple, and takes advantage of the <a href="http://msdn.microsoft.com/en-us/library/system.windows.freezable.aspx"><code>Freezable</code></a> class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that <code>Freezable</code> objects can inherit the <code>DataContext</code> even when they&#8217;re not in the visual or logical tree. I don&#8217;t know the exact mechanism that enables this behavior, but we&#8217;re going to take advantage of it to make our binding work&#8230;</p>
<p>The idea is to create a class (I called it <code>BindingProxy</code> for reasons that should become obvious very soon) that inherits <code>Freezable</code> and declares a <code>Data</code> dependency property:</p>
<pre class="brush: csharp; title: ; notranslate">
    public class BindingProxy : Freezable
    {
        #region Overrides of Freezable

        protected override Freezable CreateInstanceCore()
        {
            return new BindingProxy();
        }

        #endregion

        public object Data
        {
            get { return (object)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register(&quot;Data&quot;, typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }
</pre>
<p>We can then declare an instance of this class in the resources of the <code>DataGrid</code>, and bind the <code>Data</code> property to the current <code>DataContext</code>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataGrid.Resources&gt;
    &lt;local:BindingProxy x:Key=&quot;proxy&quot; Data=&quot;{Binding}&quot; /&gt;
&lt;/DataGrid.Resources&gt;
</pre>
<p>The last step is to specify this <code>BindingProxy</code> object (easily accessible with <code>StaticResource</code>) as the <code>Source</code> for the binding:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;
                    Visibility=&quot;{Binding Data.ShowPrice,
                        Converter={StaticResource visibilityConverter},
                        Source={StaticResource proxy}}&quot;/&gt;
</pre>
<p>Note that the binding path has been prefixed with &#8220;Data&#8221;, since the path is now relative to the <code>BindingProxy</code> object.</p>
<p>The binding now works correctly, and the column is properly shown or hidden based on the <code>ShowPrice</code> property.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/"><img src="http://dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>
