<?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>Colin Eberhardt&#039;s Adventures in WPF</title>
	<atom:link href="http://www.scottlogic.co.uk/blog/colin/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.scottlogic.co.uk/blog/colin</link>
	<description>Colin Eberhardt&#039;s Adventures in WPF</description>
	<lastBuildDate>Thu, 04 Mar 2010 13:45:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Linq to Visual Tree</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 13:45:51 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[codeproject]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[t4]]></category>
		<category><![CDATA[templates]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=588</guid>
		<description><![CDATA[
This blog post demonstrates a Linq API which can be used to query the WPF / Silverlight Visual Tree. You can find a few other Linq to Visual Tree techniques on other blogs, but what makes this one unique is that it retains, and allows queries that make use of the tree like structure rather [...]]]></description>
			<content:encoded><![CDATA[
<p><em>This blog post demonstrates a Linq API which can be used to query the WPF / Silverlight Visual Tree. You can find a few other Linq to Visual Tree techniques on other blogs, but what makes this one unique is that it retains, and allows queries that make use of the tree like structure rather than simply flattening it.</em></p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/tree-300x92.jpg" alt="" title="tree" width="300" height="92" class="aligncenter size-medium wp-image-608" /></p>
<p>I have recently published an article on codeproject which describes a technique for <a href="http://www.codeproject.com/KB/linq/LinqToTree.aspx">generating Linq API for querying tree-like structures</a>. This blog post makes use of a generated API for WPF / Silverlight. If you are interested in the more generic approach, and how this API was constructed, (and how it is influenced by XPath) head on over to codeproject &#8230;</p>
<p>What I will provide here is a brief overview of the Linq to Visual Tree API. The full sourcecode for this API is at the end of this article.</p>
<p>The Linq to Visual Tree API defines a number of extension methods on <code>DependencyObject</code> that provide mechanisms for navigating to other <code>DependencyObject</code> instances. I will provide a few examples that query the following simple markup:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;GridOne&quot;</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;White&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxOne&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;One&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;StackPanelOne&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxTwo&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Two&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;GridTwo&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;RowDefinition</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;Auto&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid.RowDefinitions<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxThree&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Three&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;0&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;StackPanelTwo&quot;</span> <span style="color: #000066;">Grid.Row</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;TextBox</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;TextBoxFour&quot;</span> <span style="color: #000066;">Text</span>=<span style="color: #ff0000;">&quot;Four&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>                    
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>We&#8217;ll start with a simple  example. Include the Linq to Visual Tree namespace, then use the Descendants method to obtain all the descendants (i.e. children and children&#8217;s children, etc &#8230;) of an object within the<br />
visual tree.</p>
<p><strong>Descendants</strong></p>
<p><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/descendants.png" alt="" title="descendants" width="200" height="117" class="aligncenter size-full wp-image-598" /></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">LinqToVisualTree</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// all items within the visual tree</span>
IEnumerable<span style="color: #008000;">&lt;</span>DependencyObject<span style="color: #008000;">&gt;</span> allDescendants <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
gives ...
0 {Grid} 	[GridOne]
1 {TextBox} 	[TextBoxOne]
2 {StackPanel} 	[StackPanelOne]
3 {TextBox} 	[TextBoxTwo]
4 {Grid} 	[GridTwo]
5 {TextBox} 	[TextBoxThree]
6 {StackPanel} 	[StackPanelTwo]
7 {TextBox} 	[TextBoxFour]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// all items within the visual tree of 'GridTwo'</span>
var descendantsOfGridTwo <span style="color: #008000;">=</span> GridTwo.<span style="color: #0000FF;">Descendants</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
gives ...
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
2 {TextBox} 	[TextBoxFour]
*/</span></pre></div></div>

<p>Each of the extension methods also has a corresponding method with a generic type parameter that filters the collection to find elements of a specific type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// all items within the visual tree of 'GridTwo' that are textboxes</span>
var textBoxDescendantsOfGridTwo <span style="color: #008000;">=</span> GridTwo.<span style="color: #0000FF;">Descendants</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                                         .<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i <span style="color: #008000;">is</span> TextBox<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// a shorthand using the generic version of Descendants</span>
var textBoxDescendantsOfGridTwo2 <span style="color: #008000;">=</span> GridTwo.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {TextBox} 	[TextBoxFour]
*/</span></pre></div></div>

<p><strong>Elements</strong></p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/child.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/child.png" alt="" title="child" width="200" height="117" class="aligncenter size-full wp-image-597" /></a></p>
<p>The elements extension method obtains all the direct children of an item in the visual tree:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// find all direct children of this user control </span>
var userControlChildren <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Elements</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {Grid} 	[GridOne]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// find all direct children of the grid 'GridTwo'</span>
var gridChildren <span style="color: #008000;">=</span> GridTwo.<span style="color: #0000FF;">Elements</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxThree]
1 {StackPanel} 	[StackPanelTwo]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// find all direct children of the grid 'GridTwo' that are StackPanels</span>
var gridChildren2 <span style="color: #008000;">=</span> GridTwo.<span style="color: #0000FF;">Elements</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
*/</span></pre></div></div>

<p>There are also, <code>ElementsBeforeSelf</code> and <code>ElementsAfterSelf</code> methods that return the elements before and after the item which the method is being invoked upon.</p>
<p><strong>Ancestors</strong></p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/ancestors.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/ancestors.png" alt="" title="ancestors" width="200" height="117" class="aligncenter size-full wp-image-599" /></a></p>
<p>The ancestors methods traverse the tree towards the root, finding all the ancestors:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// the ancestors for 'TextBoxFour'</span>
var ancestors <span style="color: #008000;">=</span> TextBoxFour.<span style="color: #0000FF;">Ancestors</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
1 {Grid} 	[GridTwo]
2 {StackPanel} 	[StackPanelOne]
3 {Grid} 	[GridOne]
4 {MainPage} 	[]
*/</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// the ancestors for 'TextBoxFour' that are StackPanels</span>
var stackPanelAncestors <span style="color: #008000;">=</span> TextBoxFour.<span style="color: #0000FF;">Ancestors</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
1 {StackPanel} 	[StackPanelOne]
*/</span></pre></div></div>

<p><strong>Putting it all together</strong></p>
<p>The Linq to Tree API not only defines extension methods on <code>DependencyObject</code>, but also the same extension methods on <code>IEnumerable&lt;DependencyObject&gt;</code>. Unless you have previous experience of Linq to XML, I would strongly suggest reading my <a href="http://www.codeproject.com/KB/linq/LinqToTree.aspx">codeproject article</a> to understand how this works! </p>
<p>This allows you to form much more complex queries. For example, you can find all <code>TextBox</code>s that have a <code>Grid</code> as a direct parent:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var itemsFluent <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                      .<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> i.<span style="color: #0000FF;">Ancestors</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FirstOrDefault</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">is</span> Grid<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var itemsQuery <span style="color: #008000;">=</span> from v <span style="color: #0600FF;">in</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>TextBox<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                 where v.<span style="color: #0000FF;">Ancestors</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FirstOrDefault</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">is</span> Grid
                 select v<span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {TextBox} 	[TextBoxOne]
1 {TextBox} 	[TextBoxThree]
*/</span></pre></div></div>

<p>Here, you can also see we are mixing the fluent and query syntax for Linq. Both give the same result.</p>
<p>The next example finds all <code>StackPanel</code>s that are within another <code>StackPanel</code>s visual tree:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var items2Fluent <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                              .<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var items2Query <span style="color: #008000;">=</span> from i <span style="color: #0600FF;">in</span>
                      <span style="color: #000000;">&#40;</span>from v <span style="color: #0600FF;">in</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                       select v<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Descendants</span><span style="color: #008000;">&lt;</span>StackPanel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                  select i<span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">/*
0 {StackPanel} 	[StackPanelTwo]
*/</span></pre></div></div>

<p>Finally, this one-liner, outputs the entire visual tree in ASCII! It makes use of the <code>DescendantsAndSelf</code>, <code>Ancestors</code> and <code>ElementsBeforeSelf</code> methods, plus the funky Linq <code>Aggregate</code> method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span> tree <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">DescendantsAndSelf</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Aggregate</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span>,
    <span style="color: #000000;">&#40;</span>bc, n<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> bc <span style="color: #008000;">+</span> n.<span style="color: #0000FF;">Ancestors</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Aggregate</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span>, <span style="color: #000000;">&#40;</span>ac, m<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#40;</span>m.<span style="color: #0000FF;">ElementsAfterSelf</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;| &quot;</span> <span style="color: #008000;">:</span> <span style="color: #666666;">&quot;  &quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> ac,
    ac <span style="color: #008000;">=&gt;</span> ac <span style="color: #008000;">+</span> <span style="color: #000000;">&#40;</span>n.<span style="color: #0000FF;">ElementsAfterSelf</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;+-&quot;</span> <span style="color: #008000;">:</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\\</span>-&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> n.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<pre>
\-MainPage
  \-Grid
    +-TextBox
    | \-Grid
    |   +-Border
    |   | \-Grid
    |   |   +-Border
    |   |   \-Border
    |   |     \-ScrollViewer
    |   |       \-Border
    |   |         \-Grid
    |   |           +-ScrollContentPresenter
    |   |           | \-TextBoxView
    |   |           +-Rectangle
    |   |           +-ScrollBar
    |   |           \-ScrollBar
    |   +-Border
    |   +-Border
    |   \-Border
    |     \-Grid
    |       +-Path
    |       \-Path
    \-StackPanel
      +-TextBox
      | \-Grid
      |   +-Border
      |   | \-Grid
      |   |   +-Border
      |   |   \-Border
      |   |     \-ScrollViewer
      |   |       \-Border
      |   |         \-Grid
      |   |           +-ScrollContentPresenter
      |   |           | \-TextBoxView
      |   |           +-Rectangle
      |   |           +-ScrollBar
      |   |           \-ScrollBar
      |   +-Border
      |   +-Border
      |   \-Border
      |     \-Grid
      |       +-Path
      |       \-Path
      \-Grid
        +-TextBox
        | \-Grid
        |   +-Border
        |   | \-Grid
        |   |   +-Border
        |   |   \-Border
        |   |     \-ScrollViewer
        |   |       \-Border
        |   |         \-Grid
        |   |           +-ScrollContentPresenter
        |   |           | \-TextBoxView
        |   |           +-Rectangle
        |   |           +-ScrollBar
        |   |           \-ScrollBar
        |   +-Border
        |   +-Border
        |   \-Border
        |     \-Grid
        |       +-Path
        |       \-Path
        \-StackPanel
          \-TextBox
            \-Grid
              +-Border
              | \-Grid
              |   +-Border
              |   \-Border
              |     \-ScrollViewer
              |       \-Border
              |         \-Grid
              |           +-ScrollContentPresenter
              |           | \-TextBoxView
              |           +-Rectangle
              |           +-ScrollBar
              |           \-ScrollBar
              +-Border
              +-Border
              \-Border
                \-Grid
                  +-Path
                  \-Path
</pre>
<p>Note: this was invoked after the <code>LayoutUpdated</code> event so that we not only see the elements from our XAML, but also the elements created from their templates, giving us our full run-time visual tree.</p>
<p>You can download a simple Silverlight application that demonstrated all the examples given above:<br />
<a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/03/LinqToTree.zip'>LinqToTree.zip</a>. </p>
<p>Or, if you just want the Linq to VisualTree code, you can copy-n-paste from the windows below which has the entire API, which includes the methods illustrated above,, plus their <code>IEnumerable</code> equivalents, and a few others I have not illustrated.</p>
<pre style="height: 200px; overflow: scroll; border: 1px solid #aaa;">
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace LinqToVisualTree
{
    /// <summary>
    /// Adapts a DependencyObject to provide methods required for generate
    /// a Linq To Tree API
    /// </summary>
    public class VisualTreeAdapter : ILinqTree<DependencyObject>
    {
        private DependencyObject _item;

        public VisualTreeAdapter(DependencyObject item)
        {
            _item = item;
        }

        public IEnumerable<DependencyObject> Children()
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(_item);
            for (int i = 0; i < childrenCount; i++)
            {
                yield return VisualTreeHelper.GetChild(_item, i);
            }
        }

        public DependencyObject Parent
        {
            get
            {
                return VisualTreeHelper.GetParent(_item);
            }
        }
    }
}

namespace LinqToVisualTree
{
    /// <summary>
    /// Defines an interface that must be implemented to generate the LinqToTree methods
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface ILinqTree<T>
    {
        IEnumerable<T> Children();

        T Parent { get; }
    }

    public static class TreeExtensions
    {
        /// <summary>
        /// Returns a collection of descendant elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Descendants(this DependencyObject item)
        {
            ILinqTree<DependencyObject> adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;

                foreach (var grandChild in child.Descendants())
                {
                    yield return grandChild;
                }
            }
        }

        /// <summary>
        /// Returns a collection containing this element and all descendant elements.
        /// </summary>
        public static IEnumerable<DependencyObject> DescendantsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Descendants())
            {
                yield return child;
            }
        }

        /// <summary>
        /// Returns a collection of ancestor elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Ancestors(this DependencyObject item)
        {
            ILinqTree<DependencyObject> adapter = new VisualTreeAdapter(item);

            var parent = adapter.Parent;
            while (parent != null)
            {
                yield return parent;
                adapter = new VisualTreeAdapter(parent);
                parent = adapter.Parent;
            }
        }

        /// <summary>
        /// Returns a collection containing this element and all ancestor elements.
        /// </summary>
        public static IEnumerable<DependencyObject> AncestorsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var ancestor in item.Ancestors())
            {
                yield return ancestor;
            }
        }

        /// <summary>
        /// Returns a collection of child elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Elements(this DependencyObject item)
        {
            ILinqTree<DependencyObject> adapter = new VisualTreeAdapter(item);
            foreach (var child in adapter.Children())
            {
                yield return child;
            }
        }

        /// <summary>
        /// Returns a collection of the sibling elements before this node, in document order.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsBeforeSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (child.Equals(item))
                    break;
                yield return child;
            }
        }

        /// <summary>
        /// Returns a collection of the after elements after this node, in document order.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAfterSelf(this DependencyObject item)
        {
            if (item.Ancestors().FirstOrDefault() == null)
                yield break;
            bool afterSelf = false;
            foreach (var child in item.Ancestors().First().Elements())
            {
                if (afterSelf)
                    yield return child;

                if (child.Equals(item))
                    afterSelf = true;
            }
        }

        /// <summary>
        /// Returns a collection containing this element and all child elements.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAndSelf(this DependencyObject item)
        {
            yield return item;

            foreach (var child in item.Elements())
            {
                yield return child;
            }
        }

        /// <summary>
        /// Returns a collection of descendant elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Descendants<T>(this DependencyObject item)
        {
            return item.Descendants().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection of the sibling elements before this node, in document order
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsBeforeSelf<T>(this DependencyObject item)
        {
            return item.ElementsBeforeSelf().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection of the after elements after this node, in document order
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAfterSelf<T>(this DependencyObject item)
        {
            return item.ElementsAfterSelf().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection containing this element and all descendant elements
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> DescendantsAndSelf<T>(this DependencyObject item)
        {
            return item.DescendantsAndSelf().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection of ancestor elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Ancestors<T>(this DependencyObject item)
        {
            return item.Ancestors().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection containing this element and all ancestor elements
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> AncestorsAndSelf<T>(this DependencyObject item)
        {
            return item.AncestorsAndSelf().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection of child elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Elements<T>(this DependencyObject item)
        {
            return item.Elements().Where(i => i is T).Cast<DependencyObject>();
        }

        /// <summary>
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAndSelf<T>(this DependencyObject item)
        {
            return item.ElementsAndSelf().Where(i => i is T).Cast<DependencyObject>();
        }

    }

    public static class EnumerableTreeExtensions
    {
        /// <summary>
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable.
        /// </summary>
        private static IEnumerable<DependencyObject> DrillDown(this IEnumerable<DependencyObject> items,
            Func<DependencyObject, IEnumerable<DependencyObject>> function)
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    yield return itemChild;
                }
            }
        }

        /// <summary>
        /// Applies the given function to each of the items in the supplied
        /// IEnumerable, which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> DrillDown<T>(this IEnumerable<DependencyObject> items,
            Func<DependencyObject, IEnumerable<DependencyObject>> function)
            where T : DependencyObject
        {
            foreach (var item in items)
            {
                foreach (var itemChild in function(item))
                {
                    if (itemChild is T)
                    {
                        yield return (T)itemChild;
                    }
                }
            }
        }

        /// <summary>
        /// Returns a collection of descendant elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Descendants(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.Descendants());
        }

        /// <summary>
        /// Returns a collection containing this element and all descendant elements.
        /// </summary>
        public static IEnumerable<DependencyObject> DescendantsAndSelf(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.DescendantsAndSelf());
        }

        /// <summary>
        /// Returns a collection of ancestor elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Ancestors(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.Ancestors());
        }

        /// <summary>
        /// Returns a collection containing this element and all ancestor elements.
        /// </summary>
        public static IEnumerable<DependencyObject> AncestorsAndSelf(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.AncestorsAndSelf());
        }

        /// <summary>
        /// Returns a collection of child elements.
        /// </summary>
        public static IEnumerable<DependencyObject> Elements(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.Elements());
        }

        /// <summary>
        /// Returns a collection containing this element and all child elements.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAndSelf(this IEnumerable<DependencyObject> items)
        {
            return items.DrillDown(i => i.ElementsAndSelf());
        }

        /// <summary>
        /// Returns a collection of descendant elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Descendants<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.Descendants());
        }

        /// <summary>
        /// Returns a collection containing this element and all descendant elements.
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> DescendantsAndSelf<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.DescendantsAndSelf());
        }

        /// <summary>
        /// Returns a collection of ancestor elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Ancestors<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.Ancestors());
        }

        /// <summary>
        /// Returns a collection containing this element and all ancestor elements.
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> AncestorsAndSelf<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.AncestorsAndSelf());
        }

        /// <summary>
        /// Returns a collection of child elements which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> Elements<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.Elements());
        }

        /// <summary>
        /// Returns a collection containing this element and all child elements.
        /// which match the given type.
        /// </summary>
        public static IEnumerable<DependencyObject> ElementsAndSelf<T>(this IEnumerable<DependencyObject> items)
            where T : DependencyObject
        {
            return items.DrillDown<T>(i => i.ElementsAndSelf());
        }
    }
}
</pre>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Forcing Event Consumer Cleanup without Weak Events</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/02/forcing-event-consumer-cleanup-without-weak-events/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/02/forcing-event-consumer-cleanup-without-weak-events/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 11:10:44 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[memory leaks]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=568</guid>
		<description><![CDATA[
This blog post describes a simple technique for ensuring that consumers of events unsubscribe their event handlers without the need for weak events.
I think the concept of managed memory, where the cleanup of unused objects from the heap is performed by a garbage collector, is a fantastic idea. It means that developers working with Java [...]]]></description>
			<content:encoded><![CDATA[
<p><em>This blog post describes a simple technique for ensuring that consumers of events unsubscribe their event handlers without the need for weak events.</em></p>
<p>I think the concept of managed memory, where the cleanup of unused objects from the heap is performed by a garbage collector, is a fantastic idea. It means that developers working with Java or C# (or other CLR languages) can often forget all about memory allocation, concentrating on more interesting tasks. However, whereas in the Java language the concept of memory leaks has almost completely vanished, they unfortunately rear their ugly head all to often when developing applications for the Microsoft Common Language Runtime (CLR). This is almost entirely down to one thing, events.</p>
<p>The problem with events is that they form a strong reference (i.e. a link between two object instances that prohibits garbage collection) in a manner that is not immediately obvious due to the syntax that event subscription uses. When subscribing to an event, the following syntax is used:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// subscribe to an event</span>
textBox.<span style="color: #0000FF;">TextChanged</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>TextBox_TextChanged<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// or</span>
textBox.<span style="color: #0000FF;">TextChanged</span> <span style="color: #008000;">+=</span> TextBox_TextChanged<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// remove the subscription</span>
textBox.<span style="color: #0000FF;">TextChanged</span> <span style="color: #008000;">-=</span> <span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>TextBox_TextChanged<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">// or</span>
textBox.<span style="color: #0000FF;">TextChanged</span> <span style="color: #008000;">-=</span> TextBox_TextChanged<span style="color: #008000;">;</span></pre></div></div>

<p>Note the second examples use the shortened syntax where the delegate instance, <a href="http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx">EventHandler</a>, is not explicitly constructed but added by the compiler, there is <a href="http://stackoverflow.com/questions/550703/c-difference-between-anevent-and-new-eventhandleranevent/550711">no difference semantically</a>.</p>
<p>By subscribing to an event the following relationships are constructed, with the direction of reference as indicated:</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/02/NormalEvent.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/02/NormalEvent.png" alt="" title="NormalEvent" width="294" height="54" class="aligncenter size-full wp-image-581" /></a></p>
<p>As you can see from the above, adding an handler to an event creates a strong reference from <strong>source</strong> to <strong>listener</strong>. This does not cause significant problems if the listener has a shorter or the same lifecycle that the source, as is the case where you add event handlers for controls in a Windows Form for example. However, if the source has a longer lifecycle than the listener, and the listener fails to remove its event subscription, a memory leak will occur.</p>
<p>In practice this kind of problem often occurs in modular applications where there exists some sort of Shell or Environment that raises events or acts as a <a href="http://en.wikipedia.org/wiki/Mediator_pattern">mediator</a>. Within this hosting environment their exists numerous loosely coupled modules which by necessity have a shorter lifecycle than their container. If a module subscribes to events from the Shell but fails to unsubscribe at the end of its life a memory leak occurs. In complex systems this happens surprisingly often!</p>
<p>A common solution to this problem is to use Weak Events. These are events where either the reference between source and listener is <a href="http://en.wikipedia.org/wiki/Weak_reference">weak</a>, meaning that listener can be garbage collected if it is only referenced via this event handler.  An early implementation of this pattern was developed for WPF and is provided by <a href="http://blogs.msdn.com/greg_schechter/archive/2004/05/27/143605.aspx">Greg Schechter on his blog</a>. There is also an excellent <a href="http://www.codeproject.com/KB/cs/WeakEvents.aspx">codeproject article by Daniel Grunwald</a> which details many different approaches to creating weak event listeners and sources.</p>
<p>However, whilst liberally sprinkling weak events about your code will solve potential memory leaks, it should not be used as a replacement for proper event subscription clean-up. What if a module&#8217;s event handler performs non-trivial logic? Do you really want this to occur after the module is supposed to have been destroyed? So, how do you ensure that events are being unsubscribed? This can be done by code-review, or by making use of heap profiling tools such as <a href="http://www.jetbrains.com/profiler/">dotTrace</a>. With these tools you can run your application, create and destroy modules, garbage collect then inspect your heap to see that the modules and their related objects have been removed. If not, you can trace the object references to find the offending event handler. However, this is a time consuming process.</p>
<p>An alternative is to make use of the fact that events are simply delegates with a highly restrictive interface applied. However, within the class where the event is defined you can treat it as an delegate, allowing you to inspect its invocation list to find all the event handlers. Therefore, if you have a long-lived service component that raises events which are handled by shorter lived modules, you can check the event invocation list after all the modules have been destroyed at application shutdown to ensure that all modules have correctly unsubscribed. This can be achieved as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// An event which indicates that some stock price has changed</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">event</span> EventHandler<span style="color: #008000;">&lt;</span>StockPriceUpdateEventArgs<span style="color: #008000;">&gt;</span> StockPriceUpdate<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Dispose<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// check that when this service is destroyed, that there are no event</span>
    <span style="color: #008080; font-style: italic;">// subscriptions</span>
    CheckEventHasNoSubscribers<span style="color: #000000;">&#40;</span>StockPriceUpdate<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Detects whether an event has any subscribers</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #000000;">&#91;</span>Conditional<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;DEBUG&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> CheckEventHasNoSubscribers<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">Delegate</span> eventDelegate<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>eventDelegate <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// if the event has any subscribers, create an informative error message.</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>eventDelegate.<span style="color: #0000FF;">GetInvocationList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">!=</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> subscriberCount <span style="color: #008000;">=</span> eventDelegate.<span style="color: #0000FF;">GetInvocationList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// determine the consumers of this event</span>
            StringBuilder subscribers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">Delegate</span> del <span style="color: #0600FF;">in</span> eventDelegate.<span style="color: #0000FF;">GetInvocationList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                subscribers.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>subscribers.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">!=</span> <span style="color: #FF0000;">0</span> <span style="color: #008000;">?</span> <span style="color: #666666;">&quot;, &quot;</span> <span style="color: #008000;">:</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> del.<span style="color: #0000FF;">Target</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// name and shame them!</span>
            Debug.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Event: {0} still has {1} subscribers, with the following targets [{2}]&quot;</span>,
                eventDelegate.<span style="color: #0000FF;">Method</span>.<span style="color: #0000FF;">Name</span>, subscriberCount, subscribers.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Here we have an event which our service raises, on disposal we check that the event has no subscribers. If any modules have failed to cleanup properly we see the following message:</p>
<pre>
Event: PriceService_StockPriceUpdate still has 2 subscribers, with the following targets:
[MemoryLeakExamples.StockPriceViewer, Text: StockPriceViewer,
MemoryLeakExamples.StockPriceViewer, Text: StockPriceViewer]
</pre>
<p>This message tells us how many classes still have referenced event handlers, and their type. This should make it very easy to pinpoint the memory leak.</p>
<p>The sourcecode for this blog post includes a very simple WinForms application where a Stock Price service raises events that are handled by simple UI modules that can be created and destroyed by the user. Run it in DEBUG mode to see the memory leaks! Look in StockPriceViewer to see how to fix the problem.</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/02/leak.png"><img src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/02/leak-300x178.png" alt="" title="leak" width="300" height="178" class="aligncenter size-medium wp-image-583" /></a></p>
<p>Download the sourcecode: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/02/MemoryLeakExample.zip'>MemoryLeakExample.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/02/forcing-event-consumer-cleanup-without-weak-events/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Presentation on Agile Development</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/01/presentation-on-agile-development/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/01/presentation-on-agile-development/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 12:57:16 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=559</guid>
		<description><![CDATA[
Last week I gave a presentation on Agile Development for an event hosted by Codeworks and Sunderland Software City. This blog post is a brief review of my presentation and the event itself.

The event was titled, &#8220;An Introduction to Agile Methodology &#8211; Get a Head Start in 2010&#8243;, which was suitably broad for my liking! [...]]]></description>
			<content:encoded><![CDATA[
<p><em>Last week I gave a presentation on Agile Development for an event hosted by <a href="http://www.codeworks.net/">Codeworks</a> and <a href="http://www.sunderlandsoftwarecity.com/">Sunderland Software City</a>. This blog post is a brief review of my presentation and the event itself.</em></p>
<p><img class="aligncenter size-full wp-image-572" title="agile_talk" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/agile_talk.jpg" alt="" width="350" height="234" /></p>
<p>The event was titled, &#8220;An Introduction to Agile Methodology &#8211; Get a Head Start in 2010&#8243;, which was suitably broad for my liking! I have experienced heavyweight, formal methodology in the shape of the <a href="http://en.wikipedia.org/wiki/Rational_Unified_Process">Rational Unified Process</a>; At Scott Logic, we prefer the Agile way, keeping it light. However, we have a wide range of customers, each with their own preferred development process, so we must exercise further agility by adapting to their way of working. For this reason, I did not want to highlight a single Agile methodology, rather, the common themes held by all Agile methods. My talk was titled &#8220;With Agile Development &#8211; Communication is the Key&#8221;, which pretty much sums up my own opinion on what makes the Agile approach so successful.</p>
<p>To summarise my presentation in a single paragraph; requirements and estimation are probably two of the greatest challenges to any software project. Requirements are hard to capture and as a result most people would agree that it is better to allow them to evolve. Estimation is something that most software engineers would rather avoid! the most common approach is to turn to the most senior member of the team and go with what they suggest. Agile, iterative methodologies promote communication between team members, and between the team and the stakeholders. In this way, the stakeholders are engaged on a regular basis, hastening the evolution of requirements. As the team learns from their previous iterations, their estimations improve. Furthermore, estimation becomes a team exercise, with the team communicating / discussing the tasks. This provides a far superior estimate of effort and team buy-in. In short, the iterative cycles of <em>any </em>iterative methodology promote communication, and it is this which makes them successful. Or, even-shorter, my last slide pretty much captures what I am trying to say:</p>
<p><img class="aligncenter size-medium wp-image-562" style="border: 1px solid #aaa;" title="conclusions" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/conclusions-300x226.png" alt="" width="300" height="226" /></p>
<p>Following the talks, which included mine, an introduction to Agile Development from Andrew Rumfitt (Perfect Image), and a discussion of the application of Agile techniques to non software projects by Colin Ashurst (Durham Business School), everyone played the &#8220;Ball Point Game&#8221;. This is a simple training exercise where small teams are formed, the goal being to pass as many balls between the team members as possible in two minutes. However, the added twist is that before each 2 minutes &#8220;iteration&#8221; the team has to estimate how many balls they will pass. Interestingly, most teams got better with each iteration, passing more balls, but more importantly as they found their natural velocity, their estimates improved.</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/ball_game.jpg"><img class="aligncenter size-full wp-image-573" title="ball_game" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/ball_game.jpg" alt="" width="350" height="233" /></a></p>
<p>The Q&amp;A session followed the game, with myself and Andrew fielding questions. This was certainly an interesting challenge! A few of my favourite questions were as follows:</p>
<p><strong>&#8220;If you allow requirements to change, what about the project budget? I cannot see how this would be workable?&#8221;</strong></p>
<p>Great question! and not an easy one to answer. The problem with projects where the price and requirements are determined up-front is that one of the two parties involved is probably going to be unhappy with the end result. If the requirements are set-in-stone, forming an immovable contract, their natural evolution is stifled. The customer may get exactly what the described at the start of the project, however, it is probably not what they want now after they have used the software and had a chance to think more deeply about the problem. With an Agile, iterative approach, the requirements change and improve as do the estimates. And, as a result, the original budget (or scope) may prove to be unworkable. However, this extra information empowers the customer, allowing them to make a decision about the financial impact of this change in their own requirements. Although, this will only work if their is good communication and trust. To quote the <a href="http://agilemanifesto.org/">Agile Manifesto</a>, <em>&#8220;Customer collaboration over contract negotiation&#8221;</em>.</p>
<p><img class="aligncenter size-full wp-image-571" title="qa" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/qa.jpg" alt="" width="350" height="233" /></p>
<p><strong>&#8220;I am sure that you getter better at estimating after a few projects, however, if you start a project with an Agile approach, and a few days into an iteration you find that your estimates are totally wrong, do you stop the iteration and start out again?&#8221;</strong></p>
<p>This question certainly reveals the fear that a lot of software engineers have of estimation! One important point to note is that the person asking the question indicates that they think you need to run a number of agile projects before you get good at estimating. I think this is a flawed assumption. Every software project is different, and there is a certain amount of learning involved in every project. You learn about the problem being solved and about the capabilities, or velocity, of your team. The &#8220;Ball Point Game&#8221; we played earlier illustrates this point quite nicely, every team, after a few iterations, started to give very accurate estimate. With short iterations the feedback is very rapid, as a result you do not need a lot of experience from previous projects to start giving accurate estimates.</p>
<p>Regarding the question itself, should you abort the sprint? I don&#8217;t think so. If everyone (developers, and stakeholders) has bought into the agile approach, what some might see as a failure should be seen as a valuable lesson. Continue with the sprint, maximise the learning. Do not abort the sprint and try to sweep it under the carpet! This does not promote openness. Besides, can you be sure that your revised estimate after just a few days is better? Have you learnt enough?</p>
<p><strong>&#8220;Do you need the right tools and the right people for Agile development?&#8221;</strong></p>
<p>Personally I would always value people over tools, regardless of the process or project. Agile development should be quite lightweight. You can probably get away with just a simple spreadsheet, or a few post-it notes!</p>
<p>One problem with an approach that favours communication is that software engineers are not always the most communicative. A recent<a href="http://www.codeproject.com/script/Surveys/Results.aspx?srvid=954&amp;msg=3187409"> codeproject survey</a> confirmed the commonly held belief that most software engineers are introverts (the <a href="http://en.wikipedia.org/wiki/INTJ">INTJ</a> personality type was the most common). Whilst it is certainly not necessary that all team members are extroverts, I think it does help if individuals occupying certain key roles, where they facilitate communicati0n (such as the ScrumMaster in the SRUM methodology), are comfortable communicators.</p>
<p>A few questions followed about how you find the right kind of people. At Scott logic, our interviews concentrate far more on people&#8217;s problem solving abilities and how they tackle problems than on just writing code.</p>
<p>After these, and other challenging questions, we have a well earned beer and some food &#8230;</p>
<p>An interesting and enjoyable events.</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/01/presentation-on-agile-development/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My Mix10k entry &#8211; Old Skool demo &#8211; plus a few tips</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2010/01/my-mix10k-entry-old-skool-demo-plus-a-few-tips/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2010/01/my-mix10k-entry-old-skool-demo-plus-a-few-tips/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 15:27:33 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[mix10k]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[WriteableBitmap]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=539</guid>
		<description><![CDATA[
This blog post is about my entry to the Mix10k code competition, and old-skool demo, plus a few tips about how to keep you code size to below 10k.
The mix10k challenge, where you are given 10k to create a Silverlight / HTML5 application, has been on my mind for a while &#8230; the Christmas vacation [...]]]></description>
			<content:encoded><![CDATA[
<p><em>This blog post is about my entry to the Mix10k code competition, and old-skool demo, plus a few tips about how to keep you code size to below 10k.</em></p>
<p>The <a href="http://mix10k.visitmix.com/">mix10k challenge</a>, where you are given 10k to create a Silverlight / HTML5 application, has been on my mind for a while &#8230; the Christmas vacation was the perfect excuse to put together my entry. Inspired by the demo&#8217;s of the Amiga era, here is my mix10k old-skool demo entry:</p>
<div id="slPluginHost1" > <object id="SilverlightPlugin1" width="700" height="500" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/S.xap"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>You can view my entry (and more importantly vote for it!) at the <a href="http://mix10k.visitmix.com/Entry/Details/147">mix10k gallery</a>.</p>
<p>For me the greatest challenge was the music, not least for the fact that I am no good at writing the stuff myself! The mix10k rules are fairly relaxed, you can download content, such as images and music, allowing you to circumnavigate the 10k limit. However, I thought it would be a more interesting challenge to pack everything into 10k.</p>
<p>Size-limited demos typically use synthesis rather than sampling for the musics. Unfortunately Silverlight isn&#8217;t really geared towards sound synthesis, however, a few people have managed to create <a href="http://community.irritatedvowel.com/blogs/pete_browns_blog/archive/2009/03/23/Creating-Sound-using-MediaStreamSource-in-Silverlight-3-Beta.aspx">synthesized media sources</a>. I decided to go the sampling route and use an MP3 track for my music, the idea being to use a short, highly compressed MP3 track and loop it. I posted a message on the <a href="http://8bitcollective.com/">8bitcollective</a> forums and within a day had a funky, and highly compressed, 4 second MP3 clip for my demo. The MP3 filesize of 4,248 bytes left me 5,992 to play with.</p>
<p>However, the next challenge was looping the audio, which is unfortunately something that is not supported out-of-the-box. For longer media clips it is acceptable to <a href="http://www.williablog.net/williablog/post/2007/10/30/How-to-Make-a-Media-Element-Loop-Indefinitely.aspx">catch the MediaEnded event, re-wind and re-start</a>. However, there is a delay of about half a second, which with a 4 second looped audio clip is pretty disruptive! Fortunately Silverlight does expose a lower level API for media via the abstract class MediaStreamSource, which has virtual methods which you can override to supply audio direct from a stream. The codeplex project <a href="http://code.msdn.microsoft.com/ManagedMediaHelpers">ManagedMediaHelpers</a> is a great place to start for information on how to load MP3 audio from a file. Typically the code to read and stream an MP3 file is over 10k, however, I was able to trim this down to roughly 1k by removing all the code for parsing the MP3 headers, replacing it with the hard-coded values for my specific MP3 file.</p>
<p>Unfortunately, when the audio was looped, it just didn&#8217;t sound right. The trouble is, within MP3 files, the audio is split into frames. Using a useful utility from <a href="http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx">codeproject</a>, I found that my MP3 file consisted of 56 frames of ~67ms in length. However, the audio loop was not a multiple of 67ms. To rectify this, I downloaded a copy of the free audio editor <a href="http://audacity.sourceforge.net/">Audacity</a>, and &#8217;stretched&#8217; the track to fit into an integer number of frames, and re-encoded in MP3 format via <a href="http://lame.sourceforge.net/">lame</a>. Finally, I had looping MP3 audio! (and 4,958 bytes left)</p>
<p><a href="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/12/audacity.png"><img class="aligncenter size-medium wp-image-542" title="audacity" src="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/12/audacity-300x187.png" alt="audacity" width="300" height="187" /></a></p>
<p>After the battle I had with the audio, constructing the visuals, the scrolling text, interference patterns, plasma and starfield was a piece of cake!</p>
<p>Here are a few quick tips for keeping your filesize under 10k.</p>
<ul>
<li><strong>Use the <code>var</code> keyword wherever possible</strong><br />
&nbsp;
</li>
<li><strong>Use the <code>using</code> for aliasing frequently used types</strong>
<p>For example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">K </span><span style="color: #008000;">=</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Media</span>.<span style="color: #0000FF;">MediaSourceAttributesKeys</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">J</span><span style="color: #008000;">=</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Media</span>.<span style="color: #0000FF;">MediaStreamAttributeKeys</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">M </span><span style="color: #008000;">=</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Math</span><span style="color: #008000;">;</span></pre></div></div>

<p>With type names as long as <code>MediaSourceAttributesKeys</code>, you only need to use them three times for a using alias to make sense!</p>
</li>
<li><strong><em>chain </em>initialisation of variables</strong>
<p>The following code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span> x1 <span style="color: #008000;">=</span> sin1<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">8</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">200</span>
<span style="color: #FF0000;">int</span> y1 <span style="color: #008000;">=</span> sin1<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">*</span> <span style="color: #FF0000;">10</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">100</span>
<span style="color: #FF0000;">int</span> g <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>tx <span style="color: #008000;">-</span> x1<span style="color: #000000;">&#41;</span> <span style="color: #008000;">*</span> <span style="color: #000000;">&#40;</span>tx <span style="color: #008000;">-</span> x1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Can be shortened to:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">int</span> x1 <span style="color: #008000;">=</span> sin1<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">8</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">200</span>, y1 <span style="color: #008000;">=</span> sin1<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">*</span> <span style="color: #FF0000;">10</span> <span style="color: #008000;">+</span> <span style="color: #FF0000;">100</span>, g <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>tx <span style="color: #008000;">-</span> x1<span style="color: #000000;">&#41;</span> <span style="color: #008000;">*</span> <span style="color: #000000;">&#40;</span>tx <span style="color: #008000;">-</span> x1<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

</li>
<li><strong>Tabs not spaces</strong>
<p>If you are not to bothered about squeezing the most out of those 10k bytes and want your code to look pretty, at least save yourself a bit of room by using Tabs!</p>
</li>
<li><strong>Choose wisely between XAML and C#</strong>
<p>One big advantage that XAML has over C# is its use of value converters, compare the following XAML:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Ellipse</span> <span style="color: #000066;">Fill</span>=<span style="color: #ff0000;">&quot;White&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>to its equivalent in C#:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var el <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Ellipse<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   Fill <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SolidColorBrush<span style="color: #000000;">&#40;</span>Color.<span style="color: #0000FF;">FromArgb</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">255</span>,<span style="color: #FF0000;">255</span>,<span style="color: #FF0000;">255</span>,<span style="color: #FF0000;">255</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>In this case, XAML is a clear winner.</p>
</li>
<li><strong>Use lambda expressions for event handlers</strong>
<p>You can achieve great savings by including your event handling logic within anonymous delegates (via lambda expressions), it also means that you can move variables from class scope (i.e. files) to method scope and use the <code>var</code> keyword. Compare:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">WriteableBitmap bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WriteableBitmap<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">200</span>,<span style="color: #FF0000;">200</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
MyPage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	var t <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DispatcherTimer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	t.<span style="color: #0000FF;">Tick</span> <span style="color: #008000;">+=</span><span style="color: #008000;">new</span> EventHandler<span style="color: #000000;">&#40;</span>t_Tick<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">void</span>  t_Tick<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">// do stuff with the bitmap</span>
	bitmap.<span style="color: #0000FF;">Invalidate</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>to:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">MyPage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	var bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WriteableBitmap<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">200</span>,<span style="color: #FF0000;">200</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var t <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DispatcherTimer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	t.<span style="color: #0000FF;">Tick</span> <span style="color: #008000;">+=</span> <span style="color: #000000;">&#40;</span>s,e<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
		<span style="color: #000000;">&#123;</span>
			<span style="color: #008080; font-style: italic;">// do stuff with the bitmap</span>
			bitmap.<span style="color: #0000FF;">Invalidate</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</li>
<li><strong>Ditch that App!</strong>
<p>The <code>App.xaml</code> and <code>App.xaml.cs</code> full of template code that you do not need. Simply ditch these files entirely and replace with a minimal application that indicates the page to display:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> A <span style="color: #008000;">:</span> Application
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> A<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Startup <span style="color: #008000;">+=</span> <span style="color: #000000;">&#40;</span>i, j<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> RootVisual <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MainPage<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</li>
<li><strong>Minify your code</strong>
<p>Perhaps the greatest savings can be achieved by &#8216;minifying&#8217; your code, i.e. removing any extra whitespace and reducing variable, method, types names to single characters. The problem is that in doing so, your code will become unreadable!</p>
<p>In order to minify my code yet maintain readability I created a very simple console application that read my application source and performed a bunch of string replacements in order to reduce its size &#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">static</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> reps <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#123;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Environment</span>.<span style="color: #0000FF;">NewLine</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#125;</span>, 
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;  &quot;</span>, <span style="color: #666666;">&quot; &quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot; = &quot;</span>, <span style="color: #666666;">&quot;=&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot; == &quot;</span>, <span style="color: #666666;">&quot;==&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot; * &quot;</span>, <span style="color: #666666;">&quot;*&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot; &gt; &quot;</span>, <span style="color: #666666;">&quot;&gt;&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot; &lt; &quot;</span>, <span style="color: #666666;">&quot;&lt;&quot;</span><span style="color: #000000;">&#125;</span>,
  ...
&nbsp;
  <span style="color: #008080; font-style: italic;">// methods </span>
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;Timer_Tick&quot;</span>, <span style="color: #666666;">&quot;T&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;CreateLine&quot;</span>, <span style="color: #666666;">&quot;g&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;DrawLines&quot;</span>, <span style="color: #666666;">&quot;ln&quot;</span><span style="color: #000000;">&#125;</span>,
  ...
&nbsp;
  <span style="color: #008080; font-style: italic;">// xaml</span>
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;grid&quot;</span>, <span style="color: #666666;">&quot;q&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;image&quot;</span>, <span style="color: #666666;">&quot;o&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;canvas&quot;</span>, <span style="color: #666666;">&quot;c&quot;</span><span style="color: #000000;">&#125;</span>,
  <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;MainPage&quot;</span>, <span style="color: #666666;">&quot;Y&quot;</span><span style="color: #000000;">&#125;</span>,
  ...
<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>The output of this console application is sent to another project which builds my final entry. The result of this was to make my reasonably compact code <strong>47%</strong> smaller!
</li>
</ul>
<p>You can download my thoroughly messy and unreadable code: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2010/01/mix10ksrc.zip'>mix10ksrc.zip</a></p>
<p>And vote for it on the <a href="http://mix10k.visitmix.com/Entry/Details/147">mix10k site</a> (Did I say that already?)</p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2010/01/my-mix10k-entry-old-skool-demo-plus-a-few-tips/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Rippling Reflection Effect with Silverlight 3&#8217;s WriteableBitmap</title>
		<link>http://www.scottlogic.co.uk/blog/colin/2009/12/rippling-reflection-effect-with-silverlight-3s-writeablebitmap/</link>
		<comments>http://www.scottlogic.co.uk/blog/colin/2009/12/rippling-reflection-effect-with-silverlight-3s-writeablebitmap/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 11:47:46 +0000</pubDate>
		<dc:creator>Colin Eberhardt</dc:creator>
				<category><![CDATA[codeproject]]></category>
		<category><![CDATA[WriteableBitmap]]></category>

		<guid isPermaLink="false">http://www.scottlogic.co.uk/blog/colin/?p=526</guid>
		<description><![CDATA[
This blog post demonstrates how Silvelight 3&#8217;s WriteableBitmap can be used to create a UserControl that renders the content of any other Framework Element as a reflection with an animated ripple effect
  
I was sad to hear the news earlier this year that Yahoo! was pulling the plug on GeoCities. Somewhere buried deep within [...]]]></description>
			<content:encoded><![CDATA[
<p><em>This blog post demonstrates how Silvelight 3&#8217;s WriteableBitmap can be used to create a UserControl that renders the content of any other Framework Element as a reflection with an animated ripple effect</em></p>
<div id="slPluginHost1" > <object id="SilverlightPlugin1" width="320" height="260" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/12/SilverlightShimmerOne.zip"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>I was sad to hear the news earlier this year that Yahoo! was <a href="http://news.bbc.co.uk/1/hi/8016211.stm">pulling the plug on GeoCities</a>. Somewhere buried deep within GeoCities is the first web page I ever created, complete with &#8220;Under Construction&#8221; banner, animated GIFs, guestbooks, and nasty background music. Unfortunately, I have no idea what the URL for that page was, and this is long before Google ran my life!</p>
<p>This blog post is a tribute to one of the many dynamic effects that were popular in the 90&#8217;s, animated reflections. These <a href="http://javaboutique.internet.com/Lake/">Java applets</a> were quite popular for a while, but have gone the same way as GeoCities. Perhaps it is time for a revival?</p>
<p>The Silverlight application shown above contains a <code>UserControl</code> which renders an animated reflection of a referenced <code>FrameworkElement</code>.</p>
<p>The code which produces the ripple is very simple, A <code>DispatcherTimer</code> increments <code>_time</code> and redraws the reflection. The reflection itself is achieved by constructing a <code>WriteableBitmap</code> from the referenced element, allowing us to grab its pixel values. Another <code>WriteableBitmap</code> is constructed for the reflection image, and rows of pixels are copied across with a suitable Y offset to produce the ripple effect:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #FF0000;">double</span> _time <span style="color: #008000;">=</span> <span style="color: #FF0000;">0.0</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Timer_Tick<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// increment phi and update the reflection</span>
    _time <span style="color: #008000;">+=</span> <span style="color: #FF0000;">0.4</span><span style="color: #008000;">;</span>
    UpdateReflection<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Copies an inverted image of the referenced FrameworkElement</span>
<span style="color: #008080; font-style: italic;">/// with a 'ripple' effect</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> UpdateReflection<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    FrameworkElement reflectedFE <span style="color: #008000;">=</span> ReflectedElement <span style="color: #0600FF;">as</span> FrameworkElement<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>reflectedFE <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        return<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// synchronize the element width</span>
    Width <span style="color: #008000;">=</span> reflectedFE.<span style="color: #0000FF;">ActualWidth</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// copy the source into a writeable bitmap</span>
    WriteableBitmap sourceBitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WriteableBitmap<span style="color: #000000;">&#40;</span>reflectedFE, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// create a target which is the same width / height as the reflection element</span>
    WriteableBitmap targetBitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WriteableBitmap<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>ActualWidth, <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>ActualHeight<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// copy the reflection</span>
    <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> y <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> y <span style="color: #008000;">&lt;</span> targetBitmap.<span style="color: #0000FF;">PixelHeight</span><span style="color: #008000;">;</span> y<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">double</span> amplitude <span style="color: #008000;">=</span> ComputeAmplitude<span style="color: #000000;">&#40;</span>y, targetBitmap.<span style="color: #0000FF;">PixelHeight</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">double</span> sinusoid <span style="color: #008000;">=</span> ComputeRipple<span style="color: #000000;">&#40;</span>y, targetBitmap.<span style="color: #0000FF;">PixelHeight</span>, _time<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// the offset to the y value index caused by the ripple</span>
        <span style="color: #FF0000;">int</span> yOffset <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#40;</span>sinusoid <span style="color: #008000;">*</span> amplitude<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// compute the Y position of the line to copy from the source image</span>
        <span style="color: #FF0000;">int</span> sourceYLocation <span style="color: #008000;">=</span> sourceBitmap.<span style="color: #0000FF;">PixelHeight</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">-</span>
            <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>y <span style="color: #008000;">+</span> yOffset<span style="color: #000000;">&#41;</span> <span style="color: #008000;">*</span> sourceBitmap.<span style="color: #0000FF;">PixelHeight</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">/</span> targetBitmap.<span style="color: #0000FF;">PixelHeight</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// check that this value is in range</span>
        sourceYLocation <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">Min</span><span style="color: #000000;">&#40;</span>sourceBitmap.<span style="color: #0000FF;">PixelHeight</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span>, Math.<span style="color: #0000FF;">Max</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, sourceYLocation<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// copy the required row</span>
        <span style="color: #FF0000;">int</span> sourceIndex <span style="color: #008000;">=</span> sourceYLocation <span style="color: #008000;">*</span> sourceBitmap.<span style="color: #0000FF;">PixelWidth</span><span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> targetIndex <span style="color: #008000;">=</span> y <span style="color: #008000;">*</span> targetBitmap.<span style="color: #0000FF;">PixelWidth</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> targetBitmap.<span style="color: #0000FF;">PixelWidth</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            targetBitmap.<span style="color: #0000FF;">Pixels</span><span style="color: #000000;">&#91;</span>targetIndex<span style="color: #008000;">++</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> sourceBitmap.<span style="color: #0000FF;">Pixels</span><span style="color: #000000;">&#91;</span>sourceIndex<span style="color: #008000;">++</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>                
    <span style="color: #000000;">&#125;</span>
&nbsp;
    targetBitmap.<span style="color: #0000FF;">Invalidate</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    LayoutRoot.<span style="color: #0000FF;">Source</span> <span style="color: #008000;">=</span> targetBitmap<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Compute the amplitude of the oscillations at a given Y position</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">double</span> ComputeAmplitude<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> y, <span style="color: #FF0000;">int</span> height<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// our amplitude range is 1 to 3</span>
    <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span><span style="color: #000000;">&#41;</span>y <span style="color: #008000;">*</span> <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">/</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span><span style="color: #000000;">&#41;</span>height <span style="color: #008000;">+</span> <span style="color: #FF0000;">1.0</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Compute the sinusoid applied to teh image at the given location</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">double</span> ComputeRipple<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> y, <span style="color: #FF0000;">int</span> height, <span style="color: #FF0000;">double</span> time<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// provide a ripple that is the combination of two out of phase sine waves</span>
    <span style="color: #FF0000;">double</span> phaseFactor <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span><span style="color: #000000;">&#41;</span>y <span style="color: #008000;">/</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span><span style="color: #000000;">&#41;</span>height<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Math.<span style="color: #0000FF;">Sin</span><span style="color: #000000;">&#40;</span>time <span style="color: #008000;">+</span> phaseFactor <span style="color: #008000;">*</span> <span style="color: #FF0000;">16</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> Math.<span style="color: #0000FF;">Sin</span><span style="color: #000000;">&#40;</span>time <span style="color: #008000;">+</span> phaseFactor <span style="color: #008000;">*</span> <span style="color: #FF0000;">30</span><span style="color: #000000;">&#41;</span>
        <span style="color: #008000;">+</span> Math.<span style="color: #0000FF;">Sin</span><span style="color: #000000;">&#40;</span>time <span style="color: #008000;">+</span> phaseFactor <span style="color: #008000;">*</span> <span style="color: #FF0000;">62</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The XAML for this user control is simply an image with an opacity gradient:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;SilverlightShimmer.ReflectionControl&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span> </span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:x</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span> </span>
<span style="color: #009900;">    <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;300&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;300&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Image</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;LayoutRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Image.OpacityMask<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;LinearGradientBrush</span> <span style="color: #000066;">EndPoint</span>=<span style="color: #ff0000;">&quot;0.5,1&quot;</span> <span style="color: #000066;">StartPoint</span>=<span style="color: #ff0000;">&quot;0.5,0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;GradientStop</span> <span style="color: #000066;">Color</span>=<span style="color: #ff0000;">&quot;#FF000000&quot;</span> <span style="color: #000066;">Offset</span>=<span style="color: #ff0000;">&quot;0&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;GradientStop</span> <span style="color: #000066;">Color</span>=<span style="color: #ff0000;">&quot;#00000000&quot;</span> <span style="color: #000066;">Offset</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/LinearGradientBrush<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Image.OpacityMask<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Image<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This control is associated with our Christmas-ey image as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;UserControl</span> <span style="color: #000066;">x:Class</span>=<span style="color: #ff0000;">&quot;SilverlightShimmer.MainPage&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:x</span>=<span style="color: #ff0000;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:local</span>=<span style="color: #ff0000;">&quot;clr-namespace:SilverlightShimmer&quot;</span> <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;320&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;260&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Grid</span> <span style="color: #000066;">Background</span>=<span style="color: #ff0000;">&quot;Black&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;StackPanel</span> <span style="color: #000066;">Orientation</span>=<span style="color: #ff0000;">&quot;Vertical&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>            
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Border</span>  <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;controlToReflect&quot;</span> <span style="color: #000066;">BorderThickness</span>=<span style="color: #ff0000;">&quot;5&quot;</span> <span style="color: #000066;">BorderBrush</span>=<span style="color: #ff0000;">&quot;LightGray&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">CornerRadius</span>=<span style="color: #ff0000;">&quot;3&quot;</span> <span style="color: #000066;">HorizontalAlignment</span>=<span style="color: #ff0000;">&quot;Center&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Image</span>  <span style="color: #000066;">Source</span>=<span style="color: #ff0000;">&quot;christmas.jpg&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;3&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">Stretch</span>=<span style="color: #ff0000;">&quot;None&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Border<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;local:ReflectionControl</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;shimmer&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;80&quot;</span> <span style="color: #000066;">Margin</span>=<span style="color: #ff0000;">&quot;3&quot;</span></span>
<span style="color: #009900;">                       <span style="color: #000066;">ReflectedElement</span>=<span style="color: #ff0000;">&quot;{Binding ElementName=controlToReflect}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/StackPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/UserControl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>One interesting point here is the way in which the <code>Border</code> and <code>Image</code> are associated with the <code>ReflectionControl</code>. The <code>ReflectedElement</code> property is bound to the <code>Border</code> via an <code>ElementName</code> binding, however this binding has no <code>Path</code>. Therefore, rather than binding to a property of the referenced element, the <code>ReflectedElement</code> is bound to the element itself. Hence, no need for any code behind to associated the <code>ReflectionControl</code> with the element(s) to render.</p>
<p>This control can be used to render a reflection of anything (even a reflection of a reflection if you so wish). Here is a more complex example:</p>
<div id="slPluginHost2" > <object id="SilverlightPlugin2" width="450" height="310" data="data:application/x-silverlight," type="application/x-silverlight-2" ><param name="source" value="http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/12/SilverlightShimmerTwo.zip"/><a href="http://go.microsoft.com/fwlink/?LinkID=124807"  style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></object></div>
<p>You can download the full sourcecode here: <a href='http://www.scottlogic.co.uk/blog/colin/wp-content/uploads/2009/12/SilverlightShimmer.zip'>SilverlightShimmer.zip</a></p>
<p>Regards, Colin E.</p>

]]></content:encoded>
			<wfw:commentRss>http://www.scottlogic.co.uk/blog/colin/2009/12/rippling-reflection-effect-with-silverlight-3s-writeablebitmap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
