<?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>Mon, 15 Feb 2010 23:21:50 +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" type="application/rss+xml" href="http://feeds.feedburner.com/hardcodet" /><feedburner:info uri="hardcodet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><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><item>
		<title>Remote File Access in VFS using OpenRasta – Part 1 (Introduction)</title>
		<link>http://www.hardcodet.net/2010/02/remote-file-access-in-vfs-part-1</link>
		<comments>http://www.hardcodet.net/2010/02/remote-file-access-in-vfs-part-1#comments</comments>
		<pubDate>Sun, 14 Feb 2010 12:54:39 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[REST]]></category>

		<category><![CDATA[VFS]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=775</guid>
		<description><![CDATA[
This lose series of articles will cover the implementation of a file system façade that allows transparent remote file system access in VFS.
The series will cover the following topics:

Introduction and basic concept (this article)
Implementing a RESTful file system proxy service with OpenRasta (coming soon)
Unit testing the OpenRasta proxy service (not yet published)
General tutorial: Streaming binary [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>This lose series of articles will cover the implementation of a file system façade that allows transparent remote file system access in <a href="http://vfs.codeplex.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/vfs.codeplex.com');">VFS</a>.</p>
<p>The series will cover the following topics:</p>
<ul>
<li>Introduction and basic concept (this article)</li>
<li>Implementing a RESTful file system proxy service with <a href="http://trac.caffeine-it.com/openrasta" onclick="javascript:pageTracker._trackPageview('/outbound/article/trac.caffeine-it.com');">OpenRasta</a> (coming soon)</li>
<li>Unit testing the OpenRasta proxy service (not yet published)</li>
<li>General tutorial: Streaming binary data in Silverlight</li>
<li>Implementing VFS client libraries for both .NET and Silverlight (not yet published)</li>
</ul>
<h3>VFS File System Providers</h3>
<p>VFS abstracts access to arbitrary file systems through so-called “File System Providers”, which expose a common interface (<span class="code">IFileSystemProvider</span>) that allows you to browse and modify the file system. The interface is not exactly lean, but easy to understand:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/02/image1.png" width="300" height="483" /> </p>
<p>Now, common file system providers directly operate on some kind of hierarchical data. Here’s a few examples:</p>
<ul>
<li>The “Local File System Provider” allows you to access your local machine, or the contents of a dedicated directory. </li>
<li>The “ZIP File System Provider” works upon a single ZIP file, and allows you to transparently access and modify its contents. </li>
<li>An “FTP File System Provider” connects to a given FTP server and gives you access to the server’s files through the VFS API. </li>
<li>… </li>
</ul>
<p>So basically, an application uses a VFS provider, which in turn directly accesses the exposed file system:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/02/image2.png" width="262" height="46" /> </p>
<p>&#160;</p>
<h3>Tunneling Façades</h3>
<p>There is, however, a special family of file system providers that do not access any files. Instead, they forward file system requests to another file system provider, thus creating a tunnel to another file system. Basically, these file system providers are <em><strong>façades</strong></em> to another, arbitrary file system provider.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/02/image3.png" width="550" height="123" /> </p>
<p>&#160;</p>
<p>Here’s an exemplary scenario that uses a façade in order to access a ZIP file that is exposed through a ZIP file provider (click on the UML diagram in order to see it in full size).</p>
<p>&#160;<a href="http://www.hardcodet.net/uploads/2010/02/tunnelling.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Tunnelling" border="0" alt="Tunnelling" src="http://www.hardcodet.net/uploads/2010/02/tunnelling-thumb.png" width="550" height="250" /></a> </p>
<p>&#160;</p>
<p>The interesting point here: From the client’s perspective, there is no difference in accessing the file system. The façade itself implements the <span class="code">IFileSystemProvider </span>interface – it provides <em>exactly</em> the same API as any other provider.</p>
<p>As you can see from the diagram above, a façade is usually complemented by some kind of proxy that receives the forwarded requests, so in order to implement the pattern, there’s two components to be written:</p>
<ol>
<li>The façade, which implements <span class="code">IFileSystemProvider</span>. </li>
<li>The proxy that takes the forwarded requests, forwards them its own file system provider, and eventually returns the requested data. This proxy is not a VFS component, and you don’t have to implement any VFS interfaces. </li>
</ol>
<p>As you can guess, tunnels come in handy in order to access remote data. Here’s a few scenarios:</p>
<ul>
<li>Run a local file system provider on a server that provides a download service. Clients don’t have direct access to the files, but use a tunnel to access the files that are exposed through the provider that runs on the server. </li>
<li>Allow a Silverlight client to browse the contents of a ZIP file on the server, without having to download the whole ZIP file first (sample coming).</li>
<li>Host a cloud file system provider within a WCF service, and expose parts of the cloud’s data to clients. Like this, clients don’t have direct access to the cloud data.</li>
</ul>
<h3>A RESTful Façade Implementation</h3>
<p>Every façade itself is an independent file system provider – so tunneling is rather a pattern than an API, and you can write your own façade should you wish to (actually, contributions will be most welcome!).</p>
<p>However, VFS 1.0 will ship with a single façade implementation that uses HTTP/REST to create a tunnel to a remote file system. It is built upon the following libraries:</p>
<ul>
<li>On the server side, <a href="http://trac.caffeine-it.com/openrasta" onclick="javascript:pageTracker._trackPageview('/outbound/article/trac.caffeine-it.com');">OpenRasta</a> was used to expose file system access as RESTful services. OpenRasta is a lightweight, but powerful framework that comes with a API.</li>
<li>On the client side, the WCF REST Starter Kit was used for both <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644" onclick="javascript:pageTracker._trackPageview('/outbound/article/aspnet.codeplex.com');">.NET</a> and Silverlight clients (the <a href="http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight" >Silverlight library</a> hacked together by myself). The starter kit’s client libraries allow for simple access to RESTful resources, even if there is no WCF involved.</li>
</ul>
<p>&#160;</p>
<p>The upcoming articles will walk you through the implementation of the both the client and service libraries, and will also be complemented by a preview release of VFS. 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/2010/02/remote-file-access-in-vfs-part-1/feed</wfw:commentRss>
		</item>
		<item>
		<title>REST Client Library for Silverlight</title>
		<link>http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight</link>
		<comments>http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight#comments</comments>
		<pubDate>Mon, 08 Feb 2010 16:49:08 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[REST]]></category>

		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight</guid>
		<description><![CDATA[A port of the WCF REST Starter Kit to Silverlight.]]></description>
			<content:encoded><![CDATA[<p>I’ve been doing some hackery and ported the client libraries of the <a href="http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644" onclick="javascript:pageTracker._trackPageview('/outbound/article/aspnet.codeplex.com');">WCF REST Starter Kit</a> to Silverlight. The library greatly simplifies things when it comes to accessing and consuming RESTful services and resources in your Silverlight application.</p>
<p>Here’s a sample for a simple GET using the <span class="code">HttpClient </span>class:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> User GetUser(<span style="color: #0000ff">string</span> userId)
{
  <span style="color: #008000">//init client with base URI</span>
  HttpClient client = <span style="color: #0000ff">new</span> HttpClient(<span style="color: #006080"><a href="http://localhost:56789/users/" onclick="javascript:pageTracker._trackPageview('/outbound/article/localhost:56789');">http://localhost:56789/users/</a></span>);

  <span style="color: #008000">//send a HTTP GET request for a given resource</span>
  HttpResponseMessage response = client.Get(userId);

  <span style="color: #008000">//parse the received data on the fly</span>
  <span style="color: #0000ff">return</span> response.Content.ReadAsDataContract&lt;User&gt;();
}</pre>
</div>
<p>&#160;</p>
<p>Or, in order to send a DTO via HTTP POST:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> PostUser(User user)
{
  <span style="color: #008000">//init client with base URI</span>
  HttpClient client = <span style="color: #0000ff">new</span> HttpClient(<span style="color: #006080">&quot;http://localhost:56789/&quot;</span>);

  <span style="color: #008000">//serialize user object</span>
  HttpContent content = HttpContentExtensions.CreateDataContract(user);

  <span style="color: #008000">//post to user service</span>
  HttpResponseMessage response = client.Post(<span style="color: #006080">&quot;/user&quot;</span>, content);
}</pre>
</div>
<p>&#160;</p>
<p>I have removed a few bits, but most of the functionality should be there, and I added “NOTE” comments to all the sections that I had to modify. I haven’t used this port in-depth but managed to access my RESTful resources as expected so far, and I hope it will work just fine as in most scenarios that are covered in the original Starter Kit. Of course, given the Starter Kit itself is prerelease software, this applies to this release even more.</p>
<p>&#160;</p>
<h4>Blocking vs. Async Operations</h4>
<p>If you try to initiate a blocking request to your REST service on the UI thread, an <span class="code">InvalidOperationException</span> is thrown due to synchronization issues. Accordingly, a snippet as the one above should always be invoked on a worker thread (which is a best practice anyway).</p>
<p>However, in order to simplify things, I’ve added a bunch of <span class="code">XXXAsync</span> extension methods for the <span class="code">HttpClient </span>class that allow you to invoke HTTP operations such as GET, POST, PUT etc. directly on the UI thread, and have the result delivered back to you through a simple callback action. Here’s the same snippet as above, this time using the <span class="code">GetAsync </span>method of the <span class="code">HttpClient </span>class:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> GetFolder()
{
  HttpClient client = <span style="color: #0000ff">new</span> HttpClient(<span style="color: #006080">&quot;http://localhost:56789/root&quot;</span>);

  <span style="color: #008000">//you can invoke the GetAsync method on a worker thread</span>
  client.GetAsync(response =&gt;
    {
      VirtualFolder folder = response.Content.ReadAsDataContract&lt;VirtualFolder&gt;();
    });
}</pre>
</div>
<p>&#160;</p>
</p>
<p>Note that the callback action will be invoked on a worker thread, so you might have to switch back to the UI thread if you want to modify your UI.</p>
<p>&#160;</p>
<p>Oh yes: Use at your own risk <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>&#160;</p>
<p><a class="download" title="http://www.hardcodet.net/uploads/projects/silverlight/rest-starter-kit-sl.zip" href="http://www.hardcodet.net/uploads/projects/silverlight/rest-starter-kit-sl.zip" onclick="javascript:pageTracker._trackPageview('/downloads/uploads/projects/silverlight/rest-starter-kit-sl.zip');">Download REST Starter Kit for Silverlight</a></p>
<p><font color="#ff0000" size="1"><strong>Current Version: 1.0.3, 2010.02.14</strong></font></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2010/02/wcf-rest-starter-kit-for-silverlight/feed</wfw:commentRss>
		</item>
		<item>
		<title>A GetResponse Extension for Synchronized Web Requests in Silverlight</title>
		<link>http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight</link>
		<comments>http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight#comments</comments>
		<pubDate>Mon, 08 Feb 2010 11:40:55 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight</guid>
		<description><![CDATA[A snippet that bring the blocking HttpWebRequest.GetResponse functionality back to Silverlight.]]></description>
			<content:encoded><![CDATA[<p>Unlike its CLR counter part, Silverlight’s <span class="code">HttpWebRequest </span>does not provide a synchronous <span class="code">GetResponse </span>method that allows to receive an HTTP response in a blocking operation. As a result, you are forced to use the asynchronous <span class="code">BeginGetResponse </span>method, and handle the results on a callback method.</p>
<p>This makes sense if the response is requested on the UI thread (otherwise, it would freeze the UI), but it might be a problem in certain scenarios (e.g. if you want to submit multiple requests in an orderly fashion).</p>
<p>However, you can get around the issue by using wait handles, which allow you to easily block a running operation. I encapsulated the required functionality in a simple extension method that brings <span class="code">GetResponse </span>method back into Silverlight.</p>
<p>The usage is simple – you just invoke the <span class="code">GetResponse()</span> extension method with an optional timeout. Here’s a sample that submits five synchronous HTTP requests:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> RunRequests()
{
  <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0; i &lt; 5; i++)
  {
    Uri uri = <span style="color: #0000ff">new</span> Uri(<span style="color: #006080">&quot;http://localhost/users?user=&quot;</span> + i);
    HttpWebRequest request =
      (HttpWebRequest)WebRequestCreator.ClientHttp.Create(uri);

    <span style="color: #008000">//get response as blocking operation which times out after 10 secs</span>
    HttpWebResponse response = request.GetResponse(10000);
  }
}</pre>
</div>
<p>&#160;</p>
<p><em><font color="#ff0000">You will run into timeout issues if you run execute this method on the UI thread because internally, the requested response accesses the UI thread (for whatever reasons). <u>Only</u> invoke this extension method on background threads!</font></em></p>
<p>&#160;</p>
<p>Here’s the implementation:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> RequestHelper
{
  <span style="color: #008000">/// &lt;summary&gt;</span>
  <span style="color: #008000">/// A blocking operation that does not continue until a response has been</span>
  <span style="color: #008000">/// received for a given &lt;see cref=&quot;HttpWebRequest&quot;/&gt;, or the request</span>
  <span style="color: #008000">/// timed out.</span>
  <span style="color: #008000">/// &lt;/summary&gt;</span>
  <span style="color: #008000">/// &lt;param name=&quot;request&quot;&gt;The request to be sent.&lt;/param&gt;</span>
  <span style="color: #008000">/// &lt;param name=&quot;timeout&quot;&gt;An optional timeout.&lt;/param&gt;</span>
  <span style="color: #008000">/// &lt;returns&gt;The response that was received for the request.&lt;/returns&gt;</span>
  <span style="color: #008000">/// &lt;exception cref=&quot;TimeoutException&quot;&gt;If the &lt;paramref name=&quot;timeout&quot;/&gt;</span>
  <span style="color: #008000">/// parameter was set, and no response was received within the specified</span>
  <span style="color: #008000">/// time.&lt;/exception&gt;</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> HttpWebResponse GetResponse(<span style="color: #0000ff">this</span> HttpWebRequest request,
                                            <span style="color: #0000ff">int</span>? timeout)
  {
    <span style="color: #0000ff">if</span> (request == <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentNullException(<span style="color: #006080">&quot;request&quot;</span>);

    <span style="color: #0000ff">if</span> (System.Windows.Deployment.Current.Dispatcher.CheckAccess())
    {
      <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> msg = <span style="color: #006080">&quot;Invoking this method on the UI thread is forbidden.&quot;</span>;
      <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> InvalidOperationException(msg);
    }

    AutoResetEvent waitHandle = <span style="color: #0000ff">new</span> AutoResetEvent(<span style="color: #0000ff">false</span>);
    HttpWebResponse response = <span style="color: #0000ff">null</span>;
    Exception exception = <span style="color: #0000ff">null</span>;

    AsyncCallback callback = ar =&gt;
       {
         <span style="color: #0000ff">try</span>
         {
           <span style="color: #008000">//get the response</span>
           response = (HttpWebResponse)request.EndGetResponse(ar);
         }
         <span style="color: #0000ff">catch</span>(Exception e)
         {
           exception = e;
         }
         <span style="color: #0000ff">finally</span>
         {
           <span style="color: #008000">//setting the handle unblocks the loop below</span>
           waitHandle.Set();
         }
       };

    <span style="color: #008000">//request response async</span>
    var asyncResult = request.BeginGetResponse(callback, <span style="color: #0000ff">null</span>);
    <span style="color: #0000ff">if</span> (asyncResult.CompletedSynchronously) <span style="color: #0000ff">return</span> response;

    <span style="color: #0000ff">bool</span> hasSignal = waitHandle.WaitOne(timeout ?? Timeout.Infinite);
    <span style="color: #0000ff">if</span> (!hasSignal)
    {
      <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> TimeoutException(<span style="color: #006080">&quot;No response received in time.&quot;</span>);
    }

    <span style="color: #008000">//bubble exception that occurred on worker thread</span>
    <span style="color: #0000ff">if</span> (exception != <span style="color: #0000ff">null</span>) <span style="color: #0000ff">throw</span> exception;

    <span style="color: #0000ff">return</span> response;
  }
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2010/02/blocking-httpwebrequest-getresponse-for-silverlight/feed</wfw:commentRss>
		</item>
		<item>
		<title>A Simplistic Random String Generation Snippet</title>
		<link>http://www.hardcodet.net/2010/01/simple-random-strings</link>
		<comments>http://www.hardcodet.net/2010/01/simple-random-strings#comments</comments>
		<pubDate>Mon, 25 Jan 2010 12:27:00 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Random]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2010/01/simple-random-strings</guid>
		<description><![CDATA[This is just a little snippet that generates a random string, containing both upper and lower case characters and special chars, so there’s a range of 93 possible characters, taken from the UTF-8 character table. I thought I’d post it as the snippets I’ve seen after a quick search usually just generate strings with characters [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a little snippet that generates a random string, containing both upper and lower case characters and special chars, so there’s a range of 93 possible characters, taken from the <a href="http://www.utf8-chartable.de/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.utf8-chartable.de');">UTF-8 character table</a>. I thought I’d post it as the snippets I’ve seen after a quick search usually just generate strings with characters ranging from ‘A’ to ‘Z’, or do not work with properly initialized seeds.</p>
<p>Note that this method uses a static int field (<span class="code">seedCounter</span>) when in comes to creating a random seed. This counter is incremented in a thread safe manner every time the method is being invoked. This simple trick is a simple workaround to the notoriously unreliable <span class="code">Random </span>class, and effectively prevents double seeds (and thus: duplicate “random strings”) if the <span class="code">GetRandomString </span>method is being invoked several times immediately. As an alternative, you could also use a static <span class="code">Random </span>field, which would only have to be initialized once. My implementation has the smaller footprint (and integer variable), while a <span class="code">Random </span>field would perform much better (currently, every invocation calculates a seed and creates a new <span class="code">Random </span>instance). The better choice depends on the context I guess:</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// A counter that is being incremented with every invocation of</span>
<span style="color: #008000">/// &lt;see cref=&quot;GetRandomString&quot;/&gt;.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">int</span> seedCounter = (<span style="color: #0000ff">int</span>)DateTime.Now.Ticks;

<span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Generates a random string of a given length, which consists</span>
<span style="color: #008000">/// of characters taken from the UTF-8 table (0x21 - 0x7e).</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #008000">/// &lt;param name=&quot;length&quot;&gt;The length of the random string.&lt;/param&gt;</span>
<span style="color: #008000">/// &lt;returns&gt;Random characters.&lt;/returns&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">string</span> GetRandomString(<span style="color: #0000ff">int</span> length)
{
  <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> lower = 0x21;
  <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> upper = 0x7e;

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

  <span style="color: #008000">//increment thread-safe</span>
  seedCounter = Interlocked.Increment(<span style="color: #0000ff">ref</span> seedCounter);

  <span style="color: #008000">//create random with the seed (make sure it's not int.MinValue)</span>
  Random rnd = <span style="color: #0000ff">new</span> Random(seedCounter %<span style="color: #0000ff">int</span>.MinValue);

  <span style="color: #0000ff">for</span> (<span style="color: #0000ff">int</span> i = 0; i &lt; length; i++)
  {
    builder.Append((<span style="color: #0000ff">char</span>) rnd.Next(lower, upper));
  }

  <span style="color: #0000ff">return</span> builder.ToString();
}</pre>
</div>
<p>&#160;</p>
<p>Accordingly, invoking the method like this:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">string</span> random = GetRandomString(10);</pre>
</div>
<p>&#160;</p>
<p>&#8230;generates you a string comparable to this one: <span class="code">2#,R`6&gt;Cz{</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2010/01/simple-random-strings/feed</wfw:commentRss>
		</item>
		<item>
		<title>Lightweight Task Scheduling Library for .NET / Silverlight</title>
		<link>http://www.hardcodet.net/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support</link>
		<comments>http://www.hardcodet.net/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support#comments</comments>
		<pubDate>Sat, 09 Jan 2010 20:35:59 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[CodeProject]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[Silverlight]]></category>

		<category><![CDATA[VFS]]></category>

		<category><![CDATA[Scheduling]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=727</guid>
		<description><![CDATA[Presents a lightweight task scheduling library for .NET 3.5 / Silverlight.]]></description>
			<content:encoded><![CDATA[<p>I’m currently working on <a href="http://vfs.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/vfs.codeplex.com');">VFS</a>, a virtual file system. For running transfers, VFS internally maintains locks that do have expiration time. Accordingly, I found myself in need for a job scheduling mechanism in order to properly release expired locks. I looked around for a few <a href="http://quartznet.sourceforge.net/tutorial/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/quartznet.sourceforge.net');">alternatives</a>, but eventually ended up writing my own lightweight version.</p>
<p>Features:</p>
<ul>
<li>Simple scheduling and callback mechanisms </li>
<li>Silverlight compatible </li>
<li>Lightweight </li>
<li>Fluent API </li>
<li>Detection of system time changes with optional rescheduling </li>
<li>Optional forwarding of exceptions during job execution </li>
<li>Open Source (Ms-PL) </li>
</ul>
<p>&#160;</p>
<p><a title="Download Project" href="http://www.hardcodet.net/uploads/projects/scheduling/hardcodet.scheduling.zip" onclick="javascript:pageTracker._trackPageview('/downloads/uploads/projects/scheduling/hardcodet.scheduling.zip');"></a><a class="download" title="Download Project" href="http://www.hardcodet.net/uploads/projects/scheduling/hardcodet.scheduling.zip" onclick="javascript:pageTracker._trackPageview('/downloads/uploads/projects/scheduling/hardcodet.scheduling.zip');">Download library and sample</a></p>
<p><font color="#ff0000" size="1"><strong>Current Version: 1.0.2, 2010.01.12</strong></font></a></p>
<p>&#160;</p>
<h4>What Does it Do?</h4>
<p>Basically, the library allows you to create a job, and submit that job to a scheduler, along with a callback action. This callback action is invoked as soon (or every time) the job is due.</p>
<p>Before going into the details, here’s a first code snippet that creates a simple <span class="code">Job </span>that is supposed to run repeatedly (every 1.5 seconds) for a minute. Once the job is created, it is submitted to a <span class="code">Scheduler </span>instance which processes the job and makes sure the submitted callback action is being invoked every time the job is due:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> Scheduler scheduler = <span style="color: #0000ff">new</span> Scheduler();

<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> RunOnce()
{
  <span style="color: #008000">//define a start / end time</span>
  DateTime startTime = DateTime.Now.AddSeconds(5);
  DateTime endTime   = startTime.AddSeconds(60);

  <span style="color: #008000">//configure the job</span>
  Job consoleJob = <span style="color: #0000ff">new</span> Job();
  consoleJob.Run.From(startTime)
                .Every.Seconds(1.5)
                .Until(endTime);

  <span style="color: #008000">//submit the job with the callback to be invoked</span>
  scheduler.SubmitJob(consoleJob, j =&gt; Console.Out.WriteLine(<span style="color: #006080">&quot;hello world&quot;</span>));
}</pre>
</div>
<p>&#160;</p>
<h4>Silverlight</h4>
<p>The project provides class libraries for .NET 3.5 and Silverlight 3, along with a Silverlight sample application that shows how to add scheduling functionality to your SL application with just a few lines of code. </p>
<p>While long-term scheduling isn’t probably something you need to do in a Silverlight application, the scheduler simplifies the management of periodic jobs, such as polling a server for updates. Below is a snippet from the Silverlight sample application. This job starts immediately, and runs indefinitely with an interval of 2 seconds:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> CreateJob2()
{
  <span style="color: #008000">//create job</span>
  Job&lt;<span style="color: #0000ff">int</span>&gt; job = <span style="color: #0000ff">new</span> Job&lt;<span style="color: #0000ff">int</span>&gt;(<span style="color: #006080">&quot;Job 2&quot;</span>);
  job.Data = 0;
  job.Run.Every.Seconds(2);

  <span style="color: #008000">//submit to scheduler</span>
  scheduler.SubmitJob(job, LogJobExecution);
}

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> LogJobExecution(Job&lt;<span style="color: #0000ff">int</span>&gt; job, <span style="color: #0000ff">int</span> data)
{
  <span style="color: #008000">//updates user interface</span>
}</pre>
</div>
<p>&#160;</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/01/image5.png" width="352" height="292" /></p>
<p>&#160;</p>
<h2>Jobs</h2>
<p>&#160;</p>
<p>A job is a simple configuration item for the scheduler. There’s two built-in job types: <span class="code">Job </span>and <span class="code">Job&lt;T&gt;</span>. The only difference between the two is that the latter provides a <span class="code">Data </span>property which allows you to attach state information directly to the job and have it delivered back to you when the job runs.</p>
<p><span id="more-727"></span></p>
<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/02/image.png" width="180" height="445" /> </p>
<p>&#160;</p>
<h3>Creating Jobs</h3>
<p>Creating a job is pretty easy, and can be configured through a fluent interface (optional, you can also set the properties the traditional way). Jobs may run once, several times, or indefinitely – you can configure intervals, an optional expiration time, or a maximum number of executions. Here’s a few configuration samples:</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//run the job every second until we manually cancel it</span>
Job job = <span style="color: #0000ff">new</span> Job();
job.Run.Every.Seconds(1);</pre>
</div>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//create a job with an attached FileInfo</span>
Job&lt;FileInfo&gt; job = <span style="color: #0000ff">new</span> Job&lt;FileInfo&gt;();
job.Data = <span style="color: #0000ff">new</span> FileInfo(<span style="color: #006080">@&quot;C:\readme.txt&quot;</span>);

<span style="color: #008000">//run the job 5 times every 1.5 seconds, start immediately</span>
TimeSpan interval = TimeSpan.FromSeconds(1.5);
job.Run.Every.TimeSpan(interval).Times(5);</pre>
</div>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//create a simple job</span>
Job job = <span style="color: #0000ff">new</span> Job();

<span style="color: #008000">//run the job every 1.5 seconds until it expires</span>
DateTime expiration = DateTime.Now.AddMinutes(5);
job.Run.Every.Seconds(1.5).Until(expiration);</pre>
</div>
<p>&#160;</p>
<h2>The Scheduler Class</h2>
<p>&#160;</p>
<p>Jobs are being submitted to the <span class="code">Scheduler </span>class, which provides a very simple API. Most methods should be pretty self-explanatory, and they are well documented.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/01/image7.png" width="220" height="367" /> </p>
<p>&#160;</p>
<h3>Callback Actions</h3>
<p>If you add a <span class="code">Job </span>to the <span class="code">Scheduler </span>through one of the <span class="code">SubmitJob </span>overloads, you have to submit a callback action that is being invoked whenever the job runs. Depending on whether you use <span class="code">Job </span>or <span class="code">Job&lt;T&gt;</span>, a different callback delegate may be used:</p>
<p>&#160;</p>
<table border="0" cellspacing="0" cellpadding="2" width="300">
<tbody>
<tr>
<td valign="top" width="150"><em>Job Class</em></td>
<td valign="top" width="150"><em>Callback Action</em></td>
</tr>
<tr>
<td valign="top" width="150">Job</td>
<td valign="top" width="150">Action&lt;Job&gt;</td>
</tr>
<tr>
<td valign="top" width="150">Job&lt;T&gt;</td>
<td valign="top" width="150">Action&lt;Job&lt;T&gt;, T&gt;</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Here’s a sample that uses two different callback methods:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">class</span> Program
{
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> Scheduler scheduler = <span style="color: #0000ff">new</span> Scheduler();

  <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> Main(<span style="color: #0000ff">string</span>[] args)
  {
    Job simple = <span style="color: #0000ff">new</span> Job(<span style="color: #006080">&quot;simple&quot;</span>);
    simple.Run.From(DateTime.Now.AddSeconds(3)).Once();

    Job&lt;<span style="color: #0000ff">int</span>&gt; generic = <span style="color: #0000ff">new</span> Job&lt;<span style="color: #0000ff">int</span>&gt;(<span style="color: #006080">&quot;generic&quot;</span>) {Data = 123};
    generic.StartAt(DateTime.Now.AddSeconds(1)).Run.Once();

    scheduler.SubmitJob(simple, HandleSimpleJob);
    scheduler.SubmitJob(generic, HandleGenericJob);

    Console.ReadLine();
  }

  <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> HandleGenericJob(Job job, <span style="color: #0000ff">int</span> data)
  {
    Console.Out.WriteLine(<span style="color: #006080">&quot;Job '{0}' submitted data: {1}&quot;</span>, job.Id, data);
  }

  <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> HandleSimpleJob(Job job)
  {
    Console.Out.WriteLine(<span style="color: #006080">&quot;Simple job '{0}' was executed.&quot;</span>, job.Id);
  }
}</pre>
</div>
<p>&#160;</p>
<p>The sample above produces the following output on the console:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/01/image3.png" width="381" height="179" /> </p>
<p>&#160;</p>
<h3>Cancelling or Pausing a Job</h3>
<p>If you want to cancel or pause a job, you can do this either via the <span class="code">Scheduler </span>class, or directly on the <span class="code">Job </span>instance that is submitted to you whenever the job runs. Note that canceling the job is a terminal operation – a canceled job cannot be resumed.</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> MyJobCallbackAction(Job job)
{
  <span style="color: #008000">//stops execution but keeps the job alive</span>
  job.Pause();

  <span style="color: #008000">//resumes operation of a paused job</span>
  job.Resume();

  <span style="color: #008000">//terminates the job</span>
  job.Cancel();
}</pre>
</div>
<p>&#160;</p>
<p>Actually, doing these operations directly via the <span class="code">Job </span>class is the preferred mechanism – if you use the scheduler’s methods, the scheduler needs to lock its internal list and search for the job itself, which costs you processing power.</p>
<p>&#160;</p>
<h3>Exception Handling</h3>
<p>An exception that occurs during the execution of a job does not affect the scheduler – all jobs are being executed on worker threads taken from the .NET thread pool. However, in order not to miss any exceptions, you can instruct the <span class="code">Scheduler </span>class to supervise executing jobs, and forward any unhandled exceptions to a single exception handling routine. All you need to do is registering a callback action to the <span class="code">JobExceptionHandler </span>of the <span class="code">Scheduler </span>class:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> Scheduler scheduler;

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> InitScheduler()
{
  scheduler = <span style="color: #0000ff">new</span> Scheduler();
  scheduler.JobExceptionHandler = LogJobException;
}

<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> LogJobException(Job job, Exception exception)
{
  <span style="color: #0000ff">string</span> msg = <span style="color: #006080">&quot;Exception occurred while executing job {0}: {1}&quot;</span>;
  msg = String.Format(msg, job.JobId, exception.ToString());
  MyLogger.LogError(msg);
}</pre>
</div>
<p>&#160;</p>
<h2>Performance</h2>
<p>&#160;</p>
<p>The library could surely be tweaked, but it performs pretty well. Running 10000 jobs, each with an interval of 100 ms (that’s around 100 jobs per millisecond) keeps the CPU busy (at around 25% on my machine), but neither eats away your memory nor freezes the PC. Bigger intervals aren’t a problem at all because the scheduler is sleeping most of the time.</p>
<p>&#160;</p>
<h2>Reacting to System Time Change Events</h2>
<p>&#160;</p>
<p>Assume the following:</p>
<ul>
<li>The current time is 21:00, your job is scheduled to run at 22:00 </li>
<li>The user changes the computer’s time to 21:30 </li>
</ul>
<p>Now, depending on your needs, you might want the scheduler to adjust itself based on two strategies:</p>
<ul>
<li><font color="#ff0000">A</font>: If you want the job to run at a fixed time (22:00), you expect the job to run in 30 minutes. <em>This is the scheduler’s default behavior.</em> </li>
<li><font color="#ff0000">B</font>: If you want the job to run based on relative times, you still expect the job to run in an hour, so the execution time would have to be change to 22:30. </li>
</ul>
<p>In order not to miss such an event, the scheduler performs a quick self test with a fixed configurable interval from time to time - even if no jobs are up for execution. Per default, the scheduler’s <span class="code">SelfTestInterval</span> property is set to two minutes, but this can be configured should you need more (or less) accurate re-scheduling.</p>
<p>If you want the scheduler to just readjust its internal schedule and keep fixed times (<font color="#ff0000">A</font>), you don’t have to do anything. However, if you want the scheduler to reschedule its jobs if a system time change was detected (<font color="#ff0000">B</font>), you can do by setting the <span class="code">SystemTimeChangeRescheduling </span>property of the <span class="code">Scheduler </span>class, which takes an enum value of type <span class="code">ReschedulingStrategy</span>:</p>
<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2010/01/image4.png" width="307" height="138" /> </p>
<p>As you can see, you can choose not to reschedule at all (default), only reschedule the next execution time (the next time the job runs), or even shift the expiration time of your jobs.</p>
<h4>Fixed vs. Relative Rescheduling Depending on Jobs</h4>
<p>What if you have a few jobs that should run on a fixed time, while others should be rescheduled?</p>
<p>I decided against making the API more complicated by allowing jobs to be individually configured. As an alternative, I’d suggest to just use two scheduler classes with individual configurations. You could even write a wrapper class that just maintains two schedulers, and forwards all job submissions to the correct one. Here’s a quick but working implementation:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MyScheduler
{
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Scheduler fixedSchedules = <span style="color: #0000ff">new</span> Scheduler();
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Scheduler relativeSchedules = <span style="color: #0000ff">new</span> Scheduler();

  <span style="color: #0000ff">public</span> MyScheduler()
  {
    <span style="color: #008000">//configure relative rescheduling</span>
    var strategy = ReschedulingStrategy.RescheduleNextExecution;
    relativeSchedules.SystemTimeChangeRescheduling = strategy;
  }

  <span style="color: #008000">//This method just forwards submitted jobs to one of the schedulers</span>
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> SubmitJob(Job job, Action&lt;Job&gt; callback, <span style="color: #0000ff">bool</span> hasFixedSchedule)
  {
    <span style="color: #0000ff">if</span>(hasFixedSchedule)
    {
      fixedSchedules.SubmitJob(job, callback);
    }
    <span style="color: #0000ff">else</span>
    {
      relativeSchedules.SubmitJob(job, callback);
    }
  }
}</pre>
</div>
<p>&#160;</p>
<h2>Persisting Jobs</h2>
<p>&#160;</p>
<p>Persisting jobs is not part of the library, but could be done by subclassing the <span class="code">Scheduler </span>class. The class gives you protected access to all its internals, including its job list. <span class="code">Job </span>is a very simple component, so it should be fairly easy to store and reload all jobs.</p>
<p>However, from an architectural point of view, I’d probably not persist any jobs at all, but rather recreate them during initialization based on persisted business data. A job does execute in a given context, because of “something”. Let’s assume this “something” is a reminder flag in a calendar application:</p>
<ul>
<li>User sets a reminder on a calendar entry. </li>
<li>Calendar application updates database record of the calendar entry, then creates a job with the scheduler. </li>
<li>User turns off application – the scheduler and running jobs are being disposed. </li>
<li>User restarts application. </li>
<li>The application retrieves all reminders from the database and schedules jobs for them. </li>
</ul>
<p>This approach is simple, and clearly defines the responsibilities of the components in your application. It also minimizes dependencies on the scheduling system.</p>
<p>&#160;</p>
<h2>Implementation Notes</h2>
<p>&#160;</p>
</p>
<h3>Creating a Fluent Interface</h3>
<p>The library provides a fluent API that allows you to chain configuration settings:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//job starts at a given start time, repeats until expiration time</span>
Job myJob = <span style="color: #0000ff">new</span> Job();
myJob.Run.From(startTime).Every.Seconds(1.5).Until(expiration);</pre>
</div>
<p>&#160;</p>
<p>The fluent API is optional – a job can also be configured via traditional properties setters. However, the corresponding declaration is more verbose:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//job starts at a given start time, repeats until expiration time</span>
Job myJob = <span style="color: #0000ff">new</span> Job
              {
                Loops = <span style="color: #0000ff">null</span>,
                StartTime = startTime,
                Interval = TimeSpan.FromSeconds(1.5),
                ExpirationTime = expiration
              };</pre>
</div>
<p>&#160;</p>
<p>Basically, the implementation of the fluent API is very simple:</p>
<ul>
<li>The <span class="code">Run </span>property returns an instance of a helper class called <span class="code">JobSchedule</span>. This helper class provides methods such as <span class="code">From</span>, <span class="code">Until</span>, <span class="code">Every</span>, or <span class="code">Once</span>. </li>
<li>All methods of the <span class="code">JobSchedule </span>class have a return value of <span class="code">JobSchedule </span>again, which allows the developer to chain the operations as in the sample above. </li>
</ul>
<p>Below is a part of <span class="code">JobSchedule</span>’s implementation. You can see that the class receives an instance of type <span class="code">Job</span>, and just sets the properties on this class.</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> JobSchedule
{
  <span style="color: #0000ff">private</span> <span style="color: #0000ff">readonly</span> Job job;

  <span style="color: #008000">//created with the job that is being configured</span>
  <span style="color: #0000ff">public</span> JobSchedule(Job job)
  {
    <span style="color: #0000ff">this</span>.job = job;
  }

  <span style="color: #008000">//all operations just return the schedule itself again</span>
  <span style="color: #0000ff">public</span> JobSchedule From(DateTimeOffset startTime)
  {
    job.StartTime = startTime;
    <span style="color: #0000ff">return</span> <span style="color: #0000ff">this</span>;
  }

  ...

}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>DateTime, DateTimeOffset, and SystemTime</h3>
<h4>SystemTime Pattern</h4>
<p>With a scheduler, everything is about time. However, time-related code is very hard to test, which is why the scheduler does not directly access the current system time, but makes use of <a href="http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/ayende.com');">Ayende’s SystemTime</a>. This is an awesome pattern, and I highly recommend using it whenever timestamps play an important role in code.</p>
<p>&#160;</p>
<h4>DateTimeOffset vs. DateTime</h4>
<p>You might have noticed that usually, the code works with <span class="code">DateTimeOffset </span>rather then the commonly known <span class="code">DateTime</span> struct. <span class="code">DateTimeOffset </span>is basically an alternative to <span class="code">DateTime</span>, but operates on UTC which makes it an ideal candidate for most time-related scenarios. You can read more about it at <a href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');">MSDN</a> or at the <a href="http://blogs.msdn.com/bclteam/archive/2007/06/14/datetimeoffset-a-new-datetime-structure-in-net-3-5-justin-van-patten.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/blogs.msdn.com');">BCL team blog</a>.</p>
<p>However, you can even still use <span class="code">DateTime </span>in your code if you feel more comfortable with it:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">Job job = <span style="color: #0000ff">new</span> Job();

DateTimeOffset expDate1 = DateTimeOffset.Now.AddHours(2);
DateTime       expDate2 = DateTime.Now.AddHours(2);

<span style="color: #008000">//the job takes both DateTimeOffset and DateTime values</span>
job.ExpirationTime = expDate1;
job.ExpirationTime = expDate2;</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Job List, Timer and Pooled Execution</h3>
<h4>Job List</h4>
<p>Internally, the <span class="code">Scheduler </span>class uses a very simple mechanism: All jobs are being cached in a sorted list, which allows the scheduler to easily determine the next execution time. If a new job is being submitted, the scheduler only has to check whether the new job runs before the next scheduled job or not. If yes, the scheduler adjusts its next execution. If no, the job is just added to the end of the list, and a flag is set that reminds the scheduler to reorder the list once the next job was done. This approach has a big advantage: Even if many jobs are being submitted, reordering takes only place once the next job runs.</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> SubmitJob(Job job, Action&lt;Job&gt; callback)
{
  <span style="color: #008000">//[validation omitted for brevity]</span>

  JobContext context = <span style="color: #0000ff">new</span> JobContext(job, callback);

  <span style="color: #0000ff">lock</span>(syncRoot)
  {
    <span style="color: #008000">//if this job is going to be the next one, we need to reconfigure</span>
    <span style="color: #008000">//the timer. Do not reschedule if the next execution is imminent</span>
    <span style="color: #0000ff">if</span> (NextExecution == <span style="color: #0000ff">null</span> || context.NextExecution &lt;= NextExecution.Value)
    {
      <span style="color: #008000">//insert at index 0 –&gt; makes sure the job runs first on next timer event</span>
      jobs.Insert(0, context);

      <span style="color: #008000">//only reschedule if the next execution is not imminent</span>
      <span style="color: #0000ff">if</span> (NextExecution == <span style="color: #0000ff">null</span> || NextExecution.Value.Subtract(SystemTime.Now())
                                                .TotalMilliseconds &gt; MinJobInterval)
      {
        <span style="color: #008000">//no sorting required, but we need to adjust the timer</span>
        Reschedule();
      }
    }
    <span style="color: #0000ff">else</span>
    {
      <span style="color: #008000">//add at end of the list and mark list as unsorted</span>
      <span style="color: #008000">//the job will be sorted and rescheduled on the next run (which is before</span>
      <span style="color: #008000">//this job's execution time)</span>
      jobs.Add(context);
      isSorted = <span style="color: #0000ff">false</span>;
    }
  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h4>Timer and Rescheduling</h4>
<p>In order to trigger the execution, a single <span class="code">Timer </span>is used to wake up the scheduler once jobs are due. The timer is set to one of those values:</p>
<ul>
<li>If the scheduler has no jobs at all, the timer is disabled. </li>
<li>If jobs are pending, the next interval is the execution time of the next pending job. </li>
<li>If the self test interval is lower than the execution time of the next job, the scheduler will run an evaluation at this time (which ensures that a changed system time does not cause the scheduler to oversleep). </li>
</ul>
<p>The whole timer logic is encapsulated in the <span class="code">Reschedule </span>method:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Reconfigures the timer according to the</span>
<span style="color: #008000">/// next pending job execution time.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> Reschedule()
{
  <span style="color: #0000ff">if</span>(jobs.Count == 0)
  {
    <span style="color: #008000">//disable the timer if we don't have any pending jobs</span>
    NextExecution = <span style="color: #0000ff">null</span>;
    timer.Change(Timeout.Infinite, Timeout.Infinite);
  }
  <span style="color: #0000ff">else</span>
  {
    <span style="color: #008000">//schedule next event</span>
    var executionTime = jobs[0].NextExecution;

    DateTimeOffset now = SystemTime.Now();
    TimeSpan delay = executionTime.Value.Subtract(now);

    <span style="color: #008000">//in case the next execution is already pending, add a safe delay</span>
    <span style="color: #0000ff">long</span> dueTime = Math.Max(MinJobInterval, (<span style="color: #0000ff">long</span>)delay.TotalMilliseconds);

    <span style="color: #008000">//run at least with the self testing interval</span>
    dueTime = Math.Min(dueTime, SelfTestInterval);

    NextExecution = SystemTime.Now().AddMilliseconds(dueTime);
    timer.Change(dueTime, Timeout.Infinite);
  }
}</pre>
</div>
<p>&#160;</p>
<h4>Job Execution</h4>
<p>“Executing” a job basically means invoking the callback action that was submitted along with the job. This always happens asynchronously through the .NET thread pool:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/// &lt;summary&gt;</span>
<span style="color: #008000">/// Invokes the managed job's &lt;see cref=&quot;CallbackAction&quot;/&gt; through</span>
<span style="color: #008000">/// the thread pool, and updates the job's internal state.</span>
<span style="color: #008000">/// &lt;/summary&gt;</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> ExecuteAsync()
{
  <span style="color: #008000">//only execute if the job is active</span>
  <span style="color: #0000ff">if</span> (...)
  {
    ThreadPool.QueueUserWorkItem(s =&gt; CallbackAction(ManagedJob));
  }

  UpdateState();
}</pre>
</div>
<p>&#160;</p>
<h2>Conclusion</h2>
<p>&#160;</p>
<p>This is a neat little helper library, and its small footprint makes it a viable alternative to handling timers yourself even for small applications. 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/2010/01/lightweight-task-slash-job-scheduling-with-silverlight-support/feed</wfw:commentRss>
		</item>
		<item>
		<title>Announcing VFS, the Virtual File System</title>
		<link>http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement</link>
		<comments>http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement#comments</comments>
		<pubDate>Tue, 29 Dec 2009 10:00:52 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[VFS]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement</guid>
		<description><![CDATA[I’ve been working on a new project of mine for a while now, and opened the project at CodePlex: VFS, the Virtual File System, is basically an abstraction to arbitrary hierarchical resources, which can be handled like a file system.
VFS comes with a set of file system providers and clients (including Silverlight support), and allows [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been working on a new project of mine for a while now, and opened the project at CodePlex: <a title="VFS Project Home" href="http://vfs.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/vfs.codeplex.com');">VFS</a>, the Virtual File System, is basically an abstraction to arbitrary hierarchical resources, which can be handled like a file system.</p>
<p>VFS comes with a set of file system providers and clients (including Silverlight support), and allows you to easily write your own providers (e.g. to expose the contents of a ZIP file on a remote server). Additional offerings are flexible security (e.g. to access your Azure blobs via VFS in order to plug-in a custom authorization scheme), auditing and reliable file transfers.</p>
<p>VFS is currently in early Alpha, but I’m working full steam ahead. Comments and wish lists are appreciated! For a more detailed introduction and a few code snippets, visit the project home:   <br /><a href="http://vfs.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/vfs.codeplex.com');">http://vfs.codeplex.com</a></p>
<p>&#160;</p>
</p>
<p><a href="http://www.hardcodet.net/uploads/2009/12/vfs-provider-model.png" ><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="vfs_provider_model" border="0" alt="vfs_provider_model" src="http://www.hardcodet.net/uploads/2009/12/vfs-provider-model-thumb.png" width="552" height="307" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/12/vfs-virtual-file-system-announcement/feed</wfw:commentRss>
		</item>
		<item>
		<title>Convert WCF Service Exceptions into Faults using Lambdas</title>
		<link>http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults</link>
		<comments>http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults#comments</comments>
		<pubDate>Tue, 08 Dec 2009 14:25:02 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults</guid>
		<description><![CDATA[Shows a simple pattern that simplifies exception handling and the creation of FaultExceptions on WCF service methods.]]></description>
			<content:encoded><![CDATA[<p>Interoperability in WCF is a great thing, but it requires us to rethink our exception handling strategy: The simple paradigm of throwing exceptions whenever something goes wrong doesn’t cut it with distributed systems.</p>
<p>Thankfully, WCF allows us to communicate errors (or <em>faults</em>) through <a href="http://msdn.microsoft.com/en-us/library/cc304769.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/msdn.microsoft.com');" target="_blank">FaultExceptions</a>. We can just convert internal exceptions into a FaultException, and WCF will take care about everything else. However: This conversion strategy is tedious and error prone, especially if you want to do more sophisticated exception handling. Even a simplified example as the one below mainly consists of exception handling code:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//Simplified example</span>
<span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Foo(<span style="color: #0000ff">string</span> userName)
{
  <span style="color: #0000ff">try</span>
  {
     Bar.FooBar(userName);
  }
  <span style="color: #0000ff">catch</span>(ArgumentException e)
  {
    <span style="color: #008000">//convert exception into a WCF friendly FaultException</span>
    <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> FaultException(<span style="color: #006080">&quot;Info about specific error&quot;</span>);
  }
  <span style="color: #0000ff">catch</span>(Exception e)
  {
    <span style="color: #008000">//convert exception into a WCF friendly FaultException</span>
    <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> FaultException(<span style="color: #006080">&quot;Info about unspecific error&quot;</span>);
  }
}</pre>
</div>
<p>&#160;</p>
<p>I’m currently finding myself having to write a set of WCF services, and I didn’t want to go through try/catch blocks all the time just in order to wrap up the same exceptions over and over again. Accordingly, I wrote helper methods that do the exception handling for me.</p>
<ul>
<li><span class="code">SecureAction</span> is used by service methods that do not have a return value. </li>
<li><span class="code">SecureFunc&lt;T&gt;</span> is used by service methods that do have a return value. </li>
</ul>
<p>These helper methods allow me to easily delegate the exception handling from all my service methods, and if anything goes wrong, I can trust that the internal exception is safely converted into a <span class="code">FaultException</span>. Here’s is the rewritten <span class="code">Foo </span>method from above, now remarkably smaller:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Foo(<span style="color: #0000ff">string</span> userName)
{
  <span style="color: #0000ff">return</span> SecureFunc(() =&gt; Bar.FooBar(userName));
}</pre>
</div>
<p>&#160;</p>
<p>Below is the (simplified) snippet with the helper methods. <strong>Do note that the above sample methods are just starting points.</strong> My productive helper methods provide a more sophisticated exception handling than shown above (they build detailed <em>FaultContracts</em> which are specific to my application) and come with a few overloads.</p>
<p>Furthermore, you might think about adding additional parameters to your helper methods (such as fault IDs) in order to customize the generated faults.</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> SecureAction(Action action)
{
  <span style="color: #0000ff">try</span>
  {
    action();
  }
  <span style="color: #0000ff">catch</span> (Exception e)
  {
    <span style="color: #008000">//productive code provides more specific</span>
    <span style="color: #008000">//exception handling, but you should get the idea...</span>
    <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> FaultException(e.Message);
  }
}

<span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> T SecureFunc&lt;T&gt;(Func&lt;T&gt; func)
{
  <span style="color: #0000ff">try</span>
  {
    <span style="color: #0000ff">return</span> func();
  }
  <span style="color: #0000ff">catch</span> (Exception e)
  {
    <span style="color: #008000">//productive code provides more specific</span>
    <span style="color: #008000">//exception handling, but you should get the idea...</span>
    <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> FaultException(e.Message);
  }
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/12/convert-service-exceptions-to-wcf-faults/feed</wfw:commentRss>
		</item>
		<item>
		<title>NetDrives 1.0.2 Released</title>
		<link>http://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102</link>
		<comments>http://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102#comments</comments>
		<pubDate>Mon, 07 Dec 2009 17:09:21 +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/12/httpwwwhardcodetnet200909netdrives-update-102</guid>
		<description><![CDATA[I just released a minor update for NetDrives, which fixes an issue that caused settings not to be persisted correctly. NetDrives is a Windows utility that helps you manage your network shares and mapped network drives.
&#160;
 
&#160;
Download and further infos: http://www.hardcodet.net/netdrives
]]></description>
			<content:encoded><![CDATA[<p>I just released a minor update for NetDrives, which fixes an issue that caused settings not to be persisted correctly. NetDrives is a Windows utility that helps you manage your network shares and mapped network drives.</p>
<p>&#160;</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="NetDrives" border="0" alt="NetDrives" src="http://www.hardcodet.net/uploads/2009/12/notifyiconwin7.png" width="324" height="156" /> </p>
<p>&#160;</p>
<p>Download and further infos: <a href="http://www.hardcodet.net/netdrives" >http://www.hardcodet.net/netdrives</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hardcodet.net/2009/12/httpwwwhardcodetnet200909netdrives-update-102/feed</wfw:commentRss>
		</item>
		<item>
		<title>SLF Hands-on Tutorial, Part 1</title>
		<link>http://www.hardcodet.net/2009/12/slf-tutorial-1</link>
		<comments>http://www.hardcodet.net/2009/12/slf-tutorial-1#comments</comments>
		<pubDate>Wed, 02 Dec 2009 14:43:00 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[SLF]]></category>

		<category><![CDATA[Logging]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=664</guid>
		<description><![CDATA[Hands-on tutorial for SLF, the Simple Logging Façade.]]></description>
			<content:encoded><![CDATA[<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="slf" border="0" alt="slf" src="http://www.hardcodet.net/uploads/2009/10/slf-thumb.png" width="450" height="55" />&#160;</p>
<p>This is an introductory tutorial on SLF, the Simple Logging Façade. This tutorial covers the basics, which will be all you’ll ever need in most projects. I’m planning on writing a second tutorial that will show custom factories and resolvers soon.</p>
<h2>Downloading SLF</h2>
<p>To get started, visit <a href="http://slf.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/slf.codeplex.com');">http://slf.codeplex.com</a> and download the latest release. Source code is available as a Visual Studio 2008 solution, but if you’re working with VS2005, there’s also precompiled binaries for .NET 2.0 available (.NET 1.0 or 1.1 is not supported).</p>
<h3>Sample Projects</h3>
<p>SLF comes with a lot of samples, all organized as independent projects that discuss a specific use case. As you will see, most scenarios only require a few lines of code. We are planning to extend this section over time, based on your feedback.</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb.png" width="242" height="322" /></a></p>
<p>&#160;</p>
</p>
<p> <span id="more-664"></span>
</p>
<h2>ILogger</h2>
<p>The central interface in SLF is <span class="code">ILogger</span>. <span class="code">ILogger</span> provides a versatile API to log information to a specific logging framework. You could roughly say there’s three “categories” of loggers:</p>
<ol>
<li>A few simple implementations directly in the SLF core library (e.g. <span class="code">ConsoleLogger </span>or <span class="code">DelegateLogger</span>) that cover common scenarios. </li>
<li>Façades for logging frameworks that are currently supported (e.g. <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a>). A façade is usually an independent DLL. </li>
<li>Custom loggers that you implement yourself. You can do that very easily, usually by extending a simple base class. Creating fancy custom loggers will be covered in the second part of this tutorial. </li>
</ol>
<p><a href="http://www.hardcodet.net/uploads/2009/12/image.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/12/image-thumb.png" width="259" height="260" /></a> </p>
<p>&#160;</p>
<p>Here’s a first snippet, that creates a <span class="code">ConsoleLogger</span>, which is part of the core library:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = <span style="color: #0000ff">new</span> ConsoleLogger();
logger.Info(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>This produces the following output</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image1.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb1.png" width="307" height="164" /></a></p>
<p>&#160;</p>
<p>However, rather than creating your loggers all over the place, you will usually use <span class="code">LoggerService </span>to obtain your logger(s):</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = LoggerService.GetLogger();
logger.Info(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>Setting up logging with LoggerService is described in a bit further below.</p>
<h3>&#160;</h3>
<h4>Logging in Categories</h4>
<p><em>As a general guideline on how and when to use logging categories, I recommend Colin Eberhardt’s “<a title="The Art of Logging" href="http://www.codeproject.com/KB/trace/ArtOfLogging.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">The Art of Logging</a>”, which is an excellent introduction to logging in general.</em></p>
<p>SLF knows 5 logging categories (or log levels), which are covered through a set of methods that allow you to easily submit logging information.&#160; </p>
<table border="1" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td valign="top" width="200"><strong>Logging Level</strong></td>
<td valign="top" width="200"><strong>ILogger Methods</strong></td>
</tr>
<tr>
<td valign="top" width="200">Info</td>
<td valign="top" width="200">Info()</td>
</tr>
<tr>
<td valign="top" width="200">Warn</td>
<td valign="top" width="200">Warn()</td>
</tr>
<tr>
<td valign="top" width="200">Error</td>
<td valign="top" width="200">Error()</td>
</tr>
<tr>
<td valign="top" width="200">Fatal</td>
<td valign="top" width="200">Fatal()</td>
</tr>
<tr>
<td valign="top" width="200">Debug</td>
<td valign="top" width="200">Debug()</td>
</tr>
</tbody>
</table>
<p>Every one of these methods provides several overloads, which allow you to submit simple text, exceptions, or even format text on the fly. A few exemplary logging instructions:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = <span style="color: #0000ff">new</span> ConsoleLogger();

logger.Info(<span style="color: #006080">&quot;Simple Message.&quot;</span>);
logger.Info(<span style="color: #006080">&quot;User {0} logged in at {1}&quot;</span>, GetUserName(), DateTime.Now);
logger.Warn(e, <span style="color: #006080">&quot;Message for uncritical exception.&quot;</span>);
logger.Error(someException);
logger.Fatal(e, <span style="color: #006080">&quot;Login exception for user {0}&quot;</span>, GetUserName());</pre>
</div>
<p>&#160;</p>
<h4>Logging a LogItem</h4>
<p>Apart from the the above mentioned <span class="code">Info()</span>, <span class="code">Warn()</span>, <span class="code">Error()</span>, <span class="code">Fatal() </span>and <span class="code">Debug()</span> methods, there’s also the <span class="code">Log </span>method, which expects an parameter of type <span class="code">LogItem</span>. <span class="code">LogItem</span> is a simple class that encapsulates information that belongs to a given log entry:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/12/image1.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/12/image-thumb1.png" width="215" height="240" /></a> </p>
<p>&#160;</p>
<p>Working with <span class="code">LogItem</span> is not as straightforward as using the other methods, but it may be useful if you want to submit more detailed logging information. Here’s a sample that logs a warning along with an event ID:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Login(User user)
{
   <span style="color: #008000">//do the login </span>
   LoginResult result = ...

   <span style="color: #008000">//log an Info message with a title and an event ID </span>
   LogItem item = <span style="color: #0000ff">new</span> LogItem();
   item.LogLevel = LogLevel.Warn;
   item.EventId = 201;
   item.Title = <span style="color: #006080">&quot;Invalid login attempted by: &quot;</span> + user.Name;
   item.Message = result.ToDetailedString(); 

   ILogger logger = ...
   logger.Log(item);
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h2>Setting up Logging in Code</h2>
<p>&#160;</p>
<h3>Do it Yourself: Storing a Reference to ILogger</h3>
<p>Basically, the simplest possible implementation to use SLF is to just store an <span class="code">ILogger</span> instance somewhere and be on your way. The sample below uses the BitFactory logger façade, which internally forwards log messages to the <a href="http://dotnetlog.theobjectguy.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/dotnetlog.theobjectguy.com');">BitFactory</a> logging framework:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> MyApplication
{
  <span style="color: #008000">//there’s a static convenience method that creates a logger for a given file </span>
  <span style="color: #0000ff">private</span> ILogger logger = BitFactoryLogger.CreateFileLogger(<span style="color: #006080">&quot;log.txt&quot;</span>);

  <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> ILogger Logger
  {
    get { <span style="color: #0000ff">return</span> logger; }
  }
}</pre>
</div>
<p>&#160;</p>
<p><em>However, we recommend to use <span class="code">LoggerService</span> instead:</em></p>
<h3>LoggerService</h3>
<p><span class="code">LoggerService </span>is a static repository you can use in different ways. It provides support for declarative configurations (taken from app.config), lets you just plug in a single logger, or completely customize and plug in advanced logger resolution strategies.</p>
<p>Lets have a look at a simplistic example: Create the above <span class="code">ConsoleLogger </span>and make it available through <span class="code">LoggerService</span>. Again, this is as simple as it gets:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = <span style="color: #0000ff">new</span> ConsoleLogger();
LoggerService.SetLogger(logger);</pre>
</div>
<p>&#160;</p>
<p>With a logger plugged in like this, we can use <span class="code">LoggerService </span>from anywhere in our application to get a hold of the <span class="code">ConsoleLogger </span>we just plugged in:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = LoggerService.GetLogger();
logger.Info(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<h4>Good to Know: LoggerService Never Returns Null </h4>
<p><span class="code">LoggerService </span>guarantees you to <em>always</em> return a valid <span class="code">ILogger</span> instance. If no logger is configured, it will just return you a <span class="code">NullLogger </span>instance. <span class="code">NullLogger </span>is a special implementation of the <span class="code">ILogger </span>interface, which just discards everything you throw at it. You could say that <span class="code">NullLogger </span>switches off logging without requiring any changes in your code.</p>
<p>&#160;</p>
<p>Thanks to <span class="code">NullLogger</span>, you never have to check for null references when retrieving a logger. Look at the snippet below: This code will not result in an exception, because <span class="code">GetLogger </span>will not return null, but a <span class="code">NullLogger </span>instance:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//you can explicitly assign a null reference… </span>
LoggerService.SetLogger(<span style="color: #0000ff">null</span>); 

<span style="color: #008000">//…and the service will return you a NullLogger </span>
ILogger logger = LoggerService.GetLogger();

<span style="color: #008000">//NullLogger will just discard this message, so no real logging happens</span>
logger.Info(<span style="color: #006080">&quot;This message will be discarded&quot;</span>); </pre>
</div>
<p>&#160;</p>
<h2>Setting up Logging Declaratively (App.config)</h2>
<p>Per default, <span class="code">LoggerService </span>analyzes the application’s configuration file (<em>app.config</em>) in order to detect configured loggers. So if you want to go the declarative route, you don’t have to write a single line of code – it just works.</p>
<p>Here’s a sample <em>app.config</em> file that makes SLF write anything to the console through a <span class="code">ConsoleLogger</span>:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span> ?<span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;slf&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Config.SlfConfigurationSection, slf&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- log everything through the built-in ConsoleLogger --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Factories.ConsoleLoggerFactory, SLF&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">&lt;/</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>Declarative configurations often make sense in more complex scenarios, especially if you use more powerful logging frameworks such as <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a>. Here’s a complete configuration file that makes SLF use log4net. This <em>app.config</em> file contains two sections:</p>
<ul>
<li>The <em>slf</em> section tells SLF to forward all logging data to log4net. </li>
<li>The <em>log4net</em> section is a standard log4net configuration (it has nothing to do with SLF). In this example, log4net is configured to write everything into a single log file. </li>
</ul>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span> ?<span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;log4net&quot;</span>
             <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;slf&quot;</span>
             <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Config.SlfConfigurationSection, slf&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- configure single log4net factory, which will get all logging output --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #008000">&lt;!-- configures log4net to write into a local file called &quot;log.txt&quot; --&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;MainAppender&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Appender.FileAppender&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;File&quot;</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;log.txt&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;AppendToFile&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">layout</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Layout.PatternLayout&quot;</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">conversionPattern</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;%date - %message %newline&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;/</span><span style="color: #800000">layout</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">appender</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">root</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">level</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;ALL&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender-ref</span> <span style="color: #ff0000">ref</span><span style="color: #0000ff">=&quot;MainAppender&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">root</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">&lt;/</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>If you configure SLF through <em>app.config</em>, you don’t have to write any code, because SLF will detect the configuration on its own. Accordingly, just get the logger through <span class="code">LoggerService </span>and log away:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger logger = LoggerService.GetLogger();
logger.Info(<span style="color: #006080">&quot;Application started at {0}&quot;</span>, DateTime.Now);</pre>
</div>
<p>&#160;</p>
<p><em>Do note that if you plug in a custom logger through <span class="code">LoggerService.SetLogger</span>, this will override any declaratively configured loggers. You can, however, always reset <span class="code">LoggerService </span>through the <span class="code">LoggerService.Reset </span>method.</em></p>
<p>&#160;</p>
<h2>Working With Loggers and Façades</h2>
<p>&#160;</p>
<h3>Using the Built-in Loggers</h3>
<p>SLF comes with a number of built-in loggers that implement <span class="code">ILogger</span>, which you can use to quickly add logging functionality to your application. There’s the usual suspects such as <span class="code">ConsoleLogger</span>, <span class="code">DebugLogger</span>, or <span class="code">TraceLogger</span>, as well as a few more fancy implementations (e.g. <span class="code">DelegateLogger </span>or <span class="code">DecoratorLogger</span>) and base classes you can use to quickly create your own logger implementations.</p>
<p>There’s a lot of samples that demonstrate the loggers and possibilities, all wrapped into individual projects. However, here’s a few samples:</p>
<p>&#160;</p>
<h4>Delegating Logging through DelegateLogger</h4>
<p><span class="code">DelegateLogger </span>is a simple logger that allows you to quickly plug in some custom logic through a delegate or lambda expression. Here’s dummy sample for a WinForms application, which just shows a message box for every item that is logged to SLF.</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">DelegateLogger logger = <span style="color: #0000ff">new</span> DelegateLogger(ShowMessage); 

<span style="color: #008000">//this message is being invoked by the logger </span>
<span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> ShowMessage(LogItem item)
{
  MessageBox.Show(<span style="color: #006080">&quot;Logged Message: &quot;</span> + item.Message);
}</pre>
</div>
<p>&#160;</p>
<p>…or even shorter, with a Lambda Expression:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">var logger = <span style="color: #0000ff">new</span> DelegateLogger(item =&gt; MessageBox.Show(item.Message));</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h4>Combining Logged Output via CompositeLogger</h4>
<p><span class="code">CompositeLogger </span>is a logger that does not log on its own, but forwards all logging information to an arbitrary number of other loggers:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">CompositeLogger compositeLogger = <span style="color: #0000ff">new</span> CompositeLogger();

compositeLogger.Loggers.Add(<span style="color: #0000ff">new</span> ConsoleLogger);
compositeLogger.Loggers.Add(<span style="color: #0000ff">new</span> TraceLogger);
compositeLogger.Loggers.Add(<span style="color: #0000ff">new</span> DebugLogger);

compositeLogger.Info(<span style="color: #006080">&quot;Logging to all three loggers at once!&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>You can also submit the underlying loggers directly as constructor parameters:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger consoleLogger = <span style="color: #0000ff">new</span> ConsoleLogger();
ILogger traceLogger = <span style="color: #0000ff">new</span> TraceLogger();
ILogger debugLogger = <span style="color: #0000ff">new</span> DebugLogger();

ILogger composite = <span style="color: #0000ff">new</span> CompositeLogger(consoleLogger, traceLogger, debugLogger);</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Formatting Logging Output</h3>
<p>The first snippet in this tutorial wrote “hello world” to the console, which looked like this:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image1.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb1.png" width="307" height="164" /></a></p>
<p>Now, a lot of loggers derive from <span class="code">FormattableLoggerBase.</span> This base class provides a <span class="code">Formatter </span>property, which takes an instance of <span class="code">ILogItemFormatter</span>. <span class="code">ILogItemFormatter </span>is a very simple interface, which has only one task: Converting a given <span class="code">LogItem </span>into a string.</p>
<p>Accordingly, if you wanted to change the format of the above message, you could just write a custom formatter and assign it to your logger. Here’s an alternative for a simple <span class="code">XmlFormatter</span>:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> XmlFormatter : ILogItemFormatter
{
  <span style="color: #0000ff">private</span> XmlSerializer serializer = <span style="color: #0000ff">new</span> XmlSerializer(<span style="color: #0000ff">typeof</span>(LogItem));

  <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> FormatItem(LogItem item)
  {
    StringWriter writer = <span style="color: #0000ff">new</span> StringWriter();
    serializer.Serialize(writer, item);
    <span style="color: #0000ff">return</span> writer.ToString();
  }
}</pre>
</div>
<p>&#160;</p>
<p>Accordingly, we can plug in this formatter into our <span class="code">ConsoleLogger </span>like this:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">IFormattableLogger logger = <span style="color: #0000ff">new</span> ConsoleLogger();
logger.Formatter = <span style="color: #0000ff">new</span> XmlFormatter();
logger.Info(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>The above snippet produces the following output, that renders a <span class="code">LogItem </span>as an XML element:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image4.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb4.png" width="473" height="186" /></a></p>
<p>&#160;</p>
<h3>Directing Trace Output To SLF</h3>
<p>If you have an existing codebase that logs through the <span class="code">Trace </span>class, and you would like to make use of SLF, you don’t necessarily have to change the existing code. The SLF core library contains the <span class="code">SlfTraceListener </span>class which just redirects trace messages to SLF.</p>
<p>SLF comes with a sample that shows how to declare <span class="code">SlfTraceListener </span>declaratively via <em>app.config</em>. But you can do this also programmatically:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> Main(<span style="color: #0000ff">string</span>[] args)
{
  <span style="color: #008000">//add SLF listener to Trace </span>
  Trace.Listeners.Add(<span style="color: #0000ff">new</span> SlfTraceListener()); 

  <span style="color: #008000">//write to Trace – this message will be redirected to SLF </span>
  Trace.WriteLine(<span style="color: #006080">&quot;We are writing to Trace.&quot;</span>);
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Your own Logger: Extending the Logger Base Classes</h3>
<p>If you want to create your own <span class="code">ILogger</span> implementation, you can either create a new class that implements <span class="code">ILogger</span>, or extend either <span class="code">LoggerBase </span>or <span class="code">FormattableLoggerBase</span>.</p>
<p><span class="code">ILogger</span> is not a complex interface, but there’s a lot of boilerplate code to implement. So in most cases, it’s probably more convenient to extend one of the base classes. Both require you to override just one method:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MyCustomLogger : LoggerBase
{
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Log(LogItem item)
  {
     <span style="color: #008000">//your implementation goes here </span>
  }
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h4>Sample: Implementing a ColoredConsoleLogger</h4>
<p>The class below is a custom console logger which writes colored output to the console, depending on the <span class="code">LogLevel</span> of the logged item. The class derives from <span class="code">FormattableLoggerBase </span>in order to allow you to plug in a custom message formatter.</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ColoredConsoleLogger : FormattableLoggerBase
{
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Log(LogItem item)
  {
    <span style="color: #008000">//set console color depending on log level</span>
    <span style="color: #0000ff">switch</span> (item.LogLevel)
    {
      <span style="color: #0000ff">case</span> LogLevel.Info:
        Console.ForegroundColor = ConsoleColor.Green;
        <span style="color: #0000ff">break</span>;
      <span style="color: #0000ff">case</span> LogLevel.Warn:
        Console.ForegroundColor = ConsoleColor.Cyan;
        <span style="color: #0000ff">break</span>;
      <span style="color: #0000ff">case</span> LogLevel.Error:
        Console.ForegroundColor = ConsoleColor.Yellow;
        <span style="color: #0000ff">break</span>;
      <span style="color: #0000ff">case</span> LogLevel.Fatal:
        Console.ForegroundColor = ConsoleColor.Red;
        <span style="color: #0000ff">break</span>;
      <span style="color: #0000ff">default</span>:
        Console.ResetColor();
        <span style="color: #0000ff">break</span>;
    }

    <span style="color: #008000">//delegate string formatting to base class </span>
    <span style="color: #0000ff">string</span> text = FormatItem(item);

    <span style="color: #008000">//write the string to the console </span>
    Console.Out.WriteLine(text);
    Console.ResetColor();
  }
}</pre>
</div>
<p>&#160;</p>
<p>If you log through this <span class="code">ColoredConsoleLogger</span>, a logged <span class="code">Info </span>is displayed in green now:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image5.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb5.png" width="241" height="152" /></a></p>
<p>&#160;</p>
<h3>Working with Available SLF Façade Libraries</h3>
<p>SLF comes with a few façade libraries you can use to forward to a given logging frameworks. Currently, there is support for the following commonly known frameworks:</p>
<ul>
<li>log4net </li>
<li>NLog </li>
<li>Enterprise Library </li>
<li>BitFactory Framework </li>
</ul>
<p>…and if you would like to use SLF along with a framework that is not listed yet, writing your own façade is pretty easy!</p>
<p>We’ve provided samples and sample configurations for all these façades. Accordingly, you can just find the sample that suits you, and copy/paste the configuration code into your application.</p>
<h2>Named Loggers</h2>
<p>The “Named Loggers” feature allows you to define several loggers (programmatically or in code), and then access them through their names. You can even direct logging instructions to different logging frameworks based on logger names!</p>
<p>In order to get a named logger, just use the overload of <span class="code">LoggerService.GetLogger </span>that takes a string parameter:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger defaultLogger = LoggerService.GetLogger();
ILogger namedLogger   = LoggerService.GetLogger(<span style="color: #006080">&quot;LAB-DATA&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>Note that the default logger is basically a named logger with a special name (an empty string). The snippets below all return the default logger:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">ILogger defaultLogger = LoggerService.GetLogger();
ILogger defaultLogger = LoggerService.GetLogger(<span style="color: #006080">&quot;&quot;</span>);
ILogger defaultLogger = LoggerService.GetLogger(LoggerService.DefaultLoggerName);</pre>
</div>
<p>&#160;</p>
<p>The downloadable SLF solution contains sample applications that show how to configure loggers with different names both programmatically or via configuration files.</p>
<h3>The Hierarchical Lookup Process</h3>
<p>When requesting a named logger, you don’t have to submit a name that exactly matches the name of a configured logger. Instead, named loggers are organized in a hierarchical manner. As soon as a named logger is being requested, SLF will just resolve the closest match and return you a matching logger instance:</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image6.png" ><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb6.png" width="547" height="294" /></a>In the above sample, SLF was configured with a total of eight loggers. You can see, that the logger names form a hierarchy. With this setup in place, the closest match will be returned on every request.</p>
<p>Accordingly, <span class="code">LoggerService.GetLogger(&quot;Foo.AAA&quot;) </span>would return a logger of type <span class="code">Foo </span>(closest match). And <span class="code">LoggerService.GetLogger(&quot;Foo.XXX.AAA&quot;) </span>would return a logger of type <span class="code">Foo.XXX </span>(closest match again).</p>
<p>&#160;</p>
<p>Here’s some more samples, matching the above hierarchy:</p>
<table border="1" cellspacing="0" cellpadding="2" width="566">
<tbody>
<tr>
<td valign="top" width="139"><strong>Requested Logger Name</strong></td>
<td valign="top" width="262"><strong>Returned Logger Type</strong></td>
<td valign="top" width="163"><strong>Name of Returned Logger Instance</strong></td>
</tr>
<tr>
<td valign="top" width="139">&#160;</td>
<td valign="top" width="262">&#160;</td>
<td valign="top" width="163">&#160;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Foo&quot;</td>
<td valign="top" width="262">Type declared for &quot;Foo&quot;</td>
<td valign="top" width="163">&quot;Foo&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Foo.XXX&quot;</td>
<td valign="top" width="262">Type declared for &quot;Foo.XXX&quot;</td>
<td valign="top" width="163">&quot;Foo.XXX&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Foo.XXXXXX&quot;</td>
<td valign="top" width="262">Type declared for &quot;Foo.XXX&quot;</td>
<td valign="top" width="163">&quot;Foo.XXXXXX&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Foo.X&quot;</td>
<td valign="top" width="262">Type declared for &quot;Foo&quot;</td>
<td valign="top" width="163">&quot;Foo.X&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;FooXXX&quot;</td>
<td valign="top" width="262">Type declared for &quot;Foo&quot;</td>
<td valign="top" width="163">&quot;FooXXX&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Bar.XXX&quot;</td>
<td valign="top" width="262">Type declared for &quot;Bar.XXX&quot;</td>
<td valign="top" width="163">&quot;Bar.XXX&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;Bar.ZZZ&quot;</td>
<td valign="top" width="262">Type declared for &quot;Bar&quot;</td>
<td valign="top" width="163">&quot;Bar.ZZZ&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;XXX&quot;</td>
<td valign="top" width="262">Type declared for Default Logger</td>
<td valign="top" width="163">&quot;XXX&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;XXX.Foo&quot;</td>
<td valign="top" width="262">Type declared for Default Logger</td>
<td valign="top" width="163">&quot;XXX.Foo&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;TEST&quot;</td>
<td valign="top" width="262">Type declared for Default Logger</td>
<td valign="top" width="163">&quot;TEST&quot;</td>
</tr>
<tr>
<td valign="top" width="139">&quot;&quot;</td>
<td valign="top" width="262">Type declared for Default Logger</td>
<td valign="top" width="163">&quot;&quot;</td>
</tr>
<tr>
<td valign="top" width="139">null</td>
<td valign="top" width="262">Type declared for Default Logger</td>
<td valign="top" width="163">&quot;&quot;</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<h5>Fallback to Default&#160; Logger</h5>
<p>The lookup for a logger will always fall back to the default logger type if no matching named logger was found. This should not come as a surprise. After all, the default logger is just a logger with the name [<span class="code">String.Empty</span>].</p>
<p>And don’t forget – <span class="code">LoggerService </span><em>always</em> returns a valid logger instance and never a null reference. If no unnamed logger was configured at all, you would just receive an instance of <span class="code">NullLogger</span>.</p>
<p>&#160;</p>
<h5>Exceptions to Named Logger Resolving</h5>
<p>Hierarchical lookups work out of the box, but they are not guaranteed if you customize <span class="code">LoggerService</span>:</p>
<ul>
<li>If you inject a single <span class="code">ILogger </span>instance into <span class="code">LoggerService </span>via <span class="code">LoggerService.SetLogger</span>, all requests will of course return this specific logger instance, regardless of the requested logger name. </li>
<li>If you inject a custom resolver into <span class="code">LoggerService </span>by setting the <span class="code">LoggerService.FactoryResolver </span>property, you gain full control over the lookup and logger creation process. Accordingly, you can completely change this behavior.</li>
</ul>
<h3>Configuring Named Loggers in Code or Declaratively</h3>
<p>The sample projects show how to set up named loggers in code, or via the application configuration file (app.config).</p>
<p><a href="http://www.hardcodet.net/uploads/2009/12/image2.png" ><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/12/image-thumb2.png" width="244" height="224" /></a> </p>
<p>&#160;</p>
<h3>Filtering</h3>
<p>Currently, SLF provides not built-in filtering mechanism, but leaves that to the underlying logging frameworks. The reason for this is that we just wanted to provide a very lean interface to get started with.</p>
<p>However, we’ve already opened a topic on CodePlex’ discussion board, so please express your opinion. If we feel there is a demand for built-in filtering, we will provide the functionality in a matter of days:</p>
<p><a title="http://slf.codeplex.com/Thread/View.aspx?ThreadId=76857" href="http://slf.codeplex.com/Thread/View.aspx?ThreadId=76857" onclick="javascript:pageTracker._trackPageview('/outbound/article/slf.codeplex.com');">http://slf.codeplex.com/Thread/View.aspx?ThreadId=76857</a></p>
<p>&#160;</p>
<h2>Tutorial Part 2</h2>
<p>The next part of this tutorial will discuss Resolvers, Factories, and creating your own logging façades. It will cover simple scenarios (you can plug-in factories with a single line of code) and more complex resolution scenarios for those among you who happen to deal with challenging logging situations. 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/12/slf-tutorial-1/feed</wfw:commentRss>
		</item>
		<item>
		<title>An Introduction to SLF, the Simple Logging Façade</title>
		<link>http://www.hardcodet.net/2009/12/slf-introduction</link>
		<comments>http://www.hardcodet.net/2009/12/slf-introduction#comments</comments>
		<pubDate>Wed, 02 Dec 2009 14:27:00 +0000</pubDate>
		<dc:creator>Philipp Sumi</dc:creator>
		
		<category><![CDATA[C#]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[SLF]]></category>

		<category><![CDATA[Logging]]></category>

		<guid isPermaLink="false">http://www.hardcodet.net/?p=671</guid>
		<description><![CDATA[An introduction to SLF, the Simple Logging Façade.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hardcodet.net/uploads/2009/10/slf.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="slf" border="0" alt="slf" src="http://www.hardcodet.net/uploads/2009/10/slf-thumb.png" width="450" height="55" /></a>&#160;</p>
<p><strong>Release days are good days – Colin Eberhardt and I are very happy to announce SLF 1.0!</strong></p>
<p><a title="SLF home page at CodePlex" href="http://slf.codeplex.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/slf.codeplex.com');">SLF</a> is a framework with a simple but ambitious mission: To provide <strong><em>every</em></strong> developer with the means to easily plug in logging functionality into her application. As such, it aims at two fundamental goals:</p>
<ol>
<li><strong>Simplicity</strong>: SLF allows you to plug in solid logging functionality into your application with literally one line of code, while providing you with an upgrade path to complex logging scenarios at any time. </li>
<li><strong>Flexibility</strong>: SLF provides you with a common interface that decouples the logging framework of your choice (e.g. <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a> or <a href="http://www.nlog-project.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.nlog-project.org');">NLog</a>)&#160; from your code. This eliminates dependencies on a given framework, thus allowing you to switch (or even combine!) frameworks at any time. Furthermore, SLF’s modular architecture allows you to plug-in custom logging strategies very easily. </li>
</ol>
<p> <span id="more-671"></span><br />
<h4>Features</h4>
<ul>
<li>Configurable through code or configuration files (<em>app.config</em>). </li>
<li>Support for named loggers with hierarchical fallback mechanisms. </li>
<li>Support for common logging frameworks such as <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a> out of the box. </li>
<li>Silverlight support. </li>
<li>Writing your own pluggable logging strategy is easy. </li>
<li>You can exchange the underlying logging mechanism at any time, even at runtime. </li>
<li>Extensible and modular architecture. Writing your own façade can be as simple as overriding one single method, but you can cover complex scenarios, should you have to. </li>
<li>Robust: In case of invalid configurations or logging instructions, SLF rather outputs debug warnings instead of crashing your application at runtime. </li>
<li>A ton of copy-and-paste ready samples for different use cases. </li>
<li>.NET 2.0 compatible binaries. </li>
</ul>
<h4>Related Links</h4>
<ul>
<li>SLF project page: <a href="http://slf.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/slf.codeplex.com');">http://slf.codeplex.com</a> </li>
<li><a href="http://www.codeproject.com/KB/trace/ArtOfLogging.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.codeproject.com');">The Art of Logging</a> – an excellent introduction to logging in general from SLF co-creator <a href="http://www.scottlogic.co.uk/blog/wpf/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.scottlogic.co.uk');">Colin Eberhardt</a>. </li>
<li>SLF <a title="SLF Hands-on Tutorial" href="http://www.hardcodet.net/2009/12/slf-tutorial-1" >Hands-on Tutorial</a>, Part 1 </li>
</ul>
<h2>How does SLF Work?</h2>
<p>Here’s a first snippet that shows how to get a logger at runtime via the static <span class="code">LoggerService </span>class. <span class="code">LoggerService </span>is basically a convenient – and optional – repository for your loggers:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//get the default (unnamed) logger </span>
ILogger logger = LoggerService.GetLogger();

<span style="color: #008000">//log an information </span>
logger.Info(<span style="color: #006080">&quot;hello world&quot;</span>);</pre>
</div>
<p>&#160;</p>
<p>When working with SLF, you’re usually dealing with the <span class="code">ILogger </span>interface. There’s a few built-in implementations of this interface directly in the SLF core library (e.g. <span class="code">ConsoleLogger</span>), but in productive environments, your <span class="code">ILogger </span>implementation usually is a class that forwards logging instructions to a proprietary logging framework such as <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a>, or a custom logging facility you wrote yourself. Hence the name <em><strong>façade</strong></em>:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image7.png" ><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb7.png" width="500" height="400" /></a></p>
<p>&#160;</p>
<p>From your application’s point of view, there is no dependency on the underlying façade and logging framework – you are always logging through the <span class="code">ILogger </span>interface of the SLF core library. This allows you to easily exchange the underlying proprietary mechanism without having to change any of your code that performs the actual logging.</p>
<p><font size="1">SLF also allows you to directly control the logger resolution process (the process that eventually leads to an <span class="code">ILogger </span>instance). We will cover this in a later tutorial.</font></p>
<p>&#160;</p>
<h5>But why should we replace dependencies on logging framework X with dependencies on SLF?</h5>
<p>You probably won’t worry about that, as SLF really just forwards logging information, and can be easily adjusted. However: There’s a simple pattern to get rid of that dependency, too. If you download SLF, you will find a sample project that implements a wrapper for SLF itself:</p>
<p>&#160;</p>
<p><a href="http://www.hardcodet.net/uploads/2009/10/image8.png" ><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.hardcodet.net/uploads/2009/10/image-thumb8.png" width="290" height="110" /></a></p>
<p>&#160;</p>
<h2>SLF in a Fictitious Sample: The Lifecycle of an Application.</h2>
<p>I’ll try to outline the benefits of logging, and the role SLF can play in the context of a fictitious software project. We assume the following:</p>
<ul>
<li>The application will contain various modules (plug-ins). The modules will be developed individually by separate teams. </li>
<li>All modules should log important information. These modules log through SLF, so they have no idea about the underlying logging framework. </li>
<li>Parts of the logged data should be sent back to the development team as soon as the first beta versions have been deployed. </li>
</ul>
<p>&#160;</p>
<h3>Week 1: Setting Up Logging</h3>
<p>Developers have other things in mind than thinking about logging frameworks. They do, however, set SLF in place with two simple steps:</p>
<ol>
<li>Set a reference to the SLF core library. </li>
<li>Configure a logger within the main initialization routine of the application. For starters, all logged data is written to Visual Studio’s debugger by plugging a <span class="code">DebugLogger </span>instance into the global <span class="code">LoggerService</span>: </li>
</ol>
<p><font color="#ff0000">Actually, the first line of code in the application is related to logging:</font></p>
<div>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> InitApplication()
{
  <span style="color: #008000">//make sure logging is in place </span>
  LoggerService.SetLogger(<span style="color: #0000ff">new</span> DebugLogger()); 

  [some other code]
}</pre>
</div>
<ul></ul>
<ul>The application is now officially logging-enabled <img src='http://www.hardcodet.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </ul>
<ul><em>(btw: as an alternative, a one-liner in the application’s configuration file would have worked, too)</em></ul>
<ul></ul>
<h3>Week 2: Developing First Modules</h3>
<p>The first modules are being developed by individual teams. All module libraries maintain a reference to the SLF core library in order to log information. A typical method in a module looks like this:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> Foo()
{
  <span style="color: #0000ff">try</span>
  {
    ...
  }
  <span style="color: #0000ff">catch</span>(Exception e)
  {
    ILogger logger = LoggerService.GetLogger();
    logger.Fatal(e, <span style="color: #006080">&quot;Some explanation&quot;</span>);
  }
}</pre>
</div>
<p>&#160;</p>
<p><em>Note that modules have no idea about the underlying logging strategy that was plugged into SLF (currently the <span class="code">DebugLogger</span> from Week 1). They just know how to request a logger (<span class="code">ILogger </span>interface) from <span class="code">LoggerService</span>. What kind of logger they are dealing with is of no interest to them.</em></p>
<p>&#160;</p>
<h3>Week 3: Writing Logged Data to a File</h3>
<p>There’s a lot of modules by now, which all direct logging information towards SLF. Currently, all this logged messages are being written to the debug window (as configured on Week 1). However, the developers would also like to have the data persisted in a file, while keeping the debug output at the same time.</p>
<p>&#160;</p>
<p>Accordingly, the initialization routine from Week 1 is slightly altered:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">//create two independent loggers </span>
ILogger debugLogger = <span style="color: #0000ff">new</span> DebugLogger();
ILogger fileLogger = BitFactoryLogger.CreateSingleFileLogger(<span style="color: #006080">&quot;log.txt&quot;</span>); 

<span style="color: #008000">//CompositeLogger will redirect all its logging data to the two loggers… </span>
ILogger composite = <span style="color: #0000ff">new</span> CompositeLogger(debugLogger, fileLogger);
<span style="color: #008000">//…so plug it into LoggerService </span>
LoggerService.SetLogger(composite);</pre>
</div>
<p>&#160;</p>
<p>There’s now 3 loggers in play:</p>
<ul>
<li>The initial <span class="code">DebugLogger </span>that logs to the debug window. </li>
<li>The <em>BitFactory</em> façade was used to quickly set up logging to a file. The <em>BitFactory</em> façade is a library that comes with SLF (just like the <em>NLog</em> façade library or the <em>log4net</em> façade library) and makes use of the <a href="http://www.theobjectguy.com/dotnetlog/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.theobjectguy.com');">BitFactory</a> logging framework. This SLF façade library is now referenced by the main application, but not the independent module libraries. </li>
<li><span class="code">CompositeLogger </span>(part of the core library) is then used as a channel that logs output to both the <span class="code">DebugLogger </span>and the new <span class="code">BitFactoryLogger</span>: </li>
</ul>
<p><em>These four lines of code changed the logging behavior of the whole application. Even if there are now literally hundreds of logging instructions in various modules, they don’t need to be changed at all. Everything will now be logged to both the file and the debugger.</em></p>
<p>&#160;</p>
<h3>Week 4: Switching to Declarative Configurations and log4net</h3>
<p>The integration team decides to plug in their logging framework of choice, which happens to be <a href="http://logging.apache.org/log4net/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/logging.apache.org');">log4net</a>. Furthermore, they want to get rid of programmatic initialization, and switch to declarative configuration. This requires two steps:</p>
<ol>
<li>Configuring SLF and log4net in the application’s configuration file (<em>app.config</em>) </li>
<li><strong>Remove all the code (initialization of <span class="code">LoggerService</span>) from Weeks 1 and 3.</strong> </li>
</ol>
<ol>Here’s the app.config file:</ol>
<ol>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span> ?<span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>
   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;slf&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Config.SlfConfigurationSection, slf&quot;</span><span style="color: #0000ff">/&gt;</span> 

   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;log4net&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- declare a log4net factory --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;l4n&quot;</span>
               <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>

    <span style="color: #0000ff">&lt;</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- declare the default logger --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">factory</span><span style="color: #0000ff">=&quot;l4n&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>

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

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #008000">&lt;!-- standard log4net settings are here... --&gt;</span>
   <span style="color: #0000ff">&lt;/</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span></pre>
</p></div>
</ol>
<ol><em>Actually, the above SLF configuration could have been written shorter, but the verbose version is recommended for readability. This would be a shorter, but equivalent version of the <span class="code">slf </span>section:</em></ol>
<ol>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #008000">&lt;!-- this default factory is used for every logging instruction --&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span></pre>
</p></div>
</ol>
<h3>Week 5: Working with Named Loggers</h3>
<p>One of the teams develops a module that logs very important data, and they would like to gather this data separately. It is therefore decided that this output will be logged through a <strong>named logger</strong> called <em>LABDATA</em>. This LABDATA logger should store this information separately.</p>
<p>Accordingly, a lot of logging instructions in this team’s module use SLF’s capability to work with named loggers:</p>
<p>&#160;</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">private</span> <span style="color: #0000ff">void</span> Foo(<span style="color: #0000ff">string</span> someValue)
{
  <span style="color: #0000ff">try</span>
  {
    <span style="color: #008000">//get named logger to log this piece of information </span>
    ILogger labLogger = LoggerService.GetLogger(<span style="color: #006080">&quot;LABDATA&quot;</span>);
    labLogger.Info(<span style="color: #006080">&quot;Foo was invoked with value {0}&quot;,</span> someValue); 

    ...
  }
  <span style="color: #0000ff">catch</span>(Exception e)
  {
    <span style="color: #008000">//exceptions are still logged through default logger  </span>
    ILogger defaultLogger = LoggerService.GetLogger();
    defaultLogger.Fatal(e, <span style="color: #006080">&quot;Some explanation&quot;</span>);
  }
}</pre>
</div>
<p>&#160;</p>
<p>This code was written by an independent team, and they haven’t changed the configuration of the main application. Accordingly, the logged information will still be routed through the default logger, because a logger that matches the name “LABDATA” just isn’t available yet.</p>
<p>So currently, “LABDATA” output will be logged to the same file as all other logging information.</p>
<p><strong><em>But the important thing is: The mechanism is in place and SLF still works without errors!</em></strong></p>
<p>&#160;</p>
<h3>Week 6: Declaratively Configuring the “LABDATA” Logger</h3>
<p>During integration of the new module, SLF’s configuration is changed in order to support custom logging instructions for the LABDATA module.</p>
<p>Because log4net is used, which also supports named loggers out of the box, the SLF configuration does not need to be changed at all! Only the log4net section is being updated:</p>
<p>The adjustments in the application configuration file are specific to log4net:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span> ?<span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>
   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;slf&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Config.SlfConfigurationSection, slf&quot;</span><span style="color: #0000ff">/&gt;</span> 

   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;log4net&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- declare a log4net factory --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;l4n&quot;</span>
               <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade&quot;</span><span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>

    <span style="color: #0000ff">&lt;</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- declare the default logger --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">factory</span><span style="color: #0000ff">=&quot;l4n&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>

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

<span style="color: #008000">&lt;!--</span>
<span style="color: #008000">  configures log4net with two loggers:</span>
<span style="color: #008000">  - A default logger, which logs to file &quot;log-common.txt&quot;</span>
<span style="color: #008000">  - A named logger (&quot;LABDATA&quot;), which logs to file &quot;log-labdata.txt&quot;</span>
<span style="color: #008000">--&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;CommonAppender&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Appender.FileAppender&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;File&quot;</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;log-common.txt&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;AppendToFile&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">layout</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Layout.PatternLayout&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">conversionPattern</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;%date - %message %newline&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">layout</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">appender</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;LabDataAppender&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Appender.FileAppender&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;File&quot;</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;log-labdata.txt&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;AppendToFile&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">layout</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Layout.PatternLayout&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">conversionPattern</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;%date [%thread] %-5level - %message %newline&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">layout</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">appender</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender-ref</span> <span style="color: #ff0000">ref</span><span style="color: #0000ff">=&quot;CommonAppender&quot;</span> <span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">logger</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;LABDATA&quot;</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender-ref</span> <span style="color: #ff0000">ref</span><span style="color: #0000ff">=&quot;LabDataAppender&quot;</span> <span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">logger</span><span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;/</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">&lt;/</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h3>Week 7: Using Another Logging Framework for the LABDATA Loggers</h3>
<p>So far, the generated <em>LabData</em> logging file was manually sent to the development team of the new module, which proved to be tedious (somebody had to manually send a mail every day).</p>
<p>Accordingly, a team developed a simple custom logging façade for SLF. This façade uses WCF to send logged data directly to the team.</p>
<p>As a result, there are now two logging façades in play. We have a new situation:</p>
<ul>
<li>Regular logging data should be logged to a file via log4net (same as before). </li>
<li>Logging data for LABDATA should be handled by the new <span class="code">WcfLogger</span>. </li>
</ul>
<p>Fortunately, integration of the new façade library is easy! It can be plugged into SLF declaratively through the application’s configuration file:</p>
<ul>
<li>log4net configuration: The appender for the LABDATA logger is being removed. </li>
<li>SLF configuration: The new <span class="code">WcfLogger </span>is declared, and configured to handle all LABDATA output. SLF allows us to inject arbitrary configuration information into the declaration. For the WCF logger, this is address information and credentials. </li>
</ul>
<p>This is how <em>app.config</em> looks now:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span> ?<span style="color: #0000ff">&gt;</span>
<span style="color: #0000ff">&lt;</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>
   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;slf&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Slf.Config.SlfConfigurationSection, slf&quot;</span><span style="color: #0000ff">/&gt;</span> 

   <span style="color: #0000ff">&lt;</span><span style="color: #800000">section</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;log4net&quot;</span>
            <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Config.Log4NetConfigurationSectionHandler,log4net&quot;</span><span style="color: #0000ff">/&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">configSections</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #0000ff">&lt;</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- declare a log4net factory --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;l4n&quot;</span>
               <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;SLF.Log4netFacade.Log4netLoggerFactory, SLF.Log4netFacade&quot;</span><span style="color: #0000ff">/&gt;</span> 

      <span style="color: #008000">&lt;!-- the custom factory that logs to a WCF service. --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;wcf&quot;</span>
               <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;Acme.Logging.WcfLogger, Acme.Logging.Slf2WcfFacade&quot;</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">factory-data</span><span style="color: #0000ff">&gt;</span>
          <span style="color: #008000">&lt;!-- this factory takes custom configuration settings --&gt;</span>
          <span style="color: #0000ff">&lt;</span><span style="color: #800000">service</span> <span style="color: #ff0000">address</span><span style="color: #0000ff">=&quot;http://www.acme.com:8080/ws/logs&quot;</span>
                   <span style="color: #ff0000">user</span><span style="color: #0000ff">=&quot;foo&quot;</span>
                   <span style="color: #ff0000">password</span><span style="color: #0000ff">=&quot;bar&quot;</span> <span style="color: #0000ff">/&gt;</span>
        <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factory-data</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factory</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">factories</span><span style="color: #0000ff">&gt;</span>

    <span style="color: #0000ff">&lt;</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #008000">&lt;!-- the default logger that logs via log4net --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">factory</span><span style="color: #0000ff">=&quot;l4n&quot;</span> <span style="color: #0000ff">/&gt;</span>

      <span style="color: #008000">&lt;!-- the named logger that uses the WCF façade --&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">logger</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;LABDATA&quot;</span> <span style="color: #ff0000">factory</span><span style="color: #0000ff">=&quot;wcf&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">loggers</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">slf</span><span style="color: #0000ff">&gt;</span>

  <span style="color: #008000">&lt;!-- log4net configuration for the common log file --&gt;</span>
  <span style="color: #0000ff">&lt;</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;CommonAppender&quot;</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Appender.FileAppender&quot;</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;File&quot;</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;log-common.txt&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;AppendToFile&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">layout</span> <span style="color: #ff0000">type</span><span style="color: #0000ff">=&quot;log4net.Layout.PatternLayout&quot;</span><span style="color: #0000ff">&gt;</span>
        <span style="color: #0000ff">&lt;</span><span style="color: #800000">conversionPattern</span> <span style="color: #ff0000">value</span><span style="color: #0000ff">=&quot;%date - %message %newline&quot;</span> <span style="color: #0000ff">/&gt;</span>
      <span style="color: #0000ff">&lt;/</span><span style="color: #800000">layout</span><span style="color: #0000ff">&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">appender</span><span style="color: #0000ff">&gt;</span>

    <span style="color: #0000ff">&lt;</span><span style="color: #800000">root</span><span style="color: #0000ff">&gt;</span>
      <span style="color: #0000ff">&lt;</span><span style="color: #800000">appender-ref</span> <span style="color: #ff0000">ref</span><span style="color: #0000ff">=&quot;CommonAppender&quot;</span> <span style="color: #0000ff">/&gt;</span>
    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">root</span><span style="color: #0000ff">&gt;</span>
  <span style="color: #0000ff">&lt;/</span><span style="color: #800000">log4net</span><span style="color: #0000ff">&gt;</span>

<span style="color: #0000ff">&lt;/</span><span style="color: #800000">configuration</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p>&#160;</p>
<p><em>Again, only the configuration file was changed – the code in the modules was not touched at all.</em></p>
<p>&#160;</p>
<h3>Week 8 – Unit Testing Logging Instructions</h3>
<p>The developers of the LabData module notice they didn’t cover all code in their unit test: Actually, they don’t know whether their logging instruction are properly executed or not.</p>
<p>In order to unit test their module, they just replace the configured loggers at runtime: They plug in <span class="code">TestLogger </span>classes into <span class="code">LoggerService</span>.&#160; <span class="code">TestLogger</span> is a simple logger which just stores all logging input it receives.</p>
<p>This is how the initialization code of their unit test class looks like:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Given_Foo_When_Submitting_Lab_Data
{
  <span style="color: #0000ff">private</span> TestLogger defaultLogger;
  <span style="color: #0000ff">private</span> TestLogger labDataLogger;

  [SetUp]
  <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Init()
  {
    SimpleFactoryResolver resolver = <span style="color: #0000ff">new</span> SimpleFactoryResolver();
    resolver.Factory = <span style="color: #0000ff">new</span> TestLoggerFactory();
    LoggerService.FactoryResolver = resolver;

    <span style="color: #008000">//for convenience, already get the two test loggers that we will be used</span>
    defaultLogger = (TestLogger) LoggerService.GetLogger(<span style="color: #006080">&quot;&quot;</span>);
    labDataLogger = (TestLogger)LoggerService.GetLogger(<span style="color: #006080">&quot;LABDATA&quot;</span>);
  }
}</pre>
</div>
<p>&#160;</p>
<p>The above snippet installs a <span class="code">TestLoggerFactory</span>. This factory will return <span class="code">TestLogger </span>instances for every logger request that is made through <span class="code">LoggerService</span>. This allows to test whether input was logged through the correct loggers.</p>
<p>Here’s a sample unit test:</p>
<div id="codeSnippetWrapper">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">[Test]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Submitting_Regular_Data_Should_Write_Info_To_Lab_Data_Logger()
{
  <span style="color: #0000ff">string</span> testData = <span style="color: #006080">&quot;asl39-23lsd9&quot;</span>;
  Foo.FooBar(testData);

  <span style="color: #008000">//invoking Foo.FooBar should have logged 1 info to the LABDATA logger</span>
  Assert.AreEqual(1, labDataLogger.LoggedItems.Count);

  <span style="color: #008000">//make sure data was logged correctly</span>
  LogItem item = labDataLogger.LoggedItems[0];
  Assert.AreEqual(LogLevel.Info, item.LogLevel);
  StringAssert.Contains(item.Message, testData);

  <span style="color: #008000">//make sure nothing was logged to the default logger</span>
  Assert.AreEqual(0, defaultLogger.Count);
}</pre>
</div>
<p>&#160;</p>
<p>&#160;</p>
<h2>Conclusion and Further Links</h2>
<p>I hope the above scenario gave you an impression about how easily you can set up and adjust your logging environment with SLF. For more information, please visit the <a href="http://slf.codeplex.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/slf.codeplex.com');">project page</a>, check out the tutorials, or leave a feedback. Happy logging <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/12/slf-introduction/feed</wfw:commentRss>
		</item>
		<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>
	</channel>
</rss>
