<?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 &#187; C#</title>
		<atom:link href="http://northhorizon.net/tag/c/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>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 Extension Method Pack</title>
			<link>http://northhorizon.net/2010/the-extension-method-pack/</link>
			<comments>http://northhorizon.net/2010/the-extension-method-pack/#comments</comments>
			<pubDate>Thu, 27 May 2010 12:19:26 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Dependency Object]]></category>
			<category><![CDATA[Extension Methods]]></category>
			<category><![CDATA[Hash Table]]></category>
			<category><![CDATA[Lambda]]></category>
			<category><![CDATA[WPF]]></category>
			<category><![CDATA[XMP]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=220</guid>
			<description><![CDATA[Since .NET 3.0 came out, I&#8217;ve been enjoying taking advantage of extension methods and the ability to create my own. The thing I&#8217;ve noticed is that a handful of them are useful to almost any application, above and beyond what Microsoft provides in System.Linq. So over the last few days I took the time to [...]]]></description>
			<content:encoded><![CDATA[<p>Since .NET 3.0 came out, I&#8217;ve been enjoying taking advantage of extension methods and the ability to create my own. The thing I&#8217;ve noticed is that a handful of them are useful to almost any application, above and beyond what Microsoft provides in <code>System.Linq</code>. So over the last few days I took the time to gather these methods together, unit test them, and run them through FXCop to make a high-quality package ready to go in any application with a little re-namespacing.</p><p>I&#8217;ve broken each code sample into independent blocks wherein all necessary dependencies are contained, so you can take any extension method <em>a la carte</em> or you can get everything from the <a href="http://northhorizon.net/wp-content/uploads/2010/05/Extension-Method-Pack.zip">attached zip file</a>. My solution was built in .NET 4.0 in Visual Studio 2010, but everything should work just fine in .NET 3.5 with Visual Studio 2008.</p><p>Also included in the zip file are my unit tests, which may help you understand usage of some of the more esoteric extensions, such as ChainGet, and XML comments for your IntelliSense and XML documentation generator.</p><p><strong>Edit:</strong> The whole solution is now available on <a href="https://github.com/danielmoore/Extension-Method-Pack">github</a>!</p><p><span id="more-220"></span></p><p>Here&#8217;s the table of contents, so you can jump around more easily:<br /><a name="toc"></a></p><ul><li>IEnumerable<ul><li><a href="#IEnumerable.Foreach">ForEach</a></li><li><a href="#IEnumerable.Append">Append</a></li><li><a href="#IEnumerable.Prepend">Prepend</a></li><li><a href="#IEnumerable.AsObservable">AsObservable</a></li><li><a href="#IEnumerable.AsHashSet">AsHashSet</a></li><li><a href="#IEnumerable.ArgMax">ArgMax</a></li><li><a href="#IEnumerable.ArgMin">ArgMin</a></li></ul></li><li>ICollection<ul><li><a href="#ICollection.AddAll">AddAll</a></li><li><a href="#ICollection.RemoveAll">RemoveAll</a></li></ul></li><li>IDictionary<ul><li><a href="#IDictionary.Add">Add</a></li><li><a href="#IDictionary.AddAll">AddAll</a></li><li><a href="#IDictionary.Remove">Remove</a></li><li><a href="#IDictionary.RemoveAll">RemoveAll</a></li><li><a href="#IDictionary.RemoveAndClean">RemoveAndClean</a></li><li><a href="#IDictionary.RemoveAllAndClean">RemoveAllAndClean</a></li><li><a href="#IDictionary.Clean">Clean</a></li></ul></li><li>Object<ul><li><a href="#Object.As">As</a></li><li><a href="#Object.AsValueType">AsValueType</a></li><li><a href="#Object.ChainGet">ChainGet</a></li></ul></li><li>DependencyObject<ul><li><a href="#DependencyObject.SafeGetValue">SafeGetValue</a></li><li><a href="#DependencyObject.SafeSetValue">SafeSetValue</a></li></ul></li></ul><h2>IEnumerable</h2><p><a name="IEnumerable.ForEach"></a><code>ForEach</code> is pretty straightforward. It mimics <code>List&lt;T&gt;.ForEach</code>, but for all <code>IEnumerable</code>, both generic and weakly typed.</p><pre class="brush: csharp">public static void ForEach&lt;T&gt;( this IEnumerable&lt;T&gt; collection, Action&lt;T&gt; action) {if (collection == null) throw new ArgumentNullException("collection"); if (action == null) throw new ArgumentNullException("action"); foreach (var item in collection) action(item); }</pre><pre class="brush: csharp">public static void ForEach( this IEnumerable collection, Action&lt;object&gt; action) {if (collection == null) throw new ArgumentNullException("collection"); if (action == null) throw new ArgumentNullException("action"); foreach (var item in collection) action(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.Append"></a><a name="IEnumerable.Prepend"></a><code>Append</code> and <code>Prepend</code> simply take an item and return a a new <code>IEnumerable&lt;T&gt;</code> with that item on the end or beginning, respectively. <code>Prepend</code> is the equivalent of the <code><a href="http://en.wikipedia.org/wiki/cons" title="cons" >cons</a></code> operation to a list.</p><pre class="brush: csharp">public static IEnumerable&lt;T&gt; Append&lt;T&gt;( this IEnumerable&lt;T&gt; collection, T item) {if (collection == null) throw new ArgumentNullException("collection"); if (item == null) throw new ArgumentNullException("item"); foreach (var colItem in collection) yield return colItem; yield return item; }</pre><pre class="brush: csharp">public static IEnumerable&lt;T&gt; Prepend&lt;T&gt;( this IEnumerable&lt;T&gt; collection, T item) {if (collection == null) throw new ArgumentNullException("collection"); if (item == null) throw new ArgumentNullException("item"); yield return item; foreach (var colItem in collection) yield return colItem; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.AsObservable"></a><a name="IEnumerable.AsHashSet"></a><code>AsObservable</code> and <code>AsHashSet</code> yield their respective data structures, but check to see if they are already what you want, saving valuable time when dealing with interfaces.</p><pre class="brush: csharp">public static ObservableCollection&lt;T&gt; AsObservable&lt;T&gt;( this IEnumerable&lt;T&gt; collection) {if (collection == null) throw new ArgumentNullException("collection"); return collection as ObservableCollection&lt;T&gt; ?? new ObservableCollection&lt;T&gt;(collection); }</pre><pre class="brush: csharp">public static HashSet&lt;T&gt; AsHashSet&lt;T&gt;(this IEnumerable&lt;T&gt; collection) {if (collection == null) throw new ArgumentNullException("collection"); return collection as HashSet&lt;T&gt; ?? new HashSet&lt;T&gt;(collection); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.ArgMax"></a><a name="IEnumerable.ArgMin"></a><code><a href="http://en.wikipedia.org/wiki/Arg max" title="Arg max" >ArgMax</a></code> and <code>ArgMin</code> are corollaries to <code>Max</code> and <code>Min</code> in the <code>System.Linq</code> namespace, but return the item in the list that produced the highest value from <code>Max</code> or least value from <code>Min</code>, respectively.</p><pre class="brush: csharp">public static T ArgMax&lt;T, TValue&gt;( this IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function) where TValue : IComparable&lt;TValue&gt; {return ArgComp(collection, function, GreaterThan); }private static bool GreaterThan&lt;T&gt;(T first, T second) where T : IComparable&lt;T&gt; {return first.CompareTo(second) &gt; 0; }public static T ArgMin&lt;T, TValue&gt;( this IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function) where TValue : IComparable&lt;TValue&gt; {return ArgComp(collection, function, LessThan); }private static bool LessThan&lt;T&gt;(T first, T second) where T : IComparable&lt;T&gt; {return first.CompareTo(second) &lt; 0; }private static T ArgComp&lt;T, TValue&gt;( IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function, Func&lt;TValue, TValue, bool&gt; accept) where TValue : IComparable&lt;TValue&gt; {if (collection == null) throw new ArgumentNullException("collection"); if (function == null) throw new ArgumentNullException("function"); var isSet = false; var maxArg = default(T); var maxValue = default(TValue); foreach (var item in collection) {var value = function(item); if (!isSet || accept(value, maxValue)) {maxArg = item; maxValue = value; isSet = true; }} return maxArg; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>ICollection</h2><p><a name="ICollection.AddAll"></a><code>AddAll</code> imitates <code>List&lt;T&gt;.AddRange</code>.</p><pre class="brush: csharp">public static void AddAll&lt;T&gt;( this ICollection&lt;T&gt; collection, IEnumerable&lt;T&gt; additions) {if (collection == null) throw new ArgumentNullException("collection"); if (additions == null) throw new ArgumentNullException("additions"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); foreach (var item in additions) collection.Add(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="ICollection.RemoveAll"></a><code>RemoveAll</code> imitates <code>List&lt;T&gt;.RemoveAll</code>. A second overload allows you to specify the removals if you already have them.</p><pre class="brush: csharp">public static IEnumerable&lt;T&gt; RemoveAll&lt;T&gt;( this ICollection&lt;T&gt; collection, Predicate&lt;T&gt; predicate) {if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); // we can't possibly remove more than the entire list. var removals = new List&lt;T&gt;(collection.Count); // this is an O(n + m * k) operation where n is collection.Count, // m is removals.Count, and K is the removal operation time. Because // we know n &gt;= m, this is an O(n + n * k) operation or just O(n * k). foreach (var item in collection) if (predicate(item)) removals.Add(item); foreach (var item in removals) collection.Remove(item); return removals; }</pre><pre class="brush: csharp">public static void RemoveAll&lt;T&gt;( this ICollection&lt;T&gt; collection, IEnumerable&lt;T&gt; removals) {if (collection == null) throw new ArgumentNullException("collection"); if (removals == null) throw new ArgumentNullException("removals"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); foreach (var item in removals) collection.Remove(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>IDictionary</h2><p>All of these methods have to do with <a href="http://en.wikipedia.org/wiki/Hash table" title="Hash table" >hash tables</a>. I use them pretty frequently and these methods are able to make life a lot easier.</p><p><a name="IDictionary.Add"></a><a name="IDictionary.AddAll"></a><code>Add</code> and <code>AddAll</code> insert the key and a new collection into the dictionary if the key doesn&#8217;t already exist and then adds the item or items to the collection.</p><pre class="brush: csharp">public static void Add&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt;, new() {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) {if (col.IsReadOnly) throw new InvalidOperationException("bucket is read only"); }else dictionary.Add(key, col = new TCol()); col.Add(item); }</pre><pre class="brush: csharp">public static void AddAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; additions) where TCol : ICollection&lt;TItem&gt;, new() {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (additions == null) throw new ArgumentNullException("additions"); TCol col; if (!dictionary.TryGetValue(key, out col)) dictionary.Add(key, col = new TCol()); foreach (var item in additions) col.Add(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.Remove"></a><a name="IDictionary.RemoveAll"></a><code>Remove</code> and <code>RemoveAll</code> simply remove items from the collection associated with the specified key, if there is one. For the predicate overloads, you need to explicitly construct your <code>Predicate&lt;T&gt;</code> delegate because the C# compiler has trouble doing the type inference.</p><pre class="brush: csharp">public static void Remove&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) col.Remove(item); }</pre><pre class="brush: csharp">public static void RemoveAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; removals) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (removals == null) throw new ArgumentNullException("removals"); TCol col; if (dictionary.TryGetValue(key, out col)) foreach (var item in removals) col.Remove(item); }</pre><pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, Predicate&lt;TItem&gt; predicate) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (predicate == null) throw new ArgumentNullException("predicate"); var removals = new List&lt;TItem&gt;(); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in col) if (predicate(item)) removals.Add(item); foreach (var item in removals) col.Remove(item); }return removals; }// Usage: Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary; myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.RemoveAndClean"></a><a name="IDictionary.RemoveAllAndClean"></a><code>RemoveAndClean</code> and <code>RemoveAllAndClean</code> both remove items from the collection associated with the specified key and if the resulting collection is empty, they remove the key from the dictionary as well. These come in both predicate and list forms.</p><pre class="brush: csharp">public static void RemoveAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) {col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }}</pre><pre class="brush: csharp">public static void RemoveAllAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; removals) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (removals == null) throw new ArgumentNullException("removals"); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in removals) col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }}</pre><pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAllAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, Predicate&lt;TItem&gt; predicate) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (predicate == null) throw new ArgumentNullException("predicate"); var removals = new List&lt;TItem&gt;(); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in col) if (predicate(item)) removals.Add(item); foreach (var item in removals) col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }return removals; }// Usage: Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary; myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.Clean"></a><code>Clean</code> simply goes through all the keys and removes entries with empty collections.</p><pre class="brush: csharp">public static void Clean&lt;TKey, TCol&gt;(this IDictionary&lt;TKey, TCol&gt; dictionary) where TCol : ICollection {if (dictionary == null) throw new ArgumentNullException("dictionary"); var keys = dictionary.Keys.ToList(); foreach (var key in keys) if (dictionary[key].Count == 0) dictionary.Remove(key); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>Object</h2><p><a name="Object.As"></a>As casts an object to a specified type, executes an action with it, and returns whether or not the cast was successful.</p><pre class="brush: csharp">public static bool As&lt;T&gt;(this object obj, Action&lt;T&gt; action) where T : class {if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); var target = obj as T; if (target == null) return false; action(target); return true; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="Object.AsValueType"></a><code>AsValueType</code> does the same thing as <code>As</code>, but for value types.</p><pre class="brush: csharp">public static bool AsValueType&lt;T&gt;(this object obj, Action&lt;T&gt; action) where T : struct {if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); if (obj is T) {action((T)obj); return true; }return false; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="Object.ChainGet"></a><code>ChainGet</code> attempts to resolve a chain of member accesses and returns the result or <code>default(TValue)</code>. Since <code>TValue</code> could be a value type, there is also an overload that has an out parameter indicating whether the value was obtained.</p><p>Be careful with this extension. Since it uses reflection, it&#8217;s a bit slow. For discrete usage, each call is under 1 ms, but if you use it in a loop with many items, the performance hit will become more tangible.</p><pre class="brush: csharp">public static TValue ChainGet&lt;TRoot, TValue&gt;( this TRoot root, Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression) {bool success; return ChainGet(root, getExpression, out success); }public static TValue ChainGet&lt;TRoot, TValue&gt;( this TRoot root, Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression, out bool success) {// it's ok if root is null! if (getExpression == null) throw new ArgumentNullException("getExpression"); var members = new Stack&lt;MemberAccessInfo&gt;(); Expression expr = getExpression.Body; while (expr != null) {if (expr.NodeType == ExpressionType.Parameter) break; var memberExpr = expr as MemberExpression; if (memberExpr == null) throw new ArgumentException( "Given expression is not a member access chain.", "getExpression"); members.Push(new MemberAccessInfo(memberExpr.Member)); expr = memberExpr.Expression; }object node = root; foreach (var member in members) {if (node == null) {success = false; return default(TValue); }node = member.GetValue(node); }success = true; return (TValue)node; }private class MemberAccessInfo {private PropertyInfo _propertyInfo; private FieldInfo _fieldInfo; public MemberAccessInfo(MemberInfo info) {_propertyInfo = info as PropertyInfo; _fieldInfo = info as FieldInfo; }public object GetValue(object target) {if (_propertyInfo != null) return _propertyInfo.GetValue(target, null); else if (_fieldInfo != null) return _fieldInfo.GetValue(target); else throw new InvalidOperationException(); }} // Usage: var myValue = obj.ChainGet(o =&gt; o.MyProperty.MySubProperty.MySubSubProperty.MyValue);</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>DependencyObject</h2><p><a name="DependencyObject.SafeGetValue"></a><a name="DependencyObject.SafeSetValue"></a>These extensions work just like their non-safe counterparts on <code>DependencyObject</code>, but will call <code>Dispatcher.Invoke</code> to do operations if the current thread isn&#8217;t a UI thread.</p><pre class="brush: csharp">public static object SafeGetValue( this DependencyObject obj, DependencyProperty dp) {if (obj == null) throw new ArgumentNullException("obj"); if (dp == null) throw new ArgumentNullException("dp"); if (obj.CheckAccess()) return obj.GetValue(dp); var self = new Func &lt;DependencyObject, DependencyProperty, object&gt; (SafeGetValue); return Dispatcher.Invoke(self, obj, dp); }</pre><pre class="brush: csharp">public static void SafeSetValue( this DependencyObject obj, DependencyProperty dp, object value) {if (obj == null) throw new ArgumentNullException("obj"); if (dp == null) throw new ArgumentNullException("dp"); if (obj.CheckAccess()) obj.SetValue(dp, value); else {var self = new Action &lt;DependencyObject, DependencyProperty, object&gt; (SafeSetValue); Dispatcher.Invoke(self, obj, dp, value); }}</pre><pre class="brush: csharp">public static void SafeSetValue( this DependencyObject obj, DependencyPropertyKey key, object value) {if (obj == null) throw new ArgumentNullException("obj"); if (key == null) throw new ArgumentNullException("key"); if (obj.CheckAccess()) obj.SetValue(key, value); else {var self = new Action &lt;DependencyObject, DependencyPropertyKey, object&gt; (SafeSetValue); Dispatcher.Invoke(self, obj, key, value); }}</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/the-extension-method-pack/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>Getting to New York</title>
			<link>http://northhorizon.net/2010/getting-to-new-york-part-2/</link>
			<comments>http://northhorizon.net/2010/getting-to-new-york-part-2/#comments</comments>
			<pubDate>Wed, 07 Apr 2010 14:00:46 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Life in NYC]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Interviews]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=203</guid>
			<description><![CDATA[Continued from Part I. Part II. On the Phone Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled [...]]]></description>
			<content:encoded><![CDATA[<p><em>Continued from <a href="http://northhorizon.net/2010/getting-to-new-york-part-1/">Part I</a>.<a href="http://northhorizon.net/2010/getting-to-new-york-part-1/"><br /></a></em></p><h2>Part II. On the Phone</h2><p>Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled off my bookshelf my trusty copy of <a href="http://www.amazon.com/CLR-via-Dev-Pro-Jeffrey-Richter/dp/0735627045">CLR via C#</a>, which is, in my opinion, the best book you can read if you really want to take your understanding of C# and .NET from “intermediate” to “expert”. C#  Developers: no excuses, read this book cover to cover. As it turns out, my interviewer, Nick, must be a fan of the same book. When he called me that Monday morning, after introducing himself, Nick threw me a couple softballs before turning up the heat. I was queried at length about generics, delegates, anonymous methods, and the garbage collector (among other things), all of which I was more than happy to explicate in the greatest of detail, having refreshed myself on their inner workings the night before. Nick’s attention then turned to the newer .NET 3.5 features, which I had been using for almost two years, and I was more than happy to talk about those, too. I must admit, he stumped me on a concept called “attached behaviors”. I was familiar with attached properties, but it wasn’t until recently that I’ve become fully aware of attached behaviors. I’ll have another article discussing what I learned in the future.</p><p>After Nick finished grilling me for information, I had my turn to ask him questions. I seem to remember having a list of things to talk about, but I was suffering from some strange variant of vertigo, so I went with my usual developer talking points. For the record, Nick is one of the nicest guys ever. As I would find out later, Lab49 is composed solely of superb people. You may be thinking that I’m generalizing or hyperbolizing, but in all seriousness, I have yet to find a single bad apple or even mildly distasteful person at Lab49. Every time I think I’ve found one, they prove me wrong. Even the Java guys are top notch, and that’s saying something. In any case, I finished the interview enjoying a discussion of the usual programmer minutiae, talking about podcasts and developer philosophy. I’m not sure if it’s normal for one to feel a sense of camaraderie with his interviewer, but I know I sure did.<span id="more-203"></span></p><p>Later that day, I received an email from James, a Recruitment Coordinator at Lab49, asking for a “telephone conversation” with Nemo, the Director of Recruitment. I figured it was one of those psychological profiles one of my friends had been subjected to in a recent interview. I don’t think I could have been more wrong. The next morning, Nemo called, introduced himself, asked for clarification on a few points of my résumé, and opened himself up for questions. I asked him the usual questions on how Lab49 was structured, the promotion strategy, and what Lab49 does in general.</p><p>Nemo explained to me that Lab49 is somewhat loosely structured, with no real middle management. As projects start and finish, you report to the project manager and engagement manager, but every project is custom-tailored to the clients’ needs. I pressed Nemo to explain how a successful company works without the infrastructure almost every company of equal size has. Nemo couldn’t really explain how it worked, but only that it did, and quite well. Some may say, “when the cat’s away,” but I might interject that maybe without the threat of imminent death, a mouse might be more free to do something more constructive with its time than cower for its life.</p><p>Coming from a consulting background, I could really tell Lab49 really is a consulting firm in the greatest sense of the term. The answer to everything is, “it depends,” and, “what the client needs,” which is clearly working out well for them, but can be frustrating trying to pin down something concrete on which to make a decision. In general, Labbers work on-site with the clients to best make use of human and information resources. In my opinion, there’s definitely a beneficial side effect to it: when Lab49 is working side-by-side with the client, the work has a face, rather than some unknown bunch of people dropping code in a folder every week or two.</p><p>Nemo continued by telling me that Lab49 has titles out of necessity, but they don’t play as much of a role as in other companies. I really appreciated that. Being a young guy, it’s typically difficult for me to get my ideas out in a space where I’ve got a title that’s easily negligible. I can say with authority that’s not been the case at Lab49. Every day I work with guys who have decades of experience on me, but are interested to hear what I have to say. It’s not about seniority; it’s about being the best at what you do and bringing new and innovative ideas to the table. For that very reason, I prefer to keep my title to myself. There’s no real company policy on the publicity of your title, but it’s not on my business card and I certainly wouldn’t wear it on my sleeve.</p><p>Nemo concluded the interview by saying that Daniel Chait, one of the founders of Lab49 would want to talk to me over Skype before an in-person interview. That was the first time anyone had said anything about an in-person interview, and while I had expected it at some point, I couldn’t help but be excited to see some light at the end of the tunnel. I confidently told Nemo that I was available for the remainder of the day, which might have caught him a bit off-guard. He said Daniel was a busy guy and he’d see when he was available. I was confirmed for later that afternoon by email not too long after hanging up.</p><p>I’m not sure if it was then or later that I started feeling extremely skeptical of this Lab49 place. I remember telling my friend, Chris, that, “I know Nirvana Corp burned down, but Lab49 makes me wonder,” quoting from an <a href="http://www.tv.com/video/15935/the-competition">episode</a> of <em>Dilbert, The Animated Series</em>.  I found it difficult to believe that such a place could exist, so little was my faith in humanity, let alone developers.</p><p>I then realized I was about to have my fourth communiqué with a company in three business days, whereas almost no Dallas-based company had insomuch as replied in a week.  <em>These guys really don’t mess around</em>, I remember thinking.</p><p>At 3:00 PM and after a few quirky Skype issues, I was on webcam with Daniel Chait, now fully appreciating the extra money I’d spent on a <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E1682610407">nice webcam</a>. Chait went over my experience thoroughly, fully examining the roles I had played on each team. I’m not sure why, but at times I felt very intimidated. It’s perplexing because going over the conversation in my head Daniel wasn’t in the least bit condescending nor indirect in his questions. We discussed my work in WPF and LINQ and lambda expressions. Having taken Advanced Programming Languages and feeling like (but by no means) an expert in functional languages, I was glad to be on more solid ground. I had a compulsion to share with Daniel a couple extension methods I had written to succinctly state an equation in lambda. Unfortunately, since it was a compulsion I wasn’t prepared at all with the code snippet. I brought up my Machine Learning projects folder, which I knew it was in but couldn’t remember exactly which project I had written the extension for. Fumbling around, I must have spent a full five minutes of awkward silence finding the thing, which seemed anti-climactic for such a long wait, and even more so for me, since it felt like an eternity.</p><p>Afterward, I told my roommate that I wasn’t sure how that interview had gone. It was without a doubt by my estimation my weakest interview, and likewise the most important. I spent a little while going over the events, trying to find out why I felt I had done so poorly. All I can say is that I feel very confident of my technical skills and far less strongly about my experience, which was a major focus of Chait’s interview. That and that awkward silence.  I told myself that if they wanted a guy with more experience, that was a perfectly legitimate reason not to go forward, and I shouldn’t be worried about it. And if they rejected me outright for not having that bit of code on hand, they could go to Hell.</p><p>I was glad some of my friends wanted to go out that night so I could get my mind off the whole thing. When I got back, there was an email from James waiting for me, inviting me to New York for an in-person interview. I slept well that night.</p><p>The next day I made reservations airfare and lodging and ran both by James, as Lab49 kindly picked up the tab. It might be standard operating procedure for companies, but the fact is that they don’t have to do it, and I would have paid for the ticket myself if they hadn’t. Now all that was left to do was wait out the week and familiarize myself as best I could with my travel plans.</p><p>Clearly this company had their act together and was vigorously pursuing this discovery period. I was also reacquainting myself with the ever-greater possibility of leaving everything for New York. My father was supportive, and because he’s not usually too keen on my adventures, I took it for a good sign. That being the case, I started warming my close family and friends up to the idea that I might end up in New York. Most of them were surprised, marveling at the apparent spontaneity and haste in the whole process. Only months before had I told them I’d be staying in Dallas for the “foreseeable future” as a consultant writing software for my own company.</p><p>Who knew the foreseeable future was so short?</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/getting-to-new-york-part-2/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		</item>
		<item>
			<title>Variable-length Integers</title>
			<link>http://northhorizon.net/2009/variable-length-integers/</link>
			<comments>http://northhorizon.net/2009/variable-length-integers/#comments</comments>
			<pubDate>Tue, 17 Feb 2009 20:34:21 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Site News]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Chord]]></category>
			<category><![CDATA[Coursework]]></category>
			<category><![CDATA[Hashing]]></category>
			<category><![CDATA[Math]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=14</guid>
			<description><![CDATA[Wow. So it definitely took me long enough to get this blog going. A lot has happened since I got this site up and running, so hopefully there will be no shortage of thoughts to write about. This semester I&#8217;ve finally qualified to take the CS Senior Design Project, which, this semester, is to design [...]]]></description>
			<content:encoded><![CDATA[<p>Wow. So it definitely took me long enough to get this blog going. A lot has happened since I got this site up and running, so hopefully there will be no shortage of thoughts to write about.</p><p>This semester I&#8217;ve finally qualified to take the CS Senior Design Project, which, this semester, is to design a <a href="http://en.wikipedia.org/wiki/Chord_project">Chord</a> client. At the heart of the system is the <em>identifier</em>, which is essentially a glorified hash. We decided to go with SHA-256, partially because the instructor mentioned it was in the class of his favorite hashes. It didn&#8217;t really matter to me, since C# supports it just as easily as anything else.</p><p>Identifiers have two essential purposes, comparison and addition, from which every method can be derived. I wasn&#8217;t particularly intrigued by either of these topics, since almost without exception, you can rely on existing structures in the <a href="http://en.wikipedia.org/wiki/Framework_Class_Library">FCL</a> to do whatever you need to do, and it&#8217;s always better to do so. Now, I said &#8220;almost without exception,&#8221; namely because I stumbled upon the fact that these identifiers unequivocally are exceptions. The thing about using a SHA-256 hash &#8211; or any hash for that matter &#8211; is that it&#8217;s an enormous value &#8211; 256 bits to be precise. There aren&#8217;t any real 32 or even 64 bit hashes available (I doubt they&#8217;d be useful), so relying on the good ol&#8217; FCL goes out the window.<span id="more-14"></span></p><p>Other students, stuck in the abyss of Java, were having difficulty getting their socket implementations going, so mucking around in massive integer arithmetic was right out. I believe the professor advised them to take the 32 <a href="http://en.wikipedia.org/wiki/Most_significant_bit">MSB</a> and just rely on an unsigned integer. <em>(Side note: does Java even have unsigned integers?) </em>I considered a few similar options: taking the 64 <a href="http://en.wikipedia.org/wiki/Least_significant_bit">LSB</a> or separating the hash into several equal groups of 64-bits each and getting the xor result of the segments. Arrogantly I proceeded on, demanding that whatever I wrote work not only for SHA-256 but also SHA-512 or anything else using the full bit-length.</p><p>Comparison wasn&#8217;t difficult. Essentially, you start at the MSB in your array (which happens to be at <code>Length - 1</code>) and compare until you find a comparison <code>!= 0</code>:</p><pre class="brush: csharp">public int CompareTo(Identifier other) {for (int i = _hash.Length - 1; i &amp;gt;= 0; i--) {int compare = _hash[i].CompareTo(other._hash[i]); if (compare != 0) return compare; }return 0; }</pre><p>Now comes the fun part. First, I wrote a little method called <code>Pad(byte[] list, int size)</code> which pads the MSB of an array with 0&#8242;s until it&#8217;s the proper length. After several iterations, I finally ended up with this:</p><pre class="brush: csharp">public static byte[] Add(byte[] a, byte[] b) {if (a.Length &gt; b.Length) b = Pad(b, a.Length); else if (a.Length &lt; b.Length) a = Pad(a, b.Length); byte[] result = new byte[a.Length]; int carry = 0; for (int i = 0; i &lt; a.Length; i++) {int value = carry + a[i] + b[i]; // get the bottom part of the bits result[i] = (byte)value; // knock off the bottom bits that we already got and // put the rest into carry. carry = (value - result[i]) / byte.MaxValue; }return result; }</pre><p>The data holder for carry has to be large enough for the worst case scenario <code>0xFF + 0xFF + carry 1</code>, which is why I chose an <code>int</code> rather than a <code>byte</code> (although a short could have worked just as well, I suppose).</p><p>Subtraction was more difficult. Consider the way you subtract, with carrying, etc. Carrying on its own is a recursive process, and I can&#8217;t imagine writing it out. It was at that time that I remembered how the <a href="http://en.wikipedia.org/wiki/Arithmetic_logic_unit">ALU</a> does subtraction- by taking the two&#8217;s compliment of the second operand and doing addition. So I followed suit:</p><pre class="brush: csharp">public static byte[] Subtract(byte[] a, byte[] b) {if (a.Length &gt; b.Length) b = Pad(b, a.Length); else if (a.Length &lt; b.Length) a = Pad(a, b.Length); byte[] twoscomp = new byte[b.Length]; // get the 1's compliment for (int i = 0; i &lt; b.Length; i++) twoscomp[i] = (byte)(byte.MaxValue - b[i]); // add 1twoscomp = Add(twoscomp, new byte[] { 1 }); // NOTE: twoscomp is now the two's compliment of b. return Add(a, twoscomp); }</pre><p>I also needed multiplication, but I&#8217;m still working on the solution. I&#8217;ve got a working draft, but I&#8217;m not entirely sure I&#8217;m happy with it just yet. I&#8217;ll keep you notified.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/variable-length-integers/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
