<?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>Pelebyte</title>
	<atom:link href="http://pelebyte.net/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://pelebyte.net/blog</link>
	<description>because computers get angry when they are wronged</description>
	<lastBuildDate>Thu, 14 Jul 2011 18:50:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Better PowerShell Splatting</title>
		<link>http://pelebyte.net/blog/2011/07/14/better-powershell-splatting/</link>
		<comments>http://pelebyte.net/blog/2011/07/14/better-powershell-splatting/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 18:19:26 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[invoke]]></category>
		<category><![CDATA[invoke-splat]]></category>
		<category><![CDATA[Powershell]]></category>
		<category><![CDATA[splat]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=240</guid>
		<description><![CDATA[One of PowerShell&#8217;s more useful and differentiating features is its ability to splat command-line arguments. Normally, to invoke a command in PowerShell with arguments, you could do something like this: Get-Process -Name *Tomcat* -ComputerName somebox.around.here It may be useful to capture the arguments first, then invoke the command later: $myArgs = @&#123; Name = &#34;*Tomcat*&#34;; [...]]]></description>
			<content:encoded><![CDATA[<p>One of PowerShell&#8217;s more useful and differentiating features is its ability to <strong>splat</strong> command-line arguments. Normally, to invoke a command in PowerShell with arguments, you could do something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #008080; font-weight: bold;">Get-Process</span> <span style="color: #008080; font-style: italic;">-Name</span> <span style="color: pink;">*</span>Tomcat<span style="color: pink;">*</span> <span style="color: #008080; font-style: italic;">-ComputerName</span> somebox.around.here</pre></div></div>

<p>It may be useful to capture the arguments first, then invoke the command later:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #800080;">$myArgs</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span> Name <span style="color: pink;">=</span> <span style="color: #800000;">&quot;*Tomcat*&quot;</span>; ComputerName <span style="color: pink;">=</span> <span style="color: #800000;">&quot;somebox.around.here&quot;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #008080; font-weight: bold;">Get-Process</span> <span style="color: pink;">@</span>myArgs</pre></div></div>

<p>It can also be incredibly useful if you&#8217;re writing wrapper functions:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #0000FF;">Function</span> Import<span style="color: pink;">-</span>ModuleForce <span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">param</span><span style="color: #000000;">&#40;</span>
        <span style="color: #000000;">&#91;</span>Parameter<span style="color: #000000;">&#40;</span>Mandatory <span style="color: pink;">=</span> <span style="color: #800080;">$true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #000000;">&#91;</span><span style="color: #008080;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #800080;">$Name</span>
    <span style="color: #000000;">&#41;</span>
&nbsp;
    <span style="color: #800080;">$PSBoundParameters</span>.Force <span style="color: pink;">=</span> <span style="color: #800080;">$true</span>
    Import<span style="color: pink;">-</span>Module <span style="color: pink;">@</span>PSBoundParameters
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008000;"># unfortunately, aliases can't be set up to script blocks;</span>
<span style="color: #008000;"># only functions and cmdlets get that honor</span>
<span style="color: #008080; font-weight: bold;">Set-Alias</span> imf Import<span style="color: pink;">-</span>ModuleForce</pre></div></div>

<p>It can also be useful when you&#8217;re passing in the same arguments to multiple functions consecutively:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #800080;">$myArgs</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span>
    Name <span style="color: pink;">=</span> <span style="color: #800000;">&quot;*Tomcat*&quot;</span>
    ComputerName <span style="color: pink;">=</span> <span style="color: #800000;">&quot;somebox.around.here&quot;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-weight: bold;">Get-Service</span> <span style="color: pink;">@</span>myArgs
<span style="color: #008080; font-weight: bold;">Get-Process</span> <span style="color: pink;">@</span>myArgs</pre></div></div>

<p>But sometimes splatting doesn&#8217;t work, notably when you have extra values in the hashtable that the function isn&#8217;t expecting:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #800080;">$myArgs</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span>
    Name <span style="color: pink;">=</span> <span style="color: #800000;">&quot;*Tomcat*&quot;</span>
    ComputerName <span style="color: pink;">=</span> <span style="color: #800000;">&quot;somebox.around.here&quot;</span>
    DependentServices <span style="color: pink;">=</span> <span style="color: #800080;">$true</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-weight: bold;">Get-Service</span> <span style="color: pink;">@</span>myArgs
<span style="color: #008080; font-weight: bold;">Get-Process</span> <span style="color: pink;">@</span>myArgs</pre></div></div>

<p>A nasty little error is PowerShell&#8217;s response:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Get-Process : A parameter cannot be found that matches parameter name 'DependentServices'.
+ Get-Process &lt;&lt;&lt;&lt;  @myArgs
    + CategoryInfo          : InvalidArgument: (:) [Get-Process], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetProcessCommand</pre></div></div>

<p>The <span class="monospace">Get-Service</span> cmdlet has a DependentServices argument, but <span class="monospace">Get-Process</span> does not. Although this can <em>sometimes</em> be a helpful error message, in this case, it would be nice if the command just ignored the arguments it couldn&#8217;t understand.</p>
<p>So that&#8217;s why I wrote <span class="monospace">Invoke-Splat</span>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #0000FF;">Function</span> Invoke<span style="color: pink;">-</span>Splat <span style="color: #000000;">&#123;</span>
    <span style="color: #008000;">&lt;#
    .Synopsis
        Splats a hashtable on a function in a safer way than the built-in
        mechanism.
    .Example
        Invoke-Splat Get-XYZ $PSBoundParameters
    #&gt;</span>
    <span style="color: #0000FF;">param</span><span style="color: #000000;">&#40;</span>
        <span style="color: #000000;">&#91;</span>Parameter<span style="color: #000000;">&#40;</span>ValueFromPipeline<span style="color: pink;">=</span><span style="color: #800080;">$true</span><span style="color: pink;">,</span> Mandatory<span style="color: pink;">=</span><span style="color: #800080;">$true</span><span style="color: pink;">,</span> Position<span style="color: pink;">=</span><span style="color: #804000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #000000;">&#91;</span><span style="color: #008080;">string</span><span style="color: #000000;">&#93;</span>
        <span style="color: #800080;">$FunctionName</span><span style="color: pink;">,</span>
        <span style="color: #000000;">&#91;</span>Parameter<span style="color: #000000;">&#40;</span>ValueFromPipeline<span style="color: pink;">=</span><span style="color: #800080;">$true</span><span style="color: pink;">,</span> Mandatory<span style="color: pink;">=</span><span style="color: #800080;">$true</span><span style="color: pink;">,</span> Position<span style="color: pink;">=</span><span style="color: #804000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #000000;">&#91;</span>System.Collections.Hashtable<span style="color: #000000;">&#93;</span>
        <span style="color: #800080;">$Parameters</span>
    <span style="color: #000000;">&#41;</span>
&nbsp;
    <span style="color: #800080;">$h</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">ForEach</span> <span style="color: #000000;">&#40;</span><span style="color: #800080;">$key</span> <span style="color: #0000FF;">in</span> <span style="color: #000000;">&#40;</span><span style="color: #008080; font-weight: bold;">gcm</span> <span style="color: #800080;">$FunctionName</span><span style="color: #000000;">&#41;</span>.Parameters.Keys<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #800080;">$Parameters</span>.<span style="color: #800080;">$key</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            <span style="color: #800080;">$h</span>.<span style="color: #800080;">$key</span> <span style="color: pink;">=</span> <span style="color: #800080;">$Parameters</span>.<span style="color: #800080;">$key</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #800080;">$h</span>.Count <span style="color: #FF0000;">-eq</span> <span style="color: #804000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #800080;">$FunctionName</span> <span style="color: pink;">|</span> <span style="color: #008080; font-weight: bold;">Invoke-Expression</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0000FF;">else</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #800000;">&quot;$FunctionName @h&quot;</span> <span style="color: pink;">|</span> <span style="color: #008080; font-weight: bold;">Invoke-Expression</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Rewriting the example from above:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #800080;">$myArgs</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span>
    Name <span style="color: pink;">=</span> <span style="color: #800000;">&quot;*Tomcat*&quot;</span>
    ComputerName <span style="color: pink;">=</span> <span style="color: #800000;">&quot;somebox.around.here&quot;</span>
    DependentServices <span style="color: pink;">=</span> <span style="color: #800080;">$true</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
Invoke<span style="color: pink;">-</span>Splat <span style="color: #008080; font-weight: bold;">Get-Service</span> <span style="color: #800080;">$myArgs</span>
Invoke<span style="color: pink;">-</span>Splat <span style="color: #008080; font-weight: bold;">Get-Process</span> $myArgs</pre></div></div>

<p>And mixing Invoke-Splat with the @ operator:</p>

<div class="wp_syntax"><div class="code"><pre class="powershell" style="font-family:monospace;"><span style="color: #0000FF;">Function</span> Import<span style="color: pink;">-</span>ModuleForce <span style="color: #000000;">&#123;</span>
    <span style="color: #0000FF;">param</span><span style="color: #000000;">&#40;</span>
        <span style="color: #000000;">&#91;</span>Parameter<span style="color: #000000;">&#40;</span>Mandatory <span style="color: pink;">=</span> <span style="color: #800080;">$true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #000000;">&#91;</span><span style="color: #008080;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #800080;">$Name</span><span style="color: pink;">,</span>
&nbsp;
        <span style="color: #000000;">&#91;</span><span style="color: #008080;">string</span><span style="color: #000000;">&#93;</span>
        <span style="color: #800080;">$SomethingElse</span>
    <span style="color: #000000;">&#41;</span>
&nbsp;
    <span style="color: #800080;">$PSBoundParameters</span>.Force <span style="color: pink;">=</span> <span style="color: #800080;">$true</span>
    Invoke<span style="color: pink;">-</span>Splat Import<span style="color: pink;">-</span>Module <span style="color: #800080;">$PSBoundParameters</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #800080;">$myArgs</span> <span style="color: pink;">=</span> <span style="color: pink;">@</span><span style="color: #000000;">&#123;</span>
    Name <span style="color: pink;">=</span> <span style="color: #800000;">&quot;MyModule&quot;</span>
    SomethingElse <span style="color: pink;">=</span> <span style="color: #800000;">&quot;AnotherString&quot;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
Import<span style="color: pink;">-</span>ModuleForce <span style="color: pink;">@</span>myArgs</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2011/07/14/better-powershell-splatting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Twelve Ways to Improve WPF Performance</title>
		<link>http://pelebyte.net/blog/2011/07/11/twelve-ways-to-improve-wpf-performance/</link>
		<comments>http://pelebyte.net/blog/2011/07/11/twelve-ways-to-improve-wpf-performance/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 19:41:52 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DependencyPropertyDescriptor]]></category>
		<category><![CDATA[INotifyCollectionChanged]]></category>
		<category><![CDATA[ItemsControl]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[ObservableCollection]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[view]]></category>
		<category><![CDATA[viewmodel]]></category>
		<category><![CDATA[visual tree]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=224</guid>
		<description><![CDATA[There is no shortage of information out there on how to speed up the performance of WPF applications, but too often the focus is on the weird stuff instead of the simpler issues. I&#8217;m not going to talk about things like writing to WritableBitmaps to optimize drawing—it&#8217;s a topic covered to death elsewhere. Instead, this [...]]]></description>
			<content:encoded><![CDATA[<p>There is no shortage of information out there on how to speed up the performance of WPF applications, but too often the focus is on the weird stuff instead of the simpler issues. I&#8217;m not going to talk about things like writing to <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx"><span class="monospace">WritableBitmaps</span></a> to optimize drawing—it&#8217;s a topic covered to death elsewhere. Instead, this is meant to be a slightly more practical guide to squeezing performance out of WPF in ways that are probably more likely affecting you.</p>
<h3>Some general notes</h3>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx"><span class="monospace">ItemsControl</span></a> and its subclasses <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx">ListBox</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listview.aspx">ListView</a> exacerbate performance problems because these controls are highly dynamic (resolution happens &#8220;late&#8221;), involve WPF collections (which are slow), and have difficult and unpredictable lifetimes for their child controls. Scrollbar performance is often a big problem in larger WPF apps because of problems that seem trivial for small collections, but suddenly blow up with larger data sets.</p>
<p>Also, it can be difficult in WPF to know exactly when the system is finished with an object. For views, you get the <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.unloaded.aspx"><span class="monospace">FrameworkElement.Unloaded</span></a> event, but it gets raised at times you might not expect (such as system theme changes) and not at times when you might (application shutdown). On viewmodels associated with views, you&#8217;ll <em>never</em> get a WPF notification that a viewmodel is about to go unused by a view. Blend-style behaviors also have their own set of <a href="#BehaviorOnDetaching">lifetime problems</a>.</p>
<p>Then there are some problems (like <a href="#DependencyPropertyDescriptor">this</a> and <a href="#ResourceDictionary">this</a>) where WPF leaks for you too.</p>
<p>Finally, there are things (<a href="#FixBindingErrors">this</a>, <a href="#OptimizeLayout">this</a>, <a href="#AvoidGrouping">this</a>, <a href="#DynamicResource">this</a>, <a href="#ResourceDictionary">this</a>, and <a href="#Dispatcher">this</a>) that simply perform worse than you likely expect.</p>
<p>Finally, there are old UI/WinForms problems (<a href="#ViewModelEvents">this</a>, <a href="#Dispatcher">this</a>, and <a href="#MemoryLeaks">this</a>) that never really went away—they&#8217;re just less likely to happen.</p>
<ol type="I">
<li><a href="#FixBindingErrors">Fix Binding Errors</a></li>
<li><a href="#OptimizeLayout">Hard-code widths and heights where possible</a></li>
<li><a href="#AvoidGrouping">Avoid CollectionView.Grouping</a></li>
<li><a href="#BetterObservableCollection">Optimize bindings to collections that change</a>
<li><a href="#DynamicResource">Avoid DynamicResources</a></li>
<li><a href="#ResourceDictionary">Avoid ResourceDictionary</a></li>
<li><a href="#VisualTree">Simplify your visual tree</a></li>
<li><a href="#BehaviorOnDetaching">Be wary of System.Windows.Interactivity.Behavior&lt;T&gt;.OnDetaching</a></li>
<li><a href="#DependencyPropertyDescriptor">Do not use DependencyPropertyDescriptor for any reason…ever</a></li>
<li><a href="#ViewModelEvents">Be careful of viewmodel events</a></li>
<li><a href="#Dispatcher">Batch up Dispatcher.BeginInvoke</a></li>
<li><a href="#MemoryLeaks">In general, beware of memory leaks</a></li>
</ol>
<p><a name="FixBindingErrors"><br />
<h3>I. Fix Binding Errors and Exceptions</h3>
<p></a></p>
<p>Every time a binding error occurs, your app hangs for just a split second as it writes out errors to the trace log. If you have a lot of binding errors, then those split seconds start to add up. Make sure to go through your bindings, especially those on ItemsControls (ListViews, custom grids, etc.) and verify that there are no binding errors.</p>
<p>Open up your app in the debugger and play around, especially where there is slowness. Make sure all bindings resolve without errors.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx">RelativeSource</a> in DataTemplates may also result in bindings that break initially, but then later resolve properly. Be wary of them, and try to use inherited attached properties instead of relying on RelativeSource in DataTemplates.</p>
<h4>Viewmodel bindings</h4>
<ol>
<li>Make sure that your views and view models are in sync. Use <a href="http://www.jetbrains.com/resharper/features/xaml_editor.html">ReSharper 6</a> to help you find broken bindings.</li>
<li>If you&#8217;re binding to a collection of objects with mixed types, add different DataTemplates so that none of them refer to non-existent properties.</li>
<li>Make sure that your converters aren&#8217;t throwing exceptions. These have a cost too.</li>
</ol>
<h4>View-based RelativeSource bindings</h4>
<ol>
<li>When using ListBoxes and ListViews, it&#8217;s a common problem to have <a href="http://stackoverflow.com/questions/160391/listbox-with-grid-as-itemspaneltemplate-produces-weird-binding-errors">this problem</a>. Avoid RelativeSource.FindAncestor expressions at all cost here, because the deferred behavior of templates cause the object and its bindings to be created (and resolved) <em>before</em> the ListBoxItem/ListViewItem is added to the visual tree.</li>
<li>An alternative is to define an attached dependency property on the ListBoxItem/ListViewItem, and use property inheritance to give your child items the necessary property values. This essentially pushes property values <em>down</em> the visual tree instead of searching <em>up</em>.</li>
</ol>
<p><a name="OptimizeLayout"><br />
<h3>II. Hard-code sizes where possible</h3>
<p></a></p>
<p>This may not always be a practical or desirable solution, but layout passes perform faster when widths and heights do not have to be recalculated. They may also help stop a layout pass from rippling through an entire visual tree.</p>
<p>And always set specific widths on columns in a grid (be it a ListView + GridView or any third-party control), because these tend to be very expensive, especially with larger data sets. </p>
<p><a name="AvoidGrouping"><br />
<h3>III. Avoid CollectionView.Grouping</h3>
<p></a></p>
<p>Grouping in WPF doesn&#8217;t perform terribly well, especially with ListViews and GridViews. Create a collection with mixed viewmodel types–your original collection, and one that represents the &#8220;group&#8221;. Use DataTemplates to change the appearance of your &#8220;group&#8221; objects.</p>
<p>For example, if you have a PersonViewModel class with a property that you want to group by (let&#8217;s say Region), it is faster to create a mixed collection of MyGroupViewModel and PersonViewModel objects, ordered correctly by group, with different DataTemplates, than it is to bind to a grouped collection. Unfortunately, it&#8217;s a lot more work.</p>
<p><a name="BetterObservableCollection"><br />
<h3>IV. Optimize bindings to collections that change</h3>
<p></a></p>
<p>Repeatedly calling <a href="http://msdn.microsoft.com/en-us/library/ms132404.aspx">ObservableCollection&lt;T&gt;.Add</a> when the collection is data-bound can be a prohibitively expensive operation, especially with thousands of rows. Unfortunately, the framework provides no easy, satisfactory fix.</p>
<h4>Fix 1: Use ObservableCollection as-is, but break bindings</h4>
<ol>
<li>Break the binding to the collection.</li>
<li>Update the collection while not data-bound.</li>
<li>Re-bind.</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// some methods removed for brevity</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> MyViewModel <span style="color: #008000;">:</span> INotifyPropertyChanged
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> ObservableCollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> _people<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> IList People
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _people<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> set
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_people <span style="color: #008000;">!=</span> value<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                _people <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
                OnPropertyChanged<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;People&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">void</span> BatchAddPeople<span style="color: #008000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> newPeople<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        var currentPeople <span style="color: #008000;">=</span> _people<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// stop WPF from listening to the changes that we're about</span>
        <span style="color: #008080; font-style: italic;">// to perform</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">People</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// change</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var person <span style="color: #0600FF; font-weight: bold;">in</span> newPeople<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            currentPeople<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>person<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// cause WPF to rebind--but only once instead of once for</span>
        <span style="color: #008080; font-style: italic;">// each person</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">People</span> <span style="color: #008000;">=</span> currentPeople<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<h4>Fix 2: Use the older .NET 2.0-era collections instead</h4>
<ol>
<li>Use <a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx">System.ComponentModel.BindingList&lt;T&gt;</a> (from the old days) instead; it has an API for suppressing change notifications.</li>
</ol>
<h4>Fix 3: Reimplement ObservableCollection.</h4>
<ol>
<li><strong>Create your own collection that implements INotifyCollectionChanged.</strong>
<ul>
<li>Raise INotifyCollectionChanged as sparingly as you can.</li>
<li>Raise the event with a NotifyCollectionChangedAction.Reset event for anything more trivial than a simple single-item add, remove, change, or move. Do <em>not</em> take advantage of the NotifyCollectionChangedEventArgs constructors that take collections of items; you will find support for it spotty at best.</li>
</ul>
</li>
<li><strong>Implement System.Collections.IList on your collection.</strong> WPF does not use the generic System.Collections.Generic.IList&lt;T&gt; interface; it is completely ignored. If you don&#8217;t implement the interface, WPF will perform almost all operations (including accessing rows by number!) strictly by the IEnumerable implementation, and it won&#8217;t be very optimal or fast about it.</li>
<li><strong>(Probably) implement System.Collections.Generic.IList&lt;T&gt; as well.</strong> WPF doesn&#8217;t use it, but you probably will (through LINQ, Rx, etc.)
</ol>
<p><a name="DynamicResource"><br />
<h3>V. Avoid DynamicResources</h3>
<p></a></p>
<p>Even in .NET 4.0, DynamicResource access is still slower than StaticResource access. And worse, once you start nesting DynamicResources (for example, a ListView whose Style contains a ControlTemplate that references objects through DynamicResources), you&#8217;re likely to run into situations where you leak controls.</p>
<p><a name="ResourceDictionary"><br />
<h3>VI. Avoid ResourceDictionary</h3>
<p></a></p>
<p>This advice is practically impossible to follow, but do your best. There is a huge cost in constructing ResourceDictionaries, and depending on where you place them, you are probably constructing many more objects than you realize.</p>
<p>A common, sensible, and logical pattern is to keep usages of elements as close to where you use them as possible. Many people place resources in UserControl.Resources, or break up their themes into multiple ResourceDictionaries for clarity and separation. Although this is arguably good programming practice, it also tends to be insanely slow. If your windows/controls or your ListBoxItem/ListViewItems in a ListBox/ListView are coming up more slowly than you would like, it&#8217;s probably a combination of too much ResourceDictionary construction and/or DynamicResources. (Yes, even in .NET 4.0.) Collapse ResourceDictionaries as much as you can, and try to ensure that the contents of these dictionaries is only loaded once. The easiest and surest way is to include it in the resources of your System.Windows.Application object, almost always difficult or infeasible for composite applications.</p>
<p>I have also frequently taken to creating static classes that contain nothing but highly reusable resources (think static framework classes like the <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.brushes.aspx">Brushes</a> class) because it&#8217;s easier to guarantee that objects are only being created once, and hopefully at app startup instead of triggered by the user interacting with the application and forcing a lazy load at an undesirable time. Not necessary the healthiest design, but the performance is quite a bit better.</p>
<p>Using <a href="http://msdn.microsoft.com/en-us/library/ms750613.aspx#stylesimplicitkeys">implicit ControlTemplate/DataTemplate styles</a> will also help keep your code and XAML organized without the need for either <span class="monospace">StaticResource</span> or <span class="monospace">DynamicResource</span>.</p>
<p><a name="VisualTree"><br />
<h3>VII. Simplify your visual tree</h3>
<p></a></p>
<p>Shallow visual trees are better than deeper visual trees. Again, ItemsControls will usually exacerbate performance problems with deep visual trees because if they&#8217;re not being virtualized, they&#8217;re being destroyed and recreated; if they are being virtualized, changing DataContext in a deeper tree takes more time than changing DataContext in a shallower one.</p>
<p><a name="BehaviorOnDetaching"><br />
<h3>VIII. Be wary of System.Windows.Interactivity.Behavior&lt;T&gt;.OnDetaching</h3>
<p></a></p>
<p>Sadly, <a href="http://msdn.microsoft.com/en-us/library/system.windows.interactivity.behavior.ondetaching(v=expression.40).aspx">System.Windows.Interactivity.Behavior&lt;T&gt;.OnDetaching</a> will generally <em>not</em> get called. Put a breakpoint and see for yourself.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.interactivity.behavior.onattached(v=expression.40).aspx">OnAttached</a> signals the addition of a behavior to a control (generally at instantiation of your XAML); <span class="monospaced">OnDetaching</a> signals the removal of a behavior from a control (generally never, as behaviors don&#8217;t get removed from controls). Don&#8217;t put sensitive disposing behavior in OnDetaching. The Unloaded event is a better place for that, but be aware that it will get raised every time the control is removed from the visual tree.</p>
<p><a name="DependencyPropertyDescriptor"><br />
<h3>IX. Do not use DependencyPropertyDescriptor for any reason…ever</h3>
<p></a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.addvaluechanged.aspx">DependencyPropertyDescriptor.AddValueChanged</a> classes cause the WPF framework to take a strong reference to the source of the event that isn&#8217;t removed until you call <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.removevaluechanged.aspx">DependencyPropertyDescriptor.RemoveValueChanged</a>. This class is frequently used in conjunction with Behaviors, so if you have RemoveValueChanged in OnDetaching, you&#8217;re likely leaking memory. <strong>Because of WPF&#8217;s references to your objects, it is not just enough to drop references to your view and view model.</strong></p>
<p>A better alternative is to rely on data binding where you can; create a DependencyProperty for the sole purpose of listening to changes on your target property, and use the change notifications in DependencyProperty in order to listen to changes on the target property. It keeps the observed object (generally, your view model) from accidentally holding a strong reference to your view.</p>
<p><a name="ViewModelEvents"><br />
<h3>X. Be careful of view model events</h3>
<p></a></p>
<p>If your views or behaviors rely on events being raised from a viewmodel (as innocuous as <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged.PropertyChanged</a> or <a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx">INotifyCollectionChanged.CollectionChanged</a>), subscribe to them weakly. Viewmodels tend to have a longer lifetime than views (consider a virtualized ItemsControl), so it&#8217;s possible that your view model will inadvertently gather references to views. Use classes like <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.propertychangedeventmanager.aspx">PropertyChangedEventManager</a> or <a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.collectionchangedeventmanager.aspx">CollectionChangedEventManager</a>, or (painfully) use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.weakeventmanager.aspx">WeakEventManager</a> to create your own event manager for your custom events. It&#8217;s painful, but usually necessary in order to prevent view models from taking references to views.</p>
<p><a name="Dispatcher"><br />
<h3>XI. Batch up Dispatcher.BeginInvoke</h3>
<p></a></p>
<p>If your application displays data from a network, you&#8217;re probably using background threads to accomplish the task (which is good). However, you&#8217;re probably not consciously counting your <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.begininvoke.aspx">Dispatcher.BeginInvoke</a> calls (which is not as good). The more you&#8217;re able to coalesce multiple Dispatcher.BeginInvokes into a single call, the more likely WPF will be able to help you out by making single subsequent layout and render passes, and the lower your overall CPU usage.</p>
<p>To be fair, WPF is much better at trying to help you here than VB6/WinForms—you won&#8217;t often see apps that dance and flicker incessantly any more—but there is still a non-zero cost to updating the screen, and if you have a particularly large application, this could be a problem for you.</p>
<p><a name="MemoryLeaks"><br />
<h3>XII. In general, beware of memory leaks</h3>
<p></a></p>
<p>This is a bit of a generalization of the last few points, but memory leaks make apps behave worse over time. Fixing memory leaks goes a long way in fixing the performance of an application. And since most developers are constantly restarting WPF apps as they work on them, they often go undetected until the software is delivered.</p>
<p>—DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2011/07/11/twelve-ways-to-improve-wpf-performance/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Doing Simple Things with ExpressionVisitor</title>
		<link>http://pelebyte.net/blog/2011/05/13/doing-simple-things-with-expressionvisitor/</link>
		<comments>http://pelebyte.net/blog/2011/05/13/doing-simple-things-with-expressionvisitor/#comments</comments>
		<pubDate>Sat, 14 May 2011 01:40:53 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[expression trees]]></category>
		<category><![CDATA[ExpressionVisitor]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[visitor]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=148</guid>
		<description><![CDATA[LINQ is one of the more powerful technologies in .NET. Particularly, it introduced expression trees to the language, giving you the limited ability to inspect and rewrite code from code. Basically, code manipulating code&#8211;good stuff. For example, here is a very simple expression tree that adds 73 to a given number: 1 Expression&#60;Func&#60;int, int&#62;&#62; someExpr [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ is one of the more powerful technologies in .NET. Particularly, it introduced expression trees to the language, giving you the limited ability to inspect and rewrite code from code. Basically, code manipulating code&#8211;good stuff.</p>
<p>For example, here is a very simple expression tree that adds 73 to a given number:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&gt;&gt;</span> someExpr <span style="color: #008000;">=</span> x <span style="color: #008000;">=&gt;</span> x <span style="color: #008000;">+</span> <span style="color: #FF0000;">73</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>You can actually address the individual elements inside of the expression tree:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">var nodeType <span style="color: #008000;">=</span> someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">.</span><span style="color: #0000FF;">NodeType</span><span style="color: #008000;">;</span>
var otherValue <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ConstantExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span>someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Right</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// writes &quot;Add&quot; and &quot;73&quot; to the console</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>nodeType<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>otherValue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>(Let&#8217;s ignore those little ugly casts for now.)</p>
<p>Here is another expression tree that takes the average of three numbers:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;&gt;</span> someExpr <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>x, y, z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#40;</span>x <span style="color: #008000;">+</span> y <span style="color: #008000;">+</span> z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">/</span> <span style="color: #FF0000;">3.0</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>And here&#8217;s how we&#8217;d list the names of the parameters in the numerator:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ParameterExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>UnaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span>someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Operand</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ParameterExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>UnaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span>someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Operand</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Right</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ParameterExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>UnaryExpression<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>BinaryExpression<span style="color: #008000;">&#41;</span>someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Operand</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Right</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Of course, inspecting trees like this is a technique that doesn&#8217;t scale well.</p>
<p>Luckily, in .NET 4.0 (or in .NET 3.5, courtesy of <a href="http://blogs.msdn.com/b/mattwar/archive/2007/07/31/linq-building-an-iqueryable-provider-part-ii.aspx">The Wayward Weblog</a>), the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx">System.Linq.Expressions.ExpressionVisitor</a> class makes examining expression trees a bit less painful:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Linq.Expressions</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #6666cc; font-weight: bold;">class</span> MyExpressionVisitor <span style="color: #008000;">:</span> ExpressionVisitor
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> Expression VisitParameter<span style="color: #008000;">&#40;</span>ParameterExpression node<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">VisitParameter</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;&gt;</span> someExpr <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>x, y, z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#40;</span>x <span style="color: #008000;">+</span> y <span style="color: #008000;">+</span> z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">/</span> <span style="color: #FF0000;">3.0</span><span style="color: #008000;">;</span>
        var myVisitor <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MyExpressionVisitor<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        myVisitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Visit</span><span style="color: #008000;">&#40;</span>someExpr<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>ExpressionVisitor contains a method for every possible expression tree node, so we could actually write the whole expression back out to the console by overriding the methods that we care about:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> MyExpressionVisitor <span style="color: #008000;">:</span> ExpressionVisitor
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> Expression VisitBinary<span style="color: #008000;">&#40;</span>BinaryExpression node<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;(&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Visit</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">Left</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">switch</span> <span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">NodeType</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">case</span> ExpressionType<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">:</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot; + &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">case</span> ExpressionType<span style="color: #008000;">.</span><span style="color: #0000FF;">Divide</span><span style="color: #008000;">:</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot; / &quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Visit</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">Right</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;)&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> node<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> Expression VisitConstant<span style="color: #008000;">&#40;</span>ConstantExpression node<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">Value</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> node<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> Expression VisitParameter<span style="color: #008000;">&#40;</span>ParameterExpression node<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>node<span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> node<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>It actually writes out a slightly different output:</p>
<p><code>(((x + y) + z) / 3)xyz</code></p>
<p>Removing the extra parentheses actually turns out to be quite tricky because more context is required to determine which ones can be removed and which ones can&#8217;t. But for most purposes, that won&#8217;t be a problem. The extra <span class="mono">xyz</span>, however&#8230;we&#8217;ll need to get rid of that:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">class</span> Program
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">int</span>, <span style="color: #6666cc; font-weight: bold;">double</span><span style="color: #008000;">&gt;&gt;</span> someExpr <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>x, y, z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#40;</span>x <span style="color: #008000;">+</span> y <span style="color: #008000;">+</span> z<span style="color: #008000;">&#41;</span> <span style="color: #008000;">/</span> <span style="color: #FF0000;">3.0</span><span style="color: #008000;">;</span>
        var myVisitor <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MyExpressionVisitor<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// visit the expression's Body instead</span>
        myVisitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Visit</span><span style="color: #008000;">&#40;</span>someExpr<span style="color: #008000;">.</span><span style="color: #0000FF;">Body</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>By walking just the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.body.aspx">Body</a> of the lambda, we ignore the <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.parameters.aspx">Parameters</a> that we don&#8217;t need to have listed twice:</p>
<p><code>(((x + y) + z) / 3)</code></p>
<p>Much better.</p>
<p>You can use this technique to regenerate C# from LINQ, SQL from LINQ, or a lot of other different languages. Instances of <strong>ExpressionVisitor</strong> are at the heart of every interpretation of a LINQ tree, and doing anything fancy under the surface of LINQ requires a good understanding of this class. It&#8217;s also a nice illustration of the visitor pattern, which has applications even beyond LINQ.</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2011/05/13/doing-simple-things-with-expressionvisitor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Minimal WCF and REST (or whatever else you might want)</title>
		<link>http://pelebyte.net/blog/2011/01/04/minimal-wcf-and-rest/</link>
		<comments>http://pelebyte.net/blog/2011/01/04/minimal-wcf-and-rest/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 23:14:07 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ServiceHost]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=122</guid>
		<description><![CDATA[The original versions of WCF were great if you wanted to expose SOAP-RPC endpoints with predefined methods driven off of reflection in your code, but as developers in the .NET space move to join the rest of the world with REST and general HTTP services that aren&#8217;t quite so static as SOAP-RPC, where does that [...]]]></description>
			<content:encoded><![CDATA[<p>The original versions of WCF were great if you wanted to expose SOAP-RPC endpoints with predefined methods driven off of reflection in your code, but as developers in the .NET space <strike>move to</strike> join the rest of the world with REST and general HTTP services that aren&#8217;t quite so static as SOAP-RPC, where does that leave WCF?</p>
<p>Here is a minimalist version of a standalone WCF service&#8212;no XML in app.config or web.config, no IIS, no generated classes&#8212;just a copy-pasteable example of getting a <i>minimal</i> arbitrary HTTP server up and running in WCF. Note that this code <i>requires</i> .NET 4.0 because it uses the new <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.bytestreammessageencodingbindingelement.aspx">ByteStreamMessageEncodingBindingElement</a> class to allow for tighter control over the serialized output.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ServiceModel</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ServiceModel.Channels</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>ServiceContract<span style="color: #008000;">&#93;</span>
<span style="color: #008000;">&#91;</span>ServiceBehavior<span style="color: #008000;">&#40;</span>
    InstanceContextMode <span style="color: #008000;">=</span> InstanceContextMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Single</span>,
    AddressFilterMode <span style="color: #008000;">=</span> AddressFilterMode<span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> GenericService
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Starts up a generic HTTP service.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;args&quot;&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Arguments to the event.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/param&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Uri uri <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Uri<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;http://localhost:9000/&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        var serviceImpl <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GenericService<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var host <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ServiceHost<span style="color: #008000;">&#40;</span>serviceImpl<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// this gives you complete control over the stream</span>
            var binding <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CustomBinding<span style="color: #008000;">&#40;</span>
                <span style="color: #008000;">new</span> ByteStreamMessageEncodingBindingElement<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,
                <span style="color: #008000;">new</span> HttpTransportBindingElement<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            host<span style="color: #008000;">.</span><span style="color: #0000FF;">AddServiceEndpoint</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>GenericService<span style="color: #008000;">&#41;</span>, binding, uri<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// begin listening for connections</span>
            host<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// display a little message and wait for the user</span>
            <span style="color: #008080; font-style: italic;">// to kill the console app</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Listening on URI: {0}&quot;</span>, uri<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Press ENTER to stop the service.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008000;">&#91;</span>OperationContract<span style="color: #008000;">&#40;</span>Action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;*&quot;</span>, ReplyAction <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;*&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Message Process<span style="color: #008000;">&#40;</span>Message message<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// this is the incoming URI; we're not doing anything with it</span>
        <span style="color: #008080; font-style: italic;">// here, but you almost certainly will</span>
        Uri uri <span style="color: #008000;">=</span> message<span style="color: #008000;">.</span><span style="color: #0000FF;">Headers</span><span style="color: #008000;">.</span><span style="color: #0000FF;">To</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// build a stream of bytes that represents the text &quot;Test&quot; in UTF-8</span>
        var bytes <span style="color: #008000;">=</span> Encoding<span style="color: #008000;">.</span><span style="color: #0000FF;">UTF8</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetBytes</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Test&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        var memStream <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MemoryStream<span style="color: #008000;">&#40;</span>bytes<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// create and return the response message</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> Message<span style="color: #008000;">.</span><span style="color: #0000FF;">CreateMessage</span><span style="color: #008000;">&#40;</span>
            MessageVersion<span style="color: #008000;">.</span><span style="color: #0000FF;">None</span>,
            <span style="color: #666666;">&quot;OK&quot;</span>,
            <span style="color: #008000;">new</span> BodyStreamProviderWriter<span style="color: #008000;">&#40;</span>memStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>And the implementation of <b>BodyStreamProviderWriter</b>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ServiceModel.Channels</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Xml</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Allows an arbitrary &lt;see cref=&quot;Stream&quot;/&gt; to be serialized.</span>
<span style="color: #008080; font-style: italic;">/// Use in conjunction with the overloads of the</span>
<span style="color: #008080; font-style: italic;">/// &lt;see cref=&quot;Message&quot;/&gt;.CreateMessage method.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">sealed</span> <span style="color: #6666cc; font-weight: bold;">class</span> BodyStreamProviderWriter <span style="color: #008000;">:</span> BodyWriter, IStreamProvider
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> Stream innerStream<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> BodyStreamProviderWriter<span style="color: #008000;">&#40;</span>Stream stream<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">innerStream</span> <span style="color: #008000;">=</span> stream<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> OnWriteBodyContents<span style="color: #008000;">&#40;</span>XmlDictionaryWriter writer<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        writer<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteStartElement</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Binary&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        writer<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteValue</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>IStreamProvider<span style="color: #008000;">&#41;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        writer<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteEndElement</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    Stream IStreamProvider<span style="color: #008000;">.</span><span style="color: #0000FF;">GetStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">innerStream</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">void</span> IStreamProvider<span style="color: #008000;">.</span><span style="color: #0000FF;">ReleaseStream</span><span style="color: #008000;">&#40;</span>Stream stream<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>stream <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            stream<span style="color: #008000;">.</span><span style="color: #0000FF;">Dispose</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p><a href="http://pelebyte.net/downloads/GenericService.cs">GenericService.cs</a><br />
<a href="http://pelebyte.net/downloads/BodyStreamProviderWriter.cs">BodyStreamProviderWriter.cs</a></p>
<p>And presto&#8211;you&#8217;ve got a miminal WCF service for your RESTful purposes (or whatever else you might want). &#8212;DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2011/01/04/minimal-wcf-and-rest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collections, CollectionViews, and a WPF Binding Memory Leak</title>
		<link>http://pelebyte.net/blog/2009/10/01/collections-collectionviews-and-a-wpf-binding-memory-leak/</link>
		<comments>http://pelebyte.net/blog/2009/10/01/collections-collectionviews-and-a-wpf-binding-memory-leak/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 02:56:31 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[collection]]></category>
		<category><![CDATA[data binding]]></category>
		<category><![CDATA[ICollectionView]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=105</guid>
		<description><![CDATA[A colleague of mine recently came across some code that should work, but doesn&#8217;t: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 private ListBox SomeListBox; private ObservableCollection&#60;string&#62; SomeStrings = new ObservableCollection&#60;string&#62;&#40;&#41;; &#160; public void SomeMethod&#40;&#41; &#123; SomeListBox.ItemsSource = null; ThreadPool.QueueUserWorkItem&#40;o =&#62; AddToStrings&#40;&#41;&#41;; &#125; &#160; private void AddToStrings&#40;&#41; [...]]]></description>
			<content:encoded><![CDATA[<p>A colleague of mine recently came across some code that <em>should</em> work, but doesn&#8217;t:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> ListBox SomeListBox<span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> ObservableCollection<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> SomeStrings <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ObservableCollection<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> SomeMethod<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    SomeListBox<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
    ThreadPool<span style="color: #008000;">.</span><span style="color: #0000FF;">QueueUserWorkItem</span><span style="color: #008000;">&#40;</span>o <span style="color: #008000;">=&gt;</span> AddToStrings<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> AddToStrings<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// this line will actually crash the app!</span>
    SomeStrings<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;blah&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Dispatcher<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginInvoke</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Action<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">=&gt;</span> SomeListBox<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsSource</span> <span style="color: #008000;">=</span> SomeStrings<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>So basically, detaching an <font face="monospace">ObservableCollection&lt;T&gt;</font> from a view, adding an element on a background thread, and then reattaching it back on the UI thread again. Generally, view-bound objects can only be modified from the UI thread, but shouldn&#8217;t detaching the collection first should make that a non-issue?</p>
<p>When you actually run the code, you get one of those obnoxious &#8220;InvalidOperationException: The calling thread cannot access this object because a different thread owns it&#8221; messages, and then your app will probably die. These <em>usually</em> happen because you&#8217;re trying to modify a control or an object bound to a control, neither of which applies here. It also happens when you&#8217;re trying to do anything with a subclass of DispatcherObject or a DependencyObject on the wrong thread, but that doesn&#8217;t apply here either, right? <font face="monospace">ObservableCollection&lt;T&gt;</font> does not have any inherent thread affinity, and it is definitely safe to pass between threads so long as access to it is synchronized.</p>
<p>So we took the control out of the picture by writing <font face="monospace">SomeListBox.ItemsSource = null</font>, and <font face="monospace">ObservableCollection&lt;T&gt;</font> can be modified from any thread. What&#8217;s the problem? Those are the only two objects in the picture, right?</p>
<h3>ICollectionView</h3>
<p>(If you already know what <font face="monospace">ICollectionView</font> is, feel free to skip to the <a href="#TheFix">end of the story</a>.)</p>
<p>Actually, when any <font face="monospace">IEnumerable</font> is bound to an <font face="monospace">ItemsControl</font>, an implementation of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.aspx"><font face="monospace">ICollectionView</font></a> is created to wrap the collection, and it provides a means for sorting, grouping, and filtering <em>without</em> affecting the original collection. So when you bind a <font face="monospace">ListBox</font>, or <font face="monospace">ListView</font>, or the WPF Toolkit <font face="monospace">DataGrid</font>, or some other third-party <font face="monospace">ItemsControl</font> to a grid, a <font face="monospace">CollectionView</font> is created specifically to maintain intermediate state on behalf of the control without having to touch the original collection.</p>
<p>Consider some <font face="monospace">List&lt;string&gt;</font>:</p>
<table>
<tr>
<th>Index</th>
<th>Value</th>
</tr>
<tr>
<td>0</td>
<td>Cheese</td>
</tr>
<tr>
<td>1</td>
<td>Apple</td>
</tr>
<tr>
<td>2</td>
<td>Tomato</td>
</tr>
<tr>
<td>3</td>
<td>Salad</td>
</tr>
</table>
<p>We bind it to a DataGrid, and then we tell the DataGrid to sort itself. The list <em>should</em> look like this:</p>
<table>
<tr>
<th>Index</th>
<th>Value</th>
</tr>
<tr>
<td>0</td>
<td>Apple</td>
</tr>
<tr>
<td>1</td>
<td>Cheese</td>
</tr>
<tr>
<td>2</td>
<td>Salad</td>
</tr>
<tr>
<td>3</td>
<td>Tomato</td>
</tr>
</table>
<p>Note how the objects now have different indices. It&#8217;s an important detail—WPF manages to accomplish sorting, grouping, and filtering all <em>without modifying the original collection</em> because of the use of a <font face="monospace">CollectionView</font> (or one of its subclasses <font face="monospace">ListCollectionView</font>, <font face="monospace">BindingListCollectionView</font>, or the internal <font face="monospace">CollectionViewProxy</font> class). It also pulls off some shiny tricks occasionally, batching changes where appropriate and postponing actual <font face="monospace">CollectionView</font> reordering (which can obviously get expensive) until subsequent pumps of the current <font face="monospace">Dispatcher</font>. And that&#8217;s why <font face="monospace">CollectionView</font> inherits from <font face="monospace">DispatcherObject</font>.</p>
<p>And of course, if our collection changes, the <font face="monospace">CollectionView</font> listens for those notifications and responds appropriately, causing hilarious consequences when the change happens on a background thread.</p>
<p><a name="#TheFix"></a><br />
<h3>The Fix</h3>
<p>The implementation of <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx"><font face="monospace">CollectionView</font></a> is somewhat broken when collections implement <a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx"><font face="monospace">INotifyCollectionChanged</font></a>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">internal</span> CollectionView<span style="color: #008000;">&#40;</span>IEnumerable collection, <span style="color: #6666cc; font-weight: bold;">int</span> moveToFirst<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/* some code snipped for brevity */</span>
    INotifyCollectionChanged changed <span style="color: #008000;">=</span> collection <span style="color: #0600FF; font-weight: bold;">as</span> INotifyCollectionChanged<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>changed <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// this is the problem</span>
        changed<span style="color: #008000;">.</span><span style="color: #0000FF;">CollectionChanged</span> <span style="color: #008000;">+=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OnCollectionChanged</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/* some more code */</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/* still more code */</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Nowhere <em>anywhere</em> is this event handler unwired. So collections essentially retain <em>strong references</em> of their corresponding <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx"><font face="monospace">CollectionView</font></a>s. The data binding system that is responsible for creating the <font face="monospace">CollectionView</font> maintains a weak reference, but as long as the original collection is alive, the data binding system will be hooked into the <font face="monospace">CollectionView</font>, and therefore the original collection as well.</p>
<p>The fix actually isn&#8217;t so bad:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.ObjectModel</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Specialized</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Windows.Data</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> BetterObservableCollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span>
    ObservableCollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>, ICollectionViewFactory
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ICollectionView CreateView<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> BetterListCollectionView<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> BetterListCollectionView <span style="color: #008000;">:</span>
    ListCollectionView, IWeakEventListener
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> BetterListCollectionView<span style="color: #008000;">&#40;</span>IList list<span style="color: #008000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">&#40;</span>list<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        INotifyCollectionChanged changed <span style="color: #008000;">=</span> list <span style="color: #0600FF; font-weight: bold;">as</span> INotifyCollectionChanged<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>changed <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// this fixes the problem</span>
            changed<span style="color: #008000;">.</span><span style="color: #0000FF;">CollectionChanged</span> <span style="color: #008000;">-=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OnCollectionChanged</span><span style="color: #008000;">;</span>
            CollectionChangedEventManager<span style="color: #008000;">.</span><span style="color: #0000FF;">AddListener</span><span style="color: #008000;">&#40;</span>list, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>As soon as the collection is detached from the view, the view&#8217;s reference to the <font face="monospace">CollectionView</font> is broken, and the <font face="monospace">CollectionView</font> is allowed to disappear because nothing (neither the original collection nor the binding system) is holding on to a strong reference any more.</p>
<h3>What &#8220;The Fix&#8221; Breaks</h3>
<p>The <font face="monospace">CollectionView</font> is responsible for managing sorting, grouping, and filtering. If you disconnect the collection from the view, the <font face="monospace">CollectionView</font> will get garbage-collected, and the sorting, grouping, and/or filtering you had on the control will be lost. That may or may not matter for your particular use case, but it&#8217;s definitely something to think about. If that is important, it may make more sense to bind to a <a href="http://msdn.microsoft.com/en-us/library/ms132679.aspx"><font face="monospace">System.ComponentModel.BindingList&lt;T&gt;</font></a>, which tracks its own grouping, sorting, and filtering inside the list itself—the tradeoff is then you lose the ability to have multiple views on the same collection. —DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/10/01/collections-collectionviews-and-a-wpf-binding-memory-leak/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Attached Behaviors are the New OLE (a.k.a. Long Live Components)</title>
		<link>http://pelebyte.net/blog/2009/09/27/attached-behaviors-are-the-new-ole-a-k-a-long-live-components/</link>
		<comments>http://pelebyte.net/blog/2009/09/27/attached-behaviors-are-the-new-ole-a-k-a-long-live-components/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 02:05:40 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[attached behaviors]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[OLE]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=103</guid>
		<description><![CDATA[Pruning through the old Google Reader starred items list was supposed to only take me an hour or so Saturday morning. But sandwiched between some other diversions, it ended up taking me the whole weekend. One of the last things I read was Mac OS X 10.6 Snow Leopard: the Ars Technica review (that was [...]]]></description>
			<content:encoded><![CDATA[<p>Pruning through the old Google Reader starred items list was supposed to only take me an hour or so Saturday morning. But sandwiched between some other <a href="http://microsite.smithsonianmag.com/museumday/">diversions</a>, it ended up taking me the whole weekend. One of the last things I read was <a href="http://arstechnica.com/apple/reviews/2009/08/mac-os-x-10-6.ars"><br />
Mac OS X 10.6 Snow Leopard: the Ars Technica review</a> (that was an hour right there all by itself). Flipped through some of the old Mac OS X articles, particularly those right at the turn of the Classic Mac OS transition almost ten years ago. You remember Classic Mac OS, right? With <a href="http://en.wikipedia.org/wiki/Cyberdog">Cyberdog</a> and <a href="http://en.wikipedia.org/wiki/OpenDoc">OpenDoc</a>? Windows users will remember the ideas more as <a href="http://en.wikipedia.org/wiki/Object_Linking_and_Embedding">OLE</a> and its foundation <a href="http://en.wikipedia.org/wiki/Component_Object_Model">COM</a>, and a generation of applications where the screen jumped to and fro whenever you clicked somewhere you weren&#8217;t supposed to as menubars popped up and disappeared. And of course, there was <a href="http://java.sun.com/j2ee/overview.html">J2EE </a>.</p>
<p>Maybe these technologies suffered from being too ambitious or too undefined in scope, but for whatever reason, they&#8217;ve been consigned to the dustbin of history. But the dream of having arbitrary components that could just be snapped together like building blocks never seems to die, and maybe we&#8217;re finally reaching the point in technology&#8217;s history where that could be a possibility. OLE, OpenDoc, and J2EE all assumed those building blocks were gigantic—plug six or seven them together and boom, you&#8217;ve got an app—whereas realistically, they&#8217;re probably much closer to <a href="http://www.lego.com">LEGO®</a>-sized. You&#8217;ll need a lot of them before you get something that makes sense—and consequently, you need a little bit of computer know-how.</p>
<p>Fellow Lab49er <a href="http://www.charlierobbins.com/">Charlie Robbins</a> blogged a few weeks ago about a few<br />
<a href="http://www.charlierobbins.com//articles/2009/08/21/samples-samples-samples-/">sample Silverlight projects</a> that added <a href="http://www.silverlightbuzz.com/2009/08/19/additional-physics-based-behaviors-for-blend-and-silverlight/">physics-based behaviors</a> to a canvas with a few items in it. It&#8217;s downright silly what you can do with behaviors now, and I wonder if we&#8217;re not too far off from seeing a scaled-down version of the component dream realized. It always seemed like overkill to have an IntegerTextBox, or a DateTextBox. But an IntegerBehavior/DateBehavior that can be applied to a TextBox, or a grid cell? Or a behavior that could be applied to a Label to make it an editable TextBox upon a double-click? Or better yet, <em>two</em> behaviors, one to make a label editable on a double-click, and another to restrict to date entry? Much more awesome…</p>
<p>If you haven&#8217;t read up on attached behaviors yet, you should. I would argue that a proper MVVM design <em>necessitates</em> attached behaviors—they&#8217;re everything that doesn&#8217;t belong in the viewmodel layer, but since your views should be stupid and codeless, your &#8220;enforce integerness&#8221; behavior has to end up somewhere. With viewmodels and attached behaviors, you might never need to write another line of code-behind ever again. —DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/09/27/attached-behaviors-are-the-new-ole-a-k-a-long-live-components/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Links O&#8217;Clock; 2009.09.25</title>
		<link>http://pelebyte.net/blog/2009/09/27/links-oclock-2009-09-25/</link>
		<comments>http://pelebyte.net/blog/2009/09/27/links-oclock-2009-09-25/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 00:49:05 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Links O'Clock]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=98</guid>
		<description><![CDATA[Normally, throughout the week, I star a whole bunch of things in Google Reader that I want to go back to when I&#8217;m not busy jostling for space on the New York subways or when I&#8217;m back at my comfortable desk at home with my giant monitors. Unfortunately for me, I star articles about 500% [...]]]></description>
			<content:encoded><![CDATA[<p>Normally, throughout the week, I star a whole bunch of things in Google Reader that I want to go back to when I&#8217;m not busy jostling for space on the New York subways or when I&#8217;m back at my comfortable desk at home with my giant monitors. Unfortunately for me, I star articles about 500% faster than I can read them, so every once in a while, I have to give myself a weekend dedicated to purging that star list so that I don&#8217;t forget about things that I really really did want to read (Mr. Siracusa doesn&#8217;t write as often as most people, but he <a href="http://arstechnica.com/apple/reviews/2009/08/mac-os-x-10-6.ars">makes up</a> for it).</p>
<p>So it&#8217;s time for the first-ever Links O&#8217;Clock here; most of these articles go back at least two months or more, but hey, maybe you missed it the first time the Internet collectively decided they were worth reading. I don&#8217;t think Links O&#8217;Clock will normally be this long, but we&#8217;ll see.</p>
<p>Also gonna try giving Google Reader&#8217;s &#8220;Shared items&#8221; feature a ride—I keep hitting it by accident in my <a href="http://www.phantomfish.com/byline.html">main newsreader</a>, but now I&#8217;ll hit it on purpose (<a href="http://www.google.com/reader/shared/07680768900954631322">link</a>).</p>
<hr />
<p>It seems fitting that my desire to purge my starred article backlog leads me to this article likening obesity to information overload:<br />
<a href="http://www.core77.com/blog/featured_items/no_more_feeds_please_how_abundant_information_is_making_us_fat_14248.asp">http://www.core77.com/blog/featured_items/no_more_feeds_please_how_abundant_information_is_making_us_fat_14248.asp</a></p>
<p>I once tried using a 3D designing app once. I flung the mouse out the window in disgust after several hours of hair-pulling madness. This would have been a far more entertaining experience:<br />
<a href="http://www.ilovesketch.com/">http://www.ilovesketch.com/</a></p>
<p>For those of you trying to skin your latest GUI, you might be tearing your hair out trying to pick perfect colors. Don&#8217;t go bald—just use this:<br />
<a href="http://colorschemedesigner.com/">http://colorschemedesigner.com/</a></p>
<p>Matthias Shapiro talking about effective visualization with some very concrete and awesome examples—it&#8217;s an Ignite Show video, so it&#8217;s five minutes long, which is about the longest video I&#8217;ll watch before I start wishing I had my computer hooked up to my TV:<br />
<a href="http://www.designerwpf.com/2009/09/16/now-playing-on-the-ignite-show/">http://www.designerwpf.com/2009/09/16/now-playing-on-the-ignite-show/</a></p>
<p>Another interesting visualization by Ben Fry—living in this country is often defined by driving, so I shouldn&#8217;t be so surprised that roads alone do such a remarkable job punctuating the landscape:<br />
<a href="http://benfry.com/allstreets/index.html">http://benfry.com/allstreets/index.html</a></p>
<p>I&#8217;m always a sucker for a good how&#8217;d-they-done-it story: The making of the NPR News iPhone App, complete with mockups, requirements identification and gathering—all that good process-y stuff:<br />
<a href="http://www.npr.org/blogs/inside/2009/08/the_making_of_the_npr_news_iph.html">http://www.npr.org/blogs/inside/2009/08/the_making_of_the_npr_news_iph.html</a></p>
<p>If you&#8217;re working on building iPhone applications and you want to generate super-realistic pictures of what your app will look like before you even install the Developer Tools:<br />
<a href="http://mockapp.com/">http://mockapp.com/</a></p>
<p>Another UI mocking tool for iPhone apps, but you&#8217;ll have to write a little code<br />
<a href="http://giveabrief.com/">http://giveabrief.com/</a></p>
<p>—DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/09/27/links-oclock-2009-09-25/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More 2D/3D Tricks: ItemsControl3D</title>
		<link>http://pelebyte.net/blog/2009/09/22/more-2d3d-tricks-itemscontrol3d/</link>
		<comments>http://pelebyte.net/blog/2009/09/22/more-2d3d-tricks-itemscontrol3d/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 02:34:34 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ItemsControl]]></category>
		<category><![CDATA[ItemsControl3D]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[Viewport3D]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=90</guid>
		<description><![CDATA[Building on some of the cute tricks of using a Viewport3D as a two-dimensional surface, we can actually devise a fully-bindable System.Windows.Controls.ItemsControl that renders to a Viewport3D instead of a Panel. It turns out to all be quite remarkably simple: Define a class, ItemsControl3D, that will be our magic Viewport3D-holding ItemsControl. Build a ControlTemplate that [...]]]></description>
			<content:encoded><![CDATA[<p>Building on some of the <a href="http://pelebyte.net/blog/2009/09/11/2d-in-a-wpf-3d-world/">cute tricks</a> of using a Viewport3D as a two-dimensional surface, we can actually devise a fully-bindable <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">System.Windows.Controls.ItemsControl</a> that renders to a Viewport3D instead of a Panel. It turns out to all be quite remarkably simple:</p>
<ol>
<li>Define a class, ItemsControl3D, that will be our magic Viewport3D-holding ItemsControl.</li>
<li>Build a ControlTemplate that contains a Viewport3D with a named ModelVisual3D whose children will be modified as the ItemsControl sees fit.</li>
<li>Override <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.getcontainerforitemoverride.aspx">GetContainerForItemOverride()</a> to provide instances of <font face="monospace">ItemsControl3DItem</font> as the &#8220;container&#8221; for the individual items in the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">ItemsControl</a>:
<ol>
<li>Make the &#8220;container&#8221; item a zero-size, completely non-visible <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx">FrameworkElement</a>.</li>
<li>Create an ItemsControl3DItem.Geometry property; this Geometry3D object will be used to populate the ModelVisual3D in our Viewport3D.</li>
</ol>
<li>I additionally chose to implement <i>container recycling</i> (in some early drafts of ItemsControl3D, it cut processor usage down 25%).</li>
</ol>
<p>First, the static constructor:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">static</span> ItemsControl3D<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    DefaultStyleKeyProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">OverrideMetadata</span><span style="color: #008000;">&#40;</span>
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ItemsControl3D<span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">new</span> FrameworkPropertyMetadata<span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ItemsControl3D<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    ItemsPanelProperty<span style="color: #008000;">.</span><span style="color: #0000FF;">OverrideMetadata</span><span style="color: #008000;">&#40;</span>
        <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ItemsControl3D<span style="color: #008000;">&#41;</span>,
        <span style="color: #008000;">new</span> FrameworkPropertyMetadata<span style="color: #008000;">&#40;</span>
            <span style="color: #008000;">new</span> ItemsPanelTemplate<span style="color: #008000;">&#40;</span>
                <span style="color: #008000;">new</span> FrameworkElementFactory<span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ItemsControl3D<span style="color: #008000;">.</span><span style="color: #0000FF;">ItemsPanel</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>The first line should be familiar to those in the audience who have authored custom controls before; it merely indicates that somewhere, WPF should expect to find:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">&lt;b<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Style x:Key=&quot;{x:Type ThreeDee:ItemsControl3D}&quot;<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/b<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        TargetType=&quot;{x:Type ThreeDee:ItemsControl3D}&quot;&gt;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Template&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ControlTemplate</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type ThreeDee:ItemsControl3D}&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;Grid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Viewport3D</span> <span style="color: #000066;">Name</span>=<span style="color: #ff0000;">&quot;PART_Viewport&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Viewport3D.Camera<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;OrthographicCamera</span></span>
<span style="color: #009900;">                         <span style="color: #000066;">Position</span>=<span style="color: #ff0000;">&quot;0,0,1&quot;</span> <span style="color: #000066;">LookDirection</span>=<span style="color: #ff0000;">&quot;0,0,-1&quot;</span> <span style="color: #000066;">UpDirection</span>=<span style="color: #ff0000;">&quot;0,1,0&quot;</span></span>
<span style="color: #009900;">                         <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;{Binding Path=ActualWidth, ElementName=PART_Viewport}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Viewport3D.Camera<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;AmbientLight</span> <span style="color: #000066;">Color</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;/ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
              <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;PART_SceneRoot&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Viewport3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsPresenter</span><span style="color: #000000; font-weight: bold;">/&gt;</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;/Border<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ControlTemplate<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter.Value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Setter<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>The line after that (the overriding of the ItemsPanel metadata) indicates that for all ItemsControl3D, the default Panel presenting children for the panel should be ItemsControl3D.ItemsPanel. This is an inner class that we&#8217;ve defined that is specially crafted to hold the child elements of the ItemsControl.</p>
<p>In the style, we&#8217;ve given one of the ModelVisual3D children a name (PART_SceneRoot); that&#8217;s because in OnApplyTemplate(), we&#8217;re going to look for it and use that as the place to hold the 3D objects that we generate.</p>
<p>We override a trio of methods in order to perform basic container housekeeping. GetContainerForItemOverride() either creates a new container or reuses an existing one; ClearContainerForItemOverride(&#8230;) adds an unused ItemsControl3DItem back to the pool; IsItemsItsOwnContainerOverride(&#8230;) is useful to override if you wanted to manually create and add ItemsControl3DItem objects to the ItemsControl3D.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> Stack<span style="color: #008000;">&lt;</span>ItemsControl3DItem<span style="color: #008000;">&gt;</span> _unusedContainers <span style="color: #008000;">=</span>
        <span style="color: #008000;">new</span> Stack<span style="color: #008000;">&lt;</span>ItemsControl3DItem<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> DependencyObject GetContainerForItemOverride<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>_unusedContainers<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> ItemsControl3DItem<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> _unusedContainers<span style="color: #008000;">.</span><span style="color: #0000FF;">Pop</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> ClearContainerForItemOverride<span style="color: #008000;">&#40;</span>
    DependencyObject element, <span style="color: #6666cc; font-weight: bold;">object</span> item<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    _unusedContainers<span style="color: #008000;">.</span><span style="color: #0000FF;">Push</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>ItemsControl3DItem<span style="color: #008000;">&#41;</span>element<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsItemItsOwnContainerOverride<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span> item<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>item <span style="color: #008000;">is</span> ItemsControl3DItem<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Lastly, the actual &#8220;panel&#8221; that the ItemsControl thinks is doing the work:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #008000;">new</span> <span style="color: #0600FF; font-weight: bold;">sealed</span> <span style="color: #6666cc; font-weight: bold;">class</span> ItemsPanel <span style="color: #008000;">:</span> Panel
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> Size MeasureOverride<span style="color: #008000;">&#40;</span>Size availableSize<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        var ic3d <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>ItemsControl3D<span style="color: #008000;">&#41;</span>GetItemsOwner<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>ic3d <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #008000;">&lt;</span>b<span style="color: #008000;">&gt;</span>ic3d<span style="color: #008000;">.</span><span style="color: #0000FF;">UpdateViewportChildren</span><span style="color: #008000;">&#40;</span>InternalChildren<span style="color: #008000;">&#41;</span><span style="color: #008000;">;&lt;/</span>b<span style="color: #008000;">&gt;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> Size<span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>And that&#8217;s all the panel needs to do. The magic method call is actually the property accessor <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.panel.internalchildren.aspx"><font face="monospace">Panel.InternalChildren</font></a>—internal code in <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.panel.aspx">Panel</a> works together with <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">ItemsControl</a> in order to derive the appropriate children (this is ultimately what will cause <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.getcontainerforitemoverride.aspx">GetContainerForItemOverride()</a> and other methods to be called).</p>
<p>Lastly, the private method UpdateViewportChildren in ItemsControl3D:</p>
<pre>private void UpdateViewportChildren(UIElementCollection children)
{
    if (_sceneRoot == null) return;

    _sceneRoot.Children.Clear();
    foreach (ItemsControl3DItem item in children)
    {
        var m = item.Model;
        if (m != null)
        {
            _sceneRoot.Children.Add(m);
        }
    }
}</pre>
<p>And in case you were wondering, ItemsControl3DItem at a high level:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ItemsControl3DItem <span style="color: #008000;">:</span> FrameworkElement
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> X <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">double</span> Y <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Brush Background <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> Geometry3D Geometry <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> ModelVisual3D Model <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>The properties of <font face="monospace">ItemsControl3DItem</font> (X, Y, Background, Geometry) are all used to determine the Model property.</p>
<p>You can use an <font face="monospace">ItemsControl3D</font> in XAML as easily as any other subclass of <font face="monospace">ItemsControl</font>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ThreeDee:ItemsControl3D</span> <span style="color: #000066;">ItemsSource</span>=<span style="color: #ff0000;">&quot;{Binding ...}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ItemsControl.ItemContainerStyle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Style</span> <span style="color: #000066;">TargetType</span>=<span style="color: #ff0000;">&quot;{x:Type ThreeDee:ItemsControl3DItem}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;X&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Year}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Y&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;{Binding Profit}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Setter</span> <span style="color: #000066;">Property</span>=<span style="color: #ff0000;">&quot;Background&quot;</span> <span style="color: #000066;">Value</span>=<span style="color: #ff0000;">&quot;Blue&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Style<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ItemsControl.ItemContainerStyle<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #808080; font-style: italic;">&lt;!-- you could also hardcode children in the control just like </span>
<span style="color: #808080; font-style: italic;">         ListBoxItems in a ListBox or ListViewItems in a ListView --&gt;</span>
    <span style="color: #808080; font-style: italic;">&lt;!-- &lt;font color=&quot;#555555&quot;&gt;&lt;ThreeDee:ItemsControl3DItem X=&quot;5&quot; Y=&quot;6&quot; Background=&quot;Blue&quot;/&gt;</span>
<span style="color: #808080; font-style: italic;">         &lt;ThreeDee:ItemsControl3DItem X=&quot;2&quot; Y=&quot;3&quot; Background=&quot;Red&quot;/&gt;&lt;/font&gt; --&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ThreeDee:ItemsControl3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>It should be noted that this exact technique can be used to generate full-blown three-dimensional visualizations with nothing more than basic ItemsControl-style bindings. Coupled with an abstract data model, you&#8217;ve got yourself a pretty canvas to paint with, and it&#8217;s pretty responsive to updates as well and doesn&#8217;t blow a hole through your CPU either. The sample app updates all of the values in a collection of 1,000 points, ten times a second, while using less than 10% of my two-year-old MacBook&#8217;s CPU.</p>
<p>The Sample Code: <a href="http://pelebyte.net/downloads/ItemsControl3D.zip">ItemsControl3D.zip</a></p>
<p>—DKT</p>
<p><font size="-1">Sept 24: Fixed the problems with the download. Of course, since the AssemblyInfo.cs file was missing, the <font face="monospace">[assembly:ThemeInfo(ResourceDictionaryLocation.SourceAssembly)]</font> tag was missing too—that caused the default template that I defined for ItemsControl3D to not be found. This is fixed now.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/09/22/more-2d3d-tricks-itemscontrol3d/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>2D in a WPF 3D World</title>
		<link>http://pelebyte.net/blog/2009/09/11/2d-in-a-wpf-3d-world/</link>
		<comments>http://pelebyte.net/blog/2009/09/11/2d-in-a-wpf-3d-world/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 12:31:08 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[Viewport3D]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=77</guid>
		<description><![CDATA[It&#8217;s a fairly common and standard trick to take advantage of the hardware acceleration afforded by modern graphic cards and render two-dimensional figures in 3D. Here is a simple and fast way to take the 3D out of a Viewport3D: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s a fairly common and standard trick to take advantage of the hardware acceleration afforded by modern graphic cards and render two-dimensional figures in 3D. Here is a simple and fast way to take the 3D out of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.viewport3d.aspx">Viewport3D</a>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Viewport3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Viewport3D.Camera<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;OrthographicCamera</span> <span style="color: #000066;">Position</span>=<span style="color: #ff0000;">&quot;0,0,1&quot;</span> <span style="color: #000066;">LookDirection</span>=<span style="color: #ff0000;">&quot;0,0,-1&quot;</span> <span style="color: #000066;">UpDirection</span>=<span style="color: #ff0000;">&quot;0,1,0&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">Width</span>=<span style="color: #ff0000;">&quot;{Binding ActualWidth}&quot;</span> <span style="color: #000066;">Height</span>=<span style="color: #ff0000;">&quot;{Binding ActualHeight}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Viewport3D.Camera<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D.Children<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #808080; font-style: italic;">&lt;!-- render colors...relatively properly --&gt;</span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;AmbientLight</span> <span style="color: #000066;">Color</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;/ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D</span> <span style="color: #000066;">x:Name</span>=<span style="color: #ff0000;">&quot;SceneRoot&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
          <span style="color: #808080; font-style: italic;">&lt;!-- this is where stuff you want to render actually goes --&gt;</span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D.Content<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D.Children<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ModelVisual3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Viewport3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>When the camera is set up this way, the center of the Viewport3D represents (0,0). The <strong>bottom-left</strong> is (−width / 2, −height / 2) and the <strong>top-right</strong> is (+width / 2, +height / 2).</p>
<p>Now what can you put in something like this? Same thing you&#8217;d normally put in a <font face="monospace">Viewport3D</font>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Model3DGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;GeometryModel3D</span> <span style="color: #000066;">Geometry</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;GeometryModel3D.Material<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;DiffuseMaterial</span> <span style="color: #000066;">Brush</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/GeometryModel3D.Material<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/GeometryModel3D<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Model3DGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.media3d.diffusematerial.brush.aspx"><font face="monospace">Brush</font></a> property can be any old <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.brush.aspx"><font face="monospace">System.Windows.Media.Brush</font></a>. And as for that <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.media3d.geometrymodel3d.geometry.aspx"><font face="monospace">Geometry</font></a>? Well, there are squares:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MeshGeometry3D</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;Square&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                Positions=&quot;-1,-1,0  1,-1,0  1,1,0  -1,1,0&quot;
                Normals=&quot;0,0,1  0,0,1  0,0,1  0,0,1&quot;
                TriangleIndices=&quot;0 1 2 0 2 3&quot;/&gt;</pre></td></tr></table></div>

<p>isosceles triangles:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MeshGeometry3D</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;IsoscelesTriangle&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                Positions=&quot;-1,-1,0  1,-1,0  0,1,0&quot;
                Normals=&quot;0,0,1  0,0,1  0,0,1&quot;
                TriangleIndices=&quot;0 1 2&quot;/&gt;</pre></td></tr></table></div>

<p>Coming up with these little nuggets of numbers is the topic of another post. But for now, some sample code:</p>
<div style="text-align:center;"><img src="http://pelebyte.net/blog/wp-content/uploads/2009/09/ThreeDee.png" alt="ThreeDee.png" border="0" width="592" height="438" /></div>
<p>Featuring basic hit-detection and a bit of interactivity (you can drag a square to increase/decrease the space between boxes, and change the angle of rotation). It&#8217;s <em>pure</em> WPF (no unsafe code or interop), it&#8217;s 2D, and it&#8217;s fast.</p>
<p><a href="http://pelebyte.net/downloads/ThreeDee.zip">ThreeDee.zip</a></p>
<p>—DKT</p>
<p><font size="-1">Sorry the code formatting is off&#8230;the iPhone WordPress client totally destroyed it. I&#8217;ll fix it soonish.</font></p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/09/11/2d-in-a-wpf-3d-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uniqueness of Simple Demographics in the U.S. Population [Link]</title>
		<link>http://pelebyte.net/blog/2009/09/09/uniqueness-of-simple-demographics-in-the-u-s-population-link/</link>
		<comments>http://pelebyte.net/blog/2009/09/09/uniqueness-of-simple-demographics-in-the-u-s-population-link/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 02:44:44 +0000</pubDate>
		<dc:creator>dkt</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[technology]]></category>

		<guid isPermaLink="false">http://pelebyte.net/blog/?p=75</guid>
		<description><![CDATA[Sometimes, math and statistics makes me sad: &#8220;It was found that 87% (216 million of 248 million) of the population in the United States had reported characteristics that likely made them unique based only on {5-digit ZIP, gender, date of birth}. About half of the U.S. population (132 million of 248 million or 53%) are [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, math and statistics makes me sad:</p>
<blockquote><p>
&#8220;It was found that 87% (216 million of 248 million) of the population in the United States had reported characteristics that likely made them unique based only on {5-digit ZIP, gender, date of birth}. About half of the U.S. population (132 million of 248 million or 53%) are likely to be uniquely identified by only {place, gender, date of birth}, where place is basically the city, town, or municipality in which the person resides. And even at the county level, {county, gender, date of birth} are likely to uniquely identify 18% of the U.S. population. In general, few characteristics are needed to uniquely identify a person.&#8221;</p></blockquote>
<p>It&#8217;s quite terrifying to know that such a birthdate, a zip code, and a gender could potentially pass as a unique identifier for someone with the vast and overreaching &#8220;anonymized&#8221; databases that exist out there.</p>
<p><a href="http://privacy.cs.cmu.edu/dataprivacy/papers/LIDAP-WP4abstract.html"></p>
<p>http://privacy.cs.cmu.edu/dataprivacy/papers/LIDAP-WP4abstract.html</a></p>
<p><a href="http://arstechnica.com/tech-policy/news/2009/09/your-secrets-live-online-in-databases-of-ruin.ars">http://arstechnica.com/tech-policy/news/2009/09/your-secrets-live-online-in-databases-of-ruin.ars</a></p>
<p>—DKT</p>
]]></content:encoded>
			<wfw:commentRss>http://pelebyte.net/blog/2009/09/09/uniqueness-of-simple-demographics-in-the-u-s-population-link/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

