<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" >
	<channel>
		<title>North Horizon</title>
		<atom:link href="http://northhorizon.net/feed/" rel="self" type="application/rss+xml" />
		<link>http://northhorizon.net</link>
		<description></description>
		<lastBuildDate>Tue, 24 Jul 2012 05:16:08 +0000</lastBuildDate>
		<language>en</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
		<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
			<title>Leveraging Templates in psake</title>
			<link>http://northhorizon.net/2012/leveraging-templates-in-psake/</link>
			<comments>http://northhorizon.net/2012/leveraging-templates-in-psake/#comments</comments>
			<pubDate>Tue, 24 Jul 2012 05:15:30 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[powershell]]></category>
			<category><![CDATA[psake]]></category>
			<category><![CDATA[templating]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=510</guid>
			<description><![CDATA[For the past few months I&#8217;ve been a technical editor for a book my good friend and colleague, Doug Finke, is writing entitled PowerShell for Developers which has just recently become available on Amazon. The purpose of the book is to show how easy it is to accomplish normally mundane, repetitive, or clunky tasks with [...]]]></description>
			<content:encoded><![CDATA[<p>For the past few months I&#8217;ve been a technical editor for a book my good friend and colleague, <a href="http://dougfinke.com/blog">Doug Finke</a>, is writing entitled <em><a href="http://oreilly.com/catalog/0636920024491">PowerShell for Developers</a></em> which has just recently become available on <a href="http://www.amazon.com/Windows-PowerShell-Developers-Douglas-Finke/dp/1449322700">Amazon</a>. The purpose of the book is to show how easy it is to accomplish normally mundane, repetitive, or clunky tasks with PowerShell, a simple, concise scripting language that you already have installed on your box.</p><p>On my current project, I was recently tasked with setting up the build for our project. Of course, build scripts aren&#8217;t exactly glorious or interesting in any way and the prospect of dealing with MSBuild&#8217;s XML files gives me a fleeting sense of vertigo.</p><p>But fortunately, there&#8217;s a much, much less painful way to make build scripts by using psake.<span id="more-510"></span></p><h2>A Brief Introduction to psake</h2><p><em>(If you already know psake, skip to the next section!)</em></p><p><a href="https://github.com/psake/psake">psake</a> (pronounced <em>sah-kay</em>) is a build scripting DSL of the <a href="http://en.wikipedia.org/wiki/Make_(software)">make</a>, <a href="http://rake.rubyforge.org/">rake</a>, <a href="https://github.com/jcoglan/jake/">jake</a>, and <a href="http://sourceforge.net/apps/trac/cake-build/">cake</a> variety built up in PowerShell. Basically, you define tasks as small script blocks and can establish dependencies between them.</p><p>My projects tend to be organized like this:</p><pre>+-MyApp\ +-docs\ +-src\ | +-MyApp.sln +-lib\ +-tools\ | +-build\ | | +-psake.psm1 | | +-psake.ps1 | | +-default.ps1 +-psake.cmd</pre><p>Here, <code>psake.psm1</code>, <code>psake.ps1</code>, and <code>psake.cmd</code> are from psake&#8217;s github repo, except that I modify <code>psake.cmd</code> to point to <code>tools\build</code>:</p><pre>@echo off if '%1'=='/?' goto help if '%1'=='-help' goto help if '%1'=='-h' goto help powershell -NoProfile -ExecutionPolicy Bypass -Command "&amp; '%~dp0\tools\build\psake.ps1' %*; if ($psake.build_success -eq $false) { exit 1 } else { exit 0 }" goto :eof :help powershell -NoProfile -ExecutionPolicy Bypass -Command "&amp; '%~dp0\tools\build\psake.ps1' -help"</pre><p>My basic <code>default.ps1</code> psake script looks like this:</p><pre class="brush:powershell">properties {# Since we're in tools\build, root is up two dirs. $rootDir = (Resolve-Path (Join-Path $psake.build_script_dir '..\..')).Path $srcDir = Join-Path $rootDir src $slnPath = Join-Path $srcDir PsakeDemo.sln $buildProperties = @{} if(-not $buildType) {$buildType = 'Debug' }$buildProperties.Configuration = "$buildType|AnyCPU" }task default -depends Clean, Compile, Test task Clean {Invoke-MSBuild $slnPath 'Clean' $buildProperties }task Compile -depends Clean {Invoke-MSBuild $slnPath 'Build' $buildProperties }task Test -depends Compile {# TODO: call test framework CLI inside an `exec { ... }` }function Invoke-MSBuild([string]$Path, [string]$Target, [Hashtable]$Properties) {Write-Host "Invoking MSBuild" -Foreground Blue Write-Host @" Path : $Path Target : $Target Properties : $($Properties | Out-String) "@ $props = ($Properties.GetEnumerator() | % { $_.Key + '=' + $_.Value }) -join ';' exec { msbuild $Path "/t:$Target" "/p:$props" }}</pre><p>What&#8217;s great about psake is that there are really only three things you need to learn.</p><p>The first is the properties block up at the top. This guy is responsible for setting up your global state and is a good place to declare a bunch of variables that make working with your script easy to understand. As you can see, I like to declare variables for every directory path that might be needed as well as the <code>.sln</code> path. My convention here is that paths to directories are suffixed with &#8220;Dir&#8221;, paths to files are suffixed with &#8220;Path&#8221;, and all paths are always absolute. In the rare case of a need for a relative path, I would suffix the variable with &#8220;RelDir&#8221; or &#8220;RelPath&#8221; so the next guy who looks at my script knows what&#8217;s going on.</p><p>The second is <code>task</code>. This guy is the workhorse of our script; each stage of the build process should be encapsulated in a task so that we can mix and match them later on. Each task exposes out a list of other tasks that need to be done first. For instance, it&#8217;d be really problematic to run your tests before you&#8217;ve compiled! By adding the <code>-depends</code> comma-separated list of other task names, you can be sure that those tasks will be run before yours is executed, even if they&#8217;re not specified explicitly. You might also notice that I&#8217;ve defined a <code>default</code> task. This is essentially the <code>Main</code> method of our build script. While your script doesn&#8217;t <em>have</em> to have one, you should make one so your script can be run without extra parameters. As you can see, I don&#8217;t define any work to be done in the default task, I just define what tasks should be done by default. Simple. (By the way, I could technically have just said <code>task default -depends Test</code> and that would have accomplished the same thing since Test depnds on Compile and Compile depends on Clean. I specify all three just to state my intentions.)</p><p>Finally, you need to know about <code>exec { ... }</code>. This guy runs some external process (like msbuild or your test runner) inside the braces, checks the exit code and throws an error if it doesn&#8217;t return 0. Handy!</p><p>New, at the bottom of my script I&#8217;ve added a function called <code>Invoke-MSBuild</code>. What I like about this is that now I have a nice PowerShell API for kicking off msbuild. If I need more switches, I can just add more parameters to the function. Plus, working with a <code>Hashtable</code> to set msbuild properties is so much easier than trying to construct <code>key1=value1;key2=value2</code>.</p><h2>Templating <code>CommonAssemblyInfo.cs</code></h2><p>In my <code>src</code> directory, I like to create two files and add them to my soltuion files: <code>CommonAssemblyInfo.cs</code> and <code>CommonAssemblyInfo.cs.template</code>, the idea being that the <code>.cs</code> file is the one that I reference in my projects (be sure to use &#8220;<a href="http://msdn.microsoft.com/en-us/library/9f4t9t92.aspx">add as link</a>&#8220;) and the <code>.cs.template</code> file is the file that PowerShell reads teo create it. Let&#8217;s take a look at the template.</p><pre class="brush:csharp">using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("$buildType")] [assembly: AssemblyCompany("North Horizon")] [assembly: AssemblyProduct("PsakeDemo")] [assembly: AssemblyCopyright("Copyright © Daniel Moore $((Get-Date).Year)")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("$version")] [assembly: AssemblyFileVersion("$version")]</pre><p>First off, there&#8217;s no doubt how to read this file. It <em>is</em> C#. Well, kinda. But the point is that anybody can read this file and make small changes as necessary, even if they didn&#8217;t know PowerShell or psake. Quite clearly we&#8217;re using PowerShell variables throughout (<code>$buildType</code> and <code>$version</code>) and, amazingly, we&#8217;ve got an honest-to-goodness PowerShell command in play: <code>$((Get-Date).Year)</code>. So this must require a couple KLoC framework, to do the parsing and such, yeah? Actually, it&#8217;s more like two:</p><pre class="brush:powershell">properties {# ... $version = '1.0.0.0' # TODO: obtain version from build server or something. # ... }task Version {$templateName = 'CommonAssemblyInfo.cs.template' $templatePath = Join-Path $srcDir $templateName $outPath = Join-Path $srcDir ([IO.Path]::GetFileNameWithoutExtension($templateName)) # &lt;1&gt; $content = [IO.File]::ReadAllText($templatePath, [Text.Encoding]::Default) # &lt;2&gt; Invoke-Expression "@`"`r`n$content`r`n`"@" | Out-File $outPath -Encoding utf8 -Force }</pre><p>I actually learned this technique while editing <em>PowerShell for Developers</em> &#8211; this is just one small example from chapter 4, which goes into much greater depth about the awesome stuff you can do with templating.</p><p>So what does this do? Well, on mark <code>&lt;1&gt;</code>, we simply read in all the text from our template as a string using the tried-and-true <code>File</code> .NET API. I specify the encoding here so the copyright symbol gets read correctly.</p><p>On mark <code>&lt;2&gt;</code>, we wrap that string into a double-quote herdoc and invoke the whole thing as a script. This is how we leverage the entire PowerShell ecosystem with string interpolation and sub-expressions with almost no code.</p><p>This is, of course, just the begining &#8211; but that&#8217;s what makes PowerShell so awesome. With a few lines of code, you can leverage the whole of .NET in an intuitive and concise manner, and you&#8217;re not limited to just things the PowerShell team has thought of. PowerShell&#8217;s out-of-the-box cmdlet library makes common and often tough tasks easy, but the language provides all the building blocks you need to build anything you can imagine.</p><p>If you&#8217;re looking to get started in PowerShell or want to expand your toolbox of patterns and techniques, I can&#8217;t recommend enough that you take a look at <em><a href="http://oreilly.com/catalog/0636920024491">PowerShell for Developers</a></em> and see what else you can start automating.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2012/leveraging-templates-in-psake/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		</item>
		<item>
			<title>Better Commands in WPF</title>
			<link>http://northhorizon.net/2012/better-commands-in-wpf/</link>
			<comments>http://northhorizon.net/2012/better-commands-in-wpf/#comments</comments>
			<pubDate>Tue, 05 Jun 2012 21:51:22 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[commands]]></category>
			<category><![CDATA[linq]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=498</guid>
			<description><![CDATA[When I explain commands in WPF, I tend to say they are simply “bindable methods.” I like this definition not only for its brevity, but for its composition of powerful ideas into a single construct. It reinforces the axiom of “no code left behind” that we push so hard in WPF. But this leaves behind [...]]]></description>
			<content:encoded><![CDATA[<p>When I explain commands in WPF, I tend to say they are simply “bindable methods.” I like this definition not only for its brevity, but for its composition of powerful ideas into a single construct. It reinforces the axiom of “no code left behind” that we push so hard in WPF. But this leaves behind almost two thirds of the functionality given to us by <code>ICommand</code> the parameter and <code>CanExecute</code>. Parameters, admittedly, are needed less often in most designs, as commands tend to operate on the view model to which they are attached. <code>CanExecute</code>, on the other hand, is used fairly often and is also fairly broken in most implementations. <span id="more-498"></span></p><p>On my last project, I had a teammate who was learning WPF and was confused why a button bound to a command was not becoming enabled after its <code>CanExecute</code> conditions became <code>true</code>. Our implementation of <code>ICommand</code> relied on <code>CommandManager.RequerySuggested</code> to raise the <code>ICommand.CanExecuteChanged</code> event and therein lied the problem. Here’s what <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.commandmanager.requerysuggested.aspx">MSDN says about <code>RequerySuggested</code></a>:</p><blockquote><p>Occurs when the CommandManager detects conditions that might change the ability of a command to execute.</p></blockquote><p>Hm, well that’s a little vague for my taste. What conditions? And <em>might</em> change? So, after a little reflection, I found that the internal class <code>System.Windows.Input.CommandDevice</code> is responsible for raising <code>RequerySuggested</code> based on UI events. Here is the relevant method:</p><pre class="brush:csharp">private void PostProcessInput(object sender, ProcessInputEventArgs e) {if (e.StagingItem.Input.RoutedEvent == InputManager.InputReportEvent) {// abridged }else if (e.StagingItem.Input.RoutedEvent == Keyboard.KeyUpEvent || e.StagingItem.Input.RoutedEvent == Mouse.MouseUpEvent || e.StagingItem.Input.RoutedEvent == Keyboard.GotKeyboardFocusEvent || e.StagingItem.Input.RoutedEvent == Keyboard.LostKeyboardFocusEvent) {CommandManager.InvalidateRequerySuggested(); }}</pre><p>As you can see, this is really a poor way to detect if <code>CanExecute</code> has changed. In many circumstances, view model state changes are based on far more than mouse and keyboard events. In fact, when Microsoft Patterns &amp; Practices made their <code>DelegateCommand</code>, they avoided <code>RequerySuggested</code> for <a href="http://compositewpf.codeplex.com/discussions/44750">just this reason</a>.</p><p>So I advised my colleague to create a normal bindable property called <code>CanFooCommandExecute</code> and bind the <code>IsEnabled</code> property of the button to that. I think he ended up calling <code>CommandManager.InvalidateRequerySuggested</code> himself to limit the amount of rework needed to be done, but that seems far from ideal to me.</p><p>This got me thinking, though: why not leverage a bindable property to enable and disable commands? Or, even better, why not define the conditions of a command being enabled in terms of bindable properties?</p><p>Fortunately, we have everything we need already to accomplish this. What we can do is instead of taking a <code>Func&lt;bool&gt;</code> for our <code>CanExecute</code> delegate, we’ll take an <code>Expression&lt;Func&lt;bool&gt;&gt;</code>. Then we can look at the AST given to us and find any member accesses with an <code>INotifyPropertyChanged</code> root. While we’re at it, we could also look for method calls to <code>INotifyCollectionChanged</code> and <code>IBindingList</code> objects, since they tell us when their items change.</p><p>I have devised a few acceptance tests that demonstrate this behavior. First, let’s define a view model:</p><pre class="brush:csharp">class TestViewModel : BindableBase {public TestViewModel() {SimpleCommand = new ExpressionCommand(OnExecute, () =&gt; Value1 &gt; 5); }public ICommand SimpleCommand { get; private set; }private int _value1; public int Value1 {get { return _value1; }set { SetProperty(ref _value1, value, "Value1"); }} private void OnExecute() { } }</pre><p>And let’s just test the basic behavior of the command.</p><pre class="brush:csharp">[Test] public void TestSimpleCommand() {var sut = new TestViewModel(); int updateCount = 0; sut.SimpleCommand.CanExecuteChanged += (s, e) =&gt; updateCount++; sut.Value1 = 3; updateCount.ShouldEqual(1); }</pre><p>And there it is. No extra management of <code>CanExecute</code>, just the syntax you’re probably used to already with <code>DelegateCommand</code> Except this time, it works the way you think it should.</p><p>Now lets try out a property chain and an <code>ObservableCollection</code>. Here are our view models:</p><pre class="brush:csharp">private class TestViewModel : BindableBase {public TestViewModel() {ComplexCommand = new ExpressionCommand(OnExecute, () =&gt; Value2.Value4.Value3 &gt; 5); ComplexCollectionCommand = new ExpressionCommand(OnExecute, () =&gt; Value2.Value5.Contains(Value2)); }public ICommand ComplexCommand { get; private set; }public ICommand ComplexCollectionCommand { get; private set; }private int _value1; public int Value1 {get { return _value1; }set { SetProperty(ref _value1, value, "Value1"); }} private TestSubViewModel _value2; public TestSubViewModel Value2 {get { return _value2; }set { SetProperty(ref _value2, value, "Value2"); }} private void OnExecute() { } }private class TestSubViewModel : BindableBase {private int _value3; public int Value3 {get { return _value3; }set { SetProperty(ref _value3, value, "Value3"); }} private TestSubViewModel _value4; public TestSubViewModel Value4 {get { return _value4; }set { SetProperty(ref _value4, value, "Value4"); }} public ObservableCollection&lt;TestSubViewModel&gt; Value5 = new ObservableCollection&lt;TestSubViewModel&gt;(); }</pre><p>And the tests:</p><pre class="brush:csharp">[Test] public void TestComplexCommand() {var sut = new TestViewModel {Value2 = new TestSubViewModel() }; int updateCount = 0; sut.ComplexCommand.CanExecuteChanged += (s, e) =&gt; updateCount++; sut.Value2 = new TestSubViewModel(); updateCount.ShouldEqual(1); sut.Value2.Value4 = new TestSubViewModel(); updateCount.ShouldEqual(2); sut.Value2.Value4.Value3 = 3; updateCount.ShouldEqual(3); }[Test] public void TestComplexCollectionCommand() {var sut = new TestViewModel {Value2 = new TestSubViewModel() }; int updateCount = 0; sut.ComplexCollectionCommand.CanExecuteChanged += (s, e) =&gt; updateCount++; sut.Value2 = new TestSubViewModel(); updateCount.ShouldEqual(1); sut.Value2.Value5.Add(sut.Value2); updateCount.ShouldEqual(2); }</pre><p>Even when complex properties are completely reassigned, <code>ExpressionCommand</code> knows to resubscribe to the whole tree again.</p><p>I won’t get into the implementation of <code>ExpressionCommand</code> in this article as it’s pretty heavy into LINQ expressions, but I have added all the code into my <a href="https://github.com/danielmoore/InpcTemplate/">InpcTemplate on GitHub</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2012/better-commands-in-wpf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<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>3</slash:comments>
		</item>
		<item>
			<title>Reactions from Build</title>
			<link>http://northhorizon.net/2011/reactions-from-build/</link>
			<comments>http://northhorizon.net/2011/reactions-from-build/#comments</comments>
			<pubDate>Fri, 16 Sep 2011 21:51:02 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[Build Conf]]></category>
			<category><![CDATA[Metro]]></category>
			<category><![CDATA[Windows 8]]></category>
			<category><![CDATA[WinRT]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=476</guid>
			<description><![CDATA[There’s been no shortage of news and non-news coming out of Build Conference this week, and I suspect there will be continue to be no shortage of the same for the next few months. We’ve learned that WPF isn’t quite dead, Silverlight isn’t quite dead, but both are in the process of being “reimagined,” whatever [...]]]></description>
			<content:encoded><![CDATA[<p>There’s been no shortage of news and non-news coming out of Build Conference this week, and I suspect there will be continue to be no shortage of the same for the next few months. We’ve learned that WPF isn’t quite dead, Silverlight isn’t quite dead, but both are in the process of being “reimagined,” whatever that means. Metro is clearly the first step of that process and it provokes a very diametric response from developers.<span id="more-476"></span></p><p>I sat down to breakfast this morning with a couple guys I hadn’t met. Since Build Conference was an incorporation of both ISVs and IHVs, I greeted them with, “Software or hardware?” The man across the table told me he was involved with software, while the guy to my right ignored me entirely. Without quite playing <em>20 Questions</em>, I found that the more vocal one was a client side developer in health care. He told me that he was very excited about the new Metro design and especially for the upcoming Windows 8 tablets. “Right now, everything is moving to Electronic Medical Records. So, when a doctor goes into see a patient, the first thing he does is turn his back on that patient and bring up the records on a desktop. A tablet is much more like the clipboards doctors used to use.” And, of course, Metro plays a huge role in the realization of that use case; a friendly, full-screen touch-accelerated app is intrinsic to the paradigm of a tablet. Not only that, but ease of access to peripherals, especially the webcam, make Windows Runtime (WinRT) a compelling API. As an added bonus, he pointed out that he could transition his current ASP.NET development stack and programmers much more easily to use either C# and XAML or even HTML5 and JavaScript to produce a Metro app than to use Coco and Objective-C to make an iPad app. Without a doubt, this is what Microsoft had envisioned.</p><p>At the opposite end of the spectrum, I met a couple developers that maintain an institutional client-facing application written in MFC. “There’s over three hundred screens in our application. No way can we fit that into Metro.” He went on further to explain that their application opens direct connections to a SQL Server instances located on both the client and server tiers. “I have to figure out how to go back and tell my boss that there’s just no way we can move over to Metro.”</p><p>I don’t know if he was aware or not of the seemingly obvious flaws in his app’s design, or that Microsoft was encouraging developers to forsake that all-too-familiar design of MFC apps that he showed me. “It’d be a complete rewrite;” that much we completely agreed upon.</p><p>There is a continuing consensus around the notion that WinRT is by far the most ambitious thing Microsoft has done in decades. Perhaps in a lot of ways, Windows XP is an apt analog of Win32 programming: it’s been around for so long, it’s in use in so many places, and it’s so well known, that it will take a very, very long time to unwind from it. Windows 8 and WinRT have enormous potential to revitalize the failing Windows desktop software market. All that remains to be seen is whether developers choose to capitalize upon it or cut their losses and move on.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/reactions-from-build/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>Why I Use Powershell</title>
			<link>http://northhorizon.net/2011/why-i-use-powershell/</link>
			<comments>http://northhorizon.net/2011/why-i-use-powershell/#comments</comments>
			<pubDate>Sun, 07 Aug 2011 03:36:11 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[powershell]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=457</guid>
			<description><![CDATA[I&#8217;ve been using Powershell for just over a year now, and its effect on my development workflow has been steadily increasing. Looking back, I have no doubt that it is the most important tool in my belt &#8211; to be perfectly honest, I&#8217;d rather have Powershell than Visual Studio now. Of course, that&#8217;s not to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Powershell for just over a year now, and its effect on my development workflow has been steadily increasing. Looking back, I have no doubt that it is the most important tool in my belt &#8211; to be perfectly honest, I&#8217;d rather have Powershell than Visual Studio now. Of course, that&#8217;s not to say Visual Studio isn&#8217;t useful &#8211; it is &#8211; but rather more that Poweshell fills an important role in the development process that isn&#8217;t even approached by other tools on the platform. Visual Studio may be the best IDE on the market, but at the end of the day, there are other tools that can replace it, albeit imperfectly.</p><p>To take some shavings off of the top top of the iceberg that is why I use Powershell, I&#8217;d like to share a recent experience of Powershell delivering for me. <span id="more-457"></span></p><h2>Setup for Failure</h2><p>As a co-orgranizer for the <a href="http://www.meetup.com/NY-Dotnet/">New York .NET Meetup</a> I was tasked with getting the list of attendees off of meetup.com and over to the lovely people at Microsoft who kindly give us space to meet. Now, you might think there&#8217;d be some nifty &#8220;export attendee list to CSV&#8221; function the meetup.com website, but like a lot of software, it doesn&#8217;t do half the things you think it should and this is one of those things. Usually my colleague David assembles the list, but this particular month he was out on vacation. He did, however, point me over to a GitHub repository of a tool that would do the extraction.</p><p>Following his advice, I grabbed the repository and brought up the C#/WinForms solution in Visual Studio. Looking at the project structure, I was a bit stunned at the scale of it all. The author had divided his concerns very well into UI, data access, the core infrastructure, and, of course, unit testing. I thought that was pretty peculiar considering all I wanted to do was get a CSV of names and such off of a website. Far be it for me to criticize another developer&#8217;s fastidiousness. Maybe it also launched space shuttles; you never know.</p><p>In what I can only now describe as naivety, I hit F5 and expected something to happen. </p><p>I was rewarded with 76 errors.</p><p>Right off the bat, I realized that the author had botched a commit and forgot a bunch of libraries. I was able to find NHibernate fairly easily with Nuget, but had no luck with &#8220;Rhino.Commons.NHibernate&#8221;. I tried to remove the dependency problem, but didn&#8217;t have much luck. And the whole time I was wondering why the hell you needed all these libraries <b>to extract a damn CSV from the internet</b>.</p><h2>The Problem</h2><p>Rather than throw more time after the problem, I decided to forge out on my own. Really, how hard could it be to</p><ol><li>Get an XML doc from the internet</li><li>Extract the useful data</li><li>Perform some heuristics on the names</li><li>Dump a CSV file</li></ol><p>Being a long-time C# programmer, my knee-jerk reaction was to build a solution in that technology. Forgoing a GUI to spend as little time as possible in building this, I&#8217;d probably build a single file design that ostensibly could consist of a single method. And if that were the case, why not script it?</p><p>So if I was going to write a script, what to use? I could write a JavaScript and run it on node.js, but it&#8217;s lacking proper CSV utilities and I&#8217;d have to run it on something other than my main Windows box. Not to mention I don&#8217;t particularly writing in JavaScript, so I&#8217;d probably write it in CoffeeScript and have to compile it, etc, etc. </p><p>I briefly considered writing an F# script, but I suspect only about ten people would know what on earth it was, and, at the end of the day, I would like to share my script to others.</p><h2>The Solution</h2><p>In the end, I concluded what I had known already: Powershell was the tool to use. It had excellent support for dealing with XML (via accelerators) and, as a real scripting language, had no pomp and circumstance.</p><p>Here&#8217;s the script I ended up writing:</p><pre class="brush:powershell">function Get-MeetupRsvps([string]$eventId, [string]$apiKey) {$nameWord = "[\w-']{2,}" $regex = "^(?'first'$nameWord) ((\w\.?|($nameWord )+) )?(?'last'$nameWord)|(?'last'$nameWord), ?(?'first'$nameWord)( \w\.|( $nameWord)+)?$" function Get-AttendeeInfo {process {$matches = $null $answer = $_.answers.answers_item if(-not ($_.name -match $regex)) { $answer -match $regex | Out-Null }return New-Object PSObject -Property @{ 'FirstName' = $matches.first 'LastName' = $matches.last 'RSVPName' = $_.name 'RSVPAnswer' = $answer 'RSVPGuests' = $_.guests }} }$xml = [Xml](New-Object Net.WebClient).DownloadString("https://api.meetup.com/rsvps.xml?event_id=$eventId`&#038;key=$apiKey") $xml.SelectNodes('/results/items/item[response="yes"]') `| Get-AttendeeInfo `| select FirstName, LastName, RSVPName, RSVPAnswer, RSVPGuests }</pre><p>To dump this to a CSV file is then really easy:</p><pre class="brush: powershell; gutter: false">Get-MeetupRsvps -EventId 1234 -ApiKey 'MyApiKey' | Export-Csv -Path rsvps.csv -NoTypeInformation</pre><p>And because of this design, it&#8217;s really extensible. Potentially, instead of exporting to a CSV, you could pipe the information into another processor that would remove anyone named &#8220;Thorsten.&#8221; Actually, that would look like this:</p><pre class="brush: powershell; gutter: false">Get-MeetupRsvps -EventId 1234 -ApiKey 'MyApiKey' `| ? { %_.FirstName -ne 'Thorsten' } ` | Export-Csv -Path rsvps.csv -NoTypeInformation</pre><p>It&#8217;d be pretty difficult to do that if I&#8217;d written a C# executable &#8211; you&#8217;d have to go into Excel to do that. Or write a Powershell script. Just saying.</p><p>Here&#8217;s the real kicker: I spent all of five minutes writing my Powershell script and then spent minutes tweaking my regex to identify as many names as possible. I didn&#8217;t need to recompile, just F5 again in Poweshell ISE, which you have installed already if you&#8217;re on Windows 7. Since I left the <code>Export-Csv</code> part off during debugging, I could just read the console output and see what I got.</p><p>When I was happy with my output, it was dead simple to distribute: throw it in <a href="https://gist.github.com/1091011">a GitHub Gist</a> and move on with my life. If you decide to use it, all you need is Powershell installed (again, are you on Windows 7?) and the ability to copy and paste. No libraries. No worries. If you don&#8217;t like my regex, it couldn&#8217;t be easier to figure out how to replace it. If you want more fields, it&#8217;s easy to see where they should be added.</p><p>It&#8217;s really just that easy.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/why-i-use-powershell/feed/</wfw:commentRss>
			<slash:comments>8</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>8</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>9</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>7</slash:comments>
		</item>
	</channel>
</rss>