<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Critical Development</title>
	<atom:link href="http://dvanderboom.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dvanderboom.wordpress.com</link>
	<description>Enterprise modeling, design, development, languages, and tools.</description>
	<lastBuildDate>Fri, 30 Oct 2009 17:23:26 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='dvanderboom.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/15be7b591206057633412f45bc63b180?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Critical Development</title>
		<link>http://dvanderboom.wordpress.com</link>
	</image>
			<item>
		<title>Phidgets Robotics Project &#8211; Source Code Posted</title>
		<link>http://dvanderboom.wordpress.com/2009/10/30/phidgets-robotics-project-source-code-posted/</link>
		<comments>http://dvanderboom.wordpress.com/2009/10/30/phidgets-robotics-project-source-code-posted/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 17:22:57 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/10/30/phidgets-robotics-project-source-code-posted/</guid>
		<description><![CDATA[By request, I’ve made available the source code to my Wii remote controlled pan-tilt camera system using Phidgets components.&#160; See my original article here.
Warning: It’s messy in there.&#160; Don’t look to this as a good example of how robotics applications should be developed.&#160; There are far better patterns and libraries to use.&#160; This was merely [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=644&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font size="2">By request, I’ve made available the </font><a href="http://danvanderboom.com/Examples/PanTiltCameraSystem.zip"><font size="2">source code</font></a><font size="2"> to my Wii remote controlled pan-tilt camera system using Phidgets components.&#160; See my </font><a href="http://dvanderboom.wordpress.com/2008/04/21/phidgets-robotics-programming-in-c/"><font size="2">original article here</font></a><font size="2">.</font></p>
<p><font size="2">Warning: It’s messy in there.&#160; Don’t look to this as a good example of how robotics applications should be developed.&#160; There are far better patterns and libraries to use.&#160; This was merely my “get it up and running as quickly as possible” approach, to prove out the concept of getting all of the components to work together correctly.</font></p>
<p><font size="2">Enjoy!</font></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/644/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/644/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/644/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=644&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/10/30/phidgets-robotics-project-source-code-posted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>The Wonders of Aruba</title>
		<link>http://dvanderboom.wordpress.com/2009/09/22/the-wonders-of-aruba/</link>
		<comments>http://dvanderboom.wordpress.com/2009/09/22/the-wonders-of-aruba/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 01:25:42 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Aruba]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/09/22/the-wonders-of-aruba/</guid>
		<description><![CDATA[&#160; 
This morning, after being awoken at 5:30am by a rooster living nearby, I went for a walk to the northern tip of the island where beautiful homes are surrounded by lush tropical flowers and various palm trees, ferns, and cacti.&#160; Clouds with serious character muddied the early morning sky, and large birds hovered playfully [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=618&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0000708.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 00 07-08" border="0" alt="Untitled 0 00 07-08" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0000708_thumb.jpg?w=644&#038;h=364" width="644" height="364" /></a>&#160; </p>
<p><font size="2">This morning, after being awoken at 5:30am by a rooster living nearby, I went for a walk to the northern tip of the island where beautiful homes are surrounded by lush tropical flowers and various palm trees, ferns, and cacti.&#160; Clouds with serious character muddied the early morning sky, and large birds hovered playfully in the air above the beautiful homes on J. E. Irasquin Blvd—not covering any ground, simply enjoying the feeling of the strong ocean wind, gliding without effort or purpose, hovering in place just above the tallest trees.</font></p>
<p><font size="2">It’s surprising to me that humans consider such aimless delight a luxury.&#160; I’m in Aruba for the month September in part because I disagree; I think from time to time, it’s an absolute necessity to stay sane and keep a healthy perspective and sense of balance.&#160; When so many of our moments are goal-directed and serious, and as Americans we have less time off work than virtually every country on Earth, it’s only a matter of time before the intelligence of our own bodies revolts against us in protest, a petition against the undue stress and unrealistic expectations we often have of ourselves.</font></p>
<p><font size="2">An hour later, I was following the winding road past </font><a href="http://www.threebestbeaches.com/centralamcarib/aruba/2005/10/arashi-beach-aruba.html"><font size="2">Arushi beach</font></a><font size="2">, onto the part of Aruba that isn’t polluted much by light at night, where you can see thousands of stars and galaxies and the colorful dust of the Milky Way.&#160; The road curves back and forth several times and climbs steeply toward the </font><a href="http://www.aruba.com/OurPeoplePlaces/Attractions/California_Lightheouse.aspx"><font size="2">California Lighthouse</font></a><font size="2"> where I normally turn around and head back.&#160; Except today, to my surprise, I came across a herd of goats!</font></p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0003625.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 00 36-25" border="0" alt="Untitled 0 00 36-25" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0003625_thumb.jpg?w=644&#038;h=364" width="644" height="364" /></a> </p>
<p><font size="2">I first spotted them on the road and let them cross in front of me.&#160; A baby lagged behind, and I followed as closely as possible to get some better pictures.&#160; When I got within 20 feet, the little one bolted ahead, sprinting over ground that was treacherously uneven volcanic rock.&#160; The goats didn’t seem to have any problem running over this terrain, however, nor did they seem to mind me following them around for a half hour.&#160; Here you can see the little one in mid stride of a dashing pace, and notice how well it blends in with the ground’s color.&#160; I also enjoy seeing all the lizards here.&#160; I’ve seen several kinds and most of them are small, but this large one was hanging out at the Raddisson hotel by the pool.</font></p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0011304.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 01 13-04" border="0" alt="Untitled 0 01 13-04" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0011304_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0003627.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 00 36-27" border="0" alt="Untitled 0 00 36-27" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0003627_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a></p>
<p><font size="2">I had the pleasure of going to a huge DJ party called something like Maj 4 Stix.&#160; The DJ rig was enormous, with thick outdoor smoke effects, blasts of fire and bright lights of every color, and thumping dance music.&#160; There were acrobats running in translucent plastic balls in the water that surrounded the dance stage like a moat, and hundreds of people dancing to really great music.</font></p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0051321.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 05 13-21" border="0" alt="Untitled 0 05 13-21" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0051321_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0004319.jpg"><img style="display:inline;border-width:0;" title="Untitled 0 00 43-19" border="0" alt="Untitled 0 00 43-19" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0004319_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a> </p>
<p><font size="2">Every few days, I head to Oranjestad to work: the capital of Aruba.&#160; The best shopping seems to be there, since that’s where the cruise ships stop.&#160; The pictures below are of a shopping area in Oranjestad, and a church and graveyard in Noord where many people are buried in elaborate above-ground stone tombs.</font></p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0000622.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="Untitled 0 00 06-22" border="0" alt="Untitled 0 00 06-22" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0000622_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/untitled0000624.jpg"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="Untitled 0 00 06-24" border="0" alt="Untitled 0 00 06-24" src="http://dvanderboom.files.wordpress.com/2009/09/untitled0000624_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a> </p>
<p><font size="2">Finally, here are two pictures of me: one in front of the rock waterfalls at the Raddisson Hotel from a video I made to wish my niece Ava a happy birthday, and a fun picture of me at Confession Club in Palm Beach.</font></p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/happybirthdayavatrimmed0000001.jpg"><img style="display:inline;border-width:0;" title="Happy Birthday Ava - Trimmed 0 00 00-01" border="0" alt="Happy Birthday Ava - Trimmed 0 00 00-01" src="http://dvanderboom.files.wordpress.com/2009/09/happybirthdayavatrimmed0000001_thumb.jpg?w=404&#038;h=229" width="404" height="229" /></a><a href="http://dvanderboom.files.wordpress.com/2009/09/reddan.png"><img style="display:inline;border-width:0;" title="RedDan" border="0" alt="RedDan" src="http://dvanderboom.files.wordpress.com/2009/09/reddan_thumb.png?w=221&#038;h=229" width="221" height="229" /></a></p>
</p>
</p>
</p>
</p>
</p>
<p><font size="2">I’ve hiked through the unpopulated countryside of Aruba; I’ve gone to the big parties and night clubs, spent a lot of time tanning on the beaches, enjoyed Dutch food (<a href="http://rembrandtaruba.com/">Cafe Rembrandt</a> is my favorite), and went on a Jeep tour (through <a href="http://www.abc-aruba.com/">ABC Tours</a>) to the natural pools, the gold mine buildings, and the old Indian-painted caves; and somehow have still managed to be very productive writing software for my current client as well as some personal projects I have in the works.&#160; I don’t often give advice, but I would definitely recommend enjoying life as much as possible while it lasts.&#160; Travel, work remotely, start a business, or do whatever makes sense in your life to follow your dreams, but don’t wait to do it!</font></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/618/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/618/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/618/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/618/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/618/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=618&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/09/22/the-wonders-of-aruba/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0000708_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 07-08</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0003625_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 36-25</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0011304_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 01 13-04</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0003627_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 36-27</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0051321_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 05 13-21</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0004319_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 43-19</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0000622_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 06-22</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/untitled0000624_thumb.jpg" medium="image">
			<media:title type="html">Untitled 0 00 06-24</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/happybirthdayavatrimmed0000001_thumb.jpg" medium="image">
			<media:title type="html">Happy Birthday Ava - Trimmed 0 00 00-01</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/reddan_thumb.png" medium="image">
			<media:title type="html">RedDan</media:title>
		</media:content>
	</item>
		<item>
		<title>Filtering with Metadata in the Managed Extensibility Framework</title>
		<link>http://dvanderboom.wordpress.com/2009/09/19/filtering-with-metadata-in-the-managed-extensibility-framework/</link>
		<comments>http://dvanderboom.wordpress.com/2009/09/19/filtering-with-metadata-in-the-managed-extensibility-framework/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 20:19:43 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Component Based Engineering]]></category>
		<category><![CDATA[Composability]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Visual Studio Extensibility]]></category>
		<category><![CDATA[AddIn API]]></category>
		<category><![CDATA[filtering]]></category>
		<category><![CDATA[Managed Extensibility Framework]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[System.AddIn]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/09/19/filtering-with-metadata-in-the-managed-extensibility-framework/</guid>
		<description><![CDATA[The Managed Extensibility Framework (MEF) is the new extensibility framework from Microsoft.&#160; Pioneered by Glenn Block in the patterns &#38; practices group, and leveraged by the behemoth Visual Studio 2010, it has a striking resemblance to my own Inversion of Control (IoC) and Dependency Injection (DI) framework—which led to me to have a couple great [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=591&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font size="2">The </font><a href="http://mef.codeplex.com/"><font size="2">Managed Extensibility Framework</font></a><font size="2"> (MEF) is the new extensibility framework from Microsoft.&#160; Pioneered by </font><a href="http://blogs.msdn.com/gblock/"><font size="2">Glenn Block</font></a><font size="2"> in the </font><a href="http://msdn.microsoft.com/en-us/practices/default.aspx"><font size="2">patterns &amp; practices</font></a><font size="2"> group, and leveraged by the behemoth Visual Studio 2010, it has a striking resemblance to my own </font><a href="http://en.wikipedia.org/wiki/Inversion_of_control"><font size="2">Inversion of Control</font></a><font size="2"> (IoC) and </font><a href="http://en.wikipedia.org/wiki/Dependency_injection"><font size="2">Dependency Injection</font></a><font size="2"> (DI) framework—which led to me to have a couple great conversations about IoC with Glenn at Tech Ed 2008 and then again at PDC 2008.</font></p>
<p><font size="2">But MEF isn’t really written to be your IoC.&#160; Instead, the IoC engine and DI aspects are implementation details, allowing you to do really no more than “MEF things together”.&#160; The core concept of MEF is to provide very simple and powerful application composability.&#160; Not in the user interface composition sense—for that, see </font><a href="http://compositewpf.codeplex.com/"><font size="2">Prism</font></a><font size="2"> for WPF and Silverlight (explained in </font><a href="http://msdn.microsoft.com/en-us/magazine/cc785479.aspx"><font size="2">MSDN Magazine, September 2008</font></a><font size="2">)—but for virtually all other dynamic component assembly needs, MEF is your best friend.</font></p>
<p><font size="2">The two things I like most about MEF is its <strong>simplicity</strong> as its<strong> lack of presumption</strong> on how it will be used.&#160; Compose collections of strings, single method delegates, or implementations of complex services.&#160; All you’re doing is importing and exporting things, with little code required to wire things up.</font></p>
<p><font size="2">MEF is currently in its seventh preview release, so expect beta-like quality.&#160; My own experience with it has been very positive, but there are a number of shortcomings in the API.&#160; This article is about a few of them and what can be done to add some much-needed functionality.</font></p>
<h3>System.AddIn vs. MEF</h3>
<p><font size="2">There’s been some confusion with Microsoft <em>coopetition</em> among products with similar aims, and extensibility and composition are no exception.&#160; The AddIn API (</font><a href="http://blogs.msdn.com/clraddins/"><font size="2">team blog</font></a><font size="2">) serves a similar purpose as MEF.&#160; (See this two-part MSDN article on System.AddIn: </font><a href="http://msdn.microsoft.com/en-us/magazine/cc163476.aspx"><font size="2">first</font></a><font size="2"> and </font><a href="http://msdn.microsoft.com/en-us/magazine/cc163460.aspx"><font size="2">second</font></a><font size="2">.)&#160; The primary differentiator, from my understanding, is that the AddIn API is a bit more robust and a lot more complicated, and supports such things as isolating extensions in separate AppDomains.</font></p>
<p><font size="2">With Visual Studio siding with MEF, it’s personally hard for me to imagine using the AddIn API.&#160; If MEF is flexible and robust enough for Visual Studio, is it really likely to fall short for my own much smaller software systems?&#160; </font><a href="http://blogs.msdn.com/kcwalina/archive/2008/06/13/MAFMEF.aspx"><font size="2">Krzysztof Cwalina suggests</font></a><font size="2"> they are complementary approaches, but I find that hard to swallow.&#160; Why would I want to use two different extensibility frameworks instead of one coherent API?&#160; If anything, I imagine that the lessons learned from the AddIn API will eventually migrate to MEF.</font></p>
<p><a href="http://www.danielmoth.com/Blog/2007/03/systemaddin.html"><font size="2">Daniel Moth notes</font></a><font size="2"> that with the AddIn API, “there are many design decisions to make and quite a few subtleties in implementing those decisions in particular when it comes to discovering addins, version resiliency, isolation from the host etc.”&#160; A customer of mine using the AddIn API was using a Visual Studio plug-in to manage pipelines, and things were a real mess.&#160; There were a bunch of assemblies, a lot of generated code, and not much clarity or confidence that it was all really necessary.</font></p>
<h3>MEF: Import &amp; ImportMany</h3>
<p><font size="2">In MEF, the Import attribute allows you to inject a value that is exported somewhere else using the Export attribute—typically from another assembly.&#160; There is also an ImportMany attribute which is useful when you expect several exports that use the same contract.&#160; By defining an IEnumerable&lt;T&gt; field or property and decorating it with the ImportMany attribute, all matching exports will be added to an enumerable type.</font></p>
<pre class="code"><font size="2">[<span style="color:#2b91af;">ImportMany</span>]
<span style="color:blue;">public </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">IVehicle</span>&gt; Vehicles;</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">What if you want to filter the exported vehicle types by some kind of metadata, though?&#160; Let’s take a look at the IVehicle contract and some concrete classes that implement the contract.</font></p>
<pre class="code"><font size="2"><span style="color:blue;">public interface </span><span style="color:#2b91af;">IVehicle </span>{ }

[<span style="color:#2b91af;">Export</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IVehicle</span>))]
[<span style="color:#2b91af;">ExportMetadata</span>(<span style="color:#a31515;">&quot;Speed&quot;</span>, <span style="color:#a31515;">&quot;Slow&quot;</span>)]
<span style="color:blue;">public class </span><span style="color:#2b91af;">ToyotaPrius </span>: </font><font size="2"><span style="color:#2b91af;">IVehicle
</span>{
    <span style="color:blue;">public </span>ToyotaPrius() { }
}

[<span style="color:#2b91af;">Export</span>(<span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IVehicle</span>))]
[<span style="color:#2b91af;">ExportMetadata</span>(<span style="color:#a31515;">&quot;Speed&quot;</span>, <span style="color:#a31515;">&quot;Fast&quot;</span>)]
<span style="color:blue;">public class </span><span style="color:#2b91af;">LamborghiniDiablo </span>: </font><font size="2"><span style="color:#2b91af;">IVehicle
</span>{
    <span style="color:blue;">public </span>LamborghiniDiablo() { }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">The object model isn’t very interesting, but that’s not the point.&#160; What is interesting is that MEF allows us to supply metadata corresponding to our exports.&#160; In this case, my contrived example has defined a metadata variable of “Speed”, with two possible values: “Fast” and “Slow”.&#160; The variable name must be a string, but its value can be any value; that is, any value that’s supported from within an attribute, which means string literals and constants, type objects, and the like.</font></p>
<h3>Filtering Imports on Metadata</h3>
<p><font size="2">What if you want to ImportMany for all exports that have a particular metadata value?&#160; Unfortunately, there are no such options in the ImportMany attribute class.</font></p>
<p><font size="2">In my scenario, I’ve defined a static factory class called VehicleFactory, which at some imaginary point in the future will be responsible for building a city full of trafic.</font></p>
<pre class="code"><span style="color:blue;"><font size="2">public static class </font></span><font size="2"><span style="color:#2b91af;">TrafficFactory
</span>{
    </font><font size="2"><span style="color:green;">// type initialization fails without a static constructor
    </span><span style="color:blue;">static </span>TrafficFactory() { }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">IVehicle</span>&gt; SlowVehicles =
        <span style="color:#2b91af;">App</span>.Container.GetExportedValues&lt;<span style="color:#2b91af;">IVehicle</span>&gt;(metadata =&gt; metadata.ContainsKeyWithValue(<span style="color:#a31515;">&quot;Speed&quot;</span>, <span style="color:#a31515;">&quot;Slow&quot;</span>));

    <span style="color:blue;">public static </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">IVehicle</span>&gt; FastVehicles =
        <span style="color:#2b91af;">App</span>.Container.GetExportedValues&lt;<span style="color:#2b91af;">IVehicle</span>&gt;(metadata =&gt; metadata.ContainsKeyWithValue(<span style="color:#a31515;">&quot;Speed&quot;</span>, <span style="color:#a31515;">&quot;Fast&quot;</span>));

    <span style="color:blue;">public static </span><span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">IVehicle</span>&gt; AllVehicles =
        <span style="color:#2b91af;">App</span>.Container.GetKeyedExportedValues&lt;<span style="color:#2b91af;">IVehicle</span>&gt;(<span style="color:#a31515;">&quot;Speed&quot;</span>);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">This is what I want to do, but there is no overload of GetExportedValues that supplies a metadata-dependent predicate function.&#160; Adding one is easy, though.&#160; While we’re at it, we’ll also add the ContainsKeyWithValue which I borrow from <a href="http://www.thecodejunkie.com/2009/02/creating-mef-composition-container-with.html">The Code Junky article</a> also on MEF container filtering.</font></p>
<pre class="code"><span style="color:blue;"><font size="2">public static class </font></span><font size="2"><span style="color:#2b91af;">IDictionaryExtensions
</span>{
    <span style="color:blue;">public static bool </span>ContainsKeyWithValue&lt;KeyType, KeyValue&gt;(
        <span style="color:blue;">this </span><span style="color:#2b91af;">IDictionary</span>&lt;KeyType, <span style="color:#2b91af;">ValueType</span>&gt; Dictionary,
        KeyType Key, <span style="color:#2b91af;">ValueType </span>Value)
    {
        <span style="color:blue;">return </span>(Dictionary.ContainsKey(Key) &amp;&amp; Dictionary[Key].Equals(Value));
    }
}

<span style="color:blue;">public static class </span></font><font size="2"><span style="color:#2b91af;">MEFExtensions
</span>{
    <span style="color:blue;">public static </span><span style="color:#2b91af;">IEnumerable</span>&lt;T&gt; GetExportedValues&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">CompositionContainer </span>Container,
        <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt;, <span style="color:blue;">bool</span>&gt; Predicate)
    {
        <span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;T&gt;();

        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>PartDef <span style="color:blue;">in </span>Container.Catalog.Parts)
        {
            <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>ExportDef <span style="color:blue;">in </span>PartDef.ExportDefinitions)
            {
                <span style="color:blue;">if </span>(ExportDef.ContractName == <span style="color:blue;">typeof</span>(T).FullName)
                {
                    <span style="color:blue;">if </span>(Predicate(ExportDef.Metadata))
                        result.Add((T)PartDef.CreatePart().GetExportedValue(ExportDef));
                }
            }
        }

        <span style="color:blue;">return </span>result;
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">Now we can test this logic by wiring up MEF and then accessing the two filtered collections of cars, which will each contain a single IVehicle instance.</font></p>
<pre class="code"><span style="color:blue;"><font size="2">class </font></span><font size="2"><span style="color:#2b91af;">App
</span>{
    [<span style="color:#2b91af;">Export</span>]
    <span style="color:blue;">public </span><span style="color:#2b91af;">CompositionContainer </span>Container;

    <span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
    {
        <span style="color:#2b91af;">AssemblyCatalog </span>catalog = <span style="color:blue;">new </span><span style="color:#2b91af;">AssemblyCatalog</span>(<span style="color:#2b91af;">Assembly</span>.GetExecutingAssembly());
        Container = <span style="color:blue;">new </span><span style="color:#2b91af;">CompositionContainer</span>(catalog);
        Container.ComposeParts();

        <span style="color:blue;">var </span>FastCars = <span style="color:#2b91af;">TrafficFactory</span>.FastVehicles;
        <span style="color:blue;">var </span>SlowCars = <span style="color:#2b91af;">TrafficFactory</span>.SlowVehicles;
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">Viola!&#160; We have metadata-based filtering.</font></p>
<p><font size="2">You’ll also noticed that I added an <strong>Export </strong>attribute to the Container itself.&#160; By doing this, you can <strong>Import </strong>the container into any module that gets dynamically loaded.&#160; It’s not used in this article, but getting to the container from a module is otherwise impossible without some kind of work-around.&#160; (Thanks for pointing out the problem, Damon.)</font></p>
<h3>Using Metadata to Assign Dictionary Keys</h3>
<p><font size="2">Let’s take this one step further.&#160; Let’s say you want to import many instances of MEF exported values into a Dictionary, using one of the metadata properties as the key.&#160; This is how I’d like it to work:</font></p>
<pre class="code"><font size="2"><span style="color:blue;">public static </span><span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">IVehicle</span>&gt; AllVehicles =
    <span style="color:#2b91af;">App</span>.Container.GetKeyedExportedValues&lt;<span style="color:#2b91af;">IVehicle</span>&gt;(<span style="color:#a31515;">&quot;Speed&quot;</span>);</font></pre>
<p><font size="2">Again, the current MEF Preview doesn’t support this, but another extension method is all we need.&#160; We’ll add two, so that one version gives us all exported values and the other allows us to filter that selection based on other metadata.</font></p>
<pre class="code"><font size="2"><span style="color:blue;">public static </span><span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">object</span>, T&gt; GetKeyedExportedValues&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">CompositionContainer </span>Container,
    <span style="color:blue;">string </span>MetadataKey, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt;, <span style="color:blue;">bool</span>&gt; Predicate)
{
    <span style="color:blue;">var </span>result = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">object</span>, T&gt;();

    <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>PartDef <span style="color:blue;">in </span>Container.Catalog.Parts)
    {
        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>ExportDef <span style="color:blue;">in </span>PartDef.ExportDefinitions)
        {
            <span style="color:blue;">if </span>(ExportDef.ContractName == <span style="color:blue;">typeof</span>(T).FullName)
            {
                <span style="color:blue;">if </span>(Predicate(ExportDef.Metadata))
                    result.Add(ExportDef.Metadata[MetadataKey],
                        (T)PartDef.CreatePart().GetExportedValue(ExportDef));
            }
        }
    }

    <span style="color:blue;">return </span>result;
}

<span style="color:blue;">public static </span><span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">object</span>, T&gt; GetKeyedExportedValues&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">CompositionContainer </span>Container,
    <span style="color:blue;">string </span>MetadataKey)
{
    <span style="color:blue;">return </span>GetKeyedExportedValues&lt;T&gt;(Container, MetadataKey, metadata =&gt; <span style="color:blue;">true</span>);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p><font size="2">Add an assignment to TrafficFactory.AllVehicles in the App.Main method and see for yourself that it works.</font></p>
<p><font size="2">If you’re using metadata values as Dictionary keys, it’s probably important for you not to mess them up.&#160; I recommend using enum values for both metadata property names as well as valid values if it’s possible to enumerate them, and string const values otherwise.</font></p>
<p><font size="2">Now go forth and start using MEF!</font></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/591/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/591/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=591&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/09/19/filtering-with-metadata-in-the-managed-extensibility-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>Better Tool Support for .NET</title>
		<link>http://dvanderboom.wordpress.com/2009/09/07/better-tool-support-for-net/</link>
		<comments>http://dvanderboom.wordpress.com/2009/09/07/better-tool-support-for-net/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 16:01:46 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Language Innovation]]></category>
		<category><![CDATA[Oslo]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[User Interface Design]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Visual Studio Extensibility]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/09/07/better-tool-support-for-net/</guid>
		<description><![CDATA[Productivity Enhancing Tools
Visual Studio has come a long way since its debut in 2002.&#160; With the imminent release of 2010, we’ll see a desperately-needed overhauling of the archaic COM extensibility mechanisms (to support the Managed Package Framework, as well as MEF, the Managed Extensibility Framework) and a redesign of the user interface in WPF that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=588&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Productivity Enhancing Tools</h2>
<p>Visual Studio has come a long way since its debut in 2002.&#160; With the imminent release of 2010, we’ll see a desperately-needed overhauling of the archaic COM extensibility mechanisms (to support the <a href="http://msdn.microsoft.com/en-us/library/bb166360.aspx">Managed Package Framework</a>, as well as MEF, the <a href="http://www.codeplex.com/MEF">Managed Extensibility Framework</a>) and a redesign of the user interface in WPF that I’ve been pushing for and predicted as inevitable quite some time ago.</p>
<p>For many alpha geeks, the Visual Studio environment has been extended with excellent third-party, productivity-enhancing tools such as <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/">CodeRush</a> and <a href="http://www.jetbrains.com/resharper/">Resharper</a>.&#160; I personally feel that the Visual Studio IDE team has been slacking in this area, providing only very weak support for refactorings, code navigation, and better Intellisense.&#160; While I understand their desire to avoid stepping on partners’ toes, this is one area I think makes sense for them to be deeply invested in.&#160; In fact, I think a new charter for a Developer Productivity Team is warranted (or an expansion of their team if it already exists).</p>
<p>It’s unfortunately a minority of .NET developers who know about and use these third-party tools, and the .NET community as a whole would without a doubt be significantly more productive if these tools were installed in the IDE from day one.&#160; It would also help to overcome resistance from development departments in larger organizations that are wary of third-party plug-ins, due perhaps to the unstable nature of many of them.&#160; Microsoft should consider purchasing one or both of them, or paying a licensing fee to include them in every copy of Visual Studio.&#160; Doing so, in my opinion, would make them heroes in the eyes of the overwhelming majority of .NET developers around the world.</p>
<p>It’s not that I mind paying a few hundred dollars for these tools.&#160; Far from it!&#160; The tools pay for themselves very quickly in time saved.&#160; The point is to make them ubiquitous: to make high-productivity coding a standard of .NET development instead of a nice add-on that is only sometimes accepted.</p>
<p>Consider just from the perspective of watching speakers at conferences coding up samples.&#160; How many of them don’t use such a tool in their demonstration simply because they don’t want to confuse their audience with an unfamiliar development interface?&#160; How many more demonstrations could they be completing in the limited time they have available if they felt more comfortable using these tools in front of the masses?&#160; You know you pay good money to attend these conferences.&#160; Wouldn’t you like to cover significantly more ground while you’re there?&#160; This is only likely to happen when the tool’s delivery vehicle is Visual Studio itself.&#160; Damon Payne <a href="http://www.damonpayne.com/2009/08/16/WhyMEFMatters.aspx">makes a similar case</a> for the inclusion of the Managed Extensibility Framework in .NET Framework 4.0: build it into the core and people will accept it.</p>
<h2>The Gorillas in the Room</h2>
<p>CodeRush and Resharper have both received recent mention in the Hanselminutes podcast (<a href="http://hanselminutes.com/default.aspx?showID=196">episode 196 with Mark Miller</a>) and in the Deep Fried Bytes podcast (<a href="http://deepfriedbytes.com/podcast/episode-35-why-comments-are-evil-and-pair-programming-with-corey-haines/">episode 35 with Corey Haines</a>).&#160; If you haven’t heard of CodeRush, I recommend watching these videos on their use.</p>
<ul>
<li><a href="http://www.dnrtv.com/default.aspx?showNum=143">CodeRush Express</a> (which is free) </li>
<li><a href="http://www.dnrtv.com/default.aspx?showNum=107">CodeRush with Refactor!</a> </li>
<li><a href="http://www.dnrtv.com/default.aspx?showNum=5">DXCore</a> (the library you can use to build your own add-ins, and on which CodeRush and Refactor! are built) </li>
</ul>
<p>For secondary information on CodeRush, DXCore, and the principles with which they were designed, I recommend these episodes of DotNetRocks:</p>
<ul>
<li><a href="http://www.dotnetrocks.com/default.aspx?showNum=80">Tool Development</a> </li>
<li><a href="http://www.dotnetrocks.com/default.aspx?showNum=185">Discoverability</a> </li>
<li><a href="http://www.dotnetrocks.com/default.aspx?showNum=338">The Science of Good UI</a> </li>
</ul>
<p>I don’t mean to be so biased toward CodeRush, but this is the tool I’m personally familiar with, has a broader range of functionality, and it seems to get the majority of press coverage.&#160; However, those who do talk about Resharper do speak highly of it, so I recommend you check out both of them to see which one works best for you.&#160; But above all: <strong>go check them out!</strong></p>
<h2>Refactor – Rename</h2>
<p>Refactoring code is something we should all be doing constantly to avoid the accumulation of <a href="http://blogs.construx.com/blogs/stevemcc/archive/2007/11/01/technical-debt-2.aspx">technical debt</a> as software projects and the requirements on which they are based evolve.&#160; There are many refactorings in Visual Studio for C#, and many more in third-party tools for several languages, but I’m going to focus here on what I consider to be the most important refactoring of them all: <strong>Rename</strong>.</p>
<p>Why is <strong>Rename</strong> so important?&#160; Because it’s so commonly used, and it has such far-reaching effects.&#160; It is frequently the case that we give poor names to identifiers before we clearly understand their role in the “finished” system, and even more frequent that an item’s role changes as the software evolves.&#160; Failure to rename items to accurately reflect their current purpose is a recipe for code rot and greater code maintenance costs, developer confusion, and therefore buggy logic (with its associated support costs).</p>
<p>When I rename an identifier with a refactoring tool, all of the references to that identifier are also updated.&#160; There might be hundreds of references.&#160; In the days before refactoring tools, one would accomplish this with Find-and-Replace, but this is dangerous.&#160; Even with options like “match case” and “match whole word”, it’s easy to rename the wrong identifiers, rename pieces of string literals, and so on; and if you forget to set these options, it’s worse.&#160; You can go through each change individually, but that can take a very long time with hundreds of potential updates and is a far cry from a truly intelligent update.</p>
<p>Ultimately, the intelligence of the <strong>Rename </strong>refactoring provides safety and confidence for making far-reaching changes, encouraging more aggressive refactoring practices on a more regular basis.</p>
<h2>Abolishing Magic Strings</h2>
<p>I am intensely passionate about any tool <u>or coding practice</u> that encourages refactoring and better code hygiene.&#160; One example of such a coding practice is the use of lambda expressions to select identifiers instead of using evil “magical strings”.&#160; From <a href="http://dvanderboom.wordpress.com/2009/08/20/strongly-typed-dynamic-linq-order-operator/">my article on dynamically sorting Linq queries</a>, the use of “magic strings” would force me to write something like this to dynamically sort a Linq query:</p>
<p><font size="2">Customers = Customers.Order(<span style="color:#a31515;">&quot;LastName&quot;</span>).Order(<span style="color:#a31515;">&quot;FirstName&quot;</span>, <span style="color:#2b91af;">SortDirection</span>.Descending);</font></p>
<p> <a href="http://11011.net/software/vspaste"></a>
<p>The problem here is that “LastName” and “FirstName” are oblivious to the <strong>Rename </strong>refactoring.&#160; Using the refactoring tool might give me a false sense of security in thinking that all of my references to those two fields have been renamed, leading me to The Pit of Despair.&#160; Instead, I can define a function and use it like the following:</p>
<pre class="code"><font size="2"><span style="color:blue;">public static </span><span style="color:#2b91af;">IOrderedEnumerable</span>&lt;T&gt; Order&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">IEnumerable</span>&lt;T&gt; Source,
    <span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;T, <span style="color:blue;">object</span>&gt;&gt; Selector, <span style="color:#2b91af;">SortDirection </span>SortDirection)
{
    <span style="color:blue;">return </span>Order(Source, (Selector.Body <span style="color:blue;">as </span><span style="color:#2b91af;">MemberExpression</span>).Member.Name, SortDirection);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><font size="2">Customers = Customers.Order(c =&gt; c.LastName).Order(c =&gt; c.FirstName, <span style="color:#2b91af;">SortDirection</span>.Descending);</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This requires a little understanding of the structure of expressions to implement, but the benefit is huge: I can now use the refactoring tool with much greater confidence that I’m not introducing subtle reference bugs into my code.&#160; For such a simple example, the benefit is dubious, but multiply this by hundreds or thousands of magic string references, and the effort involved in refactoring quickly becomes overwhelming.</p>
<p>Coding in this style is most valuable when it’s a solution-wide convention.&#160; So long as you have code that strays from this design philosophy, you’ll find yourself grumbling and reaching for the inefficient and inelegant Find-and-Replace tool.&#160; The only time it really becomes an issue, then, is when accessing libraries that you have no control over, such as the Linq-to-Entities and the Entity Framework, which makes extensive use of magic strings.&#160; In the case of EF, this is mitigated somewhat by your ability to regenerate the code it uses.&#160; In other libraries, it may be possible to write extension methods like the Order method shown above.</p>
<p>It’s my earnest hope that library and framework authors such as the .NET Framework team will seriously consider alternatives to, and an abolition of, “magic strings” and other coding practices that frustrate otherwise-powerful refactoring tools.</p>
<h2>Refactoring Across Languages</h2>
<p>A tool is only as valuable as it is practical.&#160; The <strong>Rename</strong> refactoring is more valuable when coding practices don’t frustrate it, as explained above.&#160; Another barrier to the practical use of this tool is the prevalence of multiple languages within and across projects in a Visual Studio solution.&#160; The definition of a project as a single-language container is dubious when you consider that a C# or VB.NET project may also contain HTML, ASP.NET, XAML, or configuration XML markup.&#160; These are all languages with their own parsers and other language services.</p>
<p>So what happens when identifiers are shared across languages and a Rename refactoring is executed?&#160; It depends on the languages involved, unfortunately.</p>
<p>When refactoring a C# class in Visual Studio, the XAML’s x:Class value is also updated.&#160; What we’re seeing here is cross-language refactoring, but unfortunately it only works in one direction.&#160; There is no refactor command to update the x:Class value from the XAML editor, so manually changing it causes my C# class to become sadly out of sync.&#160; Furthermore, this seems to be XAML specific.&#160; If I refactor the name of an .aspx.cs class, the <strong>Inherits</strong> attribute of the <strong>Page</strong> directive in the .aspx file doesn’t update.</p>
<p>How frequent do you think it is that someone would want to change a code-behind file for an ASP.NET page, and yet would not want to change the Inherits attribute?&#160; Probably not very common (okay, probably NEVER).&#160; This is a matter of having sensible defaults.&#160; When you change an identifier name in this way, the development environment does not respond in a sensible way by default, forcing the developer to do extra work and waste time.&#160; This is a failure in UI design for the same reason that Intellisense has been such a resounding success: Intellisense anticipates our needs and works with us; the failure to keep identifiers in sync by default is diametrically opposed to this intelligence.&#160; This represents a fragmented and inconsistent design for an IDE to possess, thus my hope that it will be addressed in the near future.</p>
<p>The problem should be recognized as systemic, however, and addressed in a generalized way.&#160; Making individual improvements in the relationships between pairs of languages has been almost adequate, but I think it would behoove us to take a step back and take a look at the future family of languages supported by the IDE, and the circumstances that will quickly be upon us with Microsoft’s <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx">Oslo</a> platform, which enables developers to more easily build tool-supported languages (especially DSLs, <a href="http://en.wikipedia.org/wiki/Domain-specific_language">Domain Specific Languages</a>).&#160; </p>
<p>Even without Oslo, we have seen a proliferation of languages: IronRuby, IronPython, F#, and the list goes on.&#160; A refactoring tool that is hard-coded for specific languages will be unable to keep pace with the growing family of .NET and markup languages, and certainly unable to deal with the demands of every DSL that emerges in the next few years.&#160; If instead we had a way to identify our code identifiers to the refactoring tool, and indicate how they should be bound to identifiers in other languages in other files, or even other projects or solutions, the tools would be able to make some intelligent decisions without understanding each language ahead of time.&#160; Each language’s language service could supply this information.&#160; For more information on Microsoft Oslo and its relationship to a world of many languages, see <a href="http://dvanderboom.wordpress.com/2009/01/17/why-oslo-is-important/">my article on Why Oslo Is Important</a>.</p>
<p>Without this cross-language identifier binding feature, we’ll remain in refactoring hell.&#160; I <a href="https://connect.microsoft.com/oslo/feedback/ViewFeedback.aspx?FeedbackID=404898">offered a feature suggestion</a> to the Oslo team regarding this multi-master synchronization of a model across languages that was rejected, much to my dismay.&#160; I’m not sure if the Oslo team is the right group to address this, or if it’s more appropriate for the Visual Studio IDE team, so I’m not willing to give up on this yet.</p>
<h2>A Default of Refactor-Rename</h2>
<p>The next idea I’d like to propose here is that the <strong>Rename</strong> refactoring is, in fact, a sensible default behavior.&#160; In other words, when I edit an identifier in my code, I more often than not want all of the references to that identifier to change as well.&#160; This is based on my experience in invoking the refactoring explicitly countless times, compared to the relatively few times I want to “break away” that identifier from all the code that references.</p>
<p>Think about it: if you have 150 references to variable <strong>Foo</strong>, and you change <strong>Foo</strong> to <strong>FooBar</strong>, you’re going to have 150 broken references.&#160; Are you going to create a new <strong>Foo</strong> variable to replace them?&#160; That workflow doesn’t make any sense.&#160; Why not just start editing the identifier and have the references update themselves implicitly?&#160; If you want to be aware of the change, it would be trivial for the IDE to indicate the number of references that were updated behind the scenes.&#160; Then, if for some reason you really did want to break the references, you could explicitly launch a refactoring tool to “break references”, allowing you to edit that identifier definition separately.</p>
<p>The challenge that comes to mind with this default behavior concerns code that spans across solutions that aren’t loaded into the IDE at the same time.&#160; In principle, this could be dealt with by logging the refactoring somewhere accessible to all solutions involved, in a location they can all access and which gets checked into source control.&#160; The next time the other solutions are loaded, the log is loaded and the identifiers are renamed as specified.</p>
<h2>Language Property Paths</h2>
<p>If you’ve done much development with Silverlight or WPF, you’ve probably run into the PropertyPath class when using data binding or animation.&#160; PropertyPath objects represent a traversal path to a property such as “Company.CompanyName.Text”.&#160; The travesty is that they’re always “magic strings”.</p>
<p>My argument is that the property path is such an important construct that <u>it deserves to be an core part of language syntax</u> instead of just a type in some UI-platform-specific library.&#160; I created a data binding library for Windows Forms for which I created my own property path syntax and type, and there are countless non-UI scenarios in which this construct would also be incredibly useful.</p>
<p>The advantage of having a language like C# understand property path syntax is that you avoid a whole class of problems that developers have used “magic strings” to solve.&#160; The compiler can then make intelligent decisions about the correctness of paths, and errors can be identified very early in the cycle.</p>
<p>Imagine being able to pass property paths to methods or return then from functions as first-class citizens.&#160; Instead of writing this:</p>
<p>Binding NameTextBinding = new Binding(&quot;Name&quot;) { Source = customer1; }</p>
<p>… we could write something like this, have access to the <strong>Rename</strong> refactoring, and even get Intellisense support when hitting the dot (.) operator:</p>
<p>Binding NameTextBinding = new Binding(@Customer.Name) { Source = customer1; }</p>
<p>In this code example, I use the fictitious @ operator to inform the compiler that I’m specifying a property path and not trying to reference a static property called Name on the Customer class.</p>
<p>With property paths in the language, we could solve our dynamic Linq sort problem cleanly, without using lambda expressions to hack around the problem:</p>
<p><font size="2">Customers = Customers.Order(@Customer.LastName).Order(@Customer.FirstName, <span style="color:#2b91af;">SortDirection</span>.Descending);</font></p>
<p>That looks and feels right to me.&#160; How about you?</p>
<h2>Summary</h2>
<p>There are many factors of developer productivity, and I’ve established refactoring as one of them.&#160; In this article I discussed tooling and coding practices that support or frustrate refactoring.&#160; We took a deep look into the most important refactoring we have at our disposal, <strong>Rename</strong>, and examined how to get the greatest value out of it in terms of personal habits, as well as long-term tooling vision and language innovation.&#160; I proposed including property paths in language syntax due to its general usefulness and its ability to solve a whole class of problems that have traditionally been solved using problematic “magic strings”.</p>
<p>It gives me hope to see the growing popularity of <a href="http://en.wikipedia.org/wiki/Fluent_interface">Fluent Interfaces</a> and the use of lambda expressions to provide coding conventions that can be verified by the compiler, and a growing community of bloggers (such as <a href="http://weblogs.asp.net/podwysocki/archive/2009/03/19/functional-net-lose-the-magic-strings.aspx">here</a> and <a href="http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/">here</a>) writing about the abolition of “magic strings” in their code.&#160; We can only hope that Microsoft program managers, architects, and developers on the Visual Studio and .NET Framework teams are listening.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/588/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/588/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/588/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=588&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/09/07/better-tool-support-for-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>Living &amp; Working in Sunny Aruba</title>
		<link>http://dvanderboom.wordpress.com/2009/09/05/living-working-in-sunny-aruba/</link>
		<comments>http://dvanderboom.wordpress.com/2009/09/05/living-working-in-sunny-aruba/#comments</comments>
		<pubDate>Sat, 05 Sep 2009 16:51:45 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Aruba]]></category>
		<category><![CDATA[Remote Working]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/09/05/living-working-in-sunny-aruba/</guid>
		<description><![CDATA[ 
I am thrilled to finally be living in Aruba, at least for the month of September.&#160; This is an experiment in remote working, and an experiment in living outside the United States.&#160; “Why Aruba?” you ask.&#160; Why not?&#160; Aruba has weather that’s perfect for the beach year round, lies safely outside the hurricane belt, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=586&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://dvanderboom.files.wordpress.com/2009/09/aruba381.jpg"><img style="display:inline;border-width:0;" title="Aruba 381" border="0" alt="Aruba 381" src="http://dvanderboom.files.wordpress.com/2009/09/aruba381_thumb.jpg?w=642&#038;h=482" width="642" height="482" /></a> </p>
<p>I am thrilled to finally be living in Aruba, at least for the month of September.&#160; This is an experiment in remote working, and an experiment in living outside the United States.&#160; “Why Aruba?” you ask.&#160; Why not?&#160; Aruba has weather that’s perfect for the beach year round, lies safely outside the hurricane belt, and has one of the highest per capita incomes in the Caribbean, making it a very safe and happy place.&#160; In fact, their license plate tag line is “One Happy Island”.</p>
<p>&#160;<a href="http://dvanderboom.files.wordpress.com/2009/09/aruba329.jpg"><img style="display:inline;border-width:0;" title="Aruba 329" border="0" alt="Aruba 329" src="http://dvanderboom.files.wordpress.com/2009/09/aruba329_thumb.jpg?w=240&#038;h=123" width="240" height="123" /></a> </p>
<p>Indeed it is!&#160; Everyone here has been extremely friendly.&#160; The population is ethnically diverse and many languages can be heard.&#160; Residents speak Papiamento, Spanish, English, and Dutch generally, and I often hear German, French, Japanese, and other languages I can’t yet identify.&#160; It seems common for people living here to speak six or more languages.&#160; Being a lover of languages, I hope to pick up as much as I can while I have the opportunity.</p>
<p>I planned many months ahead of time, but found a paucity of information available online and have had to wing-it for many aspects of the trip, which just makes it more of an adventure.&#160; Aruban websites are geared toward mainstream tourism and high-profile resort hotel-casinos (many of which are beautiful), but I was looking for longer-term residency, and a bargain at that.&#160; I settled for a cheap room off the beaten path, which was about the same rate for a month as a hotel room would be for a week.&#160; As it turned out, I was upgraded for free to a nice two-bedroom condominium due to last-minute rescheduling of my original room.&#160; I’m a ten-minute walk from Palm Beach, a two-hour walk from the capital of Oranjestad, and at about 20 miles by 5 miles, Aruba is large enough to keep me busy exploring but small enough to make exploring most areas of it possible within my month here.</p>
<h3>Do You Ever Work?</h3>
<p>Yes, I work on projects for several customers while I’m here.&#160; I found a fantastic free-Internet Dutch cafe called <a href="http://rembrandtaruba.com/">Cafe Rembrandt</a> with a wonderful staff.&#160; I have plugs to power my laptop, and use <a href="http://www.skype.com/intl/en/welcomeback/">Skype</a> or <a href="http://icall.com/">iCall</a> to make calls to customers.&#160; Both of these have applications for iPhone.&#160; With them, I pay $0.20 &#8211; $0.27 per minute for calls.&#160; Without them, through AT&amp;T (and through <a href="http://www.setar.aw/">SETAR</a>, who is the cell and wi-fi provider for the island), I’d be paying an outrageous $1.69 per minute.&#160; This limits me to making calls from free Internet hotspots, or I could pay SETAR $70 per month for unlimited access to their wireless access that blankets the popular parts of the island.</p>
<p>From a technical communication perspective, it’s all working well so far.&#160; Because I’m working on smaller projects and my customers are geographically distributed anyway, I’m not running up against many of the hurdles that would appear on larger projects, so it’s a good way to dip one foot into the water without jumping in all the way on day one.&#160; Working side-by-side in person with other members on larger projects is always the highest-bandwidth method of communicating, but remote working scenarios are becoming more and more common and have many benefits.&#160; The only real way to identify the challenges these scenarios impose is to put yourself into them again and again, and deal with the issues as they come up, finding solutions to problems, working around limitations, and exploiting the advantages that decentralization provides.</p>
<h3>Getting Around &amp; Communicating</h3>
<p>Being an avid running and hiker, I’ve walked about four hours a day since I’ve been here, pushing myself as I usually do.&#160; The busses, however, are air-conditioned, cheap (about $1.30 per trip just about anywhere), clean and safe, so I always have an easy way home when I’m completely exhausted.&#160; They’ll go anywhere you need them to, so renting a vehicle is unnecessary, but car rentals are reasonable if you need one.&#160; If you want to rent one, make sure to go to your local AAA and get an International Driver’s License before coming.&#160; Also check AAA and tourist books for coupons, which can be 10-20% off of listed rates.</p>
<p>Phones are available for rent, or you can use your existing phone as long as your carrier allows international roaming (you may have to call them to authorize that feature).&#160; AT&amp;T customers need to sign up for their World Traveler plan.&#160; I use mine only for Google Maps to navigate and to check for email periodically, as the data plans are outrageously expensive if you go over your limit (over $5 per MB).</p>
<h3>Wrapping Up</h3>
<p>I could write many pages more about my few days here already, but instead I’ll conclude with a few of the pictures I’ve taken from my iPhone.&#160; If you have your own stories about Aruba, or living and working abroad or remotely in general and the lessons you learned, I’d love to hear about them.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/09/aruba325.jpg"><img style="display:inline;border-width:0;" title="Aruba 325" border="0" alt="Aruba 325" src="http://dvanderboom.files.wordpress.com/2009/09/aruba325_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a>&#160;<a href="http://dvanderboom.files.wordpress.com/2009/09/aruba331.jpg"><img style="display:inline;border-width:0;" title="Aruba 331" border="0" alt="Aruba 331" src="http://dvanderboom.files.wordpress.com/2009/09/aruba331_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a>&#160;&#160; <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba348.jpg"><img style="display:inline;border-width:0;" title="Aruba 348" border="0" alt="Aruba 348" src="http://dvanderboom.files.wordpress.com/2009/09/aruba348_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba357.jpg"><img style="display:inline;border-width:0;" title="Aruba 357" border="0" alt="Aruba 357" src="http://dvanderboom.files.wordpress.com/2009/09/aruba357_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba396.jpg"><img style="display:inline;border-width:0;" title="Aruba 396" border="0" alt="Aruba 396" src="http://dvanderboom.files.wordpress.com/2009/09/aruba396_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba399.jpg"><img style="display:inline;border-width:0;" title="Aruba 399" border="0" alt="Aruba 399" src="http://dvanderboom.files.wordpress.com/2009/09/aruba399_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba402.jpg"><img style="display:inline;border-width:0;" title="Aruba 402" border="0" alt="Aruba 402" src="http://dvanderboom.files.wordpress.com/2009/09/aruba402_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a> <a href="http://dvanderboom.files.wordpress.com/2009/09/aruba415.jpg"><img style="display:inline;border-width:0;" title="Aruba 415" border="0" alt="Aruba 415" src="http://dvanderboom.files.wordpress.com/2009/09/aruba415_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a><a href="http://dvanderboom.files.wordpress.com/2009/09/aruba406.jpg"><img style="display:inline;border-width:0;" title="Aruba 406" border="0" alt="Aruba 406" src="http://dvanderboom.files.wordpress.com/2009/09/aruba406_thumb.jpg?w=304&#038;h=229" width="304" height="229" /></a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/586/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=586&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/09/05/living-working-in-sunny-aruba/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba381_thumb.jpg" medium="image">
			<media:title type="html">Aruba 381</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba329_thumb.jpg" medium="image">
			<media:title type="html">Aruba 329</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba325_thumb.jpg" medium="image">
			<media:title type="html">Aruba 325</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba331_thumb.jpg" medium="image">
			<media:title type="html">Aruba 331</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba348_thumb.jpg" medium="image">
			<media:title type="html">Aruba 348</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba357_thumb.jpg" medium="image">
			<media:title type="html">Aruba 357</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba396_thumb.jpg" medium="image">
			<media:title type="html">Aruba 396</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba399_thumb.jpg" medium="image">
			<media:title type="html">Aruba 399</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba402_thumb.jpg" medium="image">
			<media:title type="html">Aruba 402</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba415_thumb.jpg" medium="image">
			<media:title type="html">Aruba 415</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/09/aruba406_thumb.jpg" medium="image">
			<media:title type="html">Aruba 406</media:title>
		</media:content>
	</item>
		<item>
		<title>Strongly-Typed, Dynamic Linq Order Operator</title>
		<link>http://dvanderboom.wordpress.com/2009/08/20/strongly-typed-dynamic-linq-order-operator/</link>
		<comments>http://dvanderboom.wordpress.com/2009/08/20/strongly-typed-dynamic-linq-order-operator/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 15:02:16 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Collaboration]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Language Extensions]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Social Networking]]></category>
		<category><![CDATA[dynamic query]]></category>
		<category><![CDATA[social networks]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/08/20/strongly-typed-dynamic-linq-order-operator/</guid>
		<description><![CDATA[A Community Solution
I love social technologies like Stack Overflow, where people can collaborate loosely to share knowledge and help get things done.&#160; Stack Overflow does on a large scale what developer blogs like mine have been doing on a smaller scale: creating a community around the sharing of ideas and methods.
Every once in a while, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=560&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h3>A Community Solution</h3>
<p>I love social technologies like <a href="http://stackoverflow.com/">Stack Overflow</a>, where people can collaborate loosely to share knowledge and help get things done.&#160; Stack Overflow does on a large scale what developer blogs like mine have been doing on a smaller scale: creating a community around the sharing of ideas and methods.</p>
<p>Every once in a while, I get some great feedback that includes a fix for one of my bugs, a performance tweak I didn’t realize was possible, or an extension to some library I left unfinished.</p>
<p>This morning I ran into <a href="http://stackoverflow.com/questions/557819/strongly-typed-dynamic-linq-sorting">a question about my dynamic Linq sort</a>, solved and answered by <a href="http://stackoverflow.com/users/489/ch00k">“Ch00k”</a>, allowing one to get compile-time checking of identifier names.&#160; Well done!</p>
<p>(It’s too bad Stack Overflow doesn’t promote the use of real names for professional developers to better market themselves with skill and reputation.)</p>
<p>My original article (with source code) is <a href="http://dvanderboom.wordpress.com/2008/12/19/dynamically-composing-linq-orderby-clauses/">here</a>.&#160; All I added to the library was this:</p>
<pre class="code"><font size="2"><span style="color:blue;">public static </span><span style="color:#2b91af;">IOrderedEnumerable</span>&lt;T&gt; Order&lt;T&gt;(<span style="color:blue;">this </span><span style="color:#2b91af;">IEnumerable</span>&lt;T&gt; Source,
    <span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;T, <span style="color:blue;">object</span>&gt;&gt; Selector, <span style="color:#2b91af;">SortDirection </span>SortDirection)
{
    <span style="color:blue;">return </span>Order(Source, (Selector.Body <span style="color:blue;">as </span><span style="color:#2b91af;">MemberExpression</span>).Member.Name, SortDirection);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a>To test it, I used this code:</p>
<pre class="code"><font size="2"><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">Customer</span>&gt; Customers = <span style="color:blue;">new </span><span style="color:#2b91af;">Customer</span>[] { <span style="color:blue;">new </span><span style="color:#2b91af;">Customer</span>(<span style="color:#a31515;">&quot;Dan&quot;</span>, <span style="color:#a31515;">&quot;Vanderboom&quot;</span>), <span style="color:blue;">new </span><span style="color:#2b91af;">Customer</span>(<span style="color:#a31515;">&quot;Steve&quot;</span>, <span style="color:#a31515;">&quot;Vanderboom&quot;</span>),
    <span style="color:blue;">new </span><span style="color:#2b91af;">Customer</span>(<span style="color:#a31515;">&quot;Tracey&quot;</span>, <span style="color:#a31515;">&quot;Vanderboom&quot;</span>), <span style="color:blue;">new </span><span style="color:#2b91af;">Customer</span>(<span style="color:#a31515;">&quot;Sarah&quot;</span>, <span style="color:#a31515;">&quot;Barkelew&quot;</span>) };

Customers = Customers.Order(c =&gt; c.LastName, <span style="color:#2b91af;">SortDirection</span>.Ascending);
Customers = Customers.Order(c =&gt; c.FirstName, <span style="color:#2b91af;">SortDirection</span>.Descending);

<span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>cust <span style="color:blue;">in </span>Customers)
{
    <span style="color:#2b91af;">Console</span>.WriteLine(cust.FirstName + <span style="color:#a31515;">&quot; &quot; </span>+ cust.LastName);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>Now I can refactor these data model classes with a tool and all my dynamic sorting queries will stay in sync!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/560/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/560/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/560/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=560&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/08/20/strongly-typed-dynamic-linq-order-operator/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>Software Development Methods</title>
		<link>http://dvanderboom.wordpress.com/2009/08/19/software-development-methods/</link>
		<comments>http://dvanderboom.wordpress.com/2009/08/19/software-development-methods/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 00:41:11 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Goal Setting]]></category>
		<category><![CDATA[Lean Agile]]></category>
		<category><![CDATA[Software Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[lean]]></category>
		<category><![CDATA[methodology]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/08/19/software-development-methods/</guid>
		<description><![CDATA[Building a House
Building a house is still one of the most common analogies I hear and use for discussing software development with customers.&#160; The problem is that the architecture of the house is left out; and unless you’re a developer, it’s hard to understand why a stack of wireframes isn’t the comprehensive description of the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=552&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h3>Building a House</h3>
<p>Building a house is still one of the most common analogies I hear and use for discussing software development with customers.&#160; The problem is that the architecture of the house is left out; and unless you’re a developer, it’s hard to understand why a stack of wireframes isn’t the comprehensive description of the system needed to provide accurate cost and schedule estimates.</p>
<p>These wireframes are like the diagrams a first-time home owner might sketch on the back of a napkin.&#160; In order to know what must be built, and to determine a realistic sense of scope and cost, those rough ideas need to be developed into something much more substantial by a professional.&#160; For our house building scenario, this would involve hiring an architect to transform those ideas into a set of drawings which include such things as plumbing, heat and air conditioning ducts, electrical access panels, drains, the appropriate foundation and structural support elements, and so on.&#160; The customer asks for a “nice room with a window looking to the back yard”, but all of these other hidden structural elements must be taken into consideration as well.</p>
<p>Unfortunately, determining the actual cost and size of a large project with any accuracy requires having this detailed design; and worse, doing this detailed design can take weeks or even months.&#160; By the time development is underway, the customer will inevitably change many of the requirements anyway.&#160; In fact, the very process of evolving such a large and detailed design brings many issues to the surface to discuss, debate, and make decisions about.&#160; It’s easy to see how this process could carry on for quite a while, and there are still changes in the market to consider and adapt to, both during and after requirements definition.</p>
<p>The house building analogy is useful, but it is also misused.&#160; To be fair, a typical waterfall software project put into house building terms would go like this.</p>
<ol>
<li>Customer sends sketches to Architect and asks for plan including schedule and cost. </li>
<li>Architect works with Customer, being paid for his services to arrive at detailed design, which provides the project schedule and cost. </li>
<li>Builder works with the Architect’s plan to build exactly what’s in the requirements. </li>
<li>Days or weeks later, Customer makes changes to requirements.&#160; This requires the Architect to get involved again, update the plan, work with the Builder to make physical adjustments, which may include tearing down existing structures and modifying others.&#160; Plan changes need to be approved by government (verified with tests), documentation updated, and Customer agrees to pay for the changes. </li>
<li>* Customer requests to now connect their house to other houses near by, the shapes and layouts of which may change over time. </li>
<li>Repeat #4. </li>
</ol>
<p>However, this is completely at odds with how homes are normally built.&#160; People typically choose a previously-implemented design, and only customize superficial features like countertops, cabinets, floors, and railings.&#160; Houses from this plan have been built before, and the labor and materials cost are known from previous experience.</p>
<p>Building software is usually more like constructing something that’s never been built before: the first sky scraper, the Golden Gate Bridge, or the Hoover Dam.&#160; The requirements are unique, the pieces have never been assembled in such a way before, and there’s an inherent level of risk in creating something new.&#160; When this is the case, the Customer needs the services of an Architect, not just a Builder who stamps out deliverables in a cookie-cutter style.</p>
<p>Waterfall methodologies have been dramatically in decline over the years in favor of so-called Agile methods.&#160; There are several problems with a Waterfall approach:</p>
<ul>
<li>Because of requirements churn, attempting to write all the requirements up-front is incredibly wasteful.&#160; Your team will end up doing a lot of design work that is eventually thrown away.&#160; When I hear about churn numbers as high as 80%, I shudder to think of all the time and money spent refining details that will never make it into the production system. </li>
<li>It tends to take a blind approach to requirements change, working under the assumption that change is bad and should be prevented.&#160; Many waterfall methodologies erect barriers to change, making Customers jump through hoops to push changes through. </li>
<li>Customers typically don’t want to pay for this architecture phase.&#160; They want to pay for actual work on their system, and the cost of defining the actual scope and cost of their system seems steep.&#160; “Why should I pay you $&lt;large number&gt; just for you to tell me how much you’ll charge me for the final system?” </li>
</ul>
<h3>An Agile Solution: Efficiency and Uncertainty</h3>
<p>The Agile community emerged largely as a reaction to the disappointing results of Waterfall projects.&#160; Customers were sick of schedules and budgets that were consistently and grossly overrun (despite all the up-front design), and wanted to more easily change requirements without being put through the wringer to do so.&#160; Developers were tired of spending their valuable time writing detailed design documents that kept changing throughout the project, and the burden to update that documentation as the project goals changed focus or priorities shifted made development a very inefficient and slow process.</p>
<p>Essentially, as is often the case, a trade-off was made.&#160; Some stakeholders realized that the predictability they were attempting to achieve by spelling out everything in detail was delusional: they were aiming at a moving target regardless of their efforts to pin things down.&#160; Project costs rose precipitously because the scope of the system grew.&#160; They needed a process that acknowledged and accepted these dynamic project forces instead of one that denied and suppressed them.&#160; They needed a process that was efficient, and they gave up the illusion of certainty to get it.</p>
<p>The <a href="http://www.construx.com/Page.aspx?hid=1648">cone of uncertainty</a> is one of the most valuable tools for visualizing and understanding uncertainty in development projects.&#160; From that article:</p>
<blockquote><p><font color="#004080">Research has found that the accuracy of the software estimate depends on the level of refinement of the software’s definition. The more refined the definition, the more accurate the estimate. The reason the estimate contains variability is that the software project itself contains variability. The only way to reduce the variability in the estimate is to reduce the variability in the project itself. </font></p>
<p><font color="#004080">An important—and difficult—concept is that the Cone of Uncertainty represents the best case accuracy it’s possible to have in software estimates at different points in a project. The Cone represents the error in estimates created by skilled estimators [which is up to 16x error at the beginning of a project]. It’s easily possible to do worse. It isn’t possible to be more accurate; it’s only possible to be more lucky. </font></p>
<p><font color="#004080">Commitments made too early in a project undermine predictability, increase risk, increase project inefficiencies, and impair the ability to manage a project to a successful conclusion. </font></p>
<p><font color="#004080">Meaningful commitments are not possible in the early, wide part of the Cone. Effective organizations delay their commitments until they have done the work to force the Cone to narrow. Meaningful commitments in the early-middle of the project (about 30% of the way into the project) are possible and appropriate.</font> </p>
</blockquote>
<p>Or as noted by the MSDN documentation for <a href="http://msdn.microsoft.com/en-us/library/dd490815.aspx">Composite Client Application Guidance</a>:</p>
<blockquote><p><font color="#004080">Application requirements can change over time. New business opportunities and challenges may present themselves, new technologies may become available, or even ongoing customer feedback during the development cycle may significantly affect the requirements of the application. Therefore, it is important to build the application so that it is flexible and can be easily modified or extended over time.</font></p>
</blockquote>
<p>Agile methods have always dealt with small iterations and early, frequent builds to evolve product functionality, but the <a href="http://en.wikipedia.org/wiki/Lean_software_development">Lean Development</a> method especially has an explicit focus on making meaningful commitments at the latest possible responsible moment.&#160; From Wikipedia:</p>
<blockquote><p><font color="#004080">As </font><a href="http://en.wikipedia.org/wiki/Software_development"><font color="#004080">software development</font></a><font color="#004080"> is always associated with some uncertainty, better results should be achieved with an options-based approach, delaying decisions as much as possible until they can be made based on facts and not on uncertain assumptions and predictions. The more complex a system is, the more capacity for change should be built into it, thus enabling the delay of important and crucial commitments. The iterative approach promotes this principle – the ability to adapt to changes and correct mistakes, which might be very costly if discovered after the release of the system.</font></p>
</blockquote>
<p>While the methodology pundits debate the relative merits of development processes, <a href="http://www.systemsguild.com/GuildSite/TDM/TDMBio.html">Tom DeMarco</a>, author of the fantastic books <a href="http://www.amazon.com/Peopleware-Productive-Projects-Teams-Second/dp/0932633439/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1250705764&amp;sr=8-1">Peopleware</a> and <a href="http://www.amazon.com/Controlling-Software-Projects-Management-Measurement/dp/0131717111/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1250705791&amp;sr=1-1">Controlling Software Projects</a>, challenges us to consider the value of our projects and to re-evaluate elaborate control measures in light of the bigger picture.&#160; From <a href="http://www2.computer.org/cms/Computer.org/ComputingNow/homepage/2009/0709/rW_SO_Viewpoints.pdf">his article</a>:</p>
<blockquote><p><font color="#004080">To understand control’s real role, you need to distinguish between two drastically different kinds of projects:</font></p>
<ul>
<li><font color="#004080">Project A will eventually cost about a million dollars and produce value of around $1.1 million.</font> </li>
<li><font color="#004080">Project B will eventually cost about a million dollars and produce value of more than $50 million.</font> </li>
</ul>
<p><font color="#004080">What’s immediately apparent is that control is really important for Project A but almost not at all important for Project B.&#160; This leads us to the odd conclusion that strict control is something that matters a lot on relatively useless projects and much less on useful projects.&#160; It suggests that the more you focus on control, the more likely you’re working on a project that’s striving to deliver something of relatively minor value.</font></p>
</blockquote>
<p>This adds additional credence to the idea of agile development, since the Big Design Up-Front (BDUF) of Waterfall is obsessed with detailed definitions to make accurate schedule promises.&#160; If the business model is sound, lots of control isn’t needed.&#160; It’s better to navigate with a good compass (the product vision) than an incorrect and constantly changing map.</p>
<h3>So What Will I Get?</h3>
<p>At the end of the day, customers want to know what they’re going to get.&#160; There are tradeshow and conference dates to meet, beta and v1.0 launch targets to hit, release cycles to determine, and so on.&#160; Ultimately, <em>some</em> up-front architecture and design is usually required.&#160; But instead of trying to pin down every detail, it’s actually best in terms of efficiency to share the vision, provide direction, and define the technical scope only in a loose way.&#160; This functional scope definition should reflect the reality of the cone of uncertainty at that point in the development process.</p>
<p>At the beginning of the project, items to include in the project should be broadly defined, having a granularity appropriate for the actual uncertainty.&#160; As the project progresses and work is done, the scope becomes better defined, risks are determined benign or neutralized, and the cadence of <strong>that specific team</strong> working on <strong>that customer’s specific product</strong> can be measured.</p>
<p>This is successfully done with Lean and <a href="http://en.wikipedia.org/wiki/Kanban">Kanban</a> approaches, providing an empirical method for measuring productivity.&#160; Planning can then be adjusted to match the regular rhythm of production that develops.&#160; This creates a semblance of real predictability.&#160; You can’t predict any one thing with absolute certainty, but if you can measure the general rhythm at which work is done, you will very quickly learn to recognize how long different kinds of tasks actually take.&#160; Because you’re focusing on measured results rather than predictions, it’s easier to normalize task size and estimate larger functional units.</p>
<p>If you’re interested in learning more about Lean development, Mary and Tom Poppendieck’s book <a href="http://www.amazon.com/Implementing-Lean-Software-Development-Addison-Wesley/dp/0321437381/ref=ntt_at_ep_dpi_2">Implementing Lean Software Development</a> is a fantastic background and explanation of the Lean process.&#160; They also have a new book coming out this November, exploring the same topics more deeply.</p>
<p>When a good process is followed by hard-working, talented developers, the customer will end up with what they need to satisfy their business goals, often in surprising ways, ways that will be radically different from what they initially asked for.</p>
<h3>What Can Be Promised?</h3>
<p>The customer has their vision, beginning with the end in mind as they do; and they are asked to break it apart, prioritize individual features, and stretch their end-goal image across a long and expensive tunnel that separates them from their goal.&#160; They usually want some kind of promise of what they’re going to get at the end, even though they’re going to keep adding and changing features throughout its development.</p>
<p>What can be promised?&#160; It would be dishonest to promise customers what they’re asking for, unless they promise not to change their minds as the project progresses, but the only certainty in software development is that requirements will change.</p>
<p>Development isn’t about creating flawless, predictable plans that eliminate business risk.&#160; Development is an unpredictable journey to create tremendous value.&#160; To achieve great reward, risk is a necessary part of the equation.&#160; Instead of coming up with creative ways to hide real project risk, it’s best to have a solid process for detecting and managing that risk.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/552/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/552/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/552/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/552/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/552/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/552/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/552/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/552/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/552/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/552/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=552&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/08/19/software-development-methods/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>Multicasting with Silverlight 3 Local Messaging</title>
		<link>http://dvanderboom.wordpress.com/2009/04/29/multicasting-with-silverlight-3-local-messaging/</link>
		<comments>http://dvanderboom.wordpress.com/2009/04/29/multicasting-with-silverlight-3-local-messaging/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 17:13:09 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Distributed Architecture]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[User Interface Design]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/04/29/multicasting-with-silverlight-3-local-messaging/</guid>
		<description><![CDATA[[This article and the sample solution included were written with Silverlight 3 Beta.]
The very first thing I did to experiment with Silverlight 3’s new local messaging feature was to create an application with a listener name of “Everyone”, pop up multiple instances of the application, and try sending a message to all of the instances.&#160; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=550&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#004080"><strong>[This article and the sample solution included were written with Silverlight 3 Beta.]</strong></font></p>
<p>The very first thing I did to experiment with Silverlight 3’s new <a href="http://blogs.msdn.com/pstubbs/archive/2009/04/02/silverlight-3-what-s-new-with-local-messaging.aspx">local messaging feature</a> was to create an application with a listener name of “Everyone”, pop up multiple instances of the application, and try sending a message to all of the instances.&#160; I got a nasty HRESULT E_FAIL exception message upon firing up the second instance.&#160; I closed the application and restarted, only to find I got the same error message on the <em>first</em> instance as well (until I rebooted).</p>
<p>The problem was that a listener must have a unique name and I was violating that rule.&#160; There are no groups, and multicasting to multiple receivers in the same group isn’t supported out of the box.&#160; Because I didn’t dispose of the object, that name was never released.&#160; This seems like a design flaw; when a Silverlight application instance ends, the Silverlight runtime should be able to detect that and release this name resource.</p>
<p>When I heard about this local message passing ability, my first thought was that it would create a neat opportunity, especially in out-of-browser applications, for multiple-window applications.&#160; This would be great for those of us who use multiple monitors, as we could then slide panels around where we wanted them, taking full advantage of our workspace.</p>
<p>My sample application, which you can <a href="http://danvanderboom.com/Examples/SilverlightLocalMessaging.zip">download here</a>, consists of a TextBox, a Submit button that sends the content of that TextBox to all the other instances, and a TextBlock that displays important events.&#160; The first time the application runs, it identifies itself as the master window.&#160; All subsequent application runs identify themselves as child windows.&#160; Here’s a screenshot of this application running out-of-browser:</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image6.png"><img title="Screenshot" style="border-right:0;border-top:0;display:inline;border-left:0;border-bottom:0;" height="408" alt="Screenshot" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb6.png?w=640&#038;h=408" width="640" border="0" /></a> </p>
<p>To accomplish this, the master window will need to have a well known name.&#160; I chose <strong>MyApp/Master</strong> to identify both the application and the window name.&#160; Each of the child windows require a unique name, so I chose the format <strong>MyApp/{guid}</strong>.&#160; Once an instance realizes there’s already a master window, it gives itself a child window GUID name and then registers that name with the master window.&#160; When a child instance exits, it unregisters itself with the master instance.&#160; And finally, when the master window exits, it informs all of the child windows (so they can shutdown, most likely).</p>
<p>I defined several static members in the App class itself, so they would be visible across pages, and also because I wanted to hook into Application_Exit and needed access from there.</p>
<pre class="code"><font size="2"><span style="color:blue;">public const string </span>MasterWindowName = <span style="color:#a31515;">&quot;MyApp/Master&quot;</span>;
<span style="color:blue;">public static string </span>WindowName;
<span style="color:blue;">public static </span><span style="color:#2b91af;">Guid </span>WindowID;
<span style="color:blue;">public static </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Guid</span>&gt; ChildWindows;</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Hooking into the LocalMessageReceiver’s MessageReceived event, I looked for specific keywords in a protocol I quickly cooked up, and in most cases extracted a parameter by parsing the message string.&#160; These commands are <strong>NewWindow</strong>, <strong>CloseWindow</strong>, <strong>MasterWindowClosed</strong>, and <strong>UpdateText</strong>.</p>
<pre class="code"><font size="2"><span style="color:blue;">void </span>MessageReceiver_MessageReceived(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">MessageReceivedEventArgs </span>e)
{
    <span style="color:blue;">if </span>(e.Message.StartsWith(<span style="color:#a31515;">&quot;NewWindow:&quot;</span>))
    {
        <span style="color:blue;">if </span>(<span style="color:#2b91af;">App</span>.ChildWindows == <span style="color:blue;">null</span>)
            <span style="color:#2b91af;">App</span>.ChildWindows = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Guid</span>&gt;();

        <span style="color:#2b91af;">Guid </span>NewWindowID = <span style="color:blue;">new </span><span style="color:#2b91af;">Guid</span>(e.Message.Substring(<span style="color:#a31515;">&quot;NewWindow:&quot;</span>.Length));

        <span style="color:#2b91af;">App</span>.ChildWindows.Add(NewWindowID);

        Log(<span style="color:#a31515;">&quot;New window detected, id = &quot; </span>+ NewWindowID.ToString());

        <span style="color:blue;">return</span>;
    }

    <span style="color:blue;">if </span>(e.Message.StartsWith(<span style="color:#a31515;">&quot;CloseWindow:&quot;</span>))
    {
        <span style="color:blue;">var </span>id = <span style="color:blue;">new </span><span style="color:#2b91af;">Guid</span>(e.Message.Substring(<span style="color:#a31515;">&quot;CloseWindow:&quot;</span>.Length));

        <span style="color:blue;">if </span>(<span style="color:#2b91af;">App</span>.WindowName == <span style="color:#2b91af;">App</span>.MasterWindowName)
            <span style="color:#2b91af;">App</span>.ChildWindows.Remove(id);

        Log(<span style="color:#a31515;">&quot;Closing window, id = &quot; </span>+ id.ToString());

        <span style="color:blue;">return</span>;
    }

    <span style="color:blue;">if </span>(e.Message == <span style="color:#a31515;">&quot;MasterWindowClosed&quot; </span>&amp;&amp; <span style="color:#2b91af;">App</span>.WindowName != <span style="color:#2b91af;">App</span>.MasterWindowName)
    {
        Log(<span style="color:#a31515;">&quot;Master Window Closed&quot;</span>);
        <span style="color:blue;">return</span>;
    }

    <span style="color:blue;">if </span>(e.Message.StartsWith(<span style="color:#a31515;">&quot;UpdateText&quot;</span>))
    {
        <span style="color:blue;">var </span>text = e.Message.Substring(<span style="color:#a31515;">&quot;UpdateText:&quot;</span>.Length);

        txtName.Text = text;

        </font><font size="2"><span style="color:green;">// if this is the master window, then distribute to all child windows
        </span><span style="color:blue;">if </span>(<span style="color:#2b91af;">App</span>.WindowName == <span style="color:#a31515;">&quot;MyApp/Master&quot;</span>)
            UpdateTextMulticast(text);

        <span style="color:blue;">return</span>;
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>As you can see, most of this is simple housekeeping code to track which application instances or windows are currently connected to the master window.&#160; The UpdateText command calls the UpdateTextMulticast method, which looks like this:</p>
<pre class="code"><font size="2"><span style="color:blue;">private void </span>UpdateTextMulticast(<span style="color:blue;">string </span>Text)
{
    <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>id <span style="color:blue;">in </span><span style="color:#2b91af;">App</span>.ChildWindows)
    {
        <span style="color:blue;">var </span>MessageSender = <span style="color:blue;">new </span><span style="color:#2b91af;">LocalMessageSender</span>(<span style="color:#a31515;">&quot;MyApp/&quot; </span>+ id.ToString());
        MessageSender.SendAsync(<span style="color:#a31515;">&quot;UpdateText:&quot; </span>+ txtName.Text);
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>If the window is a child window, the Submit button sends a message to the master window; the master window, when clicking on Submit, calls the UpdateTextMulticast method.</p>
<pre class="code"><font size="2"><span style="color:blue;">private void </span>btnSubmit_Click(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">RoutedEventArgs </span>e)
{
    <span style="color:blue;">if </span>(<span style="color:#2b91af;">App</span>.WindowName == <span style="color:#a31515;">&quot;MyApp/Master&quot;</span>)
    {
        UpdateTextMulticast(txtName.Text);
    }
    </font><font size="2"><span style="color:blue;">else
    </span>{
        <span style="color:blue;">var </span>MessageSender = <span style="color:blue;">new </span><span style="color:#2b91af;">LocalMessageSender</span>(<span style="color:#a31515;">&quot;MyApp/Master&quot;</span>);
        MessageSender.SendAsync(<span style="color:#a31515;">&quot;UpdateText:&quot; </span>+ txtName.Text);
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Finally, this is how a window alerts other windows that it’s closing (in App.xaml.cs):</p>
<pre class="code"><font size="2"><span style="color:blue;">private void </span>Application_Exit(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">EventArgs </span>e)
{
    <span style="color:blue;">if </span>(WindowName != MasterWindowName)
    {
        <span style="color:blue;">var </span>MessageSender = <span style="color:blue;">new </span><span style="color:#2b91af;">LocalMessageSender</span>(MasterWindowName);
        MessageSender.SendAsync(<span style="color:#a31515;">&quot;CloseWindow:&quot; </span>+ WindowID);
    }
    <span style="color:blue;">else if </span>(ChildWindows != <span style="color:blue;">null</span>)
    {
        <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>id <span style="color:blue;">in </span>ChildWindows)
        {
            <span style="color:blue;">var </span>MessageSender = <span style="color:blue;">new </span><span style="color:#2b91af;">LocalMessageSender</span>(<span style="color:#a31515;">&quot;MyApp/&quot; </span>+ id.ToString());
            MessageSender.SendAsync(<span style="color:#a31515;">&quot;MasterWindowClosed&quot;</span>);
        }
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>That’s about all there is to it.&#160; Admittedly, having the same Silverlight application act as both master and child window might not be the best arrangement, and it certainly adds a little to the complexity of the code, but the sky is the limit as far as how the new local messaging feature of Silverlight 3 could be used.</p>
<p>What I’d really like to see is some kind of WCF customization that could define WCF services and host them specifically for consumption across this local messaging channel.&#160; Doing so would eliminate the need for defining and parsing a protocol as I’ve done in this example, as WCF could handle the serialization and service method invocation.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/550/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=550&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/04/29/multicasting-with-silverlight-3-local-messaging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb6.png" medium="image">
			<media:title type="html">Screenshot</media:title>
		</media:content>
	</item>
		<item>
		<title>Cloud Slam &#8216;09 Conference</title>
		<link>http://dvanderboom.wordpress.com/2009/04/14/cloud-slam-09-conference/</link>
		<comments>http://dvanderboom.wordpress.com/2009/04/14/cloud-slam-09-conference/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 16:03:46 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[Conferences]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/04/14/cloud-slam-09-conference/</guid>
		<description><![CDATA[If you’re interested in Cloud Computing, you should consider signing up for Cloud Slam, a very inexpensive four-day virtual conference.&#160; You can attend from the comfort of your home (or local wine or coffee shop), and have access to about 100 hours of sessions for only $52.&#160; It goes from April 20-24.
Speakers include such industry [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=543&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>If you’re interested in Cloud Computing, you should consider signing up for <a href="http://cloudslam09.com/" target="_blank">Cloud Slam</a>, a very inexpensive four-day virtual conference.&#160; You can attend from the comfort of your home (or local wine or coffee shop), and have access to about 100 hours of sessions for only $52.&#160; It goes from April 20-24.</p>
<p>Speakers include such industry leaders as Stephen Herrod, CTO of VMWare, Simon Crosby, CTO of Citrix Systems, Werner Vogels, CTO of Amazon.com, and many more.</p>
<p>I can’t say I’ll see you there, but I’m definitely looking forward to it.&#160; It should be a great source of information for what industry leaders are thinking and where cloud computing is headed.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/543/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=543&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/04/14/cloud-slam-09-conference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>
	</item>
		<item>
		<title>Advanced Customization of a Silverlight ListBox</title>
		<link>http://dvanderboom.wordpress.com/2009/04/13/advanced-customization-of-a-silverlight-listbox/</link>
		<comments>http://dvanderboom.wordpress.com/2009/04/13/advanced-customization-of-a-silverlight-listbox/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 17:06:03 +0000</pubDate>
		<dc:creator>Dan Vanderboom</dc:creator>
				<category><![CDATA[Custom Controls]]></category>
		<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Expression Blend]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[User Interface Design]]></category>

		<guid isPermaLink="false">http://dvanderboom.wordpress.com/2009/04/13/advanced-customization-of-a-silverlight-listbox/</guid>
		<description><![CDATA[[This article and its solution are based on Silverlight 3 Beta and Blend 3 Beta.]
The more I work with Silverlight, the more impressed I am.&#160; Though I do keep running into frustrating situations, I haven’t encountered nearly as many dead ends as I did writing Windows Forms applications.&#160; But where I used to run into [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=534&subd=dvanderboom&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><font color="#0000a0">[This article and its solution are based on <strong>Silverlight 3 Beta</strong> and <strong>Blend 3 Beta</strong>.]</font></p>
<p>The more I work with Silverlight, the more impressed I am.&#160; Though I do keep running into frustrating situations, I haven’t encountered <em>nearly </em>as many dead ends as I did writing Windows Forms applications.&#160; But where I used to run into dead ends, I now find myself lost in a labyrinth of deeply-composed control hierarchies, dichotomized content controls, and numerous interrelated control and data templates.</p>
<p>But ultimately I can find a way to do what I set out to do.&#160; That’s huge.&#160; If the learning curve is treacherously steep and my solution to a problem is tricky and twisted, I can reassure myself of more fluent UI design in the future due to increased understanding.&#160; The difficulty of solving these problems is due to complexity of the UI design itself, the immaturity of Silverlight and its APIs, and my own inexperience working with it.</p>
<p>You can <a href="http://danvanderboom.com/Examples/SilverlightListBoxDemo.zip" target="_blank">download the finished solution here</a>.</p>
<h1>The Goal</h1>
<p>When I set out to customize a list control, I didn’t start with the tools of Silverlight.&#160; I sketched out a design that assumed anything would be possible, and decided to figure out later how to implement exactly that (in behavior and layout, not final visuals).&#160; The mock-up below is similar to what I came up with, simplified to include only those elements I’m going to illustrate in this article.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb.png?w=500&#038;h=277" width="500" height="277" /></a></p>
<p>The first thing you’ll notice is that the data template renders differently based on the data for that item.&#160; I found a <a href="http://www.codeproject.com/KB/silverlight/UsingMultipleTemInListBox.aspx" target="_blank">Code Project article</a> by Anil Gupta on doing the same kind of thing.&#160; This turns out to be the easy part.&#160; (The space around and between items isn’t intended to be rendered as such, and was added only to emphasize the separate identities of the item templates.)</p>
<p>I also wanted each item in the list to be expandable to display more information and to host interactive controls like sliders (shown in the example) to manipulate the underlying data.&#160; In noticing that this button and behavior, as well as the border, are common elements to each of the item templates, I decided that what I was looking at involved a <a href="http://msdn.microsoft.com/en-us/library/bb613556.aspx" target="_blank">ContentControl</a>.&#160; This new control would contain these common elements and a ContentPresenter which would be filled by the specific item type template (one for airplane, one for truck, one for boat).&#160; That way, I could build a whole bunch of new templates for new item types and I wouldn’t have to worry about placing the button correctly or wiring up its behavior each time.</p>
<p>Though the illustration might suggest that the only difference among the templates is background color, I wanted to be able to completely differentiate them.&#160; The only thing that would be standard would be a collapsed height of 32 to give a nice consistent vertical layout (and for this example, a standard expanded height of 64).&#160; Inside, the controls and their layout could follow any design.</p>
<p>Unspecified at first, one of my presumptions was that the width of each item would fill all of the available space, which is the width of the ListBox minus borders, padding, and the vertical ScrollBar.&#160; This would prove to be the most difficult challenge, and I found some discussion <a href="http://silverlight.net/forums/t/16044.aspx" target="_blank">in the forums</a>, but ultimately I would find my own way to solve it.</p>
<p>Finally, I wanted to do as much as possible in Blend.&#160; XAML is fine for setting complex bindings and wiring up other things, but for drawing of graphics (editing templates), I wanted to leverage Blend as much as possible.</p>
<h1>The Solution</h1>
<p>First we need a data model, to know the shape of items that we’re binding to in our ListBox.&#160; I used a simple example of a Vehicle base class and three derived types.&#160; Elsewhere, I instantiate several of each type of vehicle and add them to the ListBox’s ItemsSource collection.</p>
<pre class="code"><span style="color:blue;"><font size="2">public abstract class </font></span><font size="2"><span style="color:#2b91af;">Vehicle
</span>{
    <span style="color:blue;">public string </span>Manufacturer { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public string </span>Model { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public double </span>Price { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}

<span style="color:blue;">public class </span><span style="color:#2b91af;">Truck </span>: </font><font size="2"><span style="color:#2b91af;">Vehicle
</span>{
    <span style="color:blue;">public bool </span>HasFourWheelDrive { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}

<span style="color:blue;">public class </span><span style="color:#2b91af;">Boat </span>: </font><font size="2"><span style="color:#2b91af;">Vehicle
</span>{
    <span style="color:blue;">public double </span>HullWidth { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}

<span style="color:blue;">public class </span><span style="color:#2b91af;">Airplane </span>: </font><font size="2"><span style="color:#2b91af;">Vehicle
</span>{
    <span style="color:blue;">public int </span>MaxAltitude { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I then created three UserControls, one for each vehicle type, and called them <strong>AirplaneTemplate</strong>, <strong>BoatTemplate</strong>, and <strong>TruckTemplate</strong>.&#160; I gave each of them a DesignHeight of 64 to represent their expanded state, let their Width be Auto, and set HorizontalAlignment to Stretch.&#160; I set the Height of each of the two Grid rows to 32, to ensure they wouldn’t stretch as the ContentControl hosting this content collapsed.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image1.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb1.png?w=504&#038;h=117" width="504" height="117" /></a></p>
<h2>Selecting a Template Based on Item Data</h2>
<p>There’s no way that I know of to write an expression in XAML that will bind to a different data template based on item data.&#160; I also know of no way to write code behind a data template.&#160; To get around these limitations, I created a data template called <strong>VehicleListDataTemplate</strong> that contains a single <strong>VehicleItemTemplate</strong> custom control which I could write code behind.&#160; This control is a ContentControl, so it’s capable of drawing its own content as well drawing content passed into it.&#160; The content that it supplies itself consists of the common UI elements: the border and the button to toggle the expansion or collapse of the item.</p>
<p>This control is mocked up like so, showing both collapsed and expanded states:</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image2.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb2.png?w=400&#038;h=187" width="400" height="187" /></a></p>
<p>The control’s ContentPresenter, set with its Content property, would occupy the same space, although the button would be placed on top to ensure it was clickable.</p>
<p>This was my first custom Silverlight control (other than UserControls), so several things were new to me.&#160; For one, defining a default control template in generic.xaml and writing a separate class file for behavior.&#160; This is what the default template looks like:</p>
<pre class="code"><font size="2"><span style="color:blue;">&lt;</span><span style="color:#a31515;">Style </span><span style="color:red;">TargetType</span></font><font size="2"><span style="color:blue;">=&quot;local:VehicleItemTemplate&quot;&gt;
    &lt;</span><span style="color:#a31515;">Setter </span><span style="color:red;">Property</span></font><font size="2"><span style="color:blue;">=&quot;Template&quot;&gt;
        &lt;</span><span style="color:#a31515;">Setter.Value</span></font><font size="2"><span style="color:blue;">&gt;
            &lt;</span><span style="color:#a31515;">ControlTemplate </span><span style="color:red;">TargetType</span></font><font size="2"><span style="color:blue;">=&quot;local:VehicleItemTemplate&quot;&gt;

                &lt;</span><span style="color:#a31515;">Grid </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span><span style="color:blue;">=&quot;Core&quot; </span><span style="color:red;">Background</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">Background</span></font><font size="2"><span style="color:blue;">}&quot;
                      </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignHeight</span><span style="color:blue;">=&quot;32&quot; </span><span style="color:red;">Height</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">Height</span></font><font size="2"><span style="color:blue;">}&quot;
                      </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignWidth</span><span style="color:blue;">=&quot;312&quot; </span><span style="color:red;">Width</span></font><font size="2"><span style="color:blue;">=&quot;Auto&quot;
                      </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;Stretch&quot; </span><span style="color:red;">HorizontalAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Stretch&quot;&gt;

                    &lt;</span><span style="color:#a31515;">Border </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;Stretch&quot; </span><span style="color:red;">CornerRadius</span></font><font size="2"><span style="color:blue;">=&quot;5,5,5,5&quot;
                            </span><span style="color:red;">BorderBrush</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">BorderBrush</span><span style="color:blue;">}&quot; </span><span style="color:red;">BorderThickness</span></font><span style="color:blue;"><font size="2">=&quot;2&quot; /&gt;

                    &lt;</font></span><font size="2"><span style="color:#a31515;">ContentPresenter
                        </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">VerticalContentAlignment</span></font><font size="2"><span style="color:blue;">}&quot;
                        </span><span style="color:red;">HorizontalAlignment</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">HorizontalContentAlignment</span></font><font size="2"><span style="color:blue;">}&quot;
                        </span><span style="color:red;">Content</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">Content</span></font><font size="2"><span style="color:blue;">}&quot;
                        </span><span style="color:red;">ContentTemplate</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">ContentTemplate</span><span style="color:blue;">}&quot; </span><span style="color:red;">Margin</span></font><font size="2"><span style="color:blue;">=&quot;0&quot;/&gt;

                    &lt;</span><span style="color:#a31515;">Button </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span><span style="color:blue;">=&quot;Expander&quot; </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;Top&quot; </span><span style="color:red;">HorizontalAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Right&quot;
                            </span><span style="color:red;">Margin</span><span style="color:blue;">=&quot;0,4,4,0&quot; </span><span style="color:red;">Width</span><span style="color:blue;">=&quot;28&quot; </span><span style="color:red;">Height</span></font><font size="2"><span style="color:blue;">=&quot;24&quot;
                            </span><span style="color:red;">BorderBrush</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">BorderBrush</span></font><font size="2"><span style="color:blue;">}&quot;/&gt;
                &lt;/</span><span style="color:#a31515;">Grid</span></font><font size="2"><span style="color:blue;">&gt;

            &lt;/</span><span style="color:#a31515;">ControlTemplate</span></font><font size="2"><span style="color:blue;">&gt;
        &lt;/</span><span style="color:#a31515;">Setter.Value</span></font><font size="2"><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">Setter</span></font><font size="2"><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">Style</span><span style="color:blue;">&gt;</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And here it’s referenced by the data template:</p>
<pre class="code"><font size="2"><span style="color:blue;">&lt;</span><span style="color:#a31515;">DataTemplate </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Key</span></font><font size="2"><span style="color:blue;">=&quot;VehicleListDataTemplate&quot;&gt;
    &lt;</span><span style="color:#a31515;">local</span><span style="color:blue;">:</span><span style="color:#a31515;">VehicleItemTemplate </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;Top&quot; </span><span style="color:red;">HorizontalAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Left&quot;
        </span><span style="color:red;">Background</span><span style="color:blue;">=&quot;#0014145D&quot; </span><span style="color:red;">Margin</span><span style="color:blue;">=&quot;0,0,0,0&quot; </span><span style="color:red;">BorderBrush</span></font><font size="2"><span style="color:blue;">=&quot;#FF5063A5&quot;
</span></font><font size="2"><span style="color:blue;">        </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignHeight</span><span style="color:blue;">=&quot;32&quot; </span><span style="color:red;">Height</span><span style="color:blue;">=&quot;32&quot; </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignWidth</span></font><font size="2"><span style="color:blue;">=&quot;430&quot;
        </span><span style="color:red;">VerticalContentAlignment</span><span style="color:blue;">=&quot;Stretch&quot; </span><span style="color:red;">HorizontalContentAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Stretch&quot; /&gt;
&lt;/</span><span style="color:#a31515;">DataTemplate</span><span style="color:blue;">&gt;</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>So far that’s not too bad.&#160; We have a data template, which refers to <strong>VehicleItemTemplate</strong> (a ContentControl) that gives our common appearance and hosts a specific vehicle UserControl depending on the item data in question.&#160; I count three layers so far, but unfortunately that isn’t enough.</p>
<p>Let’s take a look at how we set the content:</p>
<pre class="code"><font size="2"><span style="color:blue;">private void </span>VehicleItemTemplate_Loaded(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">RoutedEventArgs </span>e)
{
    <span style="color:blue;">var </span>vehicle = DataContext <span style="color:blue;">as </span><span style="color:#2b91af;">Vehicle</span>;

    </font><font size="2"><span style="color:green;">// vehicle will be null when this is executed in the designer
    </span><span style="color:blue;">if </span>(vehicle == <span style="color:blue;">null</span>)
        <span style="color:blue;">return</span>;

    <span style="color:blue;">if </span>(vehicle <span style="color:blue;">is </span><span style="color:#2b91af;">Airplane</span>)
        Content = <span style="color:blue;">new </span><span style="color:#2b91af;">AirplaneTemplate</span>();
    <span style="color:blue;">else if </span>(vehicle <span style="color:blue;">is </span><span style="color:#2b91af;">Truck</span>)
        Content = <span style="color:blue;">new </span><span style="color:#2b91af;">TruckTemplate</span>();
    <span style="color:blue;">else if </span>(vehicle <span style="color:blue;">is </span><span style="color:#2b91af;">Boat</span>)
        Content = <span style="color:blue;">new </span><span style="color:#2b91af;">BoatTemplate</span>();
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Pretty simple: the DataContext is our item data object, we can inspect the type to figure out which one it is, and create a new vehicle UserControl of the appropriate matching type to set the Content.</p>
<p>To make it expand and collapse, we first need to get a reference to the button in our template, which is based on the parts I defined for the control.</p>
<pre class="code"><font size="2">[<span style="color:#2b91af;">TemplatePart</span>(Name = <span style="color:#a31515;">&quot;Core&quot;</span>, Type = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">FrameworkElement</span>))]
[<span style="color:#2b91af;">TemplatePart</span>(Name = <span style="color:#a31515;">&quot;Expander&quot;</span>, Type = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">ButtonBase</span>))]
<span style="color:blue;">public class </span><span style="color:#2b91af;">VehicleItemTemplate </span>: <span style="color:#2b91af;">ContentControl</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In the template, the Expander part must be some control that inherits from ButtonBase, and which therefore implements a Click event.&#160; When the template is applied to the control at runtime, OnApplyTemplate is run, so we hook into that event there:</p>
<pre class="code"><font size="2"><span style="color:blue;">public override void </span>OnApplyTemplate()
{
    <span style="color:blue;">base</span>.OnApplyTemplate();
    ToggleButton = GetTemplateChild(<span style="color:#a31515;">&quot;Expander&quot;</span>) <span style="color:blue;">as </span><span style="color:#2b91af;">ButtonBase</span>;
    ToggleButton.Click += <span style="color:blue;">new </span><span style="color:#2b91af;">RoutedEventHandler</span>(btnToggleSize_Click);
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><font size="2"><span style="color:blue;">private void </span>btnToggleSize_Click(<span style="color:blue;">object </span>sender, <span style="color:#2b91af;">RoutedEventArgs </span>e)
{
    <span style="color:#2b91af;">Duration </span>duration = <span style="color:blue;">new </span><span style="color:#2b91af;">Duration</span>(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(0.2));

    <span style="color:#2b91af;">Storyboard </span>sb = <span style="color:blue;">new </span><span style="color:#2b91af;">Storyboard</span>();
    sb.Duration = duration;

    <span style="color:#2b91af;">DoubleAnimation </span>ani1 = <span style="color:blue;">new </span><span style="color:#2b91af;">DoubleAnimation</span>();
    ani1.Duration = duration;
    ani1.To = Height == 32 ? 64 : 32;
    <span style="color:#2b91af;">Storyboard</span>.SetTarget(ani1, <span style="color:blue;">this</span>);
    <span style="color:#2b91af;">Storyboard</span>.SetTargetProperty(ani1, <span style="color:blue;">new </span><span style="color:#2b91af;">PropertyPath</span>(<span style="color:#a31515;">&quot;FrameworkElement.Height&quot;</span>));

    <span style="color:#2b91af;">DoubleAnimation </span>ani2 = <span style="color:blue;">new </span><span style="color:#2b91af;">DoubleAnimation</span>();
    ani2.Duration = duration;
    ani2.To = Height == 32 ? 64 : 32;
    <span style="color:#2b91af;">Storyboard</span>.SetTarget(ani2, Content <span style="color:blue;">as </span><span style="color:#2b91af;">Control</span>);
    <span style="color:#2b91af;">Storyboard</span>.SetTargetProperty(ani2, <span style="color:blue;">new </span><span style="color:#2b91af;">PropertyPath</span>(<span style="color:#a31515;">&quot;FrameworkElement.Height&quot;</span>));

    sb.Children.Add(ani1);
    sb.Children.Add(ani2);

    sb.Begin();
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Now we have an animation that will smoothly expand or collapse our item and its content, and because I use the <strong>To</strong> property, we avoid jumping from one state to another.&#160; Instead, if we click to expand and then click to collapse again, it will animate from its current position to the desired position.</p>
<h2>Setting the Correct Width of ListBox Items</h2>
<p>The biggest problem I had was in setting the correct width.&#160; With all Widths set to Auto, each item in the list will take up only as much space as it needs.&#160; They can be shorter or longer than the ListBox’s width, and each item could be rendered a different width (depending on the template).</p>
<p>The first thing I tried was to set the <strong>VehicleItemTemplate</strong>’s Width to the ActualWidth of the ListBox.&#160; I didn’t have enough items in my list to see the vertical ScrollBar appear, but even without it, the borders of my item templates were being clipped by the right side of the ListBox, and I could see a gap of several pixels to the left as well as above and below each item.</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image3.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb3.png?w=500&#038;h=150" width="500" height="150" /></a></p>
<p>With the default rendering of Silverlight being that nothing is drawn (border widths are zero, brushes are null, etc.), I find it odd that the ListBox assumes I want padding where I haven’t specified any.&#160; After all, if I wanted this, couldn’t I add a Margin to my data template?</p>
<p>I removed the ListBox border, and finally added a ListBoxItem manually to the ListBox in Blend.&#160; Right-clicking on that ListBoxItem, I edited a copy of the control template, shown in the screenshot below:</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image4.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb4.png?w=504&#038;h=598" width="504" height="598" /></a></p>
<p>This turns out to be different from the data template defined earlier.&#160; This ListBoxItem template is itself a ContentControl, and its content is my VehicleListTemplate… (which is another ContentControl that hosts the specific vehicle UserControls…).&#160; See how confusing this can get?&#160; I feel like Alice in Wonderland sometimes, seeing how far the Silverlight hole really goes.&#160; I also wonder why there doesn’t appear to be any way to edit this template without manually creating a ListBoxItem, when it clearly matters even when you’re defining a data template.</p>
<p>It’s also in this ListBoxItem template that you can render visual decorators to indicate various visual states: Normal, MouseOver, Pressed, and so on.&#160; You might expect to handle that in your data template, but that doesn’t seem to be the case.</p>
<p>Anyway, within that ListBoxItem template was this ContentPresenter.</p>
<pre class="code"><font size="2"><span style="color:blue;">&lt;</span><span style="color:#a31515;">ContentPresenter </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span></font><font size="2"><span style="color:blue;">=&quot;contentPresenter&quot;
                  </span><span style="color:red;">HorizontalAlignment</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">HorizontalContentAlignment</span></font><font size="2"><span style="color:blue;">}&quot;
                  </span><span style="color:red;">Margin</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">Padding</span><span style="color:blue;">}&quot; </span><span style="color:red;">Content</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">Content</span></font><font size="2"><span style="color:blue;">}&quot;
                  </span><span style="color:red;">ContentTemplate</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">TemplateBinding </span><span style="color:red;">ContentTemplate</span><span style="color:blue;">}&quot;/&gt;</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The third line shows a Margin being bound to the Padding property.&#160; I removed this Margin altogether, and the gratuitous extra space around my items disappeared, making me happy.</p>
<p>Once you have this custom ListBoxItem template, you need to do two things:</p>
<ol>
<li>Delete the ListBoxItem you manually added in Blend.&#160; Otherwise you’ll get an error when trying to set the ListBox’s ItemsSource property. </li>
<li>Set the <strong>ItemContainerStyle</strong> property of the ListBox to point to this new template.&#160; Note that this is different from the <strong>ItemTemplate</strong> property which sets the data template. </li>
</ol>
<p>The ListBox XAML should now look something like this:</p>
<pre class="code"><font size="2"><span style="color:blue;">&lt;</span><span style="color:#a31515;">ListBox </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Name</span><span style="color:blue;">=&quot;VehicleList&quot; </span><span style="color:red;">HorizontalAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Stretch&quot;
         </span><span style="color:red;">Margin</span><span style="color:blue;">=&quot;20,20,20,20&quot; </span><span style="color:red;">Width</span></font><font size="2"><span style="color:blue;">=&quot;Auto&quot;
         </span><span style="color:red;">BorderThickness</span><span style="color:blue;">=&quot;2,2,2,2&quot; </span><span style="color:red;">BorderBrush</span></font><font size="2"><span style="color:blue;">=&quot;#FF99A712&quot;
         </span><span style="color:red;">ItemTemplate</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">StaticResource </span><span style="color:red;">VehicleListDataTemplate</span></font><font size="2"><span style="color:blue;">}&quot;
         </span><strong><span style="color:red;">ItemContainerStyle</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">StaticResource </span><span style="color:red;">ListBoxItemStyle</span></strong></font><font size="2"><span style="color:blue;"><strong>}&quot;</strong>&gt;
    &lt;</span><span style="color:#a31515;">ListBox.Background</span></font><font size="2"><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">LinearGradientBrush </span><span style="color:red;">EndPoint</span><span style="color:blue;">=&quot;0.5,1&quot; </span><span style="color:red;">StartPoint</span></font><font size="2"><span style="color:blue;">=&quot;0.5,0&quot;&gt;
            &lt;</span><span style="color:#a31515;">GradientStop </span><span style="color:red;">Color</span></font><font size="2"><span style="color:blue;">=&quot;#FF03021E&quot;/&gt;
            &lt;</span><span style="color:#a31515;">GradientStop </span><span style="color:red;">Color</span><span style="color:blue;">=&quot;#FF191651&quot; </span><span style="color:red;">Offset</span></font><font size="2"><span style="color:blue;">=&quot;1&quot;/&gt;
        &lt;/</span><span style="color:#a31515;">LinearGradientBrush</span></font><font size="2"><span style="color:blue;">&gt;
    &lt;/</span><span style="color:#a31515;">ListBox.Background</span></font><font size="2"><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">ListBox</span><span style="color:blue;">&gt;</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Now we’re at a point where the item container itself isn’t adding any extra space, so if we go without borders or a vertical ScrollBar, everything fits just right… until the vertical ScrollBar appears.&#160; This is close, but not good enough.&#160; How can we take care of the space taken up by the vertical ScrollBar?</p>
<p>While I was digging through the ListBox template, I noticed that the ScrollViewer control had a property called ViewportWidth, and with some debugging saw that it was not quite as wide as the total ListBox width.&#160; If only I had a reference to the ScrollViewer from within my <strong>VehicleItemTemplate</strong> ContentControl!&#160; I looked for a while but found nothing.&#160; You can call GetTemplateChild from within a control’s class but not from the outside because it’s a protected method.</p>
<p>I decided to cheat.&#160; I created a new ListBox class that exposed the ScrollViewer as a property.&#160; I felt it was safe to do so because ScrollViewer is a TemplatePart defined in the ListBox’s <em>parts and states</em> contract.</p>
<pre class="code"><font size="2"><span style="color:blue;">public class </span><span style="color:#2b91af;">MyListBox </span>: </font><font size="2"><span style="color:#2b91af;">ListBox
</span>{
    <span style="color:blue;">public </span>MyListBox() : <span style="color:blue;">base</span>() { }

    <span style="color:blue;">public </span><span style="color:#2b91af;">ScrollViewer </span>ScrollViewer
    {
        <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>GetTemplateChild(<span style="color:#a31515;">&quot;ScrollViewer&quot;</span>) <span style="color:blue;">as </span><span style="color:#2b91af;">ScrollViewer</span>; }
    }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I also needed to be able to reference the <strong>MyListBox</strong> object from each <strong>VehicleItemTemplate</strong>, so I created a DependencyProperty to store that:</p>
<pre class="code"><font size="2"><span style="color:green;">// store a reference to the MyListBox that contains this item
</span><span style="color:blue;">public static readonly </span><span style="color:#2b91af;">DependencyProperty </span>ParentListBoxProperty = <span style="color:#2b91af;">DependencyProperty</span>.Register(
    <span style="color:#a31515;">&quot;ParentListBox&quot;</span>, <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">MyListBox</span>), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">VehicleItemTemplate</span>), <span style="color:blue;">new </span><span style="color:#2b91af;">PropertyMetadata</span>(<span style="color:blue;">null</span>));

<span style="color:blue;">public </span><span style="color:#2b91af;">MyListBox </span>ParentListBox
{
    <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>GetValue(ParentListBoxProperty) <span style="color:blue;">as </span><span style="color:#2b91af;">MyListBox</span>; }
    <span style="color:blue;">set </span>{ SetValue(ParentListBoxProperty, <span style="color:blue;">value</span>); }
}</font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Next, I set this new <strong>ParentListBox</strong> property from within the data template I defined earlier (using Element binding, which is new to Silverlight 3):</p>
<pre class="code"><font size="2"><span style="color:blue;">&lt;</span><span style="color:#a31515;">DataTemplate </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Key</span></font><font size="2"><span style="color:blue;">=&quot;VehicleListDataTemplate&quot;&gt;
    &lt;</span><span style="color:#a31515;">local</span><span style="color:blue;">:</span><span style="color:#a31515;">VehicleItemTemplate </span><span style="color:red;">VerticalAlignment</span><span style="color:blue;">=&quot;Top&quot; </span><span style="color:red;">HorizontalAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Left&quot;
        </span><span style="color:red;">Background</span><span style="color:blue;">=&quot;#0014145D&quot; </span><span style="color:red;">Margin</span><span style="color:blue;">=&quot;0,0,0,0&quot; </span><span style="color:red;">BorderBrush</span></font><font size="2"><span style="color:blue;">=&quot;#FF5063A5&quot;
        </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignHeight</span><span style="color:blue;">=&quot;32&quot; </span><span style="color:red;">Height</span><span style="color:blue;">=&quot;32&quot; </span><span style="color:red;">d</span><span style="color:blue;">:</span><span style="color:red;">DesignWidth</span></font><font size="2"><span style="color:blue;">=&quot;430&quot;
        </span><span style="color:red;">VerticalContentAlignment</span><span style="color:blue;">=&quot;Stretch&quot; </span><span style="color:red;">HorizontalContentAlignment</span></font><font size="2"><span style="color:blue;">=&quot;Stretch&quot;
        </span><strong><span style="color:red;">ParentListBox</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">ElementName</span><span style="color:blue;">=VehicleList, </span><span style="color:red;">Mode</span></strong></font><font size="2"><span style="color:blue;"><strong>=OneWay}&quot;</strong>/&gt;
&lt;/</span><span style="color:#a31515;">DataTemplate</span><span style="color:blue;">&gt;</span></font></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Finally, I replaced the ListBox I was using with MyListBox, and in the VehicleItemTemplate_Loaded method, I added the following data binding in code:</p>
<pre class="code"><font size="2"><span style="color:green;">// set up data binding:
// ViewportWidth of the ListBox's ScrollViewer tells us how much space we have available
//(ListBox.ActualWidth - borders - scrollbar)
</span>WidthBinding = <span style="color:blue;">new </span><span style="color:#2b91af;">Binding</span>();
WidthBinding.Source = ParentListBox.ScrollViewer;
WidthBinding.Path = <span style="color:blue;">new </span><span style="color:#2b91af;">PropertyPath</span>(<span style="color:#a31515;">&quot;ViewportWidth&quot;</span>);
SetBinding(WidthProperty, WidthBinding);</font></pre>
<p>When there are more items than will fit in the ListBox, the vertical ScrollBar appears, and the width of all the item templates shrinks to accomodate it.&#160; When the ListBox itself widens or shrinks, it adjusts.&#160; This seems to produce the perfect fit for items.&#160; If you download the sample source code, you’ll notice I set the page to auto size, so when you resize the browser, the ListBox will grow and shrink along with it, and you can easily test it.&#160; Also, if you have the ListBox almost full and you expand one of the items with the expander button, you’ll see it adjust then as well.</p>
<p>Here is the final product:</p>
<p><a href="http://dvanderboom.files.wordpress.com/2009/04/image5.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://dvanderboom.files.wordpress.com/2009/04/image-thumb5.png?w=504&#038;h=206" width="504" height="206" /></a>&#160;</p>
<p>After all of that, we can finally rest assured that we’ll never see a horizontal ScrollBar in our ListBox.</p>
<h1>Conclusion</h1>
<p>There are several ListBox templates we didn’t take full advantage of: the ItemsPanel for the layout of items, the various embedded templates for parts such as ScrollBars, and the different states of the ListBoxItem template.&#160; However, customization of these templates has been covered fairly well by other articles.</p>
<p>Being somewhat new to Silverlight, I’m curious to see how others would have accomplished the same things.&#160; Is there an easier way to do some of this?&#160; Are there some Silverlight API calls I could have used to reference the ListBox’s ScrollViewer, for example?</p>
<p>I spent many hours working out these details.&#160; I hope I can spare some of you the trouble I encountered.&#160; Happy Silverlight developing!</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dvanderboom.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dvanderboom.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dvanderboom.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dvanderboom.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dvanderboom.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dvanderboom.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dvanderboom.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dvanderboom.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dvanderboom.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dvanderboom.wordpress.com/534/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dvanderboom.wordpress.com&blog=2293322&post=534&subd=dvanderboom&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://dvanderboom.wordpress.com/2009/04/13/advanced-customization-of-a-silverlight-listbox/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a59dbf3cc9c673540221e35e2c007ec1?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Dan</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://dvanderboom.files.wordpress.com/2009/04/image-thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
	</channel>
</rss>