<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" >
	<channel>
		<title>North Horizon</title>
		<atom:link href="http://northhorizon.net/feed/" rel="self" type="application/rss+xml" />
		<link>http://northhorizon.net</link>
		<description></description>
		<lastBuildDate>Sat, 12 Nov 2011 20:01:11 +0000</lastBuildDate>
		<language>en</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
		<generator>http://wordpress.org/?v=3.3</generator>
		<item>
			<title>Sharing in RX: Publish, Replay, and Multicast</title>
			<link>http://northhorizon.net/2011/sharing-in-rx/</link>
			<comments>http://northhorizon.net/2011/sharing-in-rx/#comments</comments>
			<pubDate>Fri, 11 Nov 2011 03:54:38 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[RX]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=482</guid>
			<description><![CDATA[State is a tricky thing in RX, especially when we have more than one subscriber to a stream. Consider a fairly innocuous setup: var interval = Observable.Interval(TimeSpan.FromMilliseconds(500)); interval.Subscribe(i => Console.WriteLine("First: {0}", i)); interval.Subscribe(i => Console.WriteLine("Second: {0}", i)); At first glance it might look like I&#8217;m setting up two listeners to a single interval pulse, but [...]]]></description>
			<content:encoded><![CDATA[<p>State is a tricky thing in RX, especially when we have more than one subscriber to a stream. Consider a fairly innocuous setup:</p><pre class="brush:csharp">var interval = Observable.Interval(TimeSpan.FromMilliseconds(500)); interval.Subscribe(i => Console.WriteLine("First: {0}", i)); interval.Subscribe(i => Console.WriteLine("Second: {0}", i));</pre><p>At first glance it might look like I&#8217;m setting up two listeners to a single interval pulse, but what&#8217;s actually happening is that each time I call <code>Subscribe</code>, I&#8217;ve created a new timer to tick values. Imagine how bad this could be if instead of an interval I was, say, sending a message across the network and waiting for a response. <span id="more-482"></span></p><p>There are a few ways to solve this problem, but only one of them is actually correct. The first thing most people latch on to in Intellisense is <code>Publish()</code>. Now <i>that</i> method looks useful. So I might try:</p><pre class="brush:csharp">var interval = Observable.Interval(TimeSpan.FromMilliseconds(500)).Publish(); interval.Subscribe(i => Console.WriteLine("First: {0}", i)); interval.Subscribe(i => Console.WriteLine("Second: {0}", i));</pre><p>Now I get nothing at all. Great advertising there.</p><p>So what is actually happening here? Well, for one you might notice that <code>interval</code> is no longer <code>IObservable&lt;long&gt;</code> but is now an <code>IConnectableObservable&lt;long&gt;</code>, which extends <code>IObservable</code> with a single method: <code>IDisposable Connect()</code>.</p><p>As it turns out, <code>Publish</code> is simply a convenience method for <code>Multicast</code> that supplies the parameter for you. Specifically, calling <code>stream.Publish()</code> is exactly the same as calling <code>stream.Multicast(new Subject&lt;T&gt;())</code>. Wait, a subject?</p><p>What <code>Multicast</code> does is create a concrete implementation of <code>IConnectableObservable&lt;T&gt;</code> to wrap the subject we give it and forwards the <code>Subscribe</code> method of the <code>IConnectableObservable&lt;T&gt;</code> to <code>Subject&lt;T&gt;.Subscribe</code>, so it looks something like this:</p><p><img src="http://northhorizon.net/wp-content/uploads/2011/11/before-connect.png" alt="" title="Before Connecting" width="375" height="106" class="aligncenter size-full wp-image-485" /></p><p>You might have noticed that the input doesn&#8217;t go anywhere. That&#8217;s exactly why our simple call to <code>Publish()</code> earlier didn&#8217;t produce any results at all &#8211; <code>IConnectableObservable&lt;T&gt;</code> hadn&#8217;t been fully wired up yet. To do that, we need to make a call to <code>Connect()</code>, which will subscribe our input into our subject.</p><p><img src="http://northhorizon.net/wp-content/uploads/2011/11/connect.png" alt="" title="Connect" width="375" height="163" class="aligncenter size-full wp-image-486" /></p><p><code>Connect()</code> returns to us an <code>IDisposable</code> which we can use to cut off the input again. Keep in mind the downstream observers <i>have no idea any of this is happening</i>. When we disconnect, <code>OnCompleted</code> will <i>not</i> be fired.</p><p><img src="http://northhorizon.net/wp-content/uploads/2011/11/disconnect.png" alt="" title="Disconnect" width="375" height="164" class="aligncenter size-full wp-image-487" /></p><p>Getting back to my example, the correct code looks like this:</p><pre class="brush:csharp">var interval = Observable.Interval(TimeSpan.FromMilliseconds(500)).Publish(); interval.Subscribe(i => Console.WriteLine("First: {0}", i)); interval.Subscribe(i => Console.WriteLine("Second: {0}", i)); var connection = interval.Connect(); // Later connection.Dispose();</pre><p>It is very important to make sure all of your subscribers are setup <i>before</i> you call <code>Connect()</code>. You can think of <code>Publish</code> (or, really, <code>Multicast</code>) like a valve on a pipe. You want to be sure you have all your pipes together and sealed before you open it up, otherwise you&#8217;ll have a mess.</p><p>A problem that comes up fairly often is what do you do when you do not control the number or timing of subscriptions? For instance, if I have a stream of USD/EUR market rates, there&#8217;s no need for me to keep that stream open if nobody is listening, but if someone is, I&#8217;d like to share that connection, rather than create a new one.</p><p>This is where <code>RefCount()</code> comes in. <code>RefCount()</code> takes an <code>IConnectableObservable&lt;T&gt;</code> and returns an <code>IObservable&lt;Tg&gt;</code>, but with a twist. When <code>RefCount</code> gets its first subscriber, it automatically calls <code>Connect()</code> for you and keeps the connection open as long as anyone is listening; once the last subscriber disconnects, it will call <code>Dispose</code> on its connection token.</p><p>So now you might be wondering why I didn&#8217;t use <code>RefCount()</code> in my so-called &#8220;correct&#8221; implementation. I wouldn&#8217;t have had to call either <code>Connect()</code> or <code>Dispose</code>, and less is more, right? All that is true, but it omits the cost of safety. Once I dispose my connection, my source no longer has an object reference to my object, which allows the GC to do what it does best. Often, these streams start to make their way outside of my class, which can create a long dependency chain of object references. That&#8217;s fine, but if I dispose an object in the middle, I want to make sure that that object is now ready for collection, and if I <code>RefCount()</code>, I simply can&#8217;t make that assertion, because I&#8217;d have to ensure every downstream subscriber had also disposed.</p><p>Another scenario that comes up is how to keep a record of things you&#8217;ve already received. For instance, I might make a call to find all tweets with the hashtag &#8220;#RxNet&#8221; with live updates. If I subscribe second observer, I might expect that all the previously found data to be sent again without making a new request to the server. Fortunately, we have <code>Replay()</code> for this. It literally has 15 overloads, which cover just about every permutation of windowing by count and/or time, and supplying an optional scheduler and/or selector. The parameterless call, however, just remembers everything. <code>Replay</code> is just like <code>Publish</code> in the sense that it also forwards a call to <code>Multicast</code>, but this time with a <code>ReplaySubject&lt;T&gt;</code>.</p><p>Now the temptation is to combine <code>Replay()</code> and <code>RefCount</code> to make caches of things for subscribers when they are needed. Lets look at my Twitter example.</p><pre class="brush:csharp;gutter:false">tweetService.FindByHashTag("RxNet").Replay().RefCount()</pre><p>When the first observer subscribes, <code>FindByHashTag</code> will make a call (I assume this is deferred) to the network and start streaming data, and all is well. When the second observer subscribes, he gets all the previously found data and updates. Great! Now, let&#8217;s say both unsubscribe and a third observer then subscribes. He&#8217;s going to get all that previous data, and then the deferred call in <code>FindByHashTag</code> is going to be re-triggered and provide results that we might have already received from the replay cache! Instead, we should implement a caching solution that actually does what we expect and wrap it in an <code>Observable.Create</code>, or if we expect only fresh tweets, use <code>Publish().RefCount()</code> instead.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/sharing-in-rx/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		</item>
		<item>
			<title>Reactions from Build</title>
			<link>http://northhorizon.net/2011/reactions-from-build/</link>
			<comments>http://northhorizon.net/2011/reactions-from-build/#comments</comments>
			<pubDate>Fri, 16 Sep 2011 21:51:02 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[Build Conf]]></category>
			<category><![CDATA[Metro]]></category>
			<category><![CDATA[Windows 8]]></category>
			<category><![CDATA[WinRT]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=476</guid>
			<description><![CDATA[There’s been no shortage of news and non-news coming out of Build Conference this week, and I suspect there will be continue to be no shortage of the same for the next few months. We’ve learned that WPF isn’t quite dead, Silverlight isn’t quite dead, but both are in the process of being “reimagined,” whatever [...]]]></description>
			<content:encoded><![CDATA[<p>There’s been no shortage of news and non-news coming out of Build Conference this week, and I suspect there will be continue to be no shortage of the same for the next few months. We’ve learned that WPF isn’t quite dead, Silverlight isn’t quite dead, but both are in the process of being “reimagined,” whatever that means. Metro is clearly the first step of that process and it provokes a very diametric response from developers.<span id="more-476"></span></p><p>I sat down to breakfast this morning with a couple guys I hadn’t met. Since Build Conference was an incorporation of both ISVs and IHVs, I greeted them with, “Software or hardware?” The man across the table told me he was involved with software, while the guy to my right ignored me entirely. Without quite playing <em>20 Questions</em>, I found that the more vocal one was a client side developer in health care. He told me that he was very excited about the new Metro design and especially for the upcoming Windows 8 tablets. “Right now, everything is moving to Electronic Medical Records. So, when a doctor goes into see a patient, the first thing he does is turn his back on that patient and bring up the records on a desktop. A tablet is much more like the clipboards doctors used to use.” And, of course, Metro plays a huge role in the realization of that use case; a friendly, full-screen touch-accelerated app is intrinsic to the paradigm of a tablet. Not only that, but ease of access to peripherals, especially the webcam, make Windows Runtime (WinRT) a compelling API. As an added bonus, he pointed out that he could transition his current ASP.NET development stack and programmers much more easily to use either C# and XAML or even HTML5 and JavaScript to produce a Metro app than to use Coco and Objective-C to make an iPad app. Without a doubt, this is what Microsoft had envisioned.</p><p>At the opposite end of the spectrum, I met a couple developers that maintain an institutional client-facing application written in MFC. “There’s over three hundred screens in our application. No way can we fit that into Metro.” He went on further to explain that their application opens direct connections to a SQL Server instances located on both the client and server tiers. “I have to figure out how to go back and tell my boss that there’s just no way we can move over to Metro.”</p><p>I don’t know if he was aware or not of the seemingly obvious flaws in his app’s design, or that Microsoft was encouraging developers to forsake that all-too-familiar design of MFC apps that he showed me. “It’d be a complete rewrite;” that much we completely agreed upon.</p><p>There is a continuing consensus around the notion that WinRT is by far the most ambitious thing Microsoft has done in decades. Perhaps in a lot of ways, Windows XP is an apt analog of Win32 programming: it’s been around for so long, it’s in use in so many places, and it’s so well known, that it will take a very, very long time to unwind from it. Windows 8 and WinRT have enormous potential to revitalize the failing Windows desktop software market. All that remains to be seen is whether developers choose to capitalize upon it or cut their losses and move on.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/reactions-from-build/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>Why I Use Powershell</title>
			<link>http://northhorizon.net/2011/why-i-use-powershell/</link>
			<comments>http://northhorizon.net/2011/why-i-use-powershell/#comments</comments>
			<pubDate>Sun, 07 Aug 2011 03:36:11 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[powershell]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=457</guid>
			<description><![CDATA[I&#8217;ve been using Powershell for just over a year now, and its effect on my development workflow has been steadily increasing. Looking back, I have no doubt that it is the most important tool in my belt &#8211; to be perfectly honest, I&#8217;d rather have Powershell than Visual Studio now. Of course, that&#8217;s not to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Powershell for just over a year now, and its effect on my development workflow has been steadily increasing. Looking back, I have no doubt that it is the most important tool in my belt &#8211; to be perfectly honest, I&#8217;d rather have Powershell than Visual Studio now. Of course, that&#8217;s not to say Visual Studio isn&#8217;t useful &#8211; it is &#8211; but rather more that Poweshell fills an important role in the development process that isn&#8217;t even approached by other tools on the platform. Visual Studio may be the best IDE on the market, but at the end of the day, there are other tools that can replace it, albeit imperfectly.</p><p>To take some shavings off of the top top of the iceberg that is why I use Powershell, I&#8217;d like to share a recent experience of Powershell delivering for me. <span id="more-457"></span></p><h2>Setup for Failure</h2><p>As a co-orgranizer for the <a href="http://www.meetup.com/NY-Dotnet/">New York .NET Meetup</a> I was tasked with getting the list of attendees off of meetup.com and over to the lovely people at Microsoft who kindly give us space to meet. Now, you might think there&#8217;d be some nifty &#8220;export attendee list to CSV&#8221; function the meetup.com website, but like a lot of software, it doesn&#8217;t do half the things you think it should and this is one of those things. Usually my colleague David assembles the list, but this particular month he was out on vacation. He did, however, point me over to a GitHub repository of a tool that would do the extraction.</p><p>Following his advice, I grabbed the repository and brought up the C#/WinForms solution in Visual Studio. Looking at the project structure, I was a bit stunned at the scale of it all. The author had divided his concerns very well into UI, data access, the core infrastructure, and, of course, unit testing. I thought that was pretty peculiar considering all I wanted to do was get a CSV of names and such off of a website. Far be it for me to criticize another developer&#8217;s fastidiousness. Maybe it also launched space shuttles; you never know.</p><p>In what I can only now describe as naivety, I hit F5 and expected something to happen. </p><p>I was rewarded with 76 errors.</p><p>Right off the bat, I realized that the author had botched a commit and forgot a bunch of libraries. I was able to find NHibernate fairly easily with Nuget, but had no luck with &#8220;Rhino.Commons.NHibernate&#8221;. I tried to remove the dependency problem, but didn&#8217;t have much luck. And the whole time I was wondering why the hell you needed all these libraries <b>to extract a damn CSV from the internet</b>.</p><h2>The Problem</h2><p>Rather than throw more time after the problem, I decided to forge out on my own. Really, how hard could it be to</p><ol><li>Get an XML doc from the internet</li><li>Extract the useful data</li><li>Perform some heuristics on the names</li><li>Dump a CSV file</li></ol><p>Being a long-time C# programmer, my knee-jerk reaction was to build a solution in that technology. Forgoing a GUI to spend as little time as possible in building this, I&#8217;d probably build a single file design that ostensibly could consist of a single method. And if that were the case, why not script it?</p><p>So if I was going to write a script, what to use? I could write a JavaScript and run it on node.js, but it&#8217;s lacking proper CSV utilities and I&#8217;d have to run it on something other than my main Windows box. Not to mention I don&#8217;t particularly writing in JavaScript, so I&#8217;d probably write it in CoffeeScript and have to compile it, etc, etc. </p><p>I briefly considered writing an F# script, but I suspect only about ten people would know what on earth it was, and, at the end of the day, I would like to share my script to others.</p><h2>The Solution</h2><p>In the end, I concluded what I had known already: Powershell was the tool to use. It had excellent support for dealing with XML (via accelerators) and, as a real scripting language, had no pomp and circumstance.</p><p>Here&#8217;s the script I ended up writing:</p><pre class="brush:powershell">function Get-MeetupRsvps([string]$eventId, [string]$apiKey) {$nameWord = "[\w-']{2,}" $regex = "^(?'first'$nameWord) ((\w\.?|($nameWord )+) )?(?'last'$nameWord)|(?'last'$nameWord), ?(?'first'$nameWord)( \w\.|( $nameWord)+)?$" function Get-AttendeeInfo {process {$matches = $null $answer = $_.answers.answers_item if(-not ($_.name -match $regex)) { $answer -match $regex | Out-Null }return New-Object PSObject -Property @{ 'FirstName' = $matches.first 'LastName' = $matches.last 'RSVPName' = $_.name 'RSVPAnswer' = $answer 'RSVPGuests' = $_.guests }} }$xml = [Xml](New-Object Net.WebClient).DownloadString("https://api.meetup.com/rsvps.xml?event_id=$eventId`&#038;key=$apiKey") $xml.SelectNodes('/results/items/item[response="yes"]') `| Get-AttendeeInfo `| select FirstName, LastName, RSVPName, RSVPAnswer, RSVPGuests }</pre><p>To dump this to a CSV file is then really easy:</p><pre class="brush: powershell; gutter: false">Get-MeetupRsvps -EventId 1234 -ApiKey 'MyApiKey' | Export-Csv -Path rsvps.csv -NoTypeInformation</pre><p>And because of this design, it&#8217;s really extensible. Potentially, instead of exporting to a CSV, you could pipe the information into another processor that would remove anyone named &#8220;Thorsten.&#8221; Actually, that would look like this:</p><pre class="brush: powershell; gutter: false">Get-MeetupRsvps -EventId 1234 -ApiKey 'MyApiKey' `| ? { %_.FirstName -ne 'Thorsten' } ` | Export-Csv -Path rsvps.csv -NoTypeInformation</pre><p>It&#8217;d be pretty difficult to do that if I&#8217;d written a C# executable &#8211; you&#8217;d have to go into Excel to do that. Or write a Powershell script. Just saying.</p><p>Here&#8217;s the real kicker: I spent all of five minutes writing my Powershell script and then spent minutes tweaking my regex to identify as many names as possible. I didn&#8217;t need to recompile, just F5 again in Poweshell ISE, which you have installed already if you&#8217;re on Windows 7. Since I left the <code>Export-Csv</code> part off during debugging, I could just read the console output and see what I got.</p><p>When I was happy with my output, it was dead simple to distribute: throw it in <a href="https://gist.github.com/1091011">a GitHub Gist</a> and move on with my life. If you decide to use it, all you need is Powershell installed (again, are you on Windows 7?) and the ability to copy and paste. No libraries. No worries. If you don&#8217;t like my regex, it couldn&#8217;t be easier to figure out how to replace it. If you want more fields, it&#8217;s easy to see where they should be added.</p><p>It&#8217;s really just that easy.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/why-i-use-powershell/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		</item>
		<item>
			<title>Patterns with MEF and RX</title>
			<link>http://northhorizon.net/2011/patterns-with-mef-and-rx/</link>
			<comments>http://northhorizon.net/2011/patterns-with-mef-and-rx/#comments</comments>
			<pubDate>Sun, 26 Jun 2011 21:47:57 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Moq]]></category>
			<category><![CDATA[patterns]]></category>
			<category><![CDATA[RX]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=443</guid>
			<description><![CDATA[Since I started using RX, events have played less and less of a role in my code. It&#8217;s true that in the same way LINQ has relegated for-loops to only niche situations, RX is making events all but obsolete. What does this mean for the EventAggregator? Certainly, you can implement your own version using RX. [...]]]></description>
			<content:encoded><![CDATA[<p>Since I started using RX, events have played less and less of a role in my code. It&#8217;s true that in the same way LINQ has relegated for-loops to only niche situations, RX is making events all but obsolete. What does this mean for the <code>EventAggregator</code>? Certainly, <a href="http://joseoncode.com/2010/04/29/event-aggregator-with-reactive-extensions/" target="_blank">you can implement your own version using RX</a>. But, if you happen to be using MEF (preferably as your IOC container) you can even get rid of that. <span id="more-443"></span></p><h2>Introducing the Streams Pattern</h2><p>First we need to create a &#8220;stream provider&#8221;. The purpose of this class is to establish a single place that &#8220;owns&#8221; the stream. I like to use the stream provider to establish default values and behavior:</p><pre class="brush:csharp">public static class StreamNames {private const string Prefix = "Streams_"; public const string Accounts = Prefix + "Accounts"; public const string SelectedAccount = Prefix + "SelectedAccount"; }// No need to export this type. An instance will be // shared between the two child exports. public class AccountStreamProvider {[ImportingConstructor] public AccountStreamProvider(IAccountService accountService) {// Defer the query for the list of accounts until the first subscription var publishedAccounts = Observable .Defer(() =&gt; Observable.Return(accountService.GetAccounts())) .Publish(); publishedAccounts.Connect(); Accounts = publishedAccounts; SelectedAccount = new ReplaySubject(1); // Take the first account and set it as the initially selected account. Accounts .Take(1) .Select(Enumerable.FirstOrDefault) .Subscribe(SelectedAccount.OnNext); }[Export(StreamNames.Accounts)] public IObservable&lt;IEnumerable&lt;Account&gt;&gt; Accounts { get; set; }[Export(StreamNames.SelectedAccount)] [Export(StreamNames.SelectedAccount, typeof(IObservable&lt;Account&gt;)] public ISubject&lt;Account&gt; SelectedAccount { get;set; }}</pre><p>Already the benefits of RX over the <code>EventAggregator</code> are showing.</p><p>Now we just need to get a reference to our exports in a relevant view model:</p><pre class="brush:csharp">public static class Extensions {public static void DisposeWith(this IDisposable source, CompositeDisposable disposables) {disposables.Add(source); }} [Export, PartCreationPolicty(CreationPolicy.NotShared)] public class AccountViewModel : BindableBase, IDisposable {private readonly Streams _streams; private readonly CompositeDisposable _disposables; [Export] public class Streams {[Import(StreamNames.Accounts)] public IObservable&lt;IEnumerable&lt;Account&gt;&gt; Accounts { get; set; }[Import(StreamNames.SelectedAccount)] public ISubject&lt;Account&gt; SelectedAccount { get; set; }} [ImportingConstructor] public AccountViewModel(Streams streams) {_streams = streams; _disposables = new CompositeDisposable(); _streams .Accounts .Subscribe(a =&gt; Accounts = a) .DisposeWith(_disposables); _streams .SelectedAccount .Subscribe(a =&gt; SelectedAccount = a) .DisposeWith(_disposables); }private IEnumerable&lt;Account&gt; _accounts; public IEnumerable&lt;Account&gt; Accounts {get { return _accounts; }private set { SetProperty(ref _accounts, value, "Accounts"); }} private Account _selectedAccount; public Account SelectedAccount {get { return _selectedAcccount; }private set { SetProperty(ref _selectedAccount, value, "SelectedAccount", OnSelectedAccountChanged); }} // This method is only called when _selectedAccount // actually changes, so there's no indirect recursion. private void OnSelectedAccountChanged() {_streams.SelectedAccount.OnNext(_selectedAccount); }public void Dispose() {_disposables.Dispose(); }}</pre><p>By the way, I&#8217;m using <code>BinableBase</code> from my <a href="https://github.com/danielmoore/InpcTemplate/blob/master/InpcTemplate/BindableBase.cs">INPC template</a>.</p><h2>Introducing the Config Pattern</h2><p>If you&#8217;ve been using RX for a while, you might have noticed that I forgot to put my setters on the dispatcher. Sure, I could rely on automatic dispatching to fix that problem, but if my queries got any more complicated It&#8217;d be better for me to take care of the dispatch myself.</p><p>Of course, the problem with <code>ObserveOnDispatcher</code> is that it makes testing a huge pain. Fortunately, we can use MEF to get around that problem, too.</p><pre class="brush:csharp; highlight:[19, 34, 40]">public class AccountViewModel : BindableBase, IDisposable {private readonly Streams _streams; private readonly Config _config; private readonly CompositeDisposable _disposables; [Export] public class Streams {[Import(StreamNames.Accounts)] public IObservable&lt;IEnumerable&lt;Account&gt;&gt; Accounts { get; set; }[Import(StreamNames.SelectedAccount)] public ISubject&lt;Account&gt; SelectedAccount { get; set; }} [Export] public class Config {public virtual IScheduler DispatcherScheduler { get { return Scheduler.Dispatcher; } } }[ImportingConstructor] public AccountViewModel(Streams streams, Config config) {_streams = streams; _config = config; _disposables = new CompositeDisposable(); _streams .Accounts .ObserveOn(_config.DispatcherScheduler) .Subscribe(a =&gt; Accounts = a ).DisposeWith(_disposables); _streams .SelectedAccount .ObserveOn(_config.DispatcherScheduler) .Subscribe(a =&gt; SelectedAccount = a) .DisposeWith(_disposables); }// ... }</pre><p>Since the <code>DispatcherScheduler</code> property is virtual, it&#8217;s easy to mock it out. Using Moq, all you need to do is:</p><pre class="brush:csharp; gutter:false">Mock.Of&lt;AccountViewModel.Config&gt;(m =&gt; m.DispatcherScheduler == Scheduler.Immediate)</pre>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/patterns-with-mef-and-rx/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		</item>
		<item>
			<title>Coercing ViewModel Values with INotifyPropertyChanged</title>
			<link>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/</link>
			<comments>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/#comments</comments>
			<pubDate>Sun, 08 May 2011 21:21:14 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[INotifyPropertyChanged]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=429</guid>
			<description><![CDATA[Perhaps one of the most ambivalent things about putting code on GitHub is that it&#8217;s more or less an open project. It&#8217;s great that people (including yourself) can continue to work on it, but it seems to lack closure so that you can move on with your life. So one of the things that I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>Perhaps one of the most ambivalent things about putting code on GitHub is that it&#8217;s more or less an open project. It&#8217;s great that people (including yourself) can continue to work on it, but it seems to lack closure so that you can move on with your life.</p><p>So one of the things that I&#8217;ve been missing in my <code>BindableBase</code> class is property coercion, a la dependency properties. It&#8217;s a pretty smart idea; you can keep values in a valid state without pushing change notification. Unfortunately, there are some problems that crop up pretty quickly in <code>INotifyPropertyChanged</code> based view models.<span id="more-429"></span></p><p>Consider a Foo property that refuses to set a value less than zero.</p><pre class="brush:csharp">private int _foo; public int Foo {get { return _foo; }set {if(_foo &gt;= 0) SetProperty(ref _foo, value, "Foo"); }}</pre><p>That looks like pretty good coercion, but the problem is that your binding and your property are now out of sync. That is, the binding told your object to set a value and assumed it did; you gave it no notification to the contrary. So while your object retains the old value, the bound <code>TextBox</code> will blissfully report -23.</p><p>A more brute force option would raise <code>PropertyChanged</code> in the event of this kind of coercion, but that breaks the code contract for <code>INotifyPropertyChanged</code> in that <em>nothing changed</em>. So how do we get around this problem?</p><p>If you take a look at the invocation list of your <code>PropertyChanged</code> event with some bound variables, you&#8217;ll notice that there&#8217;s a <code>PropertyChangedEventManager</code> hooked up.</p><p><a href="http://northhorizon.net/wp-content/uploads/2011/05/propertychangedeventmanager-watch.png"><img class="aligncenter size-full wp-image-432" title="PropertyChangedEventManager in the Watch" src="http://northhorizon.net/wp-content/uploads/2011/05/propertychangedeventmanager-watch.png" alt="" width="707" height="330" /></a></p><p>Considering that the other item in the list is my default delegate, this object must be responsible for communicating my events to the binding system</p><p>Of course, the next thing to do is fire up Reflector and take a look at what&#8217;s there.</p><pre class="brush:csharp">public class PropertyChangedEventManager : WeakEventManager {// Fields private WeakEventManager.ListenerList _proposedAllListenersList; private static readonly string AllListenersKey; // Methods static PropertyChangedEventManager(); private PropertyChangedEventManager(); public static void AddListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); private void OnPropertyChanged(object sender, PropertyChangedEventArgs args); private void PrivateAddListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); private void PrivateRemoveListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); protected override bool Purge(object source, object data, bool purgeAll); public static void RemoveListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); protected override void StartListening(object source); protected override void StopListening(object source); // Properties private static PropertyChangedEventManager CurrentManager { get; }}</pre><p>Basically, <code>AddListener</code> access the private <code>CurrentManager</code> singleton and subscribes the given listener to <code>OnPropertyChanged</code>. Fortunately for us, there&#8217;s a flaw in th the implementation of <code>OnPropertyChanged</code>. What it does is it gets the list of listeners based on the sender and raises their event with the given sender and args. The problem here is that it doesn&#8217;t verify that the object raising the event is actually the sender! That is to say, we should be able to send a fake PropertyChanged event through another object acting as a surrogate. All we need to do is add that object to the PropertyChangedEvenManager&#8217;s list and start impersonating.</p><p>To that end, I added this private class to <code>BindableBase</code> to lazily add the <code>INotifyPropertyChanged</code> proxy object to the <code>PropertyChangedEventManager</code>. Since we&#8217;re not actually interested in the events, I made a stub implementation of <code>IWeakEventListener</code> that returns false constantly to indicate it&#8217;s not handling the event. Finally, I hold onto both of these references to keep them from being garbage collected.</p><pre class="brush:csharp">private class PropertyChangedEventManagerProxy {// We need to hold on to these refs to keep it from getting GC'd private readonly NotifyPropertyChangedProxy _notifyPropertyChangedProxy; private readonly IWeakEventListener _weakEventListener; private PropertyChangedEventManagerProxy() {_notifyPropertyChangedProxy = new NotifyPropertyChangedProxy(); _weakEventListener = new WeakListenerStub(); PropertyChangedEventManager.AddListener(_notifyPropertyChangedProxy, _weakEventListener, string.Empty); }public void RaisePropertyChanged(object sender, string propertyName) {_notifyPropertyChangedProxy.Raise(sender, new PropertyChangedEventArgs(propertyName)); }private static PropertyChangedEventManagerProxy _instance; public static PropertyChangedEventManagerProxy Instance { get { return _instance ?? (_instance = new PropertyChangedEventManagerProxy()); } } private class NotifyPropertyChangedProxy : INotifyPropertyChanged {public event PropertyChangedEventHandler PropertyChanged = delegate { }; public void Raise(object sender, PropertyChangedEventArgs e) {PropertyChanged(sender, e); }} private class WeakListenerStub : IWeakEventListener {public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { return false; }} }</pre><p>The only thing left to do is add the coerce value function as an optional parameter on <code>SetProperty</code> and hook it up:</p><pre class="brush:csharp">protected void SetProperty&lt;T&gt;( ref T backingStore, T value, string propertyName, Action onChanged = null, Action&lt;T&gt; onChanging = null, Func&lt;T, T&gt; coerceValue = null) {VerifyCallerIsProperty(propertyName); var effectiveValue = coerceValue != null ? coerceValue(value) : value; if (EqualityComparer&lt;T&gt;.Default.Equals(backingStore, effectiveValue)) {// If we coerced this value and the coerced value is not equal to the original, we need to // send a fake PropertyChanged event to notify WPF that this value isn't what it thinks it is. if (coerceValue != null &amp;&amp; !EqualityComparer&lt;T&gt;.Default.Equals(value, effectiveValue)) PropertyChangedEventManagerProxy.Instance.RaisePropertyChanged(this, propertyName); return; }if (onChanging != null) onChanging(effectiveValue); OnPropertyChanging(propertyName); backingStore = effectiveValue; if (onChanged != null) onChanged(); OnPropertyChanged(propertyName); }</pre><p>And there you have it. All the benefits of dependency property coercion, and the same short, sweet <code>SetProperty</code> syntax.</p><p>As before, everything is on <a href="https://github.com/danielmoore/InpcTemplate">GitHub</a> so you can take a look at the whole thing and fork it if you see something to be improved.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>The Right Way to do INotifyPropertyChanged</title>
			<link>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/</link>
			<comments>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/#comments</comments>
			<pubDate>Sun, 20 Feb 2011 22:35:12 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[Uncategorized]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Extension Methods]]></category>
			<category><![CDATA[INotifyPropertyChanged]]></category>
			<category><![CDATA[Lambda]]></category>
			<category><![CDATA[patterns]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=397</guid>
			<description><![CDATA[It&#8217;s sad how much controversy there is in doing something as simple as raising property change notification to our subscribers. It seems to me that we should have settled on something by now and moved on to bigger problems, yet, still, I see developers at every level of experience doing it differently. I want to [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s sad how much controversy there is in doing something as simple as raising property change notification to our subscribers. It seems to me that we should have settled on something by now and moved on to bigger problems, yet, still, I see developers at every level of experience doing it differently.</p><p>I want to inform you all that <a href="http://xkcd.com/386/">you&#8217;re doing it wrong</a>.<span id="more-397"></span></p><h2>The Problem</h2><p>Most projects choose to implement <code>INotifyPropertyChanged</code> instead of extending <code>DependencyObject</code> for the sole reason that dependency properties are an enormous pain to write. Having worked on a large project that used the latter approach, I&#8217;ve entirely sworn it off, and I don&#8217;t care what kind of tooling you say makes life better. It&#8217;s just too complicated. On top of that, it&#8217;s really difficult to subscribe to changes programmatically. Sure you can go through <code>DependencyPropertyDescriptor</code> and subscribe yourself, but that&#8217;s a hell of a lot harder than <code>+=</code>. So that leaves some people with properties that look like this:</p><pre class="brush:csharp">private int _myValue; public int MyValue {get { return _myValue; }set { _myValue = value; OnPropertyChanged("MyValue"); }}</pre><p>Not bad, perhaps. It just doesn&#8217;t do much. What about <code>INotifyPropertyChanging</code>? How do I do things internally when that property changes other than subscribing to my own <code>PropertyChanged</code> event?</p><p>These things could almost be overlooked. The real kicker is that this isn&#8217;t actually a proper implementation of <code>INotifyPropertyChanged</code>. <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx">According to MSDN</a>, the <code>PropertyChanged</code> event is described as, &#8220;Occurs when a property value changes,&#8221; and this code will raise an event even if the value doesn&#8217;t. Their implementation looks like this:</p><pre class="brush: csharp">private string customerNameValue = String.Empty; public string CustomerName {get {return this.customerNameValue; }set {if (value != this.customerNameValue) {this.customerNameValue = value; NotifyPropertyChanged("CustomerName"); }} }</pre><p>Aside from their code style (or lack thereof), allow me to point out a few things. First &#8211; and foremost &#8211; they&#8217;re comparing string equality with operators, no mere venial sin in my book. Secondly, this puts the onus of figuring out how to compare two types on the property writer ad-hoc, rather than using something more intelligent. Finally, does anyone else think that 17 lines is a few too many for a <em>dirt simple</em> property? It&#8217;s crazy.</p><h2>The Trouble with Lambda</h2><p>Some very smart programmers I know like to have their <code>NotifyPropertyChanged</code> method take an Expression&lt;Func&lt;TProp&gt;&gt; so you can do something like:</p><pre class="brush: csharp">private int _myValue; public int MyValue {get { return _myValue; }set { _myValue = value; NotifyPropertyChanged(() =&gt; MyValue); }}</pre><p>They say it improves type checking and the ease of refactoring. But as it turns out, <a href="http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/">it&#8217;s god-awful for performance</a>, which can run you into a lot of problems if you don&#8217;t keep track of even moderate update bursts.</p><p>I&#8217;d almost be willing to accept the performance trade-off if it weren&#8217;t for the fact that the only place that&#8217;s calling it is <em>inside the property setter</em>. When you&#8217;re refactoring, I don&#8217;t see it as too much effort to go ahead and fix the string in the underlying property setter while you&#8217;re there; you have to fix the backing member anyway.</p><p>Really what we need is lambdas for subscription. All those places out in your code that subscribe to <code>PropertyChanged</code> and then you check the property name with a string! That&#8217;s the real refactoring nightmare. What I want to do is <code>myViewModel.SubscribeToPropertyChanged(vm =&gt; vm.Foo, OnFooChanged);</code></p><p>The implementation isn&#8217;t that complex at all:</p><pre class="brush:csharp">public static IDisposable SubscribeToPropertyChanged&lt;TSource, TProp&gt;( this TSource source, Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector, Action onChanged) where TSource : INotifyPropertyChanged {if (source == null) throw new ArgumentNullException("source"); if (propertySelector == null) throw new ArgumentNullException("propertySelector"); if (onChanged == null) throw new ArgumentNullException("onChanged"); var subscribedPropertyName = GetPropertyName(propertySelector); PropertyChangedEventHandler handler = (s, e) =&gt; {if (string.Equals(e.PropertyName, subscribedPropertyName, StringComparison.InvariantCulture)) onChanged(); }; source.PropertyChanged += handler; return Disposable.Create(() =&gt; source.PropertyChanged -= handler); }public static IDisposable SubscribeToPropertyChanging&lt;TSource, TProp&gt;( this TSource source, Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector, Action onChanging) where TSource : INotifyPropertyChanging {if (source == null) throw new ArgumentNullException("source"); if (propertySelector == null) throw new ArgumentNullException("propertySelector"); if (onChanging == null) throw new ArgumentNullException("onChanged"); var subscribedPropertyName = GetPropertyName(propertySelector); PropertyChangingEventHandler handler = (s, e) =&gt; {if (string.Equals(e.PropertyName, subscribedPropertyName, StringComparison.InvariantCulture)) onChanging(); }; source.PropertyChanging += handler; return Disposable.Create(() =&gt; source.PropertyChanging -= handler); }private static string GetPropertyName&lt;TSource, TProp&gt;(Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector) {var memberExpr = propertySelector.Body as MemberExpression; if (memberExpr == null) throw new ArgumentException("must be a member accessor", "propertySelector"); var propertyInfo = memberExpr.Member as PropertyInfo; if (propertyInfo == null || propertyInfo.DeclaringType != typeof(TSource)) throw new ArgumentException("must yield a single property on the given object", "propertySelector"); return propertyInfo.Name; }</pre><h2>The Best Solution</h2><p>This leaves me with a pretty explicit spec for implementing <code>INotifyPropertyChanged</code>:</p><ol><li>It will take no more lines than a basic backing field setter.</li><li>It will raise INotifyPropertyChanged and INotifyPropertyChanging.</li><li>It will only raise the properties if the value has changed.</li><li>it will provide an easy way to have internal property changed subscriptions.</li><li>It will not use Lambdas to identify the property.</li></ol><p>My solution allows you to do this:</p><pre class="brush: csharp">private int _myValue; public int MyValue {get { return _myValue; }set { SetProperty(ref _myValue, value, OnMyValueChanged, OnMyValueChanging); }} private void OnMyValueChanged() { } private void OnMyValueChanging(int newValue) { }</pre><p>Isn&#8217;t that nice? SetProperty looks like this:</p><pre class="brush:csharp">protected void SetProperty( ref T backingStore, T value, string propertyName, Action onChanged = null, Action onChanging = null) {VerifyCallerIsProperty(propertyName); if (EqualityComparer&lt;T&gt;.Default.Equals(backingStore, value)) return; if (onChanging != null) onChanging(value); OnPropertyChanging(propertyName); backingStore = value; if (onChanged != null) onChanged(); OnPropertyChanged(propertyName); }[Conditional("DEBUG")] private void VerifyCallerIsProperty(string propertyName) {var stackTrace = new StackTrace(); var frame = stackTrace.GetFrames()[2]; var caller = frame.GetMethod(); if (!caller.Name.Equals("set_" + propertyName, StringComparison.InvariantCulture)) throw new InvalidOperationException( string.Format("Called SetProperty for {0} from {1}", propertyName, caller.Name)) }</pre><p>The default parameters on <code>SetProperty</code> allow you to specify the changed callback or the changing callbacks in any permutation with the usual syntax and the stack trace analysis happens at debug time to make sure that the string you provide actually represents the property it&#8217;s being called from.</p><p>So how do we update dependent properties? The one thing you don&#8217;t want to do is <strong>ever</strong> have external property changing logic directly in your set method. It&#8217;s better to call out to a <code>OnMyPropertyChanging</code> event and have that method update your dependent method. The syntax is a little verbose, but it&#8217;s the most readable and extensible way to do it:</p><pre class="brush: csharp">private int _foo; public int Foo {get { return _foo; }set { SetProperty(ref _foo, value, "Foo", OnFooChanged); }} private int _bar; public int Bar {get { return _bar; }set { SetProperty(ref _bar, value, "Bar", OnBarChanged); }} private int _foobar; public int Foobar {get { return _foobar; }private set { SetProperty(ref _foobar, value, "Foobar"); }} private void OnFooChanged() { UpdateFoobar(); }private void OnBarChanged() { UpdateFoobar(); }private void UpdateFoobar() { Foobar = _foo + _bar; }</pre><p>In general you should <strong>never</strong> call <code>OnProeprtyChanged</code>; that decision is best left to the property and its underlying helper.</p><p>I hope this clears the water  for some people new to WPF and provides reasons for the veterans to change their tune. If you think I&#8217;m wrong, feel free to try and prove it to me in the comments section. After all, duty calls.</p><p>The source and XML documentation for all this and a few tests is on <a href="https://github.com/danielmoore/InpcTemplate">github</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		</item>
		<item>
			<title>How to Actually Change the System Theme in WPF</title>
			<link>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/</link>
			<comments>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/#comments</comments>
			<pubDate>Sun, 05 Dec 2010 22:21:22 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Reflection]]></category>
			<category><![CDATA[Styles]]></category>
			<category><![CDATA[Themes]]></category>
			<category><![CDATA[WPF]]></category>
			<category><![CDATA[XAML]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=372</guid>
			<description><![CDATA[When I first started working with WPF professionally, it wasn&#8217;t very long before I realized I needed to change the system theme of WPF to give my users a consistent experience across platforms. Not to mention that Vista&#8217;s theme was much improved over XP and even more so over the classic theme. Conceptually, this should [...]]]></description>
			<content:encoded><![CDATA[<p>When I first started working with WPF professionally, it wasn&#8217;t very long before I realized I needed to change the system theme of WPF to give my users a consistent experience across platforms. Not to mention that Vista&#8217;s theme was <em>much</em> improved over XP and even more so over the classic theme. Conceptually, this should be feasible, since WPF has its own rendering engine, as opposed to WinForms relying on GDI.<span id="more-372"></span></p><p>Naturally, the first thing I did was to <a href="http://www.google.com/search?q=wpf+force+vista+theme">Google the answer</a>. The <a href="http://arbel.net/blog/archive/2006/11/03/Forcing-WPF-to-use-a-specific-Windows-theme.aspx">first result</a> looked pretty good so I implemented that:</p><pre class="brush: xml">&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/PresentationFramework.Aero;V4.0.0.0;31bf3856ad364e35;component/themes/aero.normalcolor.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt;</pre><p>This worked great up until I started styling things. Any time I created a style for one of the system controls, it&#8217;d change the underlying style back to the original system them, rather than the one I wanted. It turns out that naturally styles are based on the system theme, rather than implicit style (for reasons we&#8217;ll get into later). So the way to base a theme off of the implicit style is like this:</p><pre class="brush: xml">&lt;Style x:Key="GreenButtonStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"&gt; &lt;Setter Property="Background" Value="Green"/&gt; &lt;Setter Property="Foreground" Value="White"/&gt; &lt;/Style&gt;</pre><p>Maybe a little inconvenient, but it gets the job done:﻿</p><p><a href="http://northhorizon.net/wp-content/uploads/2010/12/dictionary-based-theme-change.png"><img class="aligncenter size-full wp-image-383" title="Dictionary Based Theme Change" src="http://northhorizon.net/wp-content/uploads/2010/12/dictionary-based-theme-change.png" alt="" width="525" height="350" /></a></p><p>All was well up until I needed to make a new style based off of the default theme. Like many WPF applications, we had some default styles defined to give our controls a clean, consistent look. But in my particular case, I needed to make a whole new visual &#8220;branch,&#8221; using the default theme as the &#8220;trunk.&#8221; If I used my <code>BasedOn</code> workaround, I&#8217;d just get my implicit style; if I didn&#8217;t I&#8217;d get that nasty classic theme.</p><p>The more I thought about this, the more I realized that all of these problems were being caused by the fact that I was applying a system theme (aero.normalcolor) as a style on top of the actual system theme, rather than <em>actually</em> changing it. So I set off on a journey in Reflector to find out how WPF picks the current theme. This sounds hard, and it&#8217;s actually a lot harder than it sounds. After a dozen or so hours (spread out over a few weeks) and a some guidance by <a href="http://learnwpf.com/Posts/Post.aspx?postId=3f1f4b8b-b91a-442d-a531-919de70ac225">a blog that got really close</a> (unfortunately, my link is now dead), I found out that however WPF calls a native method in uxtheme.dll to get the actual system theme, then stores the result in <code>MS.Win32.UxThemeWrapper</code>, an internal static class (of course). Furthermore, the properties on the class are read only (and also marked internal), so the best way to change it was by directly manipulating the private fields. My solution looks like this:</p><pre class="brush: csharp">public partial class App : Application {public App() {SetTheme("aero", "normalcolor"); }/// &lt;summary&gt; /// Sets the WPF system theme. /// &lt;/summary&gt; /// &lt;param name="themeName"&gt;The name of the theme. (ie "aero")&lt;/param&gt; /// &lt;param name="themeColor"&gt;The name of the color. (ie "normalcolor")&lt;/param&gt; public static void SetTheme(string themeName, string themeColor) {const BindingFlags staticNonPublic = BindingFlags.Static | BindingFlags.NonPublic; var presentationFrameworkAsm = Assembly.GetAssembly(typeof(Window)); var themeWrapper = presentationFrameworkAsm.GetType("MS.Win32.UxThemeWrapper"); var isActiveField = themeWrapper.GetField("_isActive", staticNonPublic); var themeColorField = themeWrapper.GetField("_themeColor", staticNonPublic); var themeNameField = themeWrapper.GetField("_themeName", staticNonPublic); // Set this to true so WPF doesn't default to classic. isActiveField.SetValue(null, true); themeColorField.SetValue(null, themeColor); themeNameField.SetValue(null, themeName); }}</pre><p>I call the method in the <code>App</code> constructor so it sets the values after WPF does its detection, but before the system theme is loaded for rendering.</p><p>Here&#8217;s what I got back:</p><p><img class="aligncenter size-full wp-image-384" title="Basic Reflection Theme Change" src="http://northhorizon.net/wp-content/uploads/2010/12/basic-reflection-theme-change.png" alt="" width="525" height="350" />Success!</p><p>There&#8217;s still a couple downsides to this approach. First, I can&#8217;t change the theme whenever I want to, and secondly, if the user changes their Windows theme while the application is running, the theme I set gets wiped out.</p><p>Wait a minute. If Windows can change the application theme, I can too!</p><p>Poking around a little more, I found out that when WPF wants to find a system resource, it also calls <code>System.Windows.SystemResources.EnsureResourceChangeListener()</code> which makes sure there&#8217;s a listener attached to the Windows message pump, ready to interpret events like a theme change.</p><pre class="brush:csharp">[SecurityCritical, SecurityTreatAsSafe] private static void EnsureResourceChangeListener() {if (_hwndNotify == null) {HwndWrapper wrapper = new HwndWrapper(0, -2013265920, 0, 0, 0, 0, 0, "SystemResourceNotifyWindow", IntPtr.Zero, null); _hwndNotify = new SecurityCriticalDataClass&lt;HwndWrapper&gt;(wrapper); _hwndNotify.Value.Dispatcher.ShutdownFinished += new EventHandler(SystemResources.OnShutdownFinished); _hwndNotifyHook = new HwndWrapperHook(SystemResources.SystemThemeFilterMessage); _hwndNotify.Value.AddHook(_hwndNotifyHook); }}</pre><p>The handler looks like this:</p><pre class="brush: csharp">[SecurityTreatAsSafe, SecurityCritical] private static IntPtr SystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {WindowMessage message = (WindowMessage) msg; switch (message) {// abridged case WindowMessage.WM_THEMECHANGED: SystemColors.InvalidateCache(); SystemParameters.InvalidateCache(); OnThemeChanged(); InvalidateResources(false); break; }return IntPtr.Zero; }</pre><p>So the plan was to remove the hook so the message pump couldn&#8217;t change the theme out from under me and then call the handler whenever <em>I</em> want. As it turns out, it&#8217;s even easier than that. Because the list of hooks is implemented with a WeakReferenceList, all I need to do is null out the private <code>_hwndNotifyHook</code> field. There&#8217;s just one problem here: killing the handler prevents us from receiving system notifications for the other messages like device changes, power updates, etc. So we really need to inject a filter into the pipeline and pass along everything except the ThemeChanged event.</p><p>Fair warning: if you get queasy around reflection, you should probably stop reading here.</p><pre class="brush: csharp">public static class ThemeHelper {private const BindingFlags InstanceNonPublic = BindingFlags.Instance | BindingFlags.NonPublic; private const BindingFlags StaticNonPublic = BindingFlags.Static | BindingFlags.NonPublic; private const int ThemeChangedMessage = 0x31a; private static readonly MethodInfo FilteredSystemThemeFilterMessageMethod =typeof(ThemeHelper).GetMethod("FilteredSystemThemeFilterMessage", StaticNonPublic); private static readonly Assembly PresentationFramework =Assembly.GetAssembly(typeof(Window)); private static readonly Type ThemeWrapper =PresentationFramework.GetType("MS.Win32.UxThemeWrapper"); private static readonly FieldInfo ThemeWrapper_isActiveField =ThemeWrapper.GetField("_isActive", StaticNonPublic); private static readonly FieldInfo ThemeWrapper_themeColorField =ThemeWrapper.GetField("_themeColor", StaticNonPublic); private static readonly FieldInfo ThemeWrapper_themeNameField =ThemeWrapper.GetField("_themeName", StaticNonPublic); private static readonly Type SystemResources =PresentationFramework.GetType("System.Windows.SystemResources"); private static readonly FieldInfo SystemResources_hwndNotifyField =SystemResources.GetField("_hwndNotify", StaticNonPublic); private static readonly FieldInfo SystemResources_hwndNotifyHookField =SystemResources.GetField("_hwndNotifyHook", StaticNonPublic); private static readonly MethodInfo SystemResources_EnsureResourceChangeListener =SystemResources.GetMethod("EnsureResourceChangeListener", StaticNonPublic); private static readonly MethodInfo SystemResources_SystemThemeFilterMessageMethod =SystemResources.GetMethod("SystemThemeFilterMessage", StaticNonPublic); private static readonly Assembly WindowsBase =Assembly.GetAssembly(typeof(DependencyObject)); private static readonly Type HwndWrapperHook =WindowsBase.GetType("MS.Win32.HwndWrapperHook"); private static readonly Type HwndWrapper =WindowsBase.GetType("MS.Win32.HwndWrapper"); private static readonly MethodInfo HwndWrapper_AddHookMethod =HwndWrapper.GetMethod("AddHook"); private static readonly Type SecurityCriticalDataClass =WindowsBase.GetType("MS.Internal.SecurityCriticalDataClass`1") .MakeGenericType(HwndWrapper); private static readonly PropertyInfo SecurityCriticalDataClass_ValueProperty =SecurityCriticalDataClass.GetProperty("Value", InstanceNonPublic); /// &lt;summary&gt; /// Sets the WPF system theme. /// &lt;/summary&gt; /// &lt;param name="themeName"&gt;The name of the theme. (ie "aero")&lt;/param&gt; /// &lt;param name="themeColor"&gt;The name of the color. (ie "normalcolor")&lt;/param&gt; public static void SetTheme(string themeName, string themeColor) {SetHwndNotifyHook(FilteredSystemThemeFilterMessageMethod); // Call the system message handler with ThemeChanged so it // will clear the theme dictionary caches. InvokeSystemThemeFilterMessage(IntPtr.Zero, ThemeChangedMessage, IntPtr.Zero, IntPtr.Zero, false); // Need this to make sure WPF doesn't default to classic. ThemeWrapper_isActiveField.SetValue(null, true); ThemeWrapper_themeColorField.SetValue(null, themeColor); ThemeWrapper_themeNameField.SetValue(null, themeName); }public static void Reset() {SetHwndNotifyHook(SystemResources_SystemThemeFilterMessageMethod); InvokeSystemThemeFilterMessage(IntPtr.Zero, ThemeChangedMessage, IntPtr.Zero, IntPtr.Zero, false); }private static void SetHwndNotifyHook(MethodInfo method) {var hookDelegate = Delegate.CreateDelegate(HwndWrapperHook, FilteredSystemThemeFilterMessageMethod); // Note that because the HwndwWrapper uses a WeakReference list, we don't need // to remove the old value. Simply killing the reference is good enough. SystemResources_hwndNotifyHookField.SetValue(null, hookDelegate); // Make sure _hwndNotify is set! SystemResources_EnsureResourceChangeListener.Invoke(null, null); // this does SystemResources._hwndNotify.Value.AddHook(hookDelegate) var hwndNotify = SystemResources_hwndNotifyField.GetValue(null); var hwndNotifyValue = SecurityCriticalDataClass_ValueProperty.GetValue(hwndNotify, null); HwndWrapper_AddHookMethod.Invoke(hwndNotifyValue, new object[] { hookDelegate }); }private static IntPtr InvokeSystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, bool handled) {return (IntPtr)SystemResources_SystemThemeFilterMessageMethod.Invoke(null, new object[] { hwnd, msg, wParam, lParam, handled }); }private static IntPtr FilteredSystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {if (msg == ThemeChangedMessage) return IntPtr.Zero; return InvokeSystemThemeFilterMessage(hwnd, msg, wParam, lParam, handled); }}</pre><p>What a mess! What&#8217;s really annoying is that this entire process could have (and, I argue, should have) been made public to user code. In the very least, I&#8217;d like to be able to decorate my assembly with an attribute declaring which theme I&#8217;d like to run under, but I think it&#8217;s completely reasonable to have an public static class provide the same API I have here.</p><p>The whole test suite is available <del><a href="http://northhorizon.net/wp-content/uploads/2010/12/SystemThemeChangeTest.zip">here</a></del> on <a href="https://github.com/danielmoore/SystemThemeChange">GitHub</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		</item>
		<item>
			<title>Interview with Kalani Thielen: Trends in Programming Languages</title>
			<link>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/</link>
			<comments>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/#comments</comments>
			<pubDate>Mon, 27 Sep 2010 13:30:45 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Cayenne]]></category>
			<category><![CDATA[Clojure]]></category>
			<category><![CDATA[DSLs]]></category>
			<category><![CDATA[Epigram]]></category>
			<category><![CDATA[F#]]></category>
			<category><![CDATA[Haskell]]></category>
			<category><![CDATA[Kalani Thielen]]></category>
			<category><![CDATA[Lisp]]></category>
			<category><![CDATA[OCaml]]></category>
			<category><![CDATA[Python]]></category>
			<category><![CDATA[Ruby]]></category>
			<category><![CDATA[Scala]]></category>
			<category><![CDATA[Scheme]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=358</guid>
			<description><![CDATA[Last week I interviewed colleague Kalani Thielen, Lab49&#8242;s resident expert on programming language theory. We discussed some of the new languages we&#8217;ve seen this decade, the recent functional additions to imperative languages, and the role DSLs will play in the future. Read on for the full interview. DM F#, Clojure, and Scala are all fairly [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I interviewed colleague <a href="http://blog.lab49.com/archives/author/kthielen">Kalani Thielen</a>, Lab49&#8242;s resident expert on programming language theory. We discussed some of the new languages we&#8217;ve seen this decade, the recent functional additions to imperative languages, and the role DSLs will play in the future. Read on for the full interview.<span id="more-358"></span></p><p><strong>DM</strong> F#, Clojure, and Scala are all fairly new and popular languages this decade, the former two with striking resemblance to OCaml and Lisp, respectively, and the lattermost being more original in syntax. In what way do these languages represent forward thinking in language design, or how do they fail to build upon lessons learned in more venerable languages like Haskell?</p><p><strong>KT</strong> It’s a common story in the world of software that time brings increasingly precise and accurate programs.  Anybody who grew up playing games on an Atari 2600 has witnessed this firsthand.  The image of a character has changed from one block, to five blocks, to fifty blocks, to (eventually) thousands of polygons.  By this modern analog of the Greeks’ method of exhaustion, Mario’s facial structure has become increasingly clear.  This inevitable progression, squeezed out between the increasing sophistication of programmers and the decreasing punishment of Moore’s Law, has primarily operated at three levels: the images produced by game programs, the logic of the game programs themselves, and finally the programming languages with which programs are produced.  It’s this last group that deserves special attention today.</p><p>The lambda calculus (and its myriad derivatives) exemplifies this progression at the level of programming languages.  In the broadest terms, you have the untyped lambda calculus at the least-defined end (which closely fits languages like Lisp, Scheme, Clojure, Ruby and Python), and the calculus of constructions at the most-defined end (which closely fits languages like Cayenne and Epigram).  With the least imposed structure, you can’t solve the halting problem, and with the most imposed structure you (trivially) can solve it.  With the language of the untyped lambda calculus, you get a blocky, imprecise image of what your program does, and in the calculus of constructions you get a crisp, precise image.</p><p>Languages like F#, Scala and Haskell each fall somewhere in between these two extremes.  None of them are precise enough to accept only halting programs (although Haskell is inching more and more toward a dependently-typed language every year).  Yet all of them are more precise than (say) Scheme, where fallible human convention alone determines whether or not the “+” function returns an integer or a chicken.  But even between these languages there is a gulf of expressiveness.  Where a language like C is monomorphically-typed (and an “int_list” must remain ever distinguished from a “char_list”), F# introduces principled polymorphic types (where, pun intended, you can have “’a list” for any type ‘a).  Beyond that, Haskell (and Scala) offer bounded polymorphism so that constraints can be imposed (or inferred) on any polymorphic type – you can correctly identify the “==” function as having type “Eq a =&gt; a -&gt; a -&gt; Bool” so that equality can be determined only on those types which have an equivalence relation, whereas F# has to make do with the imprecise claim that its “=” function can compare any types.</p><p>No modern programming language is perfect, but the problems that we face today and the history of our industry points the way toward ever more precise languages.  Logic, unreasonably effective in the field of computer science, has already set the ideal that we’re working toward.  Although today you might hear talk that referential transparency in functional languages makes a parallel map safe, tomorrow it will be that a type-level proof of associativity makes a parallel <em>reduce</em> safe.  Until then, it’s worth learning Haskell (or Scala if you must), where you can count the metaphorical fingers on Mario’s hands, though not yet the hairs of his moustache.</p><p><strong>DM</strong> One might assume that increased &#8220;precision&#8221; in a language would come at the cost of increased complexity in concepts and/or syntax. In a research scenario, the ability to solve the halting problem certainly has its merits, but is that useful for modern commercial application development, and, if so, does it justify the steeper learning curve?</p><p><strong>KT</strong> It&#8217;s absolutely true that languages that can express concepts more precisely also impose a burden on programmers, and that a major part of work in language design goes into making that burden as light as possible (hence type-inference, auto roll/unroll for recursive types, pack/unpack for existential types, etc).</p><p>However &#8212; to your point about the value of that increased precision – I would argue that it&#8217;s even <em>more</em> important in commercial application development than in academia.  For example, say you&#8217;ve just rolled out a new pricing server for a major client.  Does it halt?  There&#8217;s a lot more riding on that answer than you&#8217;re likely to find in academia.  And really, whether or not it halts is just one of the simplest questions you can ask.  What are its time/space characteristics?  Can it safely be run in parallel?  Is it monotonic?  In our business, these questions translate into dollars and reputation.  Frankly I think it&#8217;s amazing that we&#8217;ve managed to go on this long without formal verification.</p><p><strong>DM</strong> Most dynamic languages have some air of functional programming to them, while still being fundamentally imperative. Even more rigorous imperative languages like C# are picking up on a more functional style of programming. The two languages you mentioned earlier, Cayenne and Epigram, are both functional languages. Are we moving toward a pure functional paradigm, or will there continue to be a need for imperative/functional hybrids?</p><p><strong>KT</strong> What is a &#8220;functional language&#8221;?  If it&#8217;s a language with first-class functions, then C is a functional language.  If it&#8217;s a language that disallows hidden side-effects, then Haskell isn&#8217;t a functional language.  I think that, at least as far as discussing the design and development of programming languages is concerned, it&#8217;s well worth getting past that sort of &#8220;sales pitch&#8221;.</p><p>I believe that we&#8217;re moving toward programming languages that allow programmers to be increasingly precise about what their programs are supposed to do, up to the level of detail necessary.  The great thing about referential transparency is that it makes it very easy to reason about what a function does &#8212; it&#8217;s almost as easy as high school algebra.  However, if you&#8217;re not engaged in computational geometry, but rather need to transfer some files via FTP, there&#8217;s just no way around it.  You&#8217;ve got to do this, then this, then this, and you&#8217;ll need to switch to something more complicated, like Hoare logic, to reason about what your program is doing.  Even there, you have plenty of opportunity for precision &#8212; you expect to use hidden side-effects but only of a certain type (transfer files but don&#8217;t launch missiles).</p><p>But maybe the most important tool in programming is logic itself.  It&#8217;s a fundamental fact – well known in some circles as the &#8220;Curry-Howard isomorphism&#8221; – that programs and proofs are equivalent in a very subtle and profound way.  This fact has produced great wealth for CS researchers, who can take the results painstakingly derived by logicians 100 years ago and (almost mechanically) publish an outline of their computational analog.  Yet, although this amazing synthesis has taken place rivaling the unification of electricity and magnetism, most programmers in industry are scarcely aware of it.  It&#8217;s going to take some time.</p><p>I think there&#8217;s a good answer to your question in that correspondence between logic and programming.  The function, or &#8220;implication connective&#8221; (aka &#8220;-&gt;&#8221;), is an important tool and ought to feature in any modern language.  As well, there are other logical connectives that should be examined.  For example, conjunction is common (manifested as pair, tuple, or record types in a programming language), but disjunction (corresponding to variant types) is less common though no less important.  Negation (corresponding to continuations consuming the negated type), predicated quantified types, and so on.  The tools for building better software are there, but we need to work at recognizing them and putting them to good use.</p><p>Anybody interested in understanding these logical tools better should pick up a copy of Benjamin Pierce&#8217;s book<em> Types and Programming Languages</em>.</p><p><strong>DM </strong>Many frameworks have a one or more DSLs to express things as mundane as configuration to tasks as complicated as UI layout, in an effort to be more express specific kinds of ideas more concisely. Do you see this as an expanding part of the strategy for language designers to increase expressiveness in code? Is it possible that what we consider &#8220;general purpose languages&#8221; today will become more focused on marshalling data from one DSL to another, or will DSLs continue to remain a more niche tool?</p><p><strong>KT</strong> I guess it depends on what you mean by &#8220;DSL&#8221;.  Like you say, some people just have in mind some convenient shorthand serialization for data structures (I&#8217;ve heard some people refer to a text format for orders as a DSL, for example).  I&#8217;m sure that will always be around, and there&#8217;s nothing really profound about it.</p><p>On the other hand, by &#8220;DSL&#8221; you could mean some sub-Turing language with non-trivial semantics.  For example, context-free grammars or makefiles.  Modern programming languages, like Haskell, are often used to embed these &#8220;sub-languages&#8221; as combinator libraries (the &#8220;Composing Contracts&#8221; paper by Simon Peyton-Jones et al is a good example of this).  I think it&#8217;s likely that these will continue as valuable niche tools.  If you take monadic parser combinators for example, it&#8217;s very attractive the way that they fit together within the normal semantics of Haskell, however you&#8217;ve got to go through some severe mental gymnastics to determine for certain what the space/time characteristics of a given parser will be.  Contrast that with good old LALR(1) parsers, where if the LR table can be derived you know for certain what the space/time characteristics of your parser will be.</p><p>On the third hand, if a &#8220;DSL&#8221; is a data structure with semantics of any kind, your description of a future where programs are written as transformations between DSLs could reasonably describe the way that compilers are written today.  Generally a compiler is just a sequence of semantics-preserving transformations between data structures (up to assembly statements).  I happen to think that&#8217;s a great way to write software, so I hope it&#8217;s the case that it will become ever more successful.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		</item>
		<item>
			<title>The Value of Experience</title>
			<link>http://northhorizon.net/2010/the-value-of-experience/</link>
			<comments>http://northhorizon.net/2010/the-value-of-experience/#comments</comments>
			<pubDate>Thu, 09 Sep 2010 14:00:25 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[hiring]]></category>
			<category><![CDATA[résumé]]></category>
			<category><![CDATA[skill]]></category>
			<category><![CDATA[StackOverflow]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=348</guid>
			<description><![CDATA[I was reading a blog post by my colleague Doug Finke in reference to a &#8220;programmer competency matrix&#8221; by Sijin Joseph. I took a look at the matrix and it seemed like a set of pretty reasonable benchmarks for a programmer&#8217;s growth. My only reservation with the chart was that they claim that you need [...]]]></description>
			<content:encoded><![CDATA[<p>I was reading <a href="http://www.dougfinke.com/blog/index.php/2010/09/06/programmer-competency-matrix/">a blog post</a> by my colleague Doug Finke in reference to a &#8220;<a href="http://www.indiangeek.net/wp-content/uploads/Programmer%20competency%20matrix.htm">programmer competency matrix</a>&#8221; by <a href="http://www.indiangeek.net/">Sijin Joseph</a>. I took a look at the matrix and it seemed like a set of pretty reasonable benchmarks for a programmer&#8217;s growth. My only reservation with the chart was that they claim that you need a certain number of years experience under your belt to be a certain grade of programmer. Here&#8217;s Sijin&#8217;s criteria:</p><ul><li><strong>Level 0:</strong> 1 year</li><li><strong>Level 1:</strong> 2-5 years</li><li><strong>Level 2:</strong> 6-9 years</li><li><strong>Level 3:</strong> 10+ years</li></ul><p>To be perfectly honest, I find the entire idea reprehensible. According to this matrix, nobody could be considered an &#8220;expert&#8221; programmer in C#, since the language has only been around since 2001. I&#8217;m not breaking the news to Anders. Ok, maybe that&#8217;s a bit of a &#8220;gotcha&#8221; exception, but I think the entire idea can&#8217;t hold water. The problem with the assertion is that it assumes that all years are equal in quality. There&#8217;s no comparison between a year in a challenging company on the cutting edge of your technology field working with the leaders in industry and a year making small changes to an enterprise CMS. No offense to the latter group, but it&#8217;s just the ugly truth.<span id="more-348"></span></p><p>What really bothers me is that this kind of fallacy isn&#8217;t limited to a few people, but, as I&#8217;m sure we all know, almost every employer has some kind of experience requirement in strict years. In fact, one employer I was looking at after graduation actually wanted candidates to have experience with C# since day 1, according to the advertisement. We, as an industry, have got to dispel the myth of causation (and even really correlation) between years experience and skill in development. Basing our recruitment standards on this primitive metric only encourages age-warfare, not unlike a number of discussions I&#8217;ve seen on Slashdot, with the younger programmers calling older ones &#8220;set in their ways,&#8221; and the older programmers calling younger guys &#8220;re-creators of the wheel in their inexperience.&#8221; It&#8217;s got to stop. We have to gather together and celebrate knowledge in our field and, in turn, work to better everyone in our technical community.</p><p>This is what I think makes Lab49 recruitment so effective: we don&#8217;t predicate someone&#8217;s candidacy on experience. Don&#8217;t have a degree in computer science or software engineering? Doesn&#8217;t matter. Don&#8217;t have ten years experience in software? So what? What matters is that you are skilled in your technology, be it C#, Flex, Java, or C++, and you&#8217;re someone who works well on a team. When you think about it, this is just good business. Who cares about someone&#8217;s pedigree? We&#8217;re in the business of creating effective software solutions, not showing off our employees&#8217; education and past merits.</p><p>I think moving beyond simply removing the years experience criterion, résumés are <a href="http://www.slate.com/id/2265202/">becoming more and more deprecated</a>. It&#8217;s not because people don&#8217;t have significant accomplishments that are noteworthy, but rather that people use ambiguous language, and even outright lies on their résumés in a desperate attempt to be hired for a job for which they&#8217;re not qualified, and for every gem in a stack of résumés, there&#8217;s a lot of rocks. This is where the community steps in. People involved in their local technology meet ups and people involved in online communities like StackOverflow show their skill on a regular basis, and it&#8217;s much harder to BS someone, especially if they start asking questions.</p><p>Over the next few years I suspect we&#8217;ll start seeing a paradigm shift in the way employers find talent. I won&#8217;t prognosticate that StackOverflow and its careers division will be the future, but I&#8217;m willing to be it&#8217;s going to have a hand in it, at least. The change in talent-hunting strategy, I think, is just one facet of a larger shift in our industry towards building communities. It&#8217;s already underway, so all we have to do now is embrace the change and jump in.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/the-value-of-experience/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>Alpha-Blending Colors in PowerShell</title>
			<link>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/</link>
			<comments>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/#comments</comments>
			<pubDate>Sun, 22 Aug 2010 19:40:07 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[colors]]></category>
			<category><![CDATA[pipelining]]></category>
			<category><![CDATA[powershell]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=299</guid>
			<description><![CDATA[The other day I was given the task of converting a particularly poorly designed VisualBrush into a LinearGradientBrush. One of the problems I came across very quickly was the use of semi-transparent colors layered on top of each other, and, of course, I needed a &#8220;flattened&#8221; color for my GradientStop. Now, I could have used [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was given the task of converting a particularly poorly designed VisualBrush into a LinearGradientBrush. One of the problems I came across very quickly was the use of semi-transparent colors layered on top of each other, and, of course, I needed a &#8220;flattened&#8221; color for my GradientStop. Now, I could have used Paint.NET or GIMP or Photoshop to put out a couple layers of colors, set the transparencies and used the color dropper to get the result. Of course, since I&#8217;m not a designer, I don&#8217;t have any of those things installed on my work computer, so I decided to just find the equation to blend the channels myself. It didn&#8217;t take long, and Wikipedia delivered the goods. According to <a href="http://en.wikipedia.org/wiki/Alpha_compositing" title="Alpha_compositing" >the article</a>, the formula to merge two colors, <img src='http://s.wordpress.com/latex.php?latex=C_a&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_a' title='C_a' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=C_b&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_b' title='C_b' class='latex' />, into some output color, <img src='http://s.wordpress.com/latex.php?latex=C_o&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_o' title='C_o' class='latex' />, looks like this:</p><p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=C_o%20%3D%20C_a%5Calpha_a%2BC_b%5Calpha_b%281-%5Calpha_a%29&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_o = C_a\alpha_a+C_b\alpha_b(1-\alpha_a)' title='C_o = C_a\alpha_a+C_b\alpha_b(1-\alpha_a)' class='latex' /></p><p>Since a color can be thought of as a three-tuple of its R, G, and B channels, the formula is easily distributed to each of these values.</p><p>At this point, I decided I could probably just pull out a calculator and crunch the numbers. But maybe, in about the same time, I could also whip something together, say in PowerShell, to do it for me. Since I&#8217;m still learning PowerShell, I figured the learning experience would be worth at least something.<span id="more-299"></span></p><p>So the first thing I needed was the ability to parse an ARGB hex code into a hashtable with each channel separated out. Here&#8217;s what I got.</p><pre class="brush: powershell">function Blend-Colors ([string[]] $colors) {# $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#' # and assign them to groups named a, r, g, and b for each channel, respectively. $argbHexColorRegex = "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$" foreach($colorHex in $colors) {if($colorHex -match $argbHexColorRegex) {$color = @{ a = [int]::Parse($matches.a, 'AllowHexSpecifier') r = [int]::Parse($matches.r, 'AllowHexSpecifier'); g = [int]::Parse($matches.g, 'AllowHexSpecifier'); b = [int]::Parse($matches.b, 'AllowHexSpecifier'); }$color | ft } else {throw "Invalid color: $colorHex" }} }</pre><p>Ok, not too shabby. If you&#8217;re wondering where <code>$matches</code> came from, as a side effect of the <code>-match</code> operation, the <code>$matches</code> hashtable is set with all the matched groups defined. I just prefer to use the object syntax in this case over the index syntax.</p><p>So, I&#8217;m not real happy with the amount of repetition going on in the assignment of my hashtable. My first attempt to clean it up looked like this:</p><pre class="brush: powershell; gutter: false">$color = ('a','r','g','b') | % { @{ $_ = [int]::Parse($matches.$_, 'AllowHexSpecifier') } }</pre><p>But that just gave me an array of hashtables with one attribute in each. I asked <a href="http://www.dougfinke.com/">Doug Finke</a> what he thought and he recommended this modification:</p><pre class="brush: powershell; gutter: false">('a','r','g','b') | % { $color = @{} } { $color.$_ = [int]::Parse($matches.$_, 'AllowHexSpecifier') }</pre><p>Cool! It seems a little obvious now, though.</p><p>Next on the agenda was to translate the blending equation into PowerShell. Since the equation is a little more involved, I decided to abstract it out into a subfunction like so:</p><pre class="brush: powershell">function Merge-Channel ($c0, $c1, $c) {$a0 = $c0.a / 255 $a1 = $c1.a / 255 return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0) }</pre><p><code>$c0</code> and <code>$c1</code> are color hashtables and <code>$c</code> is the name of the channel to blend. I had to divide the alpha channels by 255 to produce a value compatible with the equation, namely, between 0 and 1.</p><p>The reason I chose to accept the entire color and desired channel, rather than a more terse definition accepting the specific channel values and related alpha values was to make calling the code a little more elegant:</p><pre class="brush: powershell; gutter: false">('r','g','b') | % `{ $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `{ $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }</pre><p>When blending, the alpha channels simply sum, so I put that in my hashtable initializer and just iterated over the color channels.</p><p>Now the final step is to return our value back in hex form. Fortunately, the formatting styles for <code>int</code> make this really easy:</p><pre class="brush: powershell; gutter: false">return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f (('a','r','g','b') | % { [int][Math]::Round($baseColor.$_, 0) })</pre><p>I&#8217;m rounding to ensure the highest accuracy to the blended color, as opposed to simply truncating.</p><p>Putting it all together, I decided to create two array constants, <code>$argb</code> and <code>$rgb</code> to alias arrays of the channels. While I was at it, I also promoted my <code>$argbHexColorRegex</code> to a constant just for good measure. Finally, I made the base color white, so there would be something to blend against. The result looks like this:</p><pre class="brush: powershell">function Blend-Colors ([Parameter(Mandatory=$true)] [string[]] $colors) {# $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#' # and assign them to groups named a, r, g, and b for each channel, respectively. Set-Variable argbHexColorRegex -Option Constant `-Value "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$" Set-Variable argb -Option Constant -Value 'a','r','g','b' Set-Variable rgb -Option Constant -Value 'r','g','b' function Merge-Channel ($c0, $c1, $c) {$a0 = $c0.a / 255 $a1 = $c1.a / 255 return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0) }$argb | % { $outColor = @{} } { $outColor.$_ = 255 } # set $outColor to white (#FFFFFFFF) foreach($color in $colors) {if(-not ($color -match $argbHexColorRegex)) {throw "Invalid color: $color" }$argb | % { $addColor = @{} } { $addColor.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }$rgb | % `{ $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `{ $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }$outColor = $mergeColor }return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f ($argb | % { [int][Math]::Round($outColor.$_, 0) }) }</pre><p>This is looking really good, and, really, I might have just stopped here. The only things I was missing at this point were pipelining and documentation, and since my solution had become completely over-engineered as it was, I decided I  might as well go for broke.</p><p>The first thing I wanted to do was abstract out my initialization of <code>$outColor</code> to a parameter. Since I&#8217;d have to parse the string, I&#8217;d also need to abstract my color hex parser.</p><pre class="brush: powershell">function Parse-Color ([string] $hex) {if($hex -match $argbHexColorRegex) {$argb | % { $color = @{} } { $color.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }return $color; } else {return $null; }}</pre><p>The reason I decided to return null instead of throwing an error immediately is because I wanted to treat errors differently in both places. Specifically, if an invalid string is passed in to the <code>-background</code>, I want to throw an argument exception, and if something invalid comes in over the pipeline, I just want to write the error to the error output and keep on trucking.</p><p>I tried a few <a href="http://huddledmasses.org/writing-better-script-functions-for-the-powershell-pipeline/">different approaches</a> to being able to both accept input over the parameter list and I finally found out about <code>[Parameter(ValueFromPipeline=$true)]</code>. Here is my test setup:</p><pre class="brush: powershell">function Get-Range([int]$max) {for($i=0; $i -lt $max; $i++) {Write-Host "pushing $i to pipeline" Write-Output $i }} function Test-Pipeline([Parameter(ValueFromPipeline=$true)][int[]]$vals = $null) {process {foreach($item in @($vals)){ Write-Host "processing $item from pipeline" }} }</pre><p>And my test output:</p><pre class="brush: plain; gutter: false">&gt; Get-Range 3 | Test-Pipeline pushing 0 to pipeline processing 0 from pipeline pushing 1 to pipeline processing 1 from pipeline pushing 2 to pipeline &gt; Test-Pipeline ('1','2','3') processing 1 from pipeline processing 2 from pipeline processing 3 from pipeline</pre><p>Notice the <code>@($vals)</code> in my <code>foreach</code>? That&#8217;s to protect against null inputs by ensuring <code>$vals</code> is a list.</p><p>Now that I&#8217;ve got all my pieces together, I just need to put everything in place with a splash of <a href="http://technet.microsoft.com/en-us/magazine/ff458353.aspx">documentation</a>.</p><pre class="brush: powershell">&lt;# .SYNOPSIS Takes a list of ARGB hex values and blends them in order against a specified background. .PARAMETER background The background color to blend against, defaults to white. .PARAMETER colors A list of ARGB hex color strings, can be pushed from the pipeline. .EXAMPLE Blend-Colors '#ff121212', '#705F6A87' .LINK http://en.wikipedia.org/wiki/Alpha_compositing #&gt; function Blend-Colors ([string] $background = '#FFFFFFFF', [Parameter(ValueFromPipeline = $true)] [string[]] $colors = $null) {begin {# $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#' # and assign them to groups named a, r, g, and b for each channel, respectively. Set-Variable argbHexColorRegex -Option Constant `-Value "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$" Set-Variable argb -Option Constant -Value 'a','r','g','b' Set-Variable rgb -Option Constant -Value 'r','g','b' function Parse-Color ([string] $hex) {if($hex -match $argbHexColorRegex) {$argb | % { $color = @{} } { $color.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }return $color; } else {return $null; }} function Merge-Channel ($c0, $c1, $c) {$a0 = $c0.a / 255 $a1 = $c1.a / 255 return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0) }$outColor = Parse-Color $background if(-not $outColor) {throw (New-Object ArgumentException -ArgumentList "Invalid color: '$background'", 'background') }} process {foreach($color in @($colors)){ $addColor = Parse-Color $color if(-not $addColor) {Write-Error "Invalid input color: $_" break }$rgb | % `{ $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `{ $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }$outColor = $mergeColor }} end {return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f ($argb | % { [int][Math]::Round($outColor.$_, 0) }) }}</pre><p>Now all you have to do is save it in %userprofile%\My Documents\WindowsPowerShell\Modules\UITools as UITools.psm1 and call <code>Import-Module UITools</code> to bring in this function.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
