<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>hardcodet.net</title>
	
	<link>http://www.hardcodet.net</link>
	<description>Confessions of a Code Addict</description>
	<pubDate>Thu, 15 Oct 2009 09:35:13 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/hardcodet" type="application/rss+xml" /><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/hardcodet" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.thefreedictionary.com/_/hp/AddRSS.aspx?http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://img.tfd.com/hp/addToTheFreeDictionary.gif">Subscribe with The Free Dictionary</feedburner:feedFlare><feedburner:feedFlare href="http://www.bitty.com/manual/?contenttype=rssfeed&amp;contentvalue=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.bitty.com/img/bittychicklet_91x17.gif">Subscribe with Bitty Browser</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsalloy.com/?rss=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.newsalloy.com/subrss3.gif">Subscribe with NewsAlloy</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://mix.excite.eu/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://image.excite.co.uk/mix/addtomix.gif">Subscribe with Excite MIX</feedburner:feedFlare><feedburner:feedFlare href="http://www.yourminis.com/subscribe.aspx?u=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.yourminis.com/images/addtoyourminisbadge.gif">Subscribe with Yourminis.com</feedburner:feedFlare><feedburner:feedFlare href="http://download.attensa.com/app/get_attensa.html?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.attensa.com/blogs/attensa/WindowsLiveWriter/BadgeredintoBadges_10C02/attensa_feed_button5.gif">Subscribe with Attensa for Outlook</feedburner:feedFlare><feedburner:feedFlare href="http://www.webwag.com/wwgthis.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.webwag.com/images/wwgthis.gif">Subscribe with Webwag</feedburner:feedFlare><feedburner:feedFlare href="http://hub.netomat.net/account/account.autoSubscribe.jspa?urls=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.netomat.net/blogger/images/icon_netomat_feedbutton.gif">Subscribe with netomat Hub</feedburner:feedFlare><feedburner:feedFlare href="http://www.podcastready.com/oneclick_bookmark.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.podcastready.com/images/podcastready_button.gif">Subscribe with Podcast Ready</feedburner:feedFlare><feedburner:feedFlare href="http://www.flurry.com/pushRssFeed.do?r=fb&amp;url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.flurry.com/images/flurry_rss_logo2.gif">Subscribe with Flurry</feedburner:feedFlare><feedburner:feedFlare href="http://www.wikio.com/subscribe?url=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.wikio.com/shared/img/add2wikio.gif">Subscribe with Wikio</feedburner:feedFlare><feedburner:feedFlare href="http://www.dailyrotation.com/index.php?feed=http%3A%2F%2Ffeeds.feedburner.com%2Fhardcodet" src="http://www.dailyrotation.com/rss-dr2.gif">Subscribe with Daily Rotation</feedburner:feedFlare><feedburner:browserFriendly>In order to import the feed into your mail client, just click on the "View Feed Xml" button.</feedburner:browserFriendly><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>WPF Disciples Resource Page Updated</title>
		<link>http://www.hardcodet.net/2009/10/wpf-disciples-resources-updated</link>
		<comments>http://www.hardcodet.net/2009/10/wpf-disciples-resources-updated#comments</comments>
		<pubDate>Thu, 15 Oct 2009 09:35:13 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[Disciples]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/10/wpf-disciples-resources-updated</guid>
		<description><![CDATA[Marlon updated the WPF Disciples resources page, which now lists a great selection of the group members’ contributions (including lots of MVVM goodness). Here’s the list: 
http://wpfdisciples.wordpress.com/resources/
&#160;

]]></description>
			<content:encoded><![CDATA[<p><a href="http://marlongrech.wordpress.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/marlongrech.wordpress.com');">Marlon</a> updated the WPF Disciples resources page, which now lists a great selection of the group members’ contributions (including lots of MVVM goodness). Here’s the list: </p>
<p><a href="http://wpfdisciples.wordpress.com/resources/" onclick="javascript:pageTracker._trackPageview('/outbound/article/wpfdisciples.wordpress.com');">http://wpfdisciples.wordpress.com/resources/</a></p>
<p>&#160;</p>
<p><img title="WPF Disciples" alt="WPF Disciples Logo" src="/uploads/wpf-disciples.png" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/10/wpf-disciples-resources-updated/feed</wfw:commentRss>
		</item>
		<item>
		<title>Windows Live Writer: Plug-ins to Format Content through CSS Classes</title>
		<link>http://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes</link>
		<comments>http://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes#comments</comments>
		<pubDate>Wed, 30 Sep 2009 20:12:15 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Blogging]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Live Writer]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=637</guid>
		<description><![CDATA[Presents two simple plug-ins that provide CSS formatting support for Windows Live Writer.]]></description>
			<content:encoded><![CDATA[<p>I like using CSS classes to format specific content of my blog posts, in order to keep my formatting centralized. I prefer HTML that looks like this over inline styles: </p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none">If you invoke the <span style="color: #0000ff">&lt;</span><span style="color: #800000">span</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;code&quot;</span><span style="color: #0000ff">&gt;</span>GetData<span style="color: #0000ff">&lt;/</span><span style="color: #800000">span</span><span style="color: #0000ff">&gt; </span>method, ...</pre>
<p></div>
<p>&#160;</p>
<p>Quickly inserting CSS directives is something you can’t easily do with <a href="http://windowslivewriter.spaces.live.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/windowslivewriter.spaces.live.com');">Windows Live Writer</a>. This started to annoy me while writing an article, so I came up with two simple plug-ins that do just that: Formatting selected text through CSS classes.</p>
<p>&#160;</p>
<p><span id="more-637"></span></p>
<p><em></em></p>
<h2>Plug-in 1: Quick-Insert a Predefined CSS Class</h2>
<p>This is a very simple plug-in that stores one (1) single CSS class name, and applies it to the selected text with a single click. This is a fastest possible way to format several junks of your post with the same CSS class.</p>
<p>The simple assignment comes has a price, however: It takes some more work to reconfigure the used CSS class. Therefore, it mainly makes sense if you have quite a lot of similar content to format at once. Otherwise, the second plug-in is probably the better choice.</p>
<p>&#160;</p>
<h3>Using the Plug-in</h3>
<p>Once the plug-in is installed (instructions at the end of the article), you’ll notice an additional entry on the side bar and the <em>Insert</em> menu of the tool bar, saying “<em>Quick CSS…</em>”:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image1.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="203" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb1.png" width="172" border="0" /></a> </p>
<p>All you have to do is selecting the portion of text you’d like to format, and click on the plug-in. The configured CSS class name will be immediately applied to the selected text.</p>
<p>&#160;</p>
<h3>First invocation / configuration</h3>
<p>The <em>first</em> time you click on the plug-in, there is no formatting happening. Instead, the plug-in displays its options dialog because no CSS class has been configured yet. This dialog allows you to quickly set the CSS class that should be applied:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image2.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="151" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb2.png" width="240" border="0" /></a> </p>
<p>Subsequent clicks on the plug-in directly apply the class name you configured – this dialog is only opened automatically the first time.</p>
<p>&#160;</p>
<h4>Changing the Class Name</h4>
<p>You can change the name of the used CSS class at any time. This requires a bit of work though, as you’ll have to go through Live Writer’s options dialog:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image3.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="300" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb3.png" width="300" border="0" /></a> </p>
<p>&#160;</p>
<h2>Plug-in 2: Selecting a CSS Class from a List of Class Names</h2>
<p>This is a more flexible plug-in. It takes two clicks to format your text with a given CSS class, but it maintains a configurable list of CSS class names, and allows you to quickly select the class name to be applied from a popup.</p>
<h3>Using the Plug-in</h3>
<p>Once the plug-in is installed (instructions below), you will find a new entry saying <em>“CSS Format</em>…” on the side bar and Live Writer’s <em>Insert</em> menu. Clicking the plug-in (which causes a short delay the first time) opens a popup that lists your CSS classes in alphabetic order. In order to apply a CSS class to the selected text, just double-click a class name:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image4.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="349" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb4.png" width="244" border="0" /></a> </p>
<p>&#160;</p>
<h4>Most Recently Used Items</h4>
<p>Note that if you have configured 10 or more CSS class names, the popup will display two lists, of which the upper list contains the 5 most recently used class names.</p>
<p>(I could make that feature configurable in a subsequent release, if requested.)</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image5.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="244" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb5.png" width="166" border="0" /></a> </p>
<p>&#160;</p>
<h3>Configuring / Importing CSS Class Names</h3>
<p>The plug-in allows you to quickly configure class names through a custom configuration dialog, and also supports importing class names directly from a CSS Style Sheet. You can open the dialog through the Popup by clicking the “<em>Options</em>” button:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/09/image6.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="331" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb6.png" width="304" border="0" /></a> </p>
<p>&#160;</p>
<h4>Style Sheet Import</h4>
<p>Clicking the <em>Import Style Sheet</em> button opens a file dialog that allows you to select a style sheet (probably the one you’re also using on your blog). Once selected, the plug-in imports all new class names from the style sheet.</p>
<p>&#160;</p>
<h2>Live Writer Bug: Reformatting Span-Tags</h2>
<p>It appears that Live Writer has a bug when it comes to reformatting already formatted text spans. There’s currently no simple fix for this bug, so keep this in mind:</p>
<p>Imagine you have a preformatted junk of text that looks like this:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">span</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;foo&quot;</span><span style="color: #0000ff">&gt;</span>hello<span style="color: #0000ff">&lt;/</span><span style="color: #800000">span</span><span style="color: #0000ff">&gt;</span></pre>
<p></div>
<p>Now, if you select the word “hello”, and try to assign it another CSS class (<span class="code">bar</span>), you’d expect the new markup to look like this:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">span</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;bar&quot;</span><span style="color: #0000ff">&gt;</span>hello<span style="color: #0000ff">&lt;/</span><span style="color: #800000">span</span><span style="color: #0000ff">&gt;</span></pre>
<p></div>
<p>Instead, Live Writer just keeps the old span, and wraps it into a second one.</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">span</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;foo&quot;</span><span style="color: #0000ff">&gt;&lt;</span><span style="color: #800000">span</span> <span style="color: #ff0000">class</span><span style="color: #0000ff">=&quot;bar&quot;</span><span style="color: #0000ff">&gt;</span>world<span style="color: #0000ff">&lt;/</span><span style="color: #800000">span</span><span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">span</span><span style="color: #0000ff">&gt;</span></pre>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </p></div>
<p>&#160;</p>
<h2>Download and Installation Instructions</h2>
<p>&#160;</p>
<h4>Download Links</h4>
<p>Plug-in 1: <a href="/uploads/projects/livewriter/Hardcodet.LiveWriter.QuickClassInsert.dll">Hardcodet.LiveWriter.QuickClassInsert.dll</a></p>
<p>Plug-in 2: <a href="/uploads/projects/livewriter/Hardcodet.LiveWriter.ApplyCss.dll">Hardcodet.LiveWriter.ApplyCss.dll</a><a href="/uploads/projects/livewriter/Hardcodet.LiveWriter.ApplyCss.dll"></a> </p>
<p><font size="1">The second plug-in <font color="#ff0000">requires Microsoft .NET Framework 3.5 SP1</font> (download <a href="http://go.microsoft.com/fwlink/?LinkId=76617" onclick="javascript:pageTracker._trackPageview('/outbound/article/go.microsoft.com');">here</a>)</font></p>
<p>&#160;</p>
<h4>Installation</h4>
<p>In order to install a plug-in:</p>
<ol>
<li>Make sure Live Writer is not running </li>
<li>Copy the plug-in DLL into Live Writer’s <em>Plugins</em> folder. Usually, this is the following path: <em>C:\Program Files\Windows Live Writer\Plugins\ </em></li>
</ol>
<ol>&#160;</ol>
<h4>Source Code Download for Developers</h4>
<p>You can also download the source code of the plug-ins:</p>
<p>&#160;</p>
<p><a href="/uploads/projects/livewriter/css-plugins-for-live-writer.zip"></a><a class="download" href="/uploads/projects/livewriter/css-plugins-for-live-writer.zip">css-plugins-for-live-writer.zip</a></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/09/live-writer-plugins-to-format-content-through-css-classes/feed</wfw:commentRss>
		</item>
		<item>
		<title>Making WPF Popups Work in Windowless Applications</title>
		<link>http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled</link>
		<comments>http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled#comments</comments>
		<pubDate>Wed, 23 Sep 2009 10:08:24 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled</guid>
		<description><![CDATA[I’ve first encountered this issue with my WPF NotifyIcon, and now again while writing a plug-in for Windows Live Writer: If you try to display a WPF popup without any Windows open (the Popup is the only UI component there is), certain controls such as TextBox, ListView, or ListBox don’t receive proper mouse and/or keyboard [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve first encountered this issue with my WPF NotifyIcon, and now again while writing a plug-in for Windows Live Writer: If you try to display a WPF popup without any Windows open (the Popup is the only UI component there is), certain controls such as TextBox, ListView, or ListBox don’t receive proper mouse and/or keyboard input, and cannot be selected.</p>
<p>The reason for this issue is buried in the WPF framework, and how it interacts with Windows. Fellow WPF Disciple Andrew Smith pointed me in the right direction:</p>
<p>&#160;</p>
<blockquote><p>…because a Popup&#8217;s HWND has the WS_EX_NOACTIVATE so the WPF framework will not attempt to actually focus the associated hwnd (because its usually used with a window and you don&#8217;t want to deactivate the window when you focus something in the popup).</p>
</blockquote>
<p>&#160;</p>
<p>Accordingly, you’ll have to fiddle with Windows Interop to make things work. Here’s the snippet:</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> WinApi
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Gives focus to a given window.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  [DllImport(<span style="color: #006080">&quot;USER32.DLL&quot;</span>)]
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">extern</span> <span style="color: #0000ff">bool</span> SetForegroundWindow(IntPtr hWnd);

  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> ActivatePopup(Popup popup)
  {
    <span style="color: #008000">//try to get a handle on the popup itself (via its child)</span>
    HwndSource source = (HwndSource)PresentationSource.FromVisual(popup.Child);
    IntPtr handle = source.Handle;

    <span style="color: #008000">//activate the popup</span>
    SetForegroundWindow(handle);
  }
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/09/activating-wpf-popups-ensures-controls-are-enabled/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF NotifyIcon – Bugfix and WinForms Support</title>
		<link>http://www.hardcodet.net/2009/09/wpf-notifyicon-bugfix-and-winforms-support</link>
		<comments>http://www.hardcodet.net/2009/09/wpf-notifyicon-bugfix-and-winforms-support#comments</comments>
		<pubDate>Tue, 22 Sep 2009 07:32:15 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/09/wpf-notifyicon-bugfix-and-winforms-support</guid>
		<description><![CDATA[I released an update to my WPF NotifyIcon, which fixes two issues:

Interactive Popups should now fully support all control types. 
The control can now be used in Windows Forms projects, if you need more functionality than the built-in component. 

The solution now comes with an additional WinForms sample project, which shows how to display a [...]]]></description>
			<content:encoded><![CDATA[<p>I released an update to my WPF NotifyIcon, which fixes two issues:</p>
<ul>
<li>Interactive Popups should now fully support all control types. </li>
<li>The control can now be used in Windows Forms projects, if you need more functionality than the built-in component. </li>
</ul>
<p>The solution now comes with an additional WinForms sample project, which shows how to display a WPF user control as an interactive popup.</p>
<p> <a href="http://www.hardcodet.net/uploads/2009/09/image.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="155" alt="image" src="http://www.hardcodet.net/uploads/2009/09/image-thumb.png" width="214" border="0" /></a>
<ul></ul>
<p>&#160;</p>
<p>Download link and further information can be found on the control’s home page:    <br /><a href="http://www.hardcodet.net/wpf-notifyicon" >http://www.hardcodet.net/wpf-notifyicon</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/09/wpf-notifyicon-bugfix-and-winforms-support/feed</wfw:commentRss>
		</item>
		<item>
		<title>NetDrives 1.0.1 Fixes Settings Bug</title>
		<link>http://www.hardcodet.net/2009/09/netdrives-update-101</link>
		<comments>http://www.hardcodet.net/2009/09/netdrives-update-101#comments</comments>
		<pubDate>Tue, 22 Sep 2009 07:30:52 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[NetDrives]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/09/netdrives-update-101</guid>
		<description><![CDATA[I updated NetDrives, which fixes a registry issue when it comes to saving the application settings. Functionality is still the same, though.
Project Page: http://www.hardcodet.net/netdrives
]]></description>
			<content:encoded><![CDATA[<p>I updated NetDrives, which fixes a registry issue when it comes to saving the application settings. Functionality is still the same, though.</p>
<p>Project Page: <a title="http://www.hardcodet.net/netdrives" href="http://www.hardcodet.net/netdrives" >http://www.hardcodet.net/netdrives</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/09/netdrives-update-101/feed</wfw:commentRss>
		</item>
		<item>
		<title>Snippet Time: Helper Libraries for C# / WPF</title>
		<link>http://www.hardcodet.net/2009/09/common-helper-libraries</link>
		<comments>http://www.hardcodet.net/2009/09/common-helper-libraries#comments</comments>
		<pubDate>Mon, 14 Sep 2009 19:23:35 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[WPF]]></category>

		<category><![CDATA[Utils]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=601</guid>
		<description><![CDATA[I just made a few minor updates to two libraries which assemble as set of helper classes for C# and WPF and thought: Why not share them? The libraries aren’t really intended to be used directly in your code, but you might find one or another helper method or snippet that might make a nice [...]]]></description>
			<content:encoded><![CDATA[<p>I just made a few minor updates to two libraries which assemble as set of helper classes for C# and WPF and thought: Why not share them? The libraries aren’t really intended to be used directly in your code, but you might find one or another helper method or snippet that might make a nice addition to your own toolbox <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&#160;</p>
<p><a class="download" title="Hardcodet.Commons Library" href="/uploads/2009/09/Hardcodet.Commons.zip">Hardcodet.Commons</a> (C#, .NET 3.5)    </p>
<p>Common helper classes and snippets (simple base classes, file management, weak events, extension methods etc.)</p>
<p>&#160;</p>
<p><a class="download" title="Hardcodet.Commons Library for WPF" href="/uploads/2009/09/Hardcodet.Wpf.Commons.zip">Hardcodet.Wpf.Commons</a> (C#, .NET 3.5)    </p>
<p>Stuff I commonly use in WPF projects, such as checking for design time, base classes for commands and converters, data binding helpers and other stuff.</p>
<p>&#160;</p>
<p>I’ll keep these libraries up-to-date, version history will be posted here.</p>
<p>&#160;</p>
<p><strong>History:</strong></p>
<p><font face="Courier New">2009.09.14&#160; Initial blog release</font></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/09/common-helper-libraries/feed</wfw:commentRss>
		</item>
		<item>
		<title>Linked Images in WPF Projects – Bad Idea?</title>
		<link>http://www.hardcodet.net/2009/08/linked-images-in-wpf-projects-cause-issues</link>
		<comments>http://www.hardcodet.net/2009/08/linked-images-in-wpf-projects-cause-issues#comments</comments>
		<pubDate>Mon, 10 Aug 2009 18:25:07 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF Controls]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/08/linked-images-in-wpf-projects-cause-issues</guid>
		<description><![CDATA[Describes potential issues when using linked images in WPF projects, which do not show at runtime.]]></description>
			<content:encoded><![CDATA[<p>I discovered today that images that are included in a VS project as links are compiled differently than images that are stored as part of the project. This one might cost you quite some time, so here’s a few observations on the issue…</p>
<p>Look at this simple project that contains two image files. One file is part of the project (physically stored in the <em>Images</em> folder), the other one added as a link. Both files have the same build action (Resource):</p>
<p><a href="http://www.hardcodet.net/uploads/2009/08/image.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="179" alt="image" src="http://www.hardcodet.net/uploads/2009/08/image-thumb.png" width="253" border="0" /></a> </p>
<p>&#160;</p>
<p>Now, if you declare these two images the same way, everything appears to be fine in the designer (both Visual Studio and Blend):</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Window</span> <span style="color: #ff0000">x:Class</span><span style="color: #0000ff">=&quot;WpfApplication2.Window1&quot;</span>
    <span style="color: #ff0000">xmlns</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span>
    <span style="color: #ff0000">xmlns:x</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span>
    <span style="color: #ff0000">Title</span><span style="color: #0000ff">=&quot;Window1&quot;</span> <span style="color: #ff0000">Height</span><span style="color: #0000ff">=&quot;150&quot;</span> <span style="color: #ff0000">Width</span><span style="color: #0000ff">=&quot;150&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">StackPanel</span> <span style="color: #ff0000">VerticalAlignment</span><span style="color: #0000ff">=&quot;Center&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span> <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;/Images/Add-Item.png&quot;</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;None&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span> <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;/Images/Remove-Item.png&quot;</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;None&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">StackPanel</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Window</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/08/image1.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="154" alt="image" src="http://www.hardcodet.net/uploads/2009/08/image-thumb1.png" width="207" border="0" /></a> </p>
<p>&#160;</p>
<p>However, as soon as you compile and start your application, the linked image does not appear – obviously, the runtime could not resolve it at runtime:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/08/image2.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="144" alt="image" src="http://www.hardcodet.net/uploads/2009/08/image-thumb2.png" width="244" border="0" /></a> </p>
<p>&#160;</p>
<p>I was quite surprised about this until I reverted to Reflector, which reveals that the linked image was embedded differently than the other one. Here’s the resource entries of the compiled WPF application:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/08/image3.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="133" alt="image" src="http://www.hardcodet.net/uploads/2009/08/image-thumb3.png" width="421" border="0" /></a> </p>
<p>&#160;</p>
<p>As you can see, the linked image (<em>Remove-Item.</em>png) was included without the folder name, in lower case. Accordingly, I had to adjust the image source in XAML as follows:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Window</span> <span style="color: #ff0000">x:Class</span><span style="color: #0000ff">=&quot;WpfApplication2.Window1&quot;</span>
    <span style="color: #ff0000">xmlns</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span>
    <span style="color: #ff0000">xmlns:x</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span>
    <span style="color: #ff0000">Title</span><span style="color: #0000ff">=&quot;Window1&quot;</span> <span style="color: #ff0000">Height</span><span style="color: #0000ff">=&quot;150&quot;</span> <span style="color: #ff0000">Width</span><span style="color: #0000ff">=&quot;150&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">StackPanel</span> <span style="color: #ff0000">VerticalAlignment</span><span style="color: #0000ff">=&quot;Center&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span> <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;/Images/Add-Item.png&quot;</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;None&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span> <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;/remove-item.png&quot;</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;None&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">StackPanel</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Window</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>This one works at runtime. BUT it breaks the designer. I’m not too happy about that one – whether a file is linked to or not should not affect the outcome of the compiled build all. <strike>I’m not too sure whether this was a conscious decision or a bug, but it sure is a major pain.</strike> </p>
<p><strong><font color="#ff0000">Update:</font></strong> Microsoft confirmed this to be a bug, which should be fixed in the upcoming version of the framework / VS2010. So for now, linking is out of the picture for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/08/linked-images-in-wpf-projects-cause-issues/feed</wfw:commentRss>
		</item>
		<item>
		<title>Finding Elements in the WPF Tree - Both Ways</title>
		<link>http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways</link>
		<comments>http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways#comments</comments>
		<pubDate>Thu, 25 Jun 2009 12:42:06 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=575</guid>
		<description><![CDATA[A complementary snippet to an earlier post that allows you now to find either a parent or children of a given item within WPF visual or logical tree.]]></description>
			<content:encoded><![CDATA[<p>A while ago I posted a helper method to traverse a (visual or logical) tree in order to find an element’s <em>parent</em> of a given type. The corresponding blog entry is <a title="Finding ancestor of a WPF dependency object" href="http://www.hardcodet.net/2008/02/find-wpf-parent"  target="_blank">here</a>.</p>
<p>This time, I needed to search the other way: I wanted to find all descendants (direct or indirect childs) of a given element that match a given type. As a result, I came up with a complementary extension method that does the job for me:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">//get all TextBox controls within the grid:</span>
Grid container;
IEnumerable&lt;TextBox&gt; editors = container.FindChildren&lt;TextBox&gt;();</pre>
</div>
<p>&#160;</p>
<h3>Usage Sample</h3>
<p>As a sample, let’s use a window dialog which contains several images:</p>
<ul>
<li>Images that were pasted into a <em>RichTextBox </em>control. </li>
<li>Images that are part of the UI, nested within the control hierarchy of a ribbon. </li>
</ul>
<p><img title="editor" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="377" alt="editor" src="http://www.hardcodet.net/uploads/2009/06/editor.png" width="524" border="0" /> </p>
<p>&#160;</p>
<p>In order to find all these <em>Image</em> elements you can see on the screenshot, this will do:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">//start a the root (the window itself)</span>
Window window = <span style="color: #0000ff">this</span>;
<span style="color: #0000ff">foreach</span> (Image img <span style="color: #0000ff">in</span> window.FindChildren&lt;Image&gt;())
{
  Console.WriteLine(<span style="color: #006080">&quot;Image source: &quot;</span> + img.Source);
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<p>&#8230;the above snippet produces the following output:</p>
<p><em><font size="1">Image source: pack://payload:,,wpf1,/Xaml/Image1.png<br />
      <br />Image source: pack://payload:,,wpf1,/Xaml/Image2.png </p>
<p>Image source: pack://application:,,,/Shared/Images/Ribbon/Paste_32&#215;32.png </p>
<p>Image source: System.Windows.Media.Imaging.FormatConvertedBitmap </p>
<p>Image source: System.Windows.Media.Imaging.FormatConvertedBitmap </p>
<p>Image source: pack://application:,,,/Shared/Images/Ribbon/EditUndo.png </p>
<p>Image source: pack://application:,,,/Shared/Images/Ribbon/EditRedo.png </p>
<p>Image source: pack://application:,,,/Shared/Images/Ribbon/Bold.png </p>
<p>Image source: System.Windows.Media.Imaging.BitmapFrameEncode </p>
<p>[…]</font></em></p>
<p>&#160;</p>
<p>Accordingly, in order to analyze only the contents of the rich text editor, just start on a lower level of the tree:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">//only examine the contents of the editor</span>
RichTextBox editor = <span style="color: #0000ff">this</span>.txtContent;
<span style="color: #0000ff">foreach</span> (Image img <span style="color: #0000ff">in</span> editor.FindChildren&lt;Image&gt;())
{
  Console.WriteLine(<span style="color: #006080">&quot;Image source: &quot;</span> + img.Source);
}</pre>
</div>
<p>&#160;</p>
<p><a title="http://www.hardcodet.net/uploads/2009/06/UIHelper.cs" href="http://www.hardcodet.net/uploads/2009/06/UIHelper.cs" ></a></p>
<h3>Implementation</h3>
<p>
  <br />(Download link at the end of the posting)</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none">

<span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Analyzes both visual and logical tree in order to find all elements</span>
<span style="color: #008000">/// of a given type that are descendants of the &lt;paramref name=&quot;source&quot;/&gt;</span>
<span style="color: #008000">/// item.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;typeparam name=&quot;T&quot;&gt;The type of the queried items.&lt;/typeparam&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;source&quot;&gt;The root element that marks the source of the</span>
<span style="color: #008000">/// search. If the source is already of the requested type, it will not</span>
<span style="color: #008000">/// be included in the result.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;All descendants of &lt;paramref name=&quot;source&quot;/&gt; that match the</span>
<span style="color: #008000">/// requested type.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> IEnumerable&lt;T&gt; FindChildren&lt;T&gt;(<span style="color: #0000ff">this</span> DependencyObject source)
                                             <span style="color: #0000ff">where</span> T : DependencyObject
{
  <span style="color: #0000ff">if</span> (source != <span style="color: #0000ff">null</span>)
  {
    var childs = GetChildObjects(source);
    <span style="color: #0000ff">foreach</span> (DependencyObject child <span style="color: #0000ff">in</span> childs)
    {
      <span style="color: #008000">//analyze if children match the requested type</span>
      <span style="color: #0000ff">if</span> (child != <span style="color: #0000ff">null</span> &amp;&amp; child <span style="color: #0000ff">is</span> T)
      {
        <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> (T) child;
      }

      <span style="color: #008000">//recurse tree</span>
      <span style="color: #0000ff">foreach</span> (T descendant <span style="color: #0000ff">in</span> FindChildren&lt;T&gt;(child))
      {
        <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> descendant;
      }
    }
  }
}

<span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// This method is an alternative to WPF's</span>
<span style="color: #008000">/// &lt;see cref=&quot;VisualTreeHelper.GetChild&quot;/&gt; method, which also</span>
<span style="color: #008000">/// supports content elements. Do note, that for content elements,</span>
<span style="color: #008000">/// this method falls back to the logical tree of the element.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;parent&quot;&gt;The item to be processed.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;The submitted item's child elements, if available.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> IEnumerable&lt;DependencyObject&gt; GetChildObjects(
                                            <span style="color: #0000ff">this</span> DependencyObject parent)
{
  <span style="color: #0000ff">if</span> (parent == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">yield</span> <span style="color: #0000ff">break</span>;
  

  <span style="color: #0000ff">if</span> (parent <span style="color: #0000ff">is</span> ContentElement || parent <span style="color: #0000ff">is</span> FrameworkElement)
  {
    <span style="color: #008000">//use the logical tree for content / framework elements</span>
    <span style="color: #0000ff">foreach</span> (<span style="color: #0000ff">object</span> obj <span style="color: #0000ff">in</span> LogicalTreeHelper.GetChildren(parent))
    {
      var depObj = obj <span style="color: #0000ff">as</span> DependencyObject;
      <span style="color: #0000ff">if</span> (depObj != <span style="color: #0000ff">null</span>) <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> (DependencyObject) obj;
    }
  }
  <span style="color: #0000ff">else</span>
  {
    <span style="color: #008000">//use the visual tree per default</span>
    <span style="color: #0000ff">int</span> count = VisualTreeHelper.GetChildrenCount(parent);
    <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0; i &lt; count; i++)
    {
      <span style="color: #0000ff">yield</span> <span style="color: #0000ff">return</span> VisualTreeHelper.GetChild(parent, i);
    }
  }
}
</pre>
</div>
<p>&#160;</p>
<p>For your convenience, I’ve put together a simple helper class that contains the helper methods to search for both children and parent elements in the tree:</p>
<p><a title="http://www.hardcodet.net/uploads/2009/06/UIHelper.cs" href="http://www.hardcodet.net/uploads/2009/06/UIHelper.cs" >http://www.hardcodet.net/uploads/2009/06/UIHelper.cs</a></p>
<p>&#160;</p>
<p>Happy coding <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/06/finding-elements-in-wpf-tree-both-ways/feed</wfw:commentRss>
		</item>
		<item>
		<title>Beginner’s Tutorial: 3D Line and Border Effects in XAML</title>
		<link>http://www.hardcodet.net/2009/05/tutorial-on-3d-line-and-border-effects-in-xaml</link>
		<comments>http://www.hardcodet.net/2009/05/tutorial-on-3d-line-and-border-effects-in-xaml#comments</comments>
		<pubDate>Thu, 28 May 2009 10:54:15 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/tutorial-on-3d-line-and-border-effects-in-xaml</guid>
		<description><![CDATA[Mini tutorial which shows how to simply create 3D line and border effects in XAML.]]></description>
			<content:encoded><![CDATA[<p>This mini-tutorial might be for you if you’re having troubles finding the right line colors to achieve simple 3D effects like these:</p>
<p><img title="linesamples" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="178" alt="linesamples" src="http://www.hardcodet.net/uploads/2009/05/linesamples.png" width="331" border="0" /> </p>
<p>&#160;</p>
<p>The solution to this very problem is actually pretty simple, and it always takes the same three ingredients:</p>
<ul>
<li>A white line </li>
<li>A black line </li>
<li>Reduced opacity </li>
</ul>
<p>Basically, to get an edged line on a green background, <strong>you don’t need to fiddle with different shades of green</strong>. Just use white and black lines and play with the opacity. Here’s the settings in Blend for one of the white lines in the above screenshot:</p>
<p><img title="highlighted-line-settings" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="338" alt="highlighted-line-settings" src="http://www.hardcodet.net/uploads/2009/05/highlightedlinesettings.png" width="282" border="0" /> </p>
<p>&#160;</p>
<p>…and this is the corresponding XAML for the two vertical lines:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">Background</span><span style="color: #0000ff">=&quot;Green&quot;</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Path</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;Fill&quot;</span> <span style="color: #ff0000">Stroke</span><span style="color: #0000ff">=&quot;#5A000000&quot;</span> <span style="color: #ff0000">Margin</span><span style="color: #0000ff">=&quot;25,62,0,0&quot;</span>
        <span style="color: #ff0000">Width</span><span style="color: #0000ff">=&quot;1&quot;</span> <span style="color: #ff0000">Height</span><span style="color: #0000ff">=&quot;100&quot;</span> <span style="color: #ff0000">Data</span><span style="color: #0000ff">=&quot;M130,176 L130,303.03543&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Path</span> <span style="color: #ff0000">Stretch</span><span style="color: #0000ff">=&quot;Fill&quot;</span> <span style="color: #ff0000">Stroke</span><span style="color: #0000ff">=&quot;#5AFFFFFF&quot;</span> <span style="color: #ff0000">Margin</span><span style="color: #0000ff">=&quot;26,62,0,0&quot;</span>
        <span style="color: #ff0000">Width</span><span style="color: #0000ff">=&quot;1&quot;</span> <span style="color: #ff0000">Height</span><span style="color: #0000ff">=&quot;100&quot;</span> <span style="color: #ff0000">Data</span><span style="color: #0000ff">=&quot;M130,176 L130,303.03543&quot;</span><span style="color: #0000ff">/&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<h4>Tip: Hiding Blend’s Handles</h4>
<p>If you’re trying to format a line, Blend’s handles don’t help much, as the basically hide the whole content:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/05/blendhandles.png" ><img title="blend-handles" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="135" alt="blend-handles" src="http://www.hardcodet.net/uploads/2009/05/blendhandles-thumb.png" width="93" border="0" /></a> </p>
<p>However - you can easily hide / show them by <strong>pressing the F9 button</strong>.</p>
<p>&#160;</p>
<h3>Tutorial: Creating a 3D Toggle Button Style</h3>
<p>Another usage of white and black lines is a 3D effect for borders. Let’s put this to action and create a reusable style that can be applied to a <em>ToggleButton</em> control:</p>
<p><img title="toggle-buttons" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="142" alt="toggle-buttons" src="http://www.hardcodet.net/uploads/2009/05/togglebuttons.png" width="292" border="0" />&#160; </p>
<p>Rather than joining four lines for each button state, I’ll use two <em>Border</em> controls with the same dimensions for each state, taking advantage that the <em>BorderThickness</em> property can be set independently for every edge. Here’s the borders for the unchecked state:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">=&quot;uncheckedState&quot;</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49FFFFFF&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;1,1,0,0&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49000000&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;0,0,1,1&quot;</span><span style="color: #0000ff">/&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>…and here’s the borders for the checked state. Note that its <em>Visibility</em> property of the surrounding grid is set to <em>Collapsed</em> in order to hide the borders:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">=&quot;checkedState&quot;</span> <span style="color: #ff0000">Visibility</span><span style="color: #0000ff">=&quot;Collapsed&quot;</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49000000&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;1,1,0,0&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49FFFFFF&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;0,0,1,1&quot;</span><span style="color: #0000ff">/&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>  </pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<p>I put these borders together in a simple style, which uses a trigger to switch the visibility of the two borders as soon as the <em>IsChecked</em> property of the <em>ToggleButton</em> changes:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Style</span> <span style="color: #ff0000">TargetType</span><span style="color: #0000ff">=&quot;{x:Type ToggleButton}&quot;</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Setter</span> <span style="color: #ff0000">Property</span><span style="color: #0000ff">=&quot;Template&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">Setter.Value</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">ControlTemplate</span> <span style="color: #ff0000">TargetType</span><span style="color: #0000ff">=&quot;{x:Type ToggleButton}&quot;</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">=&quot;mainGrid&quot;</span> <span style="color: #ff0000">Margin</span><span style="color: #0000ff">=&quot;0,0,1,1&quot;</span><span style="color: #0000ff">&gt;</span>

          <span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">=&quot;uncheckedState&quot;</span><span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49FFFFFF&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;1,1,0,0&quot;</span><span style="color: #0000ff">/&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49000000&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;0,0,1,1&quot;</span><span style="color: #0000ff">/&gt;</span>
          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>

          <span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span> <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">=&quot;checkedState&quot;</span> <span style="color: #ff0000">Visibility</span><span style="color: #0000ff">=&quot;Collapsed&quot;</span><span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49000000&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;1,1,0,0&quot;</span><span style="color: #0000ff">/&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">=&quot;#49FFFFFF&quot;</span> <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">=&quot;0,0,1,1&quot;</span><span style="color: #0000ff">/&gt;</span>
          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>   

          <span style="color: #008000">&lt;!--</span>
<span style="color: #008000">            WPF needs a background to toggle IsChecked</span>
<span style="color: #008000">            if the ContentPresenter does not fill the whole area</span>
<span style="color: #008000">          --&gt;</span>
          <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span> <span style="color: #ff0000">Background</span><span style="color: #0000ff">=&quot;#00000000&quot;</span> <span style="color: #0000ff">/&gt;</span>

          <span style="color: #0000ff">&lt;</span><span style="color: #800000">ContentPresenter</span> <span style="color: #ff0000">VerticalAlignment</span><span style="color: #0000ff">=&quot;Center&quot;</span>
                            <span style="color: #ff0000">HorizontalAlignment</span><span style="color: #0000ff">=&quot;Center&quot;</span> <span style="color: #0000ff">/&gt;</span>

        <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>

        <span style="color: #008000">&lt;!-- triggers toggle visual appearance --&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">ControlTemplate.Triggers</span><span style="color: #0000ff">&gt;</span>
          <span style="color: #0000ff">&lt;</span><span style="color: #800000">Trigger</span> <span style="color: #ff0000">Property</span><span style="color: #0000ff">=&quot;IsChecked&quot;</span> <span style="color: #ff0000">Value</span><span style="color: #0000ff">=&quot;True&quot;</span><span style="color: #0000ff">&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Setter</span> <span style="color: #ff0000">TargetName</span><span style="color: #0000ff">=&quot;checkedState&quot;</span>
                    <span style="color: #ff0000">Property</span><span style="color: #0000ff">=&quot;Visibility&quot;</span>
                    <span style="color: #ff0000">Value</span><span style="color: #0000ff">=&quot;Visible&quot;</span> <span style="color: #0000ff">/&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Setter</span> <span style="color: #ff0000">TargetName</span><span style="color: #0000ff">=&quot;uncheckedState&quot;</span>
                    <span style="color: #ff0000">Property</span><span style="color: #0000ff">=&quot;Visibility&quot;</span>
                    <span style="color: #ff0000">Value</span><span style="color: #0000ff">=&quot;Collapsed&quot;</span> <span style="color: #0000ff">/&gt;</span>
            <span style="color: #0000ff">&lt;</span><span style="color: #800000">Setter</span> <span style="color: #ff0000">TargetName</span><span style="color: #0000ff">=&quot;mainGrid&quot;</span>
                    <span style="color: #ff0000">Property</span><span style="color: #0000ff">=&quot;Margin&quot;</span>
                    <span style="color: #ff0000">Value</span><span style="color: #0000ff">=&quot;1,1,0,0&quot;</span><span style="color: #0000ff">/&gt;</span>
          <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Trigger</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;/</span><span style="color: #800000">ControlTemplate.Triggers</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;/</span><span style="color: #800000">ControlTemplate</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Setter.Value</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Setter</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Style</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<p>With the style in place, you can easily declare a <em>ToggleButton</em> like this:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">ToggleButton</span> <span style="color: #ff0000">Width</span><span style="color: #0000ff">=&quot;100&quot;</span> <span style="color: #ff0000">Height</span><span style="color: #0000ff">=&quot;24&quot;</span> <span style="color: #ff0000">Content</span><span style="color: #0000ff">=&quot;hello world&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
<p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/tutorial-on-3d-line-and-border-effects-in-xaml/feed</wfw:commentRss>
		</item>
		<item>
		<title>I’m a WPF Disciple</title>
		<link>http://www.hardcodet.net/2009/05/me-wpf-disciple</link>
		<comments>http://www.hardcodet.net/2009/05/me-wpf-disciple#comments</comments>
		<pubDate>Wed, 27 May 2009 22:32:20 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Personal]]></category>

		<category><![CDATA[Disciples]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/me-wpf-disciple</guid>
		<description><![CDATA[I have been invited by the WPF Disciples to become one of their own, which I – of course – gladly accepted.
I feel honored (and a little proud, too) to stand among some of the biggest names in WPF, and I’m looking forward to being part of the discussions within the group. After all, there’s [...]]]></description>
			<content:encoded><![CDATA[<p><img title="WPF Disciples" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin-bottom: 20px; margin-left: 0px; margin-right: 20px; border-right-width: 0px" height="174" alt="WPF Disciples" src="http://www.hardcodet.net/uploads/2009/05/disciples.png" width="174" align="left" border="0" />I have been invited by the <a href="http://wpfdisciples.wordpress.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/wpfdisciples.wordpress.com');" target="_blank">WPF Disciples</a> to become one of their own, which I – of course – gladly accepted.</p>
<p>I feel honored (and a little proud, too) to stand among some of the biggest names in WPF, and I’m looking forward to being part of the discussions within the group. After all, there’s still lots and lots to learn, discover and write about on planet WPF <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/me-wpf-disciple/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF NotifyIcon 1.0.1 – Minor Improvements, Major Tutorial</title>
		<link>http://www.hardcodet.net/2009/05/wpf-notifyicon-101-minor-improvements-major-tutorial</link>
		<comments>http://www.hardcodet.net/2009/05/wpf-notifyicon-101-minor-improvements-major-tutorial#comments</comments>
		<pubDate>Fri, 15 May 2009 18:07:01 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[WPF NotifyIcon]]></category>

		<category><![CDATA[NotifyIcon]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/wpf-notifyicon-101-minor-improvements-major-tutorial</guid>
		<description><![CDATA[WPF NotifyIcon was upgraded to 1.0.1. More shinyness galore!]]></description>
			<content:encoded><![CDATA[<p>I just posted an upgrade to my WPF NotifyIcon, which adds some minor improvements to the control. The most important one is probably the simplified data binding support for context menus (thanks to Nic Pillinger for the hint), but I also managed to add some polish in a few other areas.</p>
<p>&#160;</p>
<p><img height="94" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image13.png" width="297" border="0" /></p>
<p>&#160;</p>
<p>Apart from the updated control itself, I completely revamped the sample project. It’s no longer just a showcase but contains various standalone samples which cover all aspects of the control. And last but not least, I published a complementary <a title="CodeProject tutorial" href="http://www.codeproject.com/KB/WPF/wpf_notifyicon.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">tutorial on the CodeProject</a>. One could say I was quite busy <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>&#160;</p>
<p>Further information and download on the project page:    <br /><a href="http://www.hardcodet.net/projects/wpf-notifyicon" ><strong>http://www.hardcodet.net/projects/wpf-notifyicon</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/wpf-notifyicon-101-minor-improvements-major-tutorial/feed</wfw:commentRss>
		</item>
		<item>
		<title>Using Attached Events to Trigger Animations in WPF</title>
		<link>http://www.hardcodet.net/2009/05/trigger-wpf-animations-through-attached-events</link>
		<comments>http://www.hardcodet.net/2009/05/trigger-wpf-animations-through-attached-events#comments</comments>
		<pubDate>Fri, 08 May 2009 14:22:24 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[Attached Events]]></category>

		<category><![CDATA[Blend]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=525</guid>
		<description><![CDATA[Attached events allow you to trigger animations on arbitrary controls without having to write a single line of code on the control. This article shows the pattern with a simple tutorial.]]></description>
			<content:encoded><![CDATA[<p>This is a pattern I applied when implementing the <a title="WPF NotifyIcon" href="http://www.hardcodet.net/wpf-notifyicon" >WPF NotifyIcon</a> component in order to provide animation support for popups, tooltips, and balloon messages. The problem I had to solve was the loose coupling between the NotifyIcon and displayed controls:</p>
<p>&#160;</p>
<p><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="103" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image2.png" width="591" border="0" /></p>
<p>Accordingly, I didn’t know anything about these controls at runtime. Nonetheless, I wanted to provide a communication channel to inform that <em>UIElement</em> that it is being displayed. And I wanted to do it declaratively.</p>
<h3>Attached Events to the Rescue</h3>
<p>Enter <a title="Attached events on MSDN" href="http://msdn.microsoft.com/en-us/library/bb613550.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">attached events</a>. Just like the better known attached properties, they can be declared in a static class and attached to arbitrary dependency objects. Accordingly, a control X does not need to declare an event itself in order to raise it.</p>
<p>If you are working with Expression Blend, chances are high that you are already using attached events quite often. As an example, the <em>Mouse.MouseDown</em> attached event that lets you trigger an animation if the user clicks on an arbitrary control. And nothing stops you from defining your own custom events <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Creating a Sample Application</h3>
<p>Let’s create a simple sample. The scenario is the following:</p>
<ul>
<li>Sometimes, some kind of critical event occurs (simulated through a button click). </li>
<li>Every time this happens, we want a “status control” to show an alarm. </li>
</ul>
<p>We will implement this status control purely in XAML – an attached event will trigger an animation that displays a warning sign:</p>
<p><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="210" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image3.png" width="421" border="0" /></p>
<p>&#160;</p>
<p> <span id="more-525"></span>
<p>(For a real-life usage scenario, have a look at the sample application that comes with the <a title="WPF NotifyIcon" href="http://www.hardcodet.net/wpf-notifyicon" >WPF NotifyIcon</a> control.)</p>
<p>&#160;</p>
<h4>Preparing the Status Control</h4>
<p>The control below is pretty simple. It just contains two images:</p>
<ul>
<li>The regular image shows a star. Its initial opacity is set to 100%. </li>
<li>The second image is the alarm icon. Its initial opacity is set to 0% so it’s not visible (I changed that a little for the screenshot). </li>
</ul>
<p><a href="http://www.hardcodet.net/uploads/2009/05/image4.png" ><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="205" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image-thumb.png" width="244" border="0" /></a></p>
<p>&#160;</p>
<h4>Defining the Attached Routed Event</h4>
<p>In order to work with a custom event, it needs to be declared first. In the NotifyIcon library, the <em>NotifyIcon</em> control itself exposes the event. In this sample, however, we will declare an <em>Alarm</em> event in its own class called <em>Monitor</em>. Note that everything is static:</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;///</span>
 Hosts the &lt;see cref=<span style="color: #006080">&quot;AlarmEvent&quot;</span>/&gt; attached routed <span style="color: #0000ff">event</span>.
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> Monitor{

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Alarm Attached Routed Event</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">readonly</span> RoutedEvent AlarmEvent =
      EventManager.RegisterRoutedEvent(<span style="color: #006080">&quot;Alarm&quot;</span>,
                                       RoutingStrategy.Bubble,
                                       <span style="color: #0000ff">typeof</span> (RoutedEventHandler),
                                       <span style="color: #0000ff">typeof</span> (Monitor));
}</pre>
</div>
<p><em></em></p>
<p><em>BTW: I didn’t write the code above on my own - code snippets greatly simplify things here. I’ve used one of </em><a href="http://www.drwpf.com/blog/Home/tabid/36/EntryId/22/Default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.drwpf.com');"><em>Dr. WPF’s snippets</em></a><em> which will not only generate the event declarations but also some helper methods to deal with events in code.</em></p>
<p><em></em></p>
<p><em></em></p>
<p><em></em></p>
<h4>Raising the Event</h4>
<p>The screenshot below shows a simple form that contains a button and the <em>StatusRenderer </em>user control. In order to keep things simple, we will simply raise the attached routed event on the status control every time the user clicks on the button.</p>
<p><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="206" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image20.png" width="417" border="0" /></p>
<p>&#160;</p>
<p>In order to trigger the event, we’ll add a simple static helper method to the <em>Monitor</em> class:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// A static helper method to raise the Alarm event on a target element.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;target&quot;&gt;UIElement or ContentElement on which to raise</span>
<span style="color: #008000">/// the event&lt;/param&gt;</span>
<span style="color: #0000ff">internal</span> <span style="color: #0000ff">static</span> RoutedEventArgs RaiseAlarmEvent(DependencyObject target)
{
  <span style="color: #0000ff">if</span> (target == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span>;

  RoutedEventArgs args = <span style="color: #0000ff">new</span> RoutedEventArgs();
  args.RoutedEvent = AlarmEvent;

  <span style="color: #0000ff">if</span> (target <span style="color: #0000ff">is</span> UIElement)
  {
    (target <span style="color: #0000ff">as</span> UIElement).RaiseEvent(args);
  }
  <span style="color: #0000ff">else</span> <span style="color: #0000ff">if</span> (target <span style="color: #0000ff">is</span> ContentElement)
  {
    (target <span style="color: #0000ff">as</span> ContentElement).RaiseEvent(args);
  }

  <span style="color: #0000ff">return</span> args;
}</pre>
</div>
<p>&#160;</p>
<p>We want to raise the event every time the button on the main form is clicked. Accordingly, we invoke RaiseAlarmEvent in the button’s click event handler.</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> btnTrigger_Click(<span style="color: #0000ff">object</span> sender, RoutedEventArgs e)
{
  <span style="color: #008000">//raise the attached event on the status control</span>
  Monitor.RaiseAlarmEvent(status);
}</pre>
</div>
<p>&#160;</p>
<h4>Consuming the Event</h4>
<p>The nice thing is – once the event is in place, it can be consumed through XAML only, so there’ no need to write code. Lets complete the sample by adding a simple listener to our user control that triggers an animation. I’m using Blend for that job.</p>
<p><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="422" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image5.png" width="570" border="0" /></p>
<p>&#160;</p>
<h5>1: Create a new event trigger</h5>
<p>Start by clicking on the <strong><em>+ Event</em></strong> tab in Blend. You will see that the Monitor.Alarm event is not available through this list. Accordingly, we will just use the <em>Loaded</em> event that is offered for now…</p>
<h5>2. Create a storyboard to animate the UI</h5>
<p>Next, click on the <strong>+ </strong>button to create a new storyboard. For the sample application, I created a storyboard called <em>ShowWarning</em> that fades in the invisible warning sign and hides the default image.</p>
<h5>3: Switch to the <em>Monitor.Alarm</em> event</h5>
<p>In the first step, we registered our animation to be triggered whenever the user control’s <em>Loaded</em> event fires. However, we want our animation to be fired upon the attached <em>Monitor.Alarm</em> event. As Blend does not provide attached events through its UI, this needs to be changed XAML. Switch to XAML view and find the following line part.</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">UserControl.Triggers</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">EventTrigger</span> <span style="color: #ff0000">RoutedEvent</span><span style="color: #0000ff">=&quot;FrameworkElement.Loaded&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">BeginStoryboard</span> <span style="color: #ff0000">Storyboard</span><span style="color: #0000ff">=&quot;{StaticResource ShowWarning}&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">EventTrigger</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">UserControl.Triggers</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>Now change the RoutedEvent attribute in order to look like this:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">UserControl.Triggers</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">EventTrigger</span> <span style="color: #ff0000">RoutedEvent</span><span style="color: #0000ff">=&quot;att:Monitor.Alarm&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">BeginStoryboard</span> <span style="color: #ff0000">Storyboard</span><span style="color: #0000ff">=&quot;{StaticResource ShowWarning}&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">EventTrigger</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">UserControl.Triggers</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#8230;and of course, you also need to register the namespace prefix in the header of user control:</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">UserControl</span>
  <span style="color: #ff0000">xmlns</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span>
  <span style="color: #ff0000">xmlns:x</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span>
  <span style="color: #ff0000">xmlns:att</span><span style="color: #0000ff">=&quot;clr-namespace:AttachedEventSample&quot;</span>
  ...  <span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
</p>
<h4>The Result</h4>
<p>That’s it. Now, as soon as you click the button, the attached event is being consumed by the user control and triggers the animation. Without a single line of code on the consumer side <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&#160;</p>
<p><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="210" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image3.png" width="421" border="0" /></p>
<p>&#160;</p>
<p><a class="download" title="Sample application" href="http://www.hardcodet.net/uploads/2009/05/attached-event-sample.zip" onclick="javascript:pageTracker._trackPageview('/downloads/uploads/2009/05/attached-event-sample.zip');">Download Sample Application</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/trigger-wpf-animations-through-attached-events/feed</wfw:commentRss>
		</item>
		<item>
		<title>NetDrives 1.0 Released</title>
		<link>http://www.hardcodet.net/2009/05/netdrives-release-announcement</link>
		<comments>http://www.hardcodet.net/2009/05/netdrives-release-announcement#comments</comments>
		<pubDate>Wed, 06 May 2009 13:52:10 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[NetDrives]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/netdrives-release-announcement</guid>
		<description><![CDATA[NetDrives is an open source utility that helps you manage your network shares and mapped network drives. Unlike Windows, it can reconnect to secured shares during startup and provides you quick access to your configured shares.]]></description>
			<content:encoded><![CDATA[<p><em><img height="128" alt="NetDrives" src="/uploads/2009/04/netdrives.jpg" width="128" align="right" border="0" /></em>I’ve just uploaded installer and source code of NetDrives 1.0. This is my first tool that does not only address fellow developers, but a wider audience <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In a few words, NetDrives is an open source utility that helps you manage your network shares and mapped network drives. Unlike Windows, it can reconnect to secured shares during startup and provides you quick access to your configured shares.</p>
<p>&#160;</p>
<p><img height="273" alt="quickaccess" src="http://www.hardcodet.net/uploads/2009/04/quickaccess.png" width="386" border="0" /></p>
</p>
<p>&#160;</p>
<p>More information, screenshots, and downloads at the project page:</p>
<p><a title="Go to NetDrives project page" href="http://www.hardcodet.net/netdrives" >http://www.hardcodet.net/netdrives</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/netdrives-release-announcement/feed</wfw:commentRss>
		</item>
		<item>
		<title>Twitter Debut</title>
		<link>http://www.hardcodet.net/2009/05/twitter-debut</link>
		<comments>http://www.hardcodet.net/2009/05/twitter-debut#comments</comments>
		<pubDate>Tue, 05 May 2009 13:47:31 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/twitter-debut</guid>
		<description><![CDATA[I’ve been somewhat hesitant, but being able to quickly exchange thoughts with the community just sounds too good – I have to try this out.
&#160;
Follow me @ http://twitter.com/phsumi
]]></description>
			<content:encoded><![CDATA[<p><a title="Follow me" href="http://twitter.com/phsumi" onclick="javascript:pageTracker._trackPageview('/outbound/article/twitter.com');"><img title="Follow me" style="border-right: 0px; border-top: 0px; display: inline; margin-left: 0px; border-left: 0px; margin-right: 0px; border-bottom: 0px" height="85" alt="image" src="http://www.hardcodet.net/uploads/2009/05/image1.png" width="179" align="right" border="0" /></a>I’ve been somewhat hesitant, but being able to quickly exchange thoughts with the community just sounds too good – I have to try this out.</p>
<p>&#160;</p>
<p>Follow me @ <a title="http://twitter.com/phsumi" href="http://twitter.com/phsumi" onclick="javascript:pageTracker._trackPageview('/outbound/article/twitter.com');">http://twitter.com/phsumi</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/twitter-debut/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF NotifyIcon Released</title>
		<link>http://www.hardcodet.net/2009/05/wpf-notifyicon-released</link>
		<comments>http://www.hardcodet.net/2009/05/wpf-notifyicon-released#comments</comments>
		<pubDate>Mon, 04 May 2009 13:20:41 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[WPF NotifyIcon]]></category>

		<category><![CDATA[NotifyIcon]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/05/wpf-notifyicon-released</guid>
		<description><![CDATA[This is an implementation of a NotifyIcon (aka system tray icon or taskbar icon) for the WPF platform. It does not just rely on the Windows Forms NotifyIcon component, but is a purely independent control which leverages features of the WPF framework.]]></description>
			<content:encoded><![CDATA[<p>I’m happy to announce the public release of my WPF NotifyIcon control <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>This is an implementation of a <em>NotifyIcon</em> (aka system tray icon or taskbar icon) for the WPF platform. It does not just rely on the existing Windows Forms component, but is a purely independent control which leverages several features of the WPF framework in order to display rich ToolTips, Popups, context menus, and balloon messages.</p>
<p>&#160;</p>
<p><img height="94" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image13.png" width="297" border="0" /></p>
<p>&#160;</p>
<p>I’m planning on doing an introductory article on <a href="http://www.codeproject.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">CodeProject</a> (well, somewhere along the way&#8230;) but you’ll probably get along just fine – the control comes with a sample application that shows off most of the control’s features.</p>
<p>&#160;</p>
<p>Further information and download on the project page:    <br /><a title="http://www.hardcodet.net/projects/wpf-notifyicon" href="http://www.hardcodet.net/projects/wpf-notifyicon" ><strong>http://www.hardcodet.net/projects/wpf-notifyicon</strong></a></p>
<p>&#160;</p>
<p> <a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.hardcodet.net%2fwpf-notifyicon" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dotnetkicks.com');"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.hardcodet.net%2fwpf-notifyicon" border="0" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/05/wpf-notifyicon-released/feed</wfw:commentRss>
		</item>
		<item>
		<title>Declaring Custom WPF Commands via MarkupExtensions</title>
		<link>http://www.hardcodet.net/2009/04/wpf-command-markup-extension</link>
		<comments>http://www.hardcodet.net/2009/04/wpf-command-markup-extension#comments</comments>
		<pubDate>Sat, 25 Apr 2009 09:13:24 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[Commands]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/04/wpf-command-markup-extension</guid>
		<description><![CDATA[Shows the usage of a WPF markup extension that simplifies declaration of custom commands.]]></description>
			<content:encoded><![CDATA[<p>And yet another markup extension that hopefully makes things a little easier for you. Basically, it&#8217;s the same pattern that <a title="Visit Dr. WPF" href="http://www.drwpf.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.drwpf.com');">the good doctor</a> described <a href="http://www.drwpf.com/blog/Home/tabid/36/EntryID/48/Default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.drwpf.com');">here</a> for value converters, but with custom commands in mind.</p>
<h3>Without Extension</h3>
<p>Basically, this extension makes your commands immediately available without having to declare them. One &quot;traditional&quot; way to declare a command is directly in XAML:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Window.Resources</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">cmd:HelloWorldCommand</span> <span style="color: #ff0000">x:Key</span><span style="color: #0000ff">=&quot;SayHello&quot;</span> <span style="color: #0000ff">/&gt;</span>

<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Window.Resources</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#8230;and then apply it like this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Button</span> <span style="color: #ff0000">Command</span><span style="color: #0000ff">=&quot;{StaticResource SayHello}&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&#160;</p>
<h3>Using the Markup Extension</h3>
<p>The declaration part above can become somewhat tedious, especially if you have quite a few commands (e.g. because you are using a ribbon with lots of buttons on it). Thanks to using a markup extension, you can skip the declaration part altogether and just declare your command.</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Button</span> <span style="color: #ff0000">Command</span><span style="color: #0000ff">=&quot;{cmd:HelloWorldCommand}&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&#160;</p>
<h3>Implementation and Sample</h3>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Basic implementation of the &lt;see cref=&quot;ICommand&quot;/&gt;</span>
<span style="color: #008000">/// interface, which is also accessible as a markup</span>
<span style="color: #008000">/// extension.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">class</span> CommandExtension&lt;T&gt; : MarkupExtension, ICommand
    <span style="color: #0000ff">where</span> T:<span style="color: #0000ff">class</span>, ICommand, <span style="color: #0000ff">new</span>()
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// A singleton instance.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> T command;

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Gets a shared command instance.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">object</span> ProvideValue(IServiceProvider serviceProvider)
  {
    <span style="color: #0000ff">if</span> (command == <span style="color: #0000ff">null</span>) command = <span style="color: #0000ff">new</span> T();
    <span style="color: #0000ff">return</span> command;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Fires when changes occur that affect whether</span>
  <span style="color: #008000">/// or not the command should execute.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">event</span> EventHandler CanExecuteChanged
  {
    add { CommandManager.RequerySuggested += <span style="color: #0000ff">value</span>; }
    remove { CommandManager.RequerySuggested -= <span style="color: #0000ff">value</span>; }
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Defines the method to be called when the command is invoked.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;param name=&quot;parameter&quot;&gt;Data used by the command.</span>
  <span style="color: #008000">/// If the command does not require data to be passed,</span>
  <span style="color: #008000">/// this object can be set to null.</span>
  <span style="color: #008000">/// &lt;/param&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">void</span> Execute(<span style="color: #0000ff">object</span> parameter);

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Defines the method that determines whether the command</span>
  <span style="color: #008000">/// can execute in its current state.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;returns&gt;</span>
  <span style="color: #008000">/// This default implementation always returns true.</span>
  <span style="color: #008000">/// &lt;/returns&gt;</span>
  <span style="color: #008000">/// &lt;param name=&quot;parameter&quot;&gt;Data used by the command.  </span>
  <span style="color: #008000">/// If the command does not require data to be passed,</span>
  <span style="color: #008000">/// this object can be set to null.</span>
  <span style="color: #008000">/// &lt;/param&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">bool</span> CanExecute(<span style="color: #0000ff">object</span> parameter)
  {
    <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;
  }
}</pre>
</div>
<p>&#160;</p>
<p>&#8230;and here&#8217;s a sample implementation:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> HelloWorldCommand : CommandExtension&lt;HelloWorldCommand&gt;
{
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Execute(<span style="color: #0000ff">object</span> parameter)
  {
    MessageBox.Show(<span style="color: #006080">&quot;Hello world.&quot;</span>);
  }
}</pre>
</div>
<p>&#160;</p>
<p>Of course, nothing prevents you from pimping the base class a little to your needs <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a style="display: none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=792217" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');" rel="tag">codeproject </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/wpf-command-markup-extension/feed</wfw:commentRss>
		</item>
		<item>
		<title>A Façade for Simple and Framework-Independent Logging in .NET</title>
		<link>http://www.hardcodet.net/2009/04/simple-logging-facade</link>
		<comments>http://www.hardcodet.net/2009/04/simple-logging-facade#comments</comments>
		<pubDate>Thu, 23 Apr 2009 10:25:25 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Logging]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=422</guid>
		<description><![CDATA[Logging is an important aspect of every application, but you probably don't like to have dependencies on a specific logging framework all over the place. This logging façade provides you with a common interface that decouples the logging framework of your choice from your code.]]></description>
			<content:encoded><![CDATA[<p>Logging is an important aspect, but I don&#8217;t like to have dependencies on a specific logging framework all over the place. This is where a logging façade comes in handy. Basically, a façade just provides you with a common interface that decouples the used logging framework from your code:</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//ILogger is the facade. Behind the scenes,</span>
<span style="color: #008000">//a framework of your choice is used</span>
ILogger logger = LoggerService.Logger;
logger.Log(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>The idea of a logging façade isn&#8217;t exactly new, but I thought I&#8217;d share this one with you for a few reasons:</p>
<ul>
<li>It is dead easy to use. </li>
<li>It provides quite a few overloads when it comes to logging. </li>
<li>The core library has no dependencies on other libraries at all. </li>
<li>There are two façades (separate DLLs) that log through the <a href="http://www.codeplex.com/entlib" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeplex.com');">Enterprise Library</a> Logging block or the <a href="http://www.theobjectguy.com/dotnetlog/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.theobjectguy.com');">BitFactory logger</a>. And hopefully more to come! </li>
<li>Writing your own façade is as simple as overriding one single method. </li>
<li>It&#8217;s not part of another project (completely standalone), and <strong>there is no license attached to it. Do with it whatever you want.</strong> </li>
<li>It is dead easy to use. </li>
</ul>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/04/image18.png" ><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="207" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image-thumb1.png" width="260" border="0" /></a> </p>
<p>(click on image to enlarge)</p>
<p>&#160;</p>
<p>Here&#8217;s one way to create a file-based logger (using the <a href="http://www.theobjectguy.com/dotnetlog/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.theobjectguy.com');">BitFactory</a> façade) and make it globally accessible. This only takes you a few lines of code:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//create a new logger instance</span>
<span style="color: #0000ff">string</span> file = <span style="color: #006080">@&quot;C:\logfile.txt&quot;</span>;
ILogger logger = BitFactoryLogger.CreateSingleFileLogger(file);

<span style="color: #008000">//use the global LoggerService to store the logger</span>
LoggerService.SetLogger(logger);

...

<span style="color: #008000">//this will store the info in the log file</span>
LoggerService.Logger.Log(<span style="color: #006080">&quot;This is an information&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Logging via <em>ILogger</em></h3>
<p>The whole purpose of this project is to shield your libraries from the actually chosen logging framework. Accordingly, you are always logging through the <em><strong>ILogger</strong></em> instance. <em>ILogger</em> provides quite a few overloads of the <em>Log </em>method, here are a few of them:</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> LogData(ILogger logger)
{
  logger.Log(<span style="color: #006080">&quot;An information&quot;</span>);
  logger.Log(<span style="color: #006080">&quot;Something Happened&quot;</span>, TraceEventType.Warning);

  <span style="color: #008000">//LogItem is the most verbose version</span>
  LogItem item = <span style="color: #0000ff">new</span> LogItem();
  item.Message = <span style="color: #006080">&quot;My Message&quot;</span>;
  item.EventId = 999;
  item.Categories.Add(<span style="color: #006080">&quot;Foo&quot;</span>);
  item.Priority = 10;
  logger.Log(item); 

  <span style="color: #0000ff">try</span>
  {
    DivideByZero();
  }
  <span style="color: #0000ff">catch</span>(Exception e)
  {
    logger.Log(e);
    logger.Log(<span style="color: #006080">&quot;Additional message.&quot;</span>, e);
    logger.Log(<span style="color: #006080">&quot;Additional message.&quot;</span>, e, TraceEventType.Critical);
  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Initializing an <em>ILogger</em> Implementation</h3>
<p>During the initialization of your application, you will have to specify the the logger implementation that is supposed to be used. This might happen declaratively or directly in code. Here&#8217;s the initialization code from <a href="http://www.hardcodet.net/netdrives" >NetDrives</a>, which makes a logger available through the <a href="http://code.google.com/p/autofac/" onclick="javascript:pageTracker._trackPageview('/outbound/article/code.google.com');">AutoFac</a> IOC container. </p>
<p>Note that I&#8217;m registering a <em>ConsoleLogger</em> for debug builds, while release builds write into a log file. These are completely different classes, but it doesn&#8217;t matter - they both implement the <em>ILogger</em> interface:</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//init IOC container builder</span>
var builder = <span style="color: #0000ff">new</span> ContainerBuilder();

<span style="color: #008000">//register single logger instance</span>
ILogger logger;

<span style="color: #cc6633">#if</span> (DEBUG)
  logger = <span style="color: #0000ff">new</span> ConsoleLogger();
<span style="color: #cc6633">#else</span>
  logger = BitFactoryLogger.CreateSingleFileLogger(AppUtil.LogFile);
<span style="color: #cc6633">#endif</span>

<span style="color: #008000">//register logger</span>
builder.Register(logger).As&lt;ILogger&gt;();</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Registration and Access through <em>LoggerService</em></h3>
<p>I prefer to initialize and access my logger through an IOC container, but you can do it however you like. If you&#8217;re lacking a place to make your <em>ILogger</em> globally accessible, you can use the static <em>LoggerService</em> class:</p>
<p>&#160;<img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="193" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image17.png" width="211" border="0" /> </p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> InitApp()
{
  <span style="color: #008000">//create a file logger (use BitFactory facade)</span>
  <span style="color: #0000ff">string</span> logFile = <span style="color: #006080">@&quot;C:\MyLogFile.txt&quot;</span>;
  ILogger logger = BitFactoryLogger.CreateSingleFileLogger(logFile);

  <span style="color: #008000">//register as globally used logger</span>
  LoggerService.SetLogger(logger);
}

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> Foo()
{
  <span style="color: #0000ff">try</span>
  {
    DoSomethingWrong();
  }
  <span style="color: #0000ff">catch</span>(Exception e)
  {
    <span style="color: #008000">//get registered logger and log exception</span>
    ILogger logger = LoggerService.Logger;
    logger.Log(e);
  }
}</pre>
</div>
<p>&#160;</p>
<p>A nice thing about <em>LoggerService</em>: It guarantees you always a valid <em>ILogger</em> instance. If no logger is set, it just falls back to a <em>NullLogger</em> implementation that does not create any output at all. Here&#8217;s the implementation:</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">namespace</span> Hardcodet.Util.Logging
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Provides a global repository for a given &lt;see cref=&quot;ILogger&quot;/&gt;</span>
  <span style="color: #008000">/// instance. This class ensures that the &lt;see cref=&quot;Logger&quot;/&gt;</span>
  <span style="color: #008000">/// property is never nullo - in case no logger is defined, it</span>
  <span style="color: #008000">/// automatically installs a &lt;see cref=&quot;NullLogger&quot;/&gt;</span>
  <span style="color: #008000">/// instance.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> LoggerService
  {
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> ILogger logger = <span style="color: #0000ff">new</span> NullLogger();

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Gets the installed &lt;see cref=&quot;ILogger&quot;/&gt; implementation.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;remarks&gt;This property always returns a valid</span>
    <span style="color: #008000">/// logger.&lt;/remarks&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> ILogger Logger
    {
      get { <span style="color: #0000ff">return</span> logger; }
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Installs a given logger or resets the &lt;see cref=&quot;Logger&quot;/&gt;</span>
    <span style="color: #008000">/// to a &lt;see cref=&quot;NullLogger&quot;/&gt; instance if the</span>
    <span style="color: #008000">/// &lt;paramref name=&quot;loggerImplementation&quot;/&gt; is a null</span>
    <span style="color: #008000">/// reference.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name=&quot;loggerImplementation&quot;&gt;The logger to be</span>
    <span style="color: #008000">/// used globally, or a null reference in order to reset</span>
    <span style="color: #008000">/// the service.&lt;/param&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> SetLogger(ILogger loggerImplementation)
    {
      logger = loggerImplementation ?? <span style="color: #0000ff">new</span> NullLogger();
    }
  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Creating a new Logger Façade</h3>
<p>In case you want to use another logging framework (e.g. <a href="http://www.nlog-project.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.nlog-project.org');">NLog</a> or <a href="http://logging.apache.org/log4net/" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">Log4Net</a>), creating a new façade is very easy. Basically, you create a new project, set a reference to the base library and write a class that either</p>
<ul>
<li>implements <em>ILogger</em> directly </li>
<li>or, even simpler, derives from the abstract <em>LoggerBase</em> class. </li>
</ul>
<p>&#160;</p>
<p><strong><font color="#ff0000"><em>Feel like sharing your own façade? Just contact me and I&#8217;ll happily include your implementation <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </em></font></strong></p>
<p>&#160;</p>
<p>As a sample, here&#8217;s the code of the <em>ConsoleLogger</em> (part of the core library) and the Enterprise Library façade:</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;

<span style="color: #0000ff">namespace</span> Hardcodet.Util.Logging
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// A very simple implementation of &lt;see cref=&quot;ILogger&quot;/&gt;</span>
  <span style="color: #008000">/// that outputs all messages to the system console.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ConsoleLogger : LoggerBase
  {
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Logs a given item to the console.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name=&quot;item&quot;&gt;The item to be logged.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;exception cref=&quot;ArgumentNullException&quot;&gt;If &lt;paramref name=&quot;item&quot;/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Log(LogItem item)
    {
      <span style="color: #0000ff">if</span> (item == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">&quot;item&quot;</span>);
      Console.Out.WriteLine(item.ToLogMessage());
    }

  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> Microsoft.Practices.EnterpriseLibrary.Logging;

<span style="color: #0000ff">namespace</span> Hardcodet.Util.Logging.EntLibFacade
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// An implementation of the &lt;see cref=&quot;ILogger&quot;/&gt;</span>
  <span style="color: #008000">/// interface which outputs logged data using</span>
  <span style="color: #008000">/// the &lt;see cref=&quot;Logger&quot;/&gt; of the MS Enterprise</span>
  <span style="color: #008000">/// Library.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> EnterpriseLibraryLogger : LoggerBase
  {

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Writes a log entry to the Enterprise Library's</span>
    <span style="color: #008000">/// logging block. Output depends on the logging</span>
    <span style="color: #008000">/// block's configuration.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name=&quot;item&quot;&gt;An log item which encapsulates</span>
    <span style="color: #008000">/// information to be logged.&lt;/param&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Log(LogItem item)
    {
      LogEntry entry = ConvertLogItem(item);
      Logger.Write(entry);
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Creates a &lt;c&gt;LogEntry&lt;/c&gt; instance which can be processed</span>
    <span style="color: #008000">/// by the Enterprise Library based on a given log item. </span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name=&quot;item&quot;&gt;An log item which encapsulates information</span>
    <span style="color: #008000">/// to be logged.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;An Enterprise Library item which corresponds</span>
    <span style="color: #008000">/// to the submitted &lt;c&gt;LogItem&lt;/c&gt;.&lt;/returns&gt;</span>
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> LogEntry ConvertLogItem(LogItem item)
    {
      <span style="color: #008000">//assign properties</span>
      LogEntry entry = <span style="color: #0000ff">new</span> LogEntry();
      entry.Message = item.Message;
      entry.Title = item.Title;
      entry.AddErrorMessage(item.ErrorMessage);
      entry.EventId = item.EventId;
      entry.Priority = item.Priority;
      entry.Severity = item.Severity;
      entry.TimeStamp = item.TimeStamp;

      <span style="color: #0000ff">foreach</span> (<span style="color: #0000ff">string</span> category <span style="color: #0000ff">in</span> item.Categories)
      {
        item.Categories.Add(category);
      }

      <span style="color: #0000ff">return</span> entry;
    }

  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<p>The download contains the core library, two external façades (BitFactory, Enterprise Library), and a sample project. Hope you&#8217;ll like it <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a class="download" title="Download logging library and sample project" href="/uploads/2009/04/hardcodet-logging.zip">hardcodet-logging.zip</a> <a style="display: none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=792217" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');" rel="tag">codeproject </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/simple-logging-facade/feed</wfw:commentRss>
		</item>
		<item>
		<title>Quick and Dirty (but nice!) ToolTips via Markup Extensions</title>
		<link>http://www.hardcodet.net/2009/04/wpf-tooltips-through-markup-extension</link>
		<comments>http://www.hardcodet.net/2009/04/wpf-tooltips-through-markup-extension#comments</comments>
		<pubDate>Sun, 19 Apr 2009 12:37:01 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[MarkupExtension]]></category>

		<category><![CDATA[NetDrives]]></category>

		<category><![CDATA[ToolTip]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=406</guid>
		<description><![CDATA[Discusses the implementation of a MarkupExtension that displays a rich ToolTip.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hardcodet.net/netdrives" >NetDrives</a> does not rely on <a href="http://thewpfblog.com/?p=61" onclick="javascript:pageTracker._trackPageview('/outbound/article/thewpfblog.com');">styles</a> when it comes to displaying ToolTips, but uses a simple markup extension, that provides the following functionality:</p>
<ul>
<li>Displays a nice looking ToolTip rather than just plain text. </li>
<li>Optional lookup of strings in a resource dictionary to simplify localization. </li>
<li>Optional title text. </li>
<li>Very simple declaration. </li>
</ul>
<p>Here&#8217;s what the XAML looks like:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,&#39;Courier New&#39;,courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span>
  <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;..\Shared\Images\HelpSmall.png&quot;</span>
  <span style="color: #ff0000">ToolTip</span><span style="color: #0000ff">=&quot;{ext:Info Title=ShareNameTitleToolTip, Body=ShareNameInfoToolTip}&quot;</span>
  <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#8230;and this is the output:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="158" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image14.png" width="335" border="0" /></p>
<h3>Creating the Popup Control</h3>
<p>The first step is to create a simple control that contains the ToolTip. Basically, this is a simple <em>UserControl</em> with the following features:</p>
<ul>
<li>A grid with two rows. The first row contains just the title and is auto-sized to make sure it collapses if the title is not used at all. </li>
<li>Two TextBlocks for title and body text. </li>
<li>An image (I didn&#8217;t make that one bindable, I always use the same one). </li>
<li>Two dependency properties that provide binding capabilities for header and body text. </li>
</ul>
<p>Here&#8217;s what the control looks like in Blend:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="124" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image15.png" width="218" border="0" /></p>
<p>Of course, you can easily use this user control through styles and/or directly declared in XAML whenever you need:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,&#39;Courier New&#39;,courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span> <span style="color: #ff0000">Source</span><span style="color: #0000ff">=&quot;..\Shared\Images\HelpSmall.png&quot;</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image.ToolTip</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">MyToolTipControl</span> <span style="color: #ff0000">Header</span><span style="color: #0000ff">=&quot;My Title&quot;</span> <span style="color: #ff0000">Body</span><span style="color: #0000ff">=&quot;This is a ToolTip&quot;</span> <span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Image.ToolTip</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Image</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>However, this would still take a style to hide the tooltip border and you are lacking resource file lookups. The markup extension makes this way easier&#8230;</p>
<h3>Implementing the Markup Extension</h3>
<p><a href="http://msdn.microsoft.com/en-us/library/ms747254.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">MarkupExtension</a> is one of the lesser known stars in WPF - it requires a little coding, but once in place, it greatly simplify things for you. A simple yet brilliant example is <a href="http://www.drwpf.com/blog/Home/tabid/36/EntryID/48/Default.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.drwpf.com');">Dr. WPF&#8217;s ValueConverter extension</a>, and I already blogged <a href="http://www.hardcodet.net/?s=markup+extension" >a few times</a> about other applications.</p>
<p>This <em>Info</em> markup extension basically provides the following:</p>
<ul>
<li>Two properties (<em>Title</em> and <em>Body</em>) </li>
<li>Resource lookup with fallback mechanism (string is used directly if it&#8217;s not a resource key) </li>
<li>ToolTip creation </li>
</ul>
<p>&#160;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,&#39;Courier New&#39;,courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// A markup extension that returns a</span>
<span style="color: #008000">/// &lt;see cref=&quot;InfoPopup&quot;/&gt; control preconfigured</span>
<span style="color: #008000">/// with header and text information according to the</span>
<span style="color: #008000">/// &lt;see cref=&quot;Title&quot;/&gt; and &lt;see cref=&quot;Body&quot;/&gt;</span>
<span style="color: #008000">/// properties.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Info : MarkupExtension
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Either a title text or a resource key that can be used</span>
  <span style="color: #008000">/// to look up the title.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Title { get; set; }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Either a tooltips' main text or a resource key that can be used</span>
  <span style="color: #008000">/// to look up the text.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Body { get; set; }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Empty default constructor.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> Info()
  {
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Inits the &lt;see cref=&quot;Info&quot;/&gt; markup extension</span>
  <span style="color: #008000">/// with the title and body.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> Info(<span style="color: #0000ff">string</span> title, <span style="color: #0000ff">string</span> body)
  {
    Title = title;
    Body = body;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Performs a lookup for the defined &lt;see cref=&quot;Title&quot;/&gt; and</span>
  <span style="color: #008000">/// &lt;see cref=&quot;Info&quot;/&gt; and creates the tooltip control.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;returns&gt;</span>
  <span style="color: #008000">/// A tooltip control</span><span style="color: #008000">.</span>
  <span style="color: #008000">/// &lt;/returns&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">object</span> ProvideValue(IServiceProvider serviceProvider)
  {
    <span style="color: #008000">//create the user control that </span>
    InfoPopup popup = <span style="color: #0000ff">new</span> InfoPopup();

    <span style="color: #0000ff">if</span> (!String.IsNullOrEmpty(Title))
    {
      <span style="color: #008000">//look up title - if the string is not a</span>
      <span style="color: #008000">//resource key, use it directly</span>
      var result = Resources.ResourceManager.GetObject(Title) ?? Title;
      popup.HeaderText = (<span style="color: #0000ff">string</span>)result;
    }

    <span style="color: #0000ff">if</span> (!String.IsNullOrEmpty(Body))
    {
      <span style="color: #008000">//look up body text - if the string is not a</span>
      <span style="color: #008000">//resource key, use it directly</span>
      var result = Resources.ResourceManager.GetObject(Body) ?? Body;
      popup.BodyText = (<span style="color: #0000ff">string</span>)result;
    }

    <span style="color: #008000">//create tooltip and make sure only the content is visible</span>
    ToolTip tt = <span style="color: #0000ff">new</span> ToolTip();
    tt.HasDropShadow = <span style="color: #0000ff">false</span>;
    tt.BorderThickness = <span style="color: #0000ff">new</span> Thickness(0);
    tt.Background = Brushes.Transparent;
    tt.Content = popup;

    <span style="color: #0000ff">return</span> tt;
  }
}</pre>
</div>
<h3>Conclusion and Sample</h3>
<p>This is only one of several ways to tackle the problem, but I really like that it only takes a single line to have a rich ToolTip in place. The implementation provided here may not completely suit your requirements, but it can easily be tailored to your needs.</p>
<p>The link below points to a sample project that contains both the markup extension and <em>ToolTip</em> control. Enjoy <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a title="Download sample project" href="/uploads/2009/04/tooltip-extension.zip">tooltip-extension.zip</a></p>
<p>&#160;</p>
<p><a style="display: none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=792217" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');" rel="tag">codeproject </a></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fwpf-tooltips-through-markup-extension" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dotnetkicks.com');"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fwpf-tooltips-through-markup-extension" border="0" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/wpf-tooltips-through-markup-extension/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF Ribbon: RibbonCommands Can Cause Memory Leaks</title>
		<link>http://www.hardcodet.net/2009/04/wpf-ribboncommand-memory-leak</link>
		<comments>http://www.hardcodet.net/2009/04/wpf-ribboncommand-memory-leak#comments</comments>
		<pubDate>Wed, 15 Apr 2009 10:20:35 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[Ribbon]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/04/wpf-ribboncommand-memory-leak</guid>
		<description><![CDATA[Discusses potential (and likely) memory leaks when using the Microsoft WPF ribbon and shows an alternative implementation that prevents the issue.]]></description>
			<content:encoded><![CDATA[<p>I stumbled over an issue when dealing with Microsoft&#8217;s <a href="http://www.codeplex.com/wpf/Wiki/View.aspx?title=WPF%20Ribbon%20Preview" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeplex.com');">WPF ribbon</a> today. Apparently, the control that heavily relies on <em><a href="http://windowsclient.net/wpf/wpf35/wpf-35sp1-ribbon-walkthrough.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/windowsclient.net');">RibbonCommands</a></em> rather than arbitrary <em><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">ICommand</a></em> instances may cause severe memory leaks. Have a look at this simple Window:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">Window</span> ...<span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">Grid.Resources</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">r:RibbonCommand</span>
        <span style="color: #ff0000">x:Key</span><span style="color: #0000ff">="MyCommand"</span>
        <strong><span style="color: #ff0000">Executed</span><span style="color: #0000ff">="OnRibbonClicked"</span></strong>
        <span style="color: #ff0000">LabelTitle</span><span style="color: #0000ff">="Click Me"</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid.Resources</span><span style="color: #0000ff">&gt;</span>

    <span style="color: #008000">&lt;!-- a ribbon that only displays a command in the quick access toolbar --&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">r:Ribbon</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">r:Ribbon.QuickAccessToolBar</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">r:RibbonQuickAccessToolBar</span><span style="color: #0000ff">&gt;</span>
          <span style="color: #0000ff">&lt;</span><span style="color: #800000">r:RibbonButton</span>
            <span style="color: #ff0000">Command</span><span style="color: #0000ff">="{StaticResource MyCommand}"</span>
            <span style="color: #ff0000">r:RibbonQuickAccessToolBar</span>.<span style="color: #ff0000">Placement</span><span style="color: #0000ff">="InToolBar"</span> <span style="color: #0000ff">/&gt;</span>
        <span style="color: #0000ff">&lt;/</span><span style="color: #800000">r:RibbonQuickAccessToolBar</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;/</span><span style="color: #800000">r:Ribbon.QuickAccessToolBar</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">r:Ribbon</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Grid</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Window</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&nbsp;</p>
<p>&#8230;and here&#8217;s the event listener that was declared for the <em>RibbonCommand</em>:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnRibbonClicked(<span style="color: #0000ff">object</span> sender, ExecutedRoutedEventArgs e)
{
  MessageBox.Show(<span style="color: #006080">"Ribbon command executing."</span>);
}</pre>
</div>
<p>&nbsp;</p>
<p>Once opened and closed, <strong>this window will not be garbage collected until the application shuts down</strong>. The reason is the <em>OnRibbonClicked</em> event handler that doesn&#8217;t get deregistered.</p>
<p>There are signs that Microsoft will dump <em>RibbonCommand</em> completely once the ribbon goes live. However: This probably won&#8217;t happen too fast, so you will have to solve the issue on your own. On the bright side: It forces a cleaner design on you.</p>
<p>I prefer custom commands anyway, so the natural way to go was to simply implement my own class that derives from <em>RibbonCommand</em>:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">///&lt;summary&gt;</span>
<span style="color: #008000">/// Base class for custom &lt;see cref="RibbonCommand"/&gt;</span>
<span style="color: #008000">/// implementations.</span>
<span style="color: #008000">///&lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">class</span> RibbonCommandBase : RibbonCommand
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Creates the command and registers weak event listeners.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">protected</span> RibbonCommandBase()
  {
    Executed += OnExecute;
    CanExecute += OnCanExecute;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Determines whether the command can be executed or not.</span>
  <span style="color: #008000">/// The default implementation always allows that.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">protected</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">void</span> OnCanExecute(<span style="color: #0000ff">object</span> sender, CanExecuteRoutedEventArgs e)
  {
    e.CanExecute = <span style="color: #0000ff">true</span>;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Command implementation - executes command logic.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">protected</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">void</span> OnExecute(<span style="color: #0000ff">object</span> sender, ExecutedRoutedEventArgs e);
}</pre>
</div>
<p>&nbsp;</p>
<p>The noteworthy thing here is that this abstract base class registers event listeners for <strong>its own events</strong> - one virtual, one abstract. Accordingly, a deriving command implementation only has to provide its own <em>OnExecute</em> and <em>OnCanExecute</em> (optional) methods to get going:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MessageCommand : RibbonCommandBase
{
  <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> OnExecute(<span style="color: #0000ff">object</span> sender, ExecutedRoutedEventArgs e)
  {
    MessageBox.Show(<span style="color: #006080">"Ribbon command executing."</span>);
  }
}</pre>
</div>
<p>&nbsp;</p>
<p>The last thing to correct is the command declaration in XAML - rather than declaring a <em>RibbonCommand</em> with a code-behind event listener, you declare your custom command (<em>MessageCommand</em> in the sample below). As you can see, there is no longer a listener for the <em>Executed</em> event - the command takes care of this on its own. Accordingly, this command can be declared in a resource dictionary without a code-behind file.</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">&lt;!-- Custom command - can be declared in a resource dictionary --&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">cmd:MessageCommand</span> <span style="color: #ff0000">x:Key</span><span style="color: #0000ff">="MyCommand"</span>
                    <span style="color: #ff0000">LabelTitle</span><span style="color: #0000ff">="Click Me"</span>
                    <span style="color: #ff0000">SmallImageSource</span><span style="color: #0000ff">="About.png"</span>
<span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&nbsp;</p>
<h3>Sample Project</h3>
<p>The attached sample project shows the two variants and the missing garbage collection of the standard ribbon commands.</p>
<p>I wasn&#8217;t sure about licensing restrictions, therefore<strong><em> I did not include the WPF ribbon assembly </em></strong>in the downloadable sample - you&#8217;ll have to add the reference yourself before compiling. Sorry for the inconvenience :/</p>
<p>Download: <a title="Download sample project" href="/uploads/2009/04/ribbon-commands.zip">ribbon-commands.zip</a> </p>
<p>&nbsp;</p>
<p>&nbsp;<img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image10.png" width="234" border="0"> </p>
<p>&nbsp;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fwpf-ribboncommand-memory-leak" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dotnetkicks.com');"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fwpf-ribboncommand-memory-leak" border="0"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/wpf-ribboncommand-memory-leak/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF Behavior Samples</title>
		<link>http://www.hardcodet.net/2009/04/wpf-behavior-samples</link>
		<comments>http://www.hardcodet.net/2009/04/wpf-behavior-samples#comments</comments>
		<pubDate>Mon, 13 Apr 2009 08:24:42 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/04/wpf-behavior-samples</guid>
		<description><![CDATA[Behaviors in WPF and Silverlight are one of the features that were introduced with Blend 3, and unlike attached behaviors, they benefit from full designer support in Blend 3, thus providing a much higher level of accessibility to developers and designers alike.
Laurent Bugnion has posted a great tutorial where he walks you through the various [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://electricbeach.org/?p=147" onclick="javascript:pageTracker._trackPageview('/outbound/article/electricbeach.org');">Behaviors</a> in WPF <u>and</u> Silverlight are one of the features that were introduced with Blend 3, and unlike <a href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">attached behaviors</a>, they benefit from full designer support in Blend 3, thus providing a much higher level of accessibility to developers and designers alike.</p>
<p>Laurent Bugnion has posted a <a href="http://geekswithblogs.net/lbugnion/archive/2009/04/05/using-a-behavior-to-magnify-your-wpf-applications.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/geekswithblogs.net');">great tutorial</a> where he walks you through the various aspects of a magnifying glass behavior, and Jeremiah Morrill generates eye candy through a behavior that adds <a href="http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/403/Glass-Behavior-for-WPF.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/jmorrill.hjtcentral.com');">glass effects</a> to your visuals.</p>
<p>Last but not least, the Expression team created a new section on the <a href="http://gallery.expression.microsoft.com/site/items/behaviors" onclick="javascript:pageTracker._trackPageview('/outbound/article/gallery.expression.microsoft.com');">Expression Gallery</a> that is dedicated to behaviors. I sure like shiny new toys <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/wpf-behavior-samples/feed</wfw:commentRss>
		</item>
		<item>
		<title>String Encryption using DPAPI and Extension Methods</title>
		<link>http://www.hardcodet.net/2009/04/dpapi-string-encryption-and-extension-methods</link>
		<comments>http://www.hardcodet.net/2009/04/dpapi-string-encryption-and-extension-methods#comments</comments>
		<pubDate>Sun, 12 Apr 2009 12:40:12 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Security]]></category>

		<category><![CDATA[DPAPI]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=371</guid>
		<description><![CDATA[Extension methods that encyrpt / decrypt strings through the Windows Data Protection API (DPAPI) with optional usage of secure strings that protect data in memory.]]></description>
			<content:encoded><![CDATA[<p><em>Latest Version: 2009.04.14 (Bugfix in Matches extension method)</em></p>
<p>&nbsp;</p>
<p>The <a title="ProtectedData (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">Windows Data Protection API (DPAPI)</a> is a great technology to securely encrypt user or machine specific data without having to worry about an encryption key. Since .NET 2.0, DPAPI is part of the .NET framework, so encrypting data is as easy as this:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">byte</span>[] Encrypt(<span style="color: #0000ff">byte</span>[] data)
{
  var scope = DataProtectionScope.CurrentUser;
  <span style="color: #0000ff">return</span> ProtectedData.Protect(data, <span style="color: #0000ff">null</span>, scope);
}</pre>
</div>
<p>&nbsp;</p>
<p>As you can see, the <em>Protect</em> method of the <em><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">ProtectedData</a></em> class takes binary input and returns a byte array that contains the encrypted data. This means that you&#8217;ll have to do some conversions when dealing with strings, and the result of the encryption is a byte array anyway.</p>
<p><a href="http://www.hardcodet.net/netdrives/" >NetDrives</a> relies on the DPAPI to encrypt user passwords that are stored on disk. Accordingly, I didn&#8217;t want to deal with binary data at all: Both input and output were supposed to be strings, which why I came up with a few extension methods that nicely wrap string encryptions for me:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="297" alt="image" src="http://www.hardcodet.net/uploads/2009/04/image9.png" width="427" border="0"> </p>
<p>&nbsp;</p>
<h3>Basic String Encryption</h3>
<p>In case in-memory protection is not an issue and you just need to encrypt/decrypt strings (e.g. to store encrypted data in a configuration file), you just need two extension methods. First, in order to encrypt a string, just invoke the <em>Encrypt</em> extension method:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">string</span> password = <span style="color: #006080">"hello world"</span>;
<span style="color: #0000ff">string</span> encrypted = password.Encrypt();</pre>
</div>
<p>&nbsp;</p>
<p><em>Encrypt</em> returns you the encrypted data, represented as base64 encoded string. In order to get your password back, just invoke the <em>Decrypt</em> extension method:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">string</span> plainText = encrypted.Decrypt();</pre>
</div>
<p>&nbsp;</p>
<h3>Managed Strings vs. SecureString</h3>
<p>The above methods are convenient to encrypt sensitive data that is supposed to be serialized or transmitted in any way. They do, however, not protect data at runtime as the decrypted strings remain in memory. In case this is an issue, you should revert to the <em><a href="http://blogs.msdn.com/shawnfa/archive/2004/05/27/143254.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">SecureString</a></em> rather than using plain strings (but keep in mind that this may lure you into a <a href="http://blogs.msdn.com/shawnfa/archive/2006/11/01/securestring-redux.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">false sense of security</a>!).</p>
<p>Accordingly, I also created extension methods that use <em>SecureString </em>instances rather than managed strings and allow you to wrap / unwrap strings quite easily. Here&#8217;s a test that shows off the various conversions:</p>
<p><em>Attention: Always keep in mind that once you are dealing with a managed string (such as the plainText variable below), your code can be compromised! Accordingly, the ToSecureString / Unwrap methods should be treated carefully.</em></p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Encryption_And_Decryption_Cycle_Should_Return_Original_Value()
{
  <span style="color: #0000ff">string</span> plainText = <span style="color: #006080">"this is a password"</span>;

  <span style="color: #008000">//encrypt plain text</span>
  <span style="color: #0000ff">string</span> cipher = plainText.Encrypt();
  Assert.AreNotEqual(plainText, cipher);

  <span style="color: #008000">//decrypt cipher into managed string</span>
  <span style="color: #0000ff">string</span> decrypted = cipher.Decrypt();
  Assert.AreEqual(plainText, decrypted);

  <span style="color: #008000">//create a SecureString from the plain text</span>
  SecureString plainSecure = plainText.ToSecureString();

  <span style="color: #008000">//test unwrapping of a SecureString</span>
  Assert.AreEqual(plainText, plainSecure.Unwrap());

  <span style="color: #008000">//encrypt the string that is wrapped into the SecureString</span>
  <span style="color: #0000ff">string</span> cipherFromSecure = plainSecure.Encrypt();

  <span style="color: #008000">//decrypt the cipher that was created from the the SecureString</span>
  Assert.AreEqual(plainText, cipherFromSecure.Decrypt());
}</pre>
</div>
<p>&nbsp;</p>
<h3>Implementation</h3>
<p>Here&#8217;s the class that provides the extension methods including a few helper methods that facilitate dealing with SecureString (e.g. <em>SecureString.IsNullOrEmpty</em>).</p>
<p>Note that you need to set an assembly reference to the <em><strong>System.Security</strong></em> <strong>assembly</strong>. Also keep in mind that the class always performs DPAPI encryption with <a title="DataProtectionScope (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.dataprotectionscope.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">user scope</a>. You might want to provide some additional overloads in order to support encryption that uses the context of the machine rather than the user&#8217;s. The same goes for the optional entropy that is not used at all for simplicity.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fdpapi-string-encryption-and-extension-methods" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dotnetkicks.com');"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2fdpapi-string-encryption-and-extension-methods" border="0"></a> </p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Collections.Generic;
<span style="color: #0000ff">using</span> System.Linq;
<span style="color: #0000ff">using</span> System.Runtime.InteropServices;
<span style="color: #0000ff">using</span> System.Security;
<span style="color: #0000ff">using</span> System.Security.Cryptography;
<span style="color: #0000ff">using</span> System.Text;

<span style="color: #0000ff">namespace</span> Hardcodet.NetDrives.Platform
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Provides extension methods that deal with</span>
  <span style="color: #008000">/// string encryption/decryption and</span>
  <span style="color: #008000">/// &lt;see cref="SecureString"/&gt; encapsulation.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> SecurityExtensions
  {
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Specifies the data protection scope of the DPAPI.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> DataProtectionScope Scope = DataProtectionScope.CurrentUser;

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Encrypts a given password and returns the encrypted data</span>
    <span style="color: #008000">/// as a base64 string.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="plainText"&gt;An unencrypted string that needs</span>
    <span style="color: #008000">/// to be secured.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;A base64 encoded string that represents the encrypted</span>
    <span style="color: #008000">/// binary data.</span>
    <span style="color: #008000">/// &lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;remarks&gt;This solution is not really secure as we are</span>
    <span style="color: #008000">/// keeping strings in memory. If runtime protection is essential,</span>
    <span style="color: #008000">/// &lt;see cref="SecureString"/&gt; should be used.&lt;/remarks&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="plainText"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> Encrypt(<span style="color: #0000ff">this</span> <span style="color: #0000ff">string</span> plainText)
    {
      <span style="color: #0000ff">if</span> (plainText == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"plainText"</span>);

      <span style="color: #008000">//encrypt data</span>
      var data = Encoding.Unicode.GetBytes(plainText);
      <span style="color: #0000ff">byte</span>[] encrypted = ProtectedData.Protect(data, <span style="color: #0000ff">null</span>, Scope);

      <span style="color: #008000">//return as base64 string</span>
      <span style="color: #0000ff">return</span> Convert.ToBase64String(encrypted);
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Decrypts a given string.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="cipher"&gt;A base64 encoded string that was created</span>
    <span style="color: #008000">/// through the &lt;see cref="Encrypt(string)"/&gt; or</span>
    <span style="color: #008000">/// &lt;see cref="Encrypt(SecureString)"/&gt; extension methods.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;The decrypted string.&lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;remarks&gt;Keep in mind that the decrypted string remains in memory</span>
    <span style="color: #008000">/// and makes your application vulnerable per se. If runtime protection</span>
    <span style="color: #008000">/// is essential, &lt;see cref="SecureString"/&gt; should be used.&lt;/remarks&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="cipher"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> Decrypt(<span style="color: #0000ff">this</span> <span style="color: #0000ff">string</span> cipher)
    {
      <span style="color: #0000ff">if</span> (cipher == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"cipher"</span>);

      <span style="color: #008000">//parse base64 string</span>
      <span style="color: #0000ff">byte</span>[] data = Convert.FromBase64String(cipher);

      <span style="color: #008000">//decrypt data</span>
      <span style="color: #0000ff">byte</span>[] decrypted = ProtectedData.Unprotect(data, <span style="color: #0000ff">null</span>, Scope);
      <span style="color: #0000ff">return</span> Encoding.Unicode.GetString(decrypted);
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Encrypts the contents of a secure string.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="value"&gt;An unencrypted string that needs</span>
    <span style="color: #008000">/// to be secured.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;A base64 encoded string that represents the encrypted</span>
    <span style="color: #008000">/// binary data.</span>
    <span style="color: #008000">/// &lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="value"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> Encrypt(<span style="color: #0000ff">this</span> SecureString <span style="color: #0000ff">value</span>)
    {
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"value"</span>);

      IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(<span style="color: #0000ff">value</span>);
      <span style="color: #0000ff">try</span>
      {
        <span style="color: #0000ff">char</span>[] buffer = <span style="color: #0000ff">new</span> <span style="color: #0000ff">char</span>[<span style="color: #0000ff">value</span>.Length];
        Marshal.Copy(ptr, buffer, 0, <span style="color: #0000ff">value</span>.Length);

        <span style="color: #0000ff">byte</span>[] data = Encoding.Unicode.GetBytes(buffer);
        <span style="color: #0000ff">byte</span>[] encrypted = ProtectedData.Protect(data, <span style="color: #0000ff">null</span>, Scope);

        <span style="color: #008000">//return as base64 string</span>
        <span style="color: #0000ff">return</span> Convert.ToBase64String(encrypted);
      }
      <span style="color: #0000ff">finally</span>
      {
        Marshal.ZeroFreeCoTaskMemUnicode(ptr);
      }
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Decrypts a base64 encrypted string and returns the decrpyted data</span>
    <span style="color: #008000">/// wrapped into a &lt;see cref="SecureString"/&gt; instance.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="cipher"&gt;A base64 encoded string that was created</span>
    <span style="color: #008000">/// through the &lt;see cref="Encrypt(string)"/&gt; or</span>
    <span style="color: #008000">/// &lt;see cref="Encrypt(SecureString)"/&gt; extension methods.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;The decrypted string, wrapped into a</span>
    <span style="color: #008000">/// &lt;see cref="SecureString"/&gt; instance.&lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="cipher"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> SecureString DecryptSecure(<span style="color: #0000ff">this</span> <span style="color: #0000ff">string</span> cipher)
    {
      <span style="color: #0000ff">if</span> (cipher == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"cipher"</span>);

      <span style="color: #008000">//parse base64 string</span>
      <span style="color: #0000ff">byte</span>[] data = Convert.FromBase64String(cipher);

      <span style="color: #008000">//decrypt data</span>
      <span style="color: #0000ff">byte</span>[] decrypted = ProtectedData.Unprotect(data, <span style="color: #0000ff">null</span>, Scope);

      SecureString ss = <span style="color: #0000ff">new</span> SecureString();

      <span style="color: #008000">//parse characters one by one - doesn't change the fact that</span>
      <span style="color: #008000">//we have them in memory however...</span>
      <span style="color: #0000ff">int</span> count = Encoding.Unicode.GetCharCount(decrypted);
      <span style="color: #0000ff">int</span> bc = decrypted.Length/count;
      <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0; i &lt; count; i++)
      {
        ss.AppendChar(Encoding.Unicode.GetChars(decrypted, i*bc, bc)[0]);
      }

      <span style="color: #008000">//mark as read-only</span>
      ss.MakeReadOnly();
      <span style="color: #0000ff">return</span> ss;
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Wraps a managed string into a &lt;see cref="SecureString"/&gt; </span>
    <span style="color: #008000">/// instance.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="value"&gt;A string or char sequence that </span>
    <span style="color: #008000">/// should be encapsulated.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;A &lt;see cref="SecureString"/&gt; that encapsulates the</span>
    <span style="color: #008000">/// submitted value.&lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="value"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> SecureString ToSecureString(<span style="color: #0000ff">this</span> IEnumerable&lt;<span style="color: #0000ff">char</span>&gt; <span style="color: #0000ff">value</span>)
    {
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"value"</span>);

      var secured = <span style="color: #0000ff">new</span> SecureString();

      var charArray = <span style="color: #0000ff">value</span>.ToArray();
      <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0; i &lt; charArray.Length; i++)
      {
        secured.AppendChar(charArray[i]);
      }

      secured.MakeReadOnly();
      <span style="color: #0000ff">return</span> secured;
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Unwraps the contents of a secured string and</span>
    <span style="color: #008000">/// returns the contained value.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="value"&gt;&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span style="color: #008000">/// &lt;remarks&gt;Be aware that the unwrapped managed string can be</span>
    <span style="color: #008000">/// extracted from memory.&lt;/remarks&gt;</span>
    <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="value"/&gt;</span>
    <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> Unwrap(<span style="color: #0000ff">this</span> SecureString <span style="color: #0000ff">value</span>)
    {
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"value"</span>);

      IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(<span style="color: #0000ff">value</span>);
      <span style="color: #0000ff">try</span>
      {
        <span style="color: #0000ff">return</span> Marshal.PtrToStringUni(ptr);
      }
      <span style="color: #0000ff">finally</span>
      {
        Marshal.ZeroFreeCoTaskMemUnicode(ptr);
      }
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Checks whether a &lt;see cref="SecureString"/&gt; is either</span>
    <span style="color: #008000">/// null or has a &lt;see cref="SecureString.Length"/&gt; of 0.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="value"&gt;The secure string to be inspected.&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;True if the string is either null or empty.&lt;/returns&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">bool</span> IsNullOrEmpty(<span style="color: #0000ff">this</span> SecureString <span style="color: #0000ff">value</span>)
    {
      <span style="color: #0000ff">return</span> <span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span> || <span style="color: #0000ff">value</span>.Length == 0;
    }

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Performs bytewise comparison of two secure strings.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;param name="value"&gt;&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;param name="other"&gt;&lt;/param&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;True if the strings are equal.&lt;/returns&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">bool</span> Matches(<span style="color: #0000ff">this</span> SecureString <span style="color: #0000ff">value</span>, SecureString other)
    {
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span> &amp;&amp; other == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span> == <span style="color: #0000ff">null</span> || other == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span>.Length != other.Length) <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;
      <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span>.Length == 0 &amp;&amp; other.Length == 0) <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;

      IntPtr ptrA = Marshal.SecureStringToCoTaskMemUnicode(<span style="color: #0000ff">value</span>);
      IntPtr ptrB = Marshal.SecureStringToCoTaskMemUnicode(other);
      <span style="color: #0000ff">try</span>
      {
        <span style="color: #008000">//parse characters one by one - doesn't change the fact that</span>
        <span style="color: #008000">//we have them in memory however...</span>
        <span style="color: #0000ff">byte</span> byteA = <span style="color: #0000ff">1</span>;
        <span style="color: #0000ff">byte</span> byteB = <span style="color: #0000ff">1</span>;

        <span style="color: #0000ff">int</span> index = 0;
        <span style="color: #0000ff">while</span> (((<span style="color: #0000ff">char</span>)byteA) != <span style="color: #006080">'\0'</span> &amp;&amp; ((<span style="color: #0000ff">char</span>)byteB) != <span style="color: #006080">'\0'</span>)
        {
          byteA = Marshal.ReadByte(ptrA, index);
          byteB = Marshal.ReadByte(ptrB, index);
          <span style="color: #0000ff">if</span> (byteA != byteB) <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;
          index += 2;
        }

        <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;
      }
      <span style="color: #0000ff">finally</span>
      {
        Marshal.ZeroFreeCoTaskMemUnicode(ptrA);
        Marshal.ZeroFreeCoTaskMemUnicode(ptrB);
      }
    }
  }
}</pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a style="display: none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=792217" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');" rel="tag">codeproject </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/dpapi-string-encryption-and-extension-methods/feed</wfw:commentRss>
		</item>
		<item>
		<title>From Lambda Dependencies to Lambda Bindings</title>
		<link>http://www.hardcodet.net/2009/04/from-lambda-dependencies-to-lambda-bindings</link>
		<comments>http://www.hardcodet.net/2009/04/from-lambda-dependencies-to-lambda-bindings#comments</comments>
		<pubDate>Fri, 03 Apr 2009 15:56:58 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Dependencies]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Expressions]]></category>

		<category><![CDATA[Lambda Dependencies]]></category>

		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=271</guid>
		<description><![CDATA[Lamba bindings allow you to perform object-to-object data binding using simple LINQ expressions.]]></description>
			<content:encoded><![CDATA[<p>Lambda-based binding for the business layer or your View Model <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I&#8217;ve had this on the shelf for quite a while, but Kent Boogaart&#8217;s article on <a title="POCOs vs. Dependency Objects" href="http://kentb.blogspot.com/2009/03/view-models-pocos-versus.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/kentb.blogspot.com');">POCOs vs. DependencyObjects</a> finally got me to cleaning things up a little. Kent is coming up with a similar approach that looks very promising, so you should keep your eyes on his blog, too.</p>
<p><em>Lambda Bindings</em> are built on top of the <a title="Lambda Dependencies" href="http://www.hardcodet.net/2008/12/observe-dependencies-through-lambda-expressions-part1" >Lambda Dependencies</a> project I published a while ago. The original Lambda Dependencies allow you to observe object graphs for changes using simple LINQ expressions. Lambda Bindings leverage this pattern by not just publishing a change event but synchronizing target properties or fields automatically. </p>
<p>This provides you with a generic binding framework that can be used wherever you want to synchronize objects. Let&#8217;s have a first example:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,'Courier New',courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> TestBinding(Student student)
{
  <span style="color: #0000ff">string</span> cityName = <span style="color: #006080">""</span>;

  <span style="color: #008000">//synchronize the cityName field with the City property of the school's address</span>
  var binding = <strong>LambdaBinding.BindOneWay</strong>(
      () =&gt; student.School.Address.City,
      () =&gt; cityName);

  <span style="color: #008000">//change the property on the School object</span>
  student.School.Address.City = <span style="color: #006080">"Sin City"</span>;

  <span style="color: #008000">//the binding expression updated the local variable</span>
  Assert.AreEqual(<span style="color: #006080">"Sin City"</span>, cityName);
}</pre>
</div>
<p>What&#8217;s happening in the snippet above is that I created a binding between a nested property of a referenced object and a local field. As soon as the binding source (the <em>City</em> property of a school&#8217;s address) is changed, the local <em>cityName</em> field is being updated as well.</p>
<p>&nbsp;</p>
<p>However, the Lambda Dependencies not only cover the source properties but the whole object graph. Accordingly, exchanging the whole School (or the Student instance) also triggers an update. In the snippet below, the <em>cityName</em> variable is being updated twice:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Updating_Intermediary_Object_Should_Update_Target(Student student)
{
  <span style="color: #0000ff">string</span> cityName = <span style="color: #006080">""</span>;

  <span style="color: #008000">//synchronize the cityName field with the City property of the school's address</span>
  var binding = LambdaBinding.BindOneWay(
      () =&gt; student.School.Address.City,
      () =&gt; cityName);

  <span style="color: #008000">//change bound City property -&gt; triggers update of the local variable</span>
  student.School.Address.City = <span style="color: #006080">"Paris"</span>;
  Assert.AreEqual(<span style="color: #006080">"Paris"</span>, cityName);

  <span style="color: #008000">//create a completely different school instance</span>
  School englishSchool = <span style="color: #0000ff">new</span> School();
  englishSchool.Address = <span style="color: #0000ff">new</span> Address {City = <span style="color: #006080">"London"</span>};

  <span style="color: #008000">//assign the new school to the student</span>
  student.School = englishSchool;

  <span style="color: #008000">//setting the School property also triggered the binding</span>
  Assert.AreEqual(<span style="color: #006080">"London"</span>, cityName);
}</pre>
</div>
<p>&nbsp;</p>
<h3>Value Conversion</h3>
<p>You can do simple value conversion by just submitting a converter to the binding expression. This allows you to intercept the binding pipeline or bind objects of different types together. If you&#8217;re coming from WPF, this feels natural anyway, but the solution here does not require you to implement a value converter - a simple <em>Func&lt;TSource, TTarget&gt;</em> is sufficient.</p>
<p>Here&#8217;s a simple sample that performs a conversion of a boolean flag to into a corresponding <em>Visibility</em> enum value:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Boolean_Should_Be_Converted_To_Visibility()
{
  <span style="color: #008000">//create a hidden window</span>
  Window window = <span style="color: #0000ff">new</span> Window { Visibility = Visibiliy.Collapsed };

  <span style="color: #008000">//create a view model</span>
  MyViewModel viewModel = <span style="color: #0000ff">new</span> MyViewModel { IsVisible = <span style="color: #0000ff">false</span> };

  <span style="color: #008000">//create binding that casts the Visibility into a boolean</span>
  LambdaBinding.BindOneWay(
      () =&gt; viewModel.IsVisible,
      () =&gt; window.Visibility,
      b =&gt; b == <span style="color: #0000ff">true</span> ? Visibility.Visible : Visibility.Collapsed;

  <span style="color: #008000">//a change in the ViewModel shows/hides the window</span>
  viewModel.IsVisible = <span style="color: #0000ff">true</span>;

  Assert.AreEqual(Visibility.Visible, window.Visibility);
}</pre>
</div>
<p>&nbsp;</p>
<h3>Two-Way-Binding</h3>
<p>Two way binding works too, of course:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,'Courier New',courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Updates_Should_Work_Both_Ways()
{
  <span style="color: #008000">//create two-way binding</span>
  var binding = LambdaBinding.BindTwoWay(
    () =&gt; FirstStudent.Name,
    () =&gt; SecondStudent.Name);

  <span style="color: #008000">//change property on source</span>
  FirstStudent.Name = <span style="color: #006080">"Peter"</span>;
  Assert.AreEqual(<span style="color: #006080">"Peter"</span>, SecondStudent.Name);

  <span style="color: #008000">//change property on target</span>
  SecondStudent.Name = <span style="color: #006080">"Parker"</span>;
  Assert.AreEqual(<span style="color: #006080">"Parker"</span>, FirstStudent.Name);
}</pre>
</div>
<p>In case you need to perform type conversion, you need to supply two converter functions for forward / reverse conversion:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,'Courier New',courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//bind a boolean property to a control's Visibility property</span>
var binding = LambdaBinding.BindTwoWay(
    () =&gt; ModelItem.IsEnabled,
    () =&gt; MyControl.IsVisible,
    b =&gt; b == <span style="color: #0000ff">true</span> ? Visibility.Visible : Visibiliy.Collapsed
    v =&gt; v == Visibility.Visible ? <span style="color: #0000ff">true</span> : <span style="color: #0000ff">false</span>);</pre>
</div>
</p>
<h3>&nbsp;</h3>
<h3>Default Values</h3>
<p>In case the object graph is being broken (e.g. because the School was set to null), the target node will be automatically set to its default value (null for an object, 0 for an int etc.). However, you can also specify a default value of your own:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas,'Courier New',courier,monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//a local field to be updated</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">string</span> schoolCity;

[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Breaking_The_Chain_Should_Assign_Default_Value_To_Target_If_Specified()
{
  var binding = LambdaBinding.BindOneWay(
      () =&gt; Student.School.Address.City,
      () =&gt; schoolCity,
      <span style="color: #006080">"[No City]"</span>);

  <span style="color: #008000">//break the source chain</span>
  Student.School = <span style="color: #0000ff">null</span>;

  <span style="color: #008000">//the default value was assigned to the target</span>
  Assert.AreEqual(<span style="color: #006080">"[No City]"</span>, schoolCity);
}</pre>
</div>
<p>(btw: the above snippet also shows you that you can easily bind to a field rather than a property).</p>
<p>&nbsp;</p>
<h3>Weak References</h3>
<p>The underlying Lambda Dependencies only use weak references so you&#8217;re not at risk of creating memory leaks. However, <em>LambdaBinding</em> implements <em>IDisposable</em>, so the proper way to clean things up would be to dispose your binding.</p>
<h3>Things to Consider</h3>
<p>Remember that that <strong><font color="#ff0000">the underlying Lambda Dependencies rely on the <em>INotifyPropertyChanged</em> interface</font></strong>, so don&#8217;t expect source binding to fields (or properties that do not fire a <em>PropertyChanged</em> event) to magically update your targets.</p>
<p>&nbsp;</p>
<p><strong>Download: </strong><a title="Lambda Dependencies 1.0.3" href="/uploads/2009/04/lambda-dependencies.zip"><strong>lambda-dependencies.zip</strong></a></p>
<p>&nbsp;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2ffrom-lambda-dependencies-to-lambda-bindings" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.dotnetkicks.com');"><img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.hardcodet.net%2f2009%2f04%2ffrom-lambda-dependencies-to-lambda-bindings" border="0"></a> </p>
<p><a style="display: none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=792217" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');" rel="tag">codeproject </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/from-lambda-dependencies-to-lambda-bindings/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF NotifyIcon - Release Candidate</title>
		<link>http://www.hardcodet.net/2009/04/wpf-notifyicon-releasecandidate</link>
		<comments>http://www.hardcodet.net/2009/04/wpf-notifyicon-releasecandidate#comments</comments>
		<pubDate>Wed, 01 Apr 2009 15:17:07 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[WPF NotifyIcon]]></category>

		<category><![CDATA[NotifyIcon]]></category>

		<category><![CDATA[System Tray]]></category>

		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/04/wpf-notifyicon-releasecandidate</guid>
		<description><![CDATA[A WPF NotifyIcon that leverages the power of WPF.]]></description>
			<content:encoded><![CDATA[</p>
<p>This is an implementation of a <em>NotifyIcon</em> (aka system tray icon or taskbar icon) for the WPF platform.</p>
<p><img height="94" alt="image" src="/uploads/2009/04/image13.png" width="297" border="0" /></p>
<p><strong><font color="#ff0000"></font></strong></p>
<p><strong><font color="#ff0000">Update:</font></strong></p>
<p>The control has now its own project page. Please go to</p>
<p><a title="WPF NotifyIcon project page" href="http://www.hardcodet.net/projects/wpf-notifyicon" >http://www.hardcodet.net/projects/wpf-notifyicon</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/04/wpf-notifyicon-releasecandidate/feed</wfw:commentRss>
		</item>
		<item>
		<title>Moving WPF DataGrid Rows using Drag and Drop</title>
		<link>http://www.hardcodet.net/2009/03/moving-data-grid-rows-using-drag-and-drop</link>
		<comments>http://www.hardcodet.net/2009/03/moving-data-grid-rows-using-drag-and-drop#comments</comments>
		<pubDate>Tue, 24 Mar 2009 11:01:13 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[DataGrid]]></category>

		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=304</guid>
		<description><![CDATA[Illustrates how to provide drag and drop functionality for the WPF datagrid to move rows of the grid.]]></description>
			<content:encoded><![CDATA[<p>For my upcoming <a href="http://www.hardcodet.net/projects/netdrives" >NetDrives</a> tool (will be released shortly) I wanted to enable the user to reorder managed network shares using drag and drop using a preview of the dragged row:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="195" alt="image" src="http://www.hardcodet.net/uploads/2009/03/image2.png" width="416" border="0"> </p>
<p>&nbsp;</p>
<p>As it turned out, it&#8217;s not too hard to implement, but it took my a while to find all pieces of the puzzle, so I compiled a short sample. You can find the sample link at the end of the article.</p>
<p>&nbsp;</p>
<h3>Drag Indicator Popup</h3>
<p>I used a popup as an drag indicator, which I bound to the item that was currently dragged (<em>DraggedItem</em> dependency property):</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">&lt;!-- the popup that is displayed if user moves rows --&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">Popup</span>
  <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">="popup1"</span>
  <span style="color: #ff0000">IsHitTestVisible</span><span style="color: #0000ff">="False"</span>
  <span style="color: #ff0000">Placement</span><span style="color: #0000ff">="RelativePoint"</span>
  <span style="color: #ff0000">PlacementTarget</span><span style="color: #0000ff">="{Binding ElementName=me}"</span>
  <span style="color: #ff0000">AllowsTransparency</span><span style="color: #0000ff">="True"</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">Border</span>
    <span style="color: #ff0000">BorderBrush</span><span style="color: #0000ff">="{DynamicResource CellBorderBrush}"</span>
    <span style="color: #ff0000">BorderThickness</span><span style="color: #0000ff">="2"</span>
    <span style="color: #ff0000">Background</span><span style="color: #0000ff">="White"</span>
    <span style="color: #ff0000">Opacity</span><span style="color: #0000ff">="0.75"</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">StackPanel</span>
      <span style="color: #ff0000">Orientation</span><span style="color: #0000ff">="Horizontal"</span>
      <span style="color: #ff0000">Margin</span><span style="color: #0000ff">="4,3,8,3"</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">Image</span>
        <span style="color: #ff0000">Source</span><span style="color: #0000ff">="/Shared/Images/DragInsert.png"</span>
        <span style="color: #ff0000">Width</span><span style="color: #0000ff">="16"</span>
        <span style="color: #ff0000">Height</span><span style="color: #0000ff">="16"</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">TextBlock</span>
        <span style="color: #ff0000">Style</span><span style="color: #0000ff">="{DynamicResource DefaultLabel}"</span>
        <span style="color: #ff0000">FontWeight</span><span style="color: #0000ff">="Bold"</span>
        <span style="color: #ff0000">VerticalAlignment</span><span style="color: #0000ff">="Center"</span>
        <span style="color: #ff0000">Text</span><span style="color: #0000ff">="{Binding ElementName=me, Path=DraggedItem.Name}"</span>
        <span style="color: #ff0000">Margin</span><span style="color: #0000ff">="8,0,0,0"</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">StackPanel</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Border</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Popup</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&nbsp;</p>
<h3>Disabling Drag and Drop in Edit Mode</h3>
<p>I didn&#8217;t want to enable drag and drop if the grid was in edit mode. Accordingly, I registered two event listeners on the grid:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">dg:DataGrid</span>
  <span style="color: #ff0000">BeginningEdit</span><span style="color: #0000ff">="OnBeginEdit"</span>
  <span style="color: #ff0000">CellEditEnding</span><span style="color: #0000ff">="OnEndEdit"</span>
  .. <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&nbsp;</p>
<p>The corresponding event listeners just set the <em>IsEditing</em> flag, which is evaluated when handling mouse events:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// State flag which indicates whether the grid is in edit</span>
<span style="color: #008000">/// mode or not.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsEditing { get; set; }

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnBeginEdit(<span style="color: #0000ff">object</span> sender, DataGridBeginningEditEventArgs e)
{
  IsEditing = <span style="color: #0000ff">true</span>;
  <span style="color: #008000">//in case we are in the middle of a drag/drop operation, cancel it...</span>
  <span style="color: #0000ff">if</span> (IsDragging) ResetDragDrop();
}

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnEndEdit(<span style="color: #0000ff">object</span> sender, DataGridCellEditEndingEventArgs e)
{
  IsEditing = <span style="color: #0000ff">false</span>;
}</pre>
</div>
<p>&nbsp;</p>
<h3>Listening to Mouse Events</h3>
<p>In order to display and move the popup with the mouse, I registered listeners for the following three mouse events:</p>
<ul>
<li><em>PreviewMouseLeftButtonDown</em> (on the datagrid)
<li><em>MouseLeftButtonUp</em> (directly on the layout root)
<li><em>MouseMove</em> (directly on the layout root)</li>
</ul>
<p>&nbsp;</p>
<p><strong><em>Note</em></strong>: I started with listeners on the grid only, which caused some side effects. Apparently, the datagrid (current March release) not always fires the mouse events properly. This caused choppy animations when hovering over certain cells. Fortunately, this is not an issue with the <em>MouseMove</em> event of the layout root.</p>
<p>&nbsp;</p>
<h3>Starting Drag and Drop</h3>
<p>DnD is started as soon as the user presses the left mouse button on the datagrid. I had to use the <em><strong><u>Preview</u></strong>LeftMouseButton</em> event in order to get the notification, and I needed to determine the clicked row based on the mouse position. I blogged about finding an element under the mouse a while ago <a href="http://www.hardcodet.net/2008/02/find-wpf-parent" >here</a>, but the <em>UIHelpers</em> class is part of the sample project here.</p>
<p>My mouse button event listener basically does the following:</p>
<ul>
<li>Check if the mouse is being placed over a grid row.
<li>Set the <em>IsDragging</em> flag to true.
<li>Store the dragged item in the <em>DraggedItem</em> dependency property (used by the popup to display the name).</li>
</ul>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnMouseLeftButtonDown(<span style="color: #0000ff">object</span> sender, MouseButtonEventArgs e)
{
  <span style="color: #008000">//exit if in edit mode</span>
  <span style="color: #0000ff">if</span> (IsEditing) <span style="color: #0000ff">return</span>;

  <span style="color: #008000">//find the clicked row</span>
  var row = UIHelpers.TryFindFromPoint&lt;DataGridRow&gt;((UIElement) sender,
                                                    e.GetPosition(shareGrid));
  <span style="color: #0000ff">if</span> (row == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span>;

  <span style="color: #008000">//set flag that indicates we're capturing mouse movements</span>
  IsDragging = <span style="color: #0000ff">true</span>;
  DraggedItem = (IShareConfiguration) row.Item;
}</pre>
</div>
<p>&nbsp;</p>
<h3>Moving the Popup</h3>
<p>I registered a listener for the <em>MouseMove</em> event directly on the layout root (not on the datagrid). Basically, the event listener just moves the popup to the current mouse location along with a few minor tasks:</p>
<ul>
<li>If the popup has not been opened yet, display it.
<li>Set the grid to read-only.
<li>Reposition the popup by setting the <em>PlacementRectangle</em> property.
<li>Make sure the grid row under the mouse is being selected. Once again, this didn&#8217;t work reliably if I relied on the datagrid to do it by itself.</li>
</ul>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Completes a drag/drop operation.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnMouseLeftButtonUp(<span style="color: #0000ff">object</span> sender, MouseButtonEventArgs e)
{
  <span style="color: #0000ff">if</span> (!IsDragging || IsEditing)
  {
    <span style="color: #0000ff">return</span>;
  }

  <span style="color: #008000">//get the target item</span>
  ShareConfiguration targetItem = (ShareConfiguration) shareGrid.SelectedItem;

  <span style="color: #0000ff">if</span> (targetItem == <span style="color: #0000ff">null</span> || !ReferenceEquals(DraggedItem, targetItem))
  {
    <span style="color: #008000">//remove the source from the list</span>
    ShareList.Remove(DraggedItem);

    <span style="color: #008000">//get target index</span>
    var targetIndex = ShareList.IndexOf(targetItem);

    <span style="color: #008000">//move source at the target's location</span>
    ShareList.Insert(targetIndex, DraggedItem);

    <span style="color: #008000">//select the dropped item</span>
    shareGrid.SelectedItem = DraggedItem;
  }

  <span style="color: #008000">//reset</span>
  ResetDragDrop();
}</pre>
</div>
<p>&nbsp;</p>
<h3>Finishing Drag and Drop</h3>
<p>Once the user releases the mouse button, I need to perform the actual drop operation. I already had the dragged item (<em>DraggedItem</em> property, was set when the operation started) so all I needed was the drop target. My target is the currently selected row.</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Completes a drag/drop operation.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnMouseLeftButtonUp(<span style="color: #0000ff">object</span> sender, MouseButtonEventArgs e)
{
  <span style="color: #0000ff">if</span> (!IsDragging || IsEditing || shareGrid.SelectedItem == <span style="color: #0000ff">null</span>)
  {
    <span style="color: #0000ff">return</span>;
  }

  <span style="color: #008000">//get the target item</span>
  IShareConfiguration targetItem = (IShareConfiguration)shareGrid.SelectedItem;

  <span style="color: #0000ff">if</span> (!ReferenceEquals(DraggedItem, targetItem))
  {
    <span style="color: #008000">//the actual business logic that works on source and target</span>
  }

  <span style="color: #008000">//reset</span>
  ResetDragDrop();
}</pre>
</div>
<p>&nbsp;</p>
<p>You might also want to check whether the mouse is currently over the grid (or a grid row) or not - in that case just use the <em>TryFindFromPoint</em> method from the <em>UIHelpers</em> class.</p>
<p>&nbsp;</p>
<h3>Cleaning Up</h3>
<p>The <em>ResetDragDrop</em> method just performs a cleanup of the code by closing the popup and adjusting a few properties:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Closes the popup and resets the</span>
<span style="color: #008000">/// grid to read-enabled mode.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> ResetDragDrop()
{
  IsDragging = <span style="color: #0000ff">false</span>;
  popup1.IsOpen = <span style="color: #0000ff">false</span>;
  shareGrid.IsReadOnly = <span style="color: #0000ff">false</span>;
}</pre>
</div>
<p>&nbsp;</p>
<p><strong>Download Sample: </strong><a title="http://www.hardcodet.net/uploads/2009/03/datagrid_dragdrop.zip" href="http://www.hardcodet.net/uploads/2009/03/datagrid_dragdrop.zip" onclick="javascript:pageTracker._trackPageview('/downloads/uploads/2009/03/datagrid_dragdrop.zip');"><strong>http://www.hardcodet.net/uploads/2009/03/datagrid_dragdrop.zip</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/03/moving-data-grid-rows-using-drag-and-drop/feed</wfw:commentRss>
		</item>
		<item>
		<title>Detecting Double Click Events on the WPF DataGrid</title>
		<link>http://www.hardcodet.net/2009/03/detecting-double-click-events-on-the-wpf-datagrid</link>
		<comments>http://www.hardcodet.net/2009/03/detecting-double-click-events-on-the-wpf-datagrid#comments</comments>
		<pubDate>Sat, 21 Mar 2009 19:38:16 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[DataGrid]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/03/detecting-double-click-events-on-the-wpf-datagrid</guid>
		<description><![CDATA[Either I missed the obvious solution, or there is indeed no simple way to catch double click events on a given row of Microsoft&#8217;s WPF DataGrid.
This snippet here fires the event whenever the grid is clicked - it doesn&#8217;t matter whether the user double-clicks into an empty area (no rows) or a row:

&#60;!-- fires even [...]]]></description>
			<content:encoded><![CDATA[<p>Either I missed the obvious solution, or there is indeed no simple way to catch double click events on a given row of Microsoft&#8217;s <a href="http://www.codeplex.com/wpf" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeplex.com');">WPF DataGrid</a>.</p>
<p>This snippet here fires the event whenever the grid is clicked - it doesn&#8217;t matter whether the user double-clicks into an empty area (no rows) or a row:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">&lt;!-- fires even if the user does not click a given row --&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">dg:DataGrid</span>
  <span style="color: #ff0000">dg:DataGridRow</span>.<span style="color: #ff0000">MouseDoubleClick</span><span style="color: #0000ff">=&quot;OnDoubleClick&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&#160;</p>
<p>As a result, I reverted to a workaround by searching the Visual Tree of the event source for an instance of type <em>DataGridRow</em>. In order to find the ancestor item, I used a snippet I posted <a href="http://www.hardcodet.net/2008/02/find-wpf-parent" >here</a> a while ago. Here&#8217;s the full code:</p>
<p>&#160;</p>
<p><strong>XAML:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">&lt;!-- just register a listener on the grid --&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">dg:DataGrid</span>
  <span style="color: #ff0000">MouseDoubleClick</span><span style="color: #0000ff">=&quot;OnDoubleClick&quot;</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&#160;</p>
<p><strong>Code-Behind:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Handles double-clicks on datagrid rows.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> OnDoubleClick(<span style="color: #0000ff">object</span> sender, MouseButtonEventArgs e)
{
  <span style="color: #008000">//search the object hierarchy for a datagrid row</span>
  DependencyObject source = (DependencyObject) e.OriginalSource;
  var row = UIHelpers.TryFindParent&lt;DataGridRow&gt;(source);

  <span style="color: #008000">//the user did not click on a row</span>
  <span style="color: #0000ff">if</span> (row == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span>;

  <span style="color: #008000">//[insert great code here...]</span>

  e.Handled = <span style="color: #0000ff">true</span>;
}</pre>
</div>
<p><strong></strong>&#160;</p>
<p><strong><em>UIHelper</em> class providing the TryFindParent method:</strong></p>
<p>(Snippet updated: 2009.09.14)</p>
<div id="codeSnippetWrapper">
<pre id="codeSnippet" style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; direction: ltr; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; text-align: left; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Finds a parent of a given item on the visual tree.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;typeparam name=&quot;T&quot;&gt;The type of the queried item.&lt;/typeparam&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;child&quot;&gt;A direct or indirect child of the</span>
<span style="color: #008000">/// queried item.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;The first parent item that matches the submitted</span>
<span style="color: #008000">/// type parameter. If not matching item can be found, a null</span>
<span style="color: #008000">/// reference is being returned.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> T TryFindParent&lt;T&gt;(<span style="color: #0000ff">this</span> DependencyObject child)&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #0000ff">where</span> T : DependencyObject
{
  <span style="color: #008000">//get parent item</span>
  DependencyObject parentObject = GetParentObject(child);

  <span style="color: #008000">//we've reached the end of the tree</span>
  <span style="color: #0000ff">if</span> (parentObject == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span>;

  <span style="color: #008000">//check if the parent matches the type we're looking for</span>
  T parent = parentObject <span style="color: #0000ff">as</span> T;
  <span style="color: #0000ff">if</span> (parent != <span style="color: #0000ff">null</span>)
  {
    <span style="color: #0000ff">return</span> parent;
  }
  <span style="color: #0000ff">else</span>
  {
    <span style="color: #008000">//use recursion to proceed with next level</span>
    <span style="color: #0000ff">return</span> TryFindParent&lt;T&gt;(parentObject);
  }
}

<span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// This method is an alternative to WPF's</span>
<span style="color: #008000">/// &lt;see cref=&quot;VisualTreeHelper.GetParent&quot;/&gt; method, which also</span>
<span style="color: #008000">/// supports content elements. Keep in mind that for content element,</span>
<span style="color: #008000">/// this method falls back to the logical tree of the element!</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;child&quot;&gt;The item to be processed.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;The submitted item's parent, if available. Otherwise</span>
<span style="color: #008000">/// null.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> DependencyObject GetParentObject(<span style="color: #0000ff">this</span> DependencyObject child)
{
  <span style="color: #0000ff">if</span> (child == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span>;

  <span style="color: #008000">//handle content elements separately</span>
  ContentElement contentElement = child <span style="color: #0000ff">as</span> ContentElement;
  <span style="color: #0000ff">if</span> (contentElement != <span style="color: #0000ff">null</span>)
  {
    DependencyObject parent = ContentOperations.GetParent(contentElement);
    <span style="color: #0000ff">if</span> (parent != <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> parent;

    FrameworkContentElement fce = contentElement <span style="color: #0000ff">as</span> FrameworkContentElement;
    <span style="color: #0000ff">return</span> fce != <span style="color: #0000ff">null</span> ? fce.Parent : <span style="color: #0000ff">null</span>;
  }

  <span style="color: #008000">//also try searching for parent in framework elements (such as DockPanel, etc)</span>
  FrameworkElement frameworkElement = child <span style="color: #0000ff">as</span> FrameworkElement;
  <span style="color: #0000ff">if</span> (frameworkElement != <span style="color: #0000ff">null</span>)
  {
    DependencyObject parent = frameworkElement.Parent;
    <span style="color: #0000ff">if</span> (parent != <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> parent;
  }

  <span style="color: #008000">//if it's not a ContentElement/FrameworkElement, rely on VisualTreeHelper</span>
  <span style="color: #0000ff">return</span> VisualTreeHelper.GetParent(child);
}</pre>
</div>
<p>&#160;</p>
<p>Enjoy <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/03/detecting-double-click-events-on-the-wpf-datagrid/feed</wfw:commentRss>
		</item>
		<item>
		<title>Format WPF Bindings With Resource File Lookups</title>
		<link>http://www.hardcodet.net/2009/03/lookup-resource-value-using-markup-extension</link>
		<comments>http://www.hardcodet.net/2009/03/lookup-resource-value-using-markup-extension#comments</comments>
		<pubDate>Sat, 21 Mar 2009 10:33:58 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[Localization]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/03/lookup-resource-value-using-markup-extension</guid>
		<description><![CDATA[This post explains a pattern that combines Data Binding, the new StringFormat property and resource lookups through the application of a custom MarkupExtension.
&#160;
StringFormat
Microsoft introduced the StringFormat property with SP1 for .NET 3.5. StringFormat often eliminates the need for a custom converter if you just need to format a bound value. Here&#8217;s a very simple sample [...]]]></description>
			<content:encoded><![CDATA[<p>This post explains a pattern that combines Data Binding, the new <em>StringFormat</em> property and resource lookups through the application of a custom <em>MarkupExtension</em>.</p>
<p>&nbsp;</p>
<h2>StringFormat</h2>
<p>Microsoft introduced the <em><a href="http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">StringFormat</a></em> property with SP1 for .NET 3.5. <em>StringFormat</em> often eliminates the need for a custom converter if you just need to format a bound value.<br /> Here&#8217;s a very simple sample that displays <em>hello xxx </em>on the screen (where &#8220;<em>xxx</em>&#8221; is the value entered in a <em>TextBox</em> control:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">TextBox</span>
    <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">="name"</span>
    <span style="color: #ff0000">Text</span><span style="color: #0000ff">="world"</span> <span style="color: #0000ff">/&gt;</span>

<span style="color: #0000ff">&lt;</span><span style="color: #800000">TextBlock</span>
    <span style="color: #ff0000">Text</span><span style="color: #0000ff">="{Binding ElementName=name,
                   Path=Text,
                   StringFormat=hello \{0\}}"</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&nbsp;</p>
<h2>Resource Files</h2>
<p>I often use resource files to store strings - not only for localization tasks but also in order to maintain strings that are intended for users at a central place. My resource strings often contain placeholders which are populated at runtime using String.Format:</p>
<p>&nbsp;</p>
<p><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="88" alt="image" src="http://www.hardcodet.net/uploads/2009/03/image.png" width="454" border="0"> </p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//use resource file to create message</span>
var msg = <font color="#0000ff"><strong>Resources.Ask_Whether_To_Connect_To_New_Share</strong></font>;
msg = String.Format(msg, configuration.Name);

<span style="color: #008000">//display dialog</span>
MessageBoxResult doConnect = Dialogs.ShowYesNo(msg);</pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h2>Bringing Bindings and Resource Files Together</h2>
<p>In the sample above, I accessed the resource file programmatically. In XAML however, I prefer a declarative approach. In order to get there, I implemented a simple MarkupExtension that allows me to do just that:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">

<span style="color: #008000">&lt;!-- Display a formatted text --&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">TextBlock</span>
  <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">="Title"</span>
  <span style="color: #ff0000">Text</span><span style="color: #0000ff">="{Binding Path=Name,
                 StringFormat={<strong>ext:Resource Ask_Whether_To_Connect_To_New_Share}</strong>}"</span>

<span style="color: #0000ff"></span> <span style="color: #0000ff">/&gt;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>The above snippet results in a formatted text being displayed:</p>
<p><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="65" alt="image" src="http://www.hardcodet.net/uploads/2009/03/image1.png" width="471" border="0"> </p>
<p>&nbsp;</p>
<h2>Resource MarkupExtension</h2>
<p>Here&#8217;s the markup extension. As you can see, it&#8217;s fairly trivial. Do note that the reference to the application&#8217;s Resources file is hardcoded - you will have to set a using statement or adjust that line in order to use your custom resource file.</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// A markup extension that provides simple access to a given</span>
<span style="color: #008000">/// entry in the application's &lt;see cref="Resources"/&gt; file.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Resource : MarkupExtension
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// The resource key to be used for the lookup.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> ResourceKey { get; set; }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Inits the &lt;see cref="Resource"/&gt; markup extension</span>
  <span style="color: #008000">/// with the key to be assigned.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;param name="resourceKey"&gt;The resource key to be assigned.&lt;/param&gt;</span>
  <span style="color: #0000ff">public</span> Resource(<span style="color: #0000ff">string</span> resourceKey)
  {
    ResourceKey = resourceKey;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Performs a lookup for the defined &lt;see cref="ResourceKey"/&gt;.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;returns&gt;</span>
  <span style="color: #008000">/// The value of the resource that is specified by the</span>
  <span style="color: #008000">/// &lt;see cref="ResourceKey"/&gt; property. If the property is not</span>
  <span style="color: #008000">/// set, a null reference is returned.</span>
  <span style="color: #008000">/// &lt;/returns&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">object</span> ProvideValue(IServiceProvider serviceProvider)
  {
    <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(ResourceKey)) <span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span>;
    <span style="color: #0000ff">return</span> Resources.ResourceManager.GetObject(ResourceKey);
  }
}</pre>
</div>
<p>&nbsp;</p>
<p>Enjoy <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/03/lookup-resource-value-using-markup-extension/feed</wfw:commentRss>
		</item>
		<item>
		<title>Simplify Time Measurement in Tests and Debug Code</title>
		<link>http://www.hardcodet.net/2009/02/timeguard-helper-class-to-measure-elapsed-time</link>
		<comments>http://www.hardcodet.net/2009/02/timeguard-helper-class-to-measure-elapsed-time#comments</comments>
		<pubDate>Mon, 23 Feb 2009 13:06:37 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/02/timeguard-helper-class-to-measure-elapsed-time</guid>
		<description><![CDATA[A simple helper class I derived from a more generic pattern: For debugging and testing, I quite often want to measure the time used for a given process. Usually, this looks somewhat like this:
&#160;

public void TestElapsedTime()
{
  DateTime start = DateTime.Now;

  //do some work

  DateTime end = DateTime.Now;
  double elapsedTime = end.Subtract(start).TotalMilliseconds;
 [...]]]></description>
			<content:encoded><![CDATA[<p>A simple helper class I derived from a more generic pattern: For debugging and testing, I quite often want to measure the time used for a given process. Usually, this looks somewhat like this:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> TestElapsedTime()
{
  DateTime start = DateTime.Now;

  <span style="color: #008000">//do some work</span>

  DateTime end = DateTime.Now;
  <span style="color: #0000ff">double</span> elapsedTime = end.Subtract(start).TotalMilliseconds;
  Console.Out.WriteLine(<span style="color: #006080">"Work took {0} milliseconds"</span>, elapsedTime);
}</pre>
</div>
<p>&nbsp;</p>
<p>However: The code above, while being pretty simple, can be easily wrapped into a generic helper class:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// A guard that can be used to measure the time</span>
<span style="color: #008000">/// used for a given process by simply wrapping it</span>
<span style="color: #008000">/// in a using statement.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> TimeGuard : IDisposable
{
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Action&lt;<span style="color: #0000ff">double</span>&gt; action;
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> DateTime startTime;

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Creates the guard with a given action that receives the</span>
  <span style="color: #008000">/// elapsed time in milliseconds.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;param name="setDelta"&gt;The action that is being invoked</span>
  <span style="color: #008000">/// with time (in milleconds) that was taken between construction</span>
  <span style="color: #008000">/// of this instance until disposal.&lt;/param&gt;</span>
  <span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="setDelta"/&gt;</span>
  <span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
  <span style="color: #0000ff">public</span> TimeGuard(Action&lt;<span style="color: #0000ff">double</span>&gt; setDelta)
  {
    <span style="color: #0000ff">if</span> (setDelta == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">"setDelta"</span>);

    action = setDelta;
    startTime = DateTime.Now;
  }

  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// Calculates the elapsed time since construction</span>
  <span style="color: #008000">/// and submits the delta to the &lt;see cref="action"/&gt;</span>
  <span style="color: #008000">/// action.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Dispose()
  {
    var now = DateTime.Now;
    action(now.Subtract(startTime).TotalMilliseconds);
  }
}</pre>
</div>
<p>&nbsp;</p>
<p>Using the <em>TimeGuard</em> class, I can perform time measurements without having to deal with <em>DateTime</em> instances and the calculation of the elapsed time at all. Two samples:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> TestElapsedTime()
{
  <span style="color: #0000ff">double</span> elapsedTime = 0;
  <span style="color: #0000ff">using </span>(<span style="color: #0000ff">new</span> TimeGuard(t =&gt; elapsedTime = t))
  {
    <span style="color: #008000">//do some work</span>
  }

  Console.Out.WriteLine(<span style="color: #006080">"Work took {0} milliseconds"</span>, elapsedTime);
}</pre>
</div>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> TestElapsedTime()
{
  <span style="color: #0000ff">using</span> (<span style="color: #0000ff">new</span> TimeGuard(t =&gt; Assert.Less(t, 500)))
  {
    <span style="color: #008000">//do some work here that should take less than 500 ms</span>
  }
}</pre>
</div>
<p>&nbsp;</p>
<p>Apart from providing cleaner code, I also prefer this approach because it encapsulates time measurement functionality in a single class and simplifies adjustments, like using a <a href="http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/ayende.com');">different pattern</a> to retrieve time stamps, or using the <a title="StopWatch on MSDN" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">StopWatch</a> class to get a more accurate measurement (thanks to <a href="http://codeclimber.net.nz/" onclick="javascript:pageTracker._trackPageview('/outbound/article/codeclimber.net.nz');">Simone Chiaretta</a> for the hint).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/02/timeguard-helper-class-to-measure-elapsed-time/feed</wfw:commentRss>
		</item>
		<item>
		<title>Simple Extension Method to Evaluate Listings For a Match</title>
		<link>http://www.hardcodet.net/2009/02/extension-method-to-evaluate-listing</link>
		<comments>http://www.hardcodet.net/2009/02/extension-method-to-evaluate-listing#comments</comments>
		<pubDate>Wed, 04 Feb 2009 14:28:28 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/02/extension-method-to-evaluate-listing</guid>
		<description><![CDATA[I&#8217;m currently dealing with a system that switches between different states, which require evaluations that look similar to the snippet below:
&#160;

//check status flags
TestStatus status = GetStatus();
if (status == TestStatus.Preparing &#124;&#124;
    status == TestStatus.Running &#124;&#124;
    status == TestStatus.PostDelay)
{
  ...
}

&#160;
Given the fact that I&#8217;m having lots of states, I had [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently dealing with a system that switches between different states, which require evaluations that look similar to the snippet below:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">//check status flags</span>
TestStatus status = GetStatus();
<span style="color: #0000ff">if</span> (status == TestStatus.Preparing ||
    status == TestStatus.Running ||
    status == TestStatus.PostDelay)
{
  ...
}</pre>
</div>
<p>&nbsp;</p>
<p>Given the fact that I&#8217;m having lots of states, I had to produce pretty nasty code, so I wrote that handy little extension method that takes care of the issue once and for all:</p>
<p><em>Edit (2009.02.08): Returning false for null values which allows to submit null references without exception.</em></p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Checks a list of candidates for equality to a given</span>
<span style="color: #008000">/// reference value.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;</span>
<span style="color: #008000">/// &lt;param name="value"&gt;The evaluated value.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;param name="candidates"&gt;A liste of possible values that are</span>
<span style="color: #008000">/// regarded valid.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;True if one of the submitted &lt;paramref name="candidates"/&gt;</span>
<span style="color: #008000">/// matches the evaluated value. If the &lt;paramref name="candidates"/&gt;</span>
<span style="color: #008000">/// parameter itself is null, too, the method returns false as well,</span>
<span style="color: #008000">/// which allows to check with null values, too.&lt;/returns&gt;</span>
<span style="color: #008000">/// &lt;exception cref="ArgumentNullException"&gt;If &lt;paramref name="candidates"/&gt;</span>
<span style="color: #008000">/// is a null reference.&lt;/exception&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">bool</span> Is&lt;T&gt;(<span style="color: #0000ff">this</span> T <span style="color: #0000ff">value</span>, <span style="color: #0000ff">params</span> T[] candidates)
{
  <span style="color: #0000ff">if</span> (candidates == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;

  <span style="color: #0000ff">foreach</span> (var t <span style="color: #0000ff">in</span> candidates)
  {
    <span style="color: #0000ff">if</span> (<span style="color: #0000ff">value</span>.Equals(t)) <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;
  }

  <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;
}</pre>
</div>
<p>&nbsp;</p>
<p>Using this &#8220;<strong><em>Is</em></strong>&#8221; extension, I can now write the above code like this:</p>
<p>&nbsp;</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">if</span> (status.Is(TestStatus.Preparing, TestStatus.Running, TestStatus.PostDelay)
{
  ...
}</pre>
</div>
<p>&nbsp;</p>
<p>Of course, this is not limited to <em>Enums</em> but works with everything that supports the <em>Equals</em> operator:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">string</span> name = ...
<span style="color: #0000ff">if</span> (name.Is(<span style="color: #006080">"foo"</span>, <span style="color: #006080">"bar"</span>))
{
  <span style="color: #008000">//foobar!</span>
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/02/extension-method-to-evaluate-listing/feed</wfw:commentRss>
		</item>
		<item>
		<title>First Anniversary</title>
		<link>http://www.hardcodet.net/2009/01/first-anniversary</link>
		<comments>http://www.hardcodet.net/2009/01/first-anniversary#comments</comments>
		<pubDate>Fri, 16 Jan 2009 13:19:29 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=256</guid>
		<description><![CDATA[Wow, already a year since my first blog post! It&#8217;s been fun and I&#8217;m far from running out of ideas - stay tuned  
]]></description>
			<content:encoded><![CDATA[<p><img class="size-medium wp-image-30 alignleft" title="avatar-big.png" src="http://www.hardcodet.net/uploads/2008/01/avatar-big.png" alt="" width="96" height="96" />Wow, already a year since my first blog post! It&#8217;s been fun and I&#8217;m <em>far </em>from running out of ideas - stay tuned <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/01/first-anniversary/feed</wfw:commentRss>
		</item>
		<item>
		<title>ComboBox SelectedItem and ItemsSource: Order Matters</title>
		<link>http://www.hardcodet.net/2009/01/xaml-binding-declaration-order-matters</link>
		<comments>http://www.hardcodet.net/2009/01/xaml-binding-declaration-order-matters#comments</comments>
		<pubDate>Wed, 14 Jan 2009 10:34:06 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[WPF]]></category>

		<category><![CDATA[WPF Controls]]></category>

		<category><![CDATA[xaml]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/01/xaml-binding-declaration-order-matters</guid>
		<description><![CDATA[A co-worker of mine had a strange issue with a bound combo box that looked like this:&#160; 

&#60;ComboBox
  x:Name="cboParentUser"
  ItemsSource="{Binding Path=Order.Store.Users, ElementName=me, Mode=Default}"
  SelectedItem="{Binding Path=Order.ParentUser, ElementName=me, Mode=Default}"
  IsEditable="False"
  DisplayMemberPath="UserName" /&#62;

&#160;
As we could observe at runtime, selecting an item in the combo box properly updated the underlying ParentUser property. Furthermore, we [...]]]></description>
			<content:encoded><![CDATA[<p>A co-worker of mine had a strange issue with a bound combo box that looked like this:&nbsp; </p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">ComboBox</span>
  <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">="cboParentUser"</span>
  <span style="color: #ff0000">ItemsSource</span><span style="color: #0000ff">="{Binding Path=Order.Store.Users, ElementName=me, Mode=Default}"</span>
  <span style="color: #ff0000">SelectedItem</span><span style="color: #0000ff">="{Binding Path=Order.ParentUser, ElementName=me, Mode=Default}"</span>
  <span style="color: #ff0000">IsEditable</span><span style="color: #0000ff">="False"</span>
  <span style="color: #ff0000">DisplayMemberPath</span><span style="color: #0000ff">="UserName"</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&nbsp;</p>
<p>As we could observe at runtime, selecting an item in the combo box properly updated the underlying <em>ParentUser </em>property. Furthermore, we could easily exchange the data context (<em>Order </em>dependency property) in order to edit different items.</p>
<p>However: As soon a the editor control that contained the combo box was unloaded, the <em>ParentUser </em>property of the currently edited <em>Order </em>was set to null, so all previously made adjustments were lost.</p>
<p>The reason behind this behavior seems to be the fact that both <em>ItemsSource</em> and <em>SelectedItem</em> are bound to the same dependency property: Apparently, when <em>Order </em>is set to null during unloading, WPF realizes that the <em>ItemsSource</em> is no longer valid, and therefore clears the <em>SelectedItem</em>, to which the combo box still appears to hold a reference at this moment - which brings it down to a question of proper coercion. Or maybe not - the reason behind this is not entirely clear to me.</p>
<p>However: Changing the declaration order of <em>SelectedItem</em> and <em>ItemsSource</em> fixes the problem: </p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;</span><span style="color: #800000">ComboBox</span>
  <span style="color: #ff0000">x:Name</span><span style="color: #0000ff">="cboParentUser"</span>
  <span style="color: #ff0000">SelectedItem</span><span style="color: #0000ff">="{Binding Path=Order.ParentUser, ElementName=me, Mode=Default}"</span>
  <span style="color: #ff0000">ItemsSource</span><span style="color: #0000ff">="{Binding Path=Order.Store.Users, ElementName=me, Mode=Default}"</span>
  <span style="color: #ff0000">IsEditable</span><span style="color: #0000ff">="False"</span>
  <span style="color: #ff0000">DisplayMemberPath</span><span style="color: #0000ff">="UserName"</span> <span style="color: #0000ff">/&gt;</span></pre>
</div>
<p>&nbsp;</p>
<p>And yes: This <em>does</em> feel like a dirty hack.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/01/xaml-binding-declaration-order-matters/feed</wfw:commentRss>
		</item>
	</channel>
</rss>
