<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" >
	<channel>
		<title>North Horizon &#187; WPF</title>
		<atom:link href="http://northhorizon.net/tag/wpf/feed/" rel="self" type="application/rss+xml" />
		<link>http://northhorizon.net</link>
		<description></description>
		<lastBuildDate>Sat, 12 Nov 2011 20:01:11 +0000</lastBuildDate>
		<language>en</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
		<generator>http://wordpress.org/?v=3.3</generator>
		<item>
			<title>Coercing ViewModel Values with INotifyPropertyChanged</title>
			<link>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/</link>
			<comments>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/#comments</comments>
			<pubDate>Sun, 08 May 2011 21:21:14 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[INotifyPropertyChanged]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=429</guid>
			<description><![CDATA[Perhaps one of the most ambivalent things about putting code on GitHub is that it&#8217;s more or less an open project. It&#8217;s great that people (including yourself) can continue to work on it, but it seems to lack closure so that you can move on with your life. So one of the things that I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>Perhaps one of the most ambivalent things about putting code on GitHub is that it&#8217;s more or less an open project. It&#8217;s great that people (including yourself) can continue to work on it, but it seems to lack closure so that you can move on with your life.</p><p>So one of the things that I&#8217;ve been missing in my <code>BindableBase</code> class is property coercion, a la dependency properties. It&#8217;s a pretty smart idea; you can keep values in a valid state without pushing change notification. Unfortunately, there are some problems that crop up pretty quickly in <code>INotifyPropertyChanged</code> based view models.<span id="more-429"></span></p><p>Consider a Foo property that refuses to set a value less than zero.</p><pre class="brush:csharp">private int _foo; public int Foo {get { return _foo; }set {if(_foo &gt;= 0) SetProperty(ref _foo, value, "Foo"); }}</pre><p>That looks like pretty good coercion, but the problem is that your binding and your property are now out of sync. That is, the binding told your object to set a value and assumed it did; you gave it no notification to the contrary. So while your object retains the old value, the bound <code>TextBox</code> will blissfully report -23.</p><p>A more brute force option would raise <code>PropertyChanged</code> in the event of this kind of coercion, but that breaks the code contract for <code>INotifyPropertyChanged</code> in that <em>nothing changed</em>. So how do we get around this problem?</p><p>If you take a look at the invocation list of your <code>PropertyChanged</code> event with some bound variables, you&#8217;ll notice that there&#8217;s a <code>PropertyChangedEventManager</code> hooked up.</p><p><a href="http://northhorizon.net/wp-content/uploads/2011/05/propertychangedeventmanager-watch.png"><img class="aligncenter size-full wp-image-432" title="PropertyChangedEventManager in the Watch" src="http://northhorizon.net/wp-content/uploads/2011/05/propertychangedeventmanager-watch.png" alt="" width="707" height="330" /></a></p><p>Considering that the other item in the list is my default delegate, this object must be responsible for communicating my events to the binding system</p><p>Of course, the next thing to do is fire up Reflector and take a look at what&#8217;s there.</p><pre class="brush:csharp">public class PropertyChangedEventManager : WeakEventManager {// Fields private WeakEventManager.ListenerList _proposedAllListenersList; private static readonly string AllListenersKey; // Methods static PropertyChangedEventManager(); private PropertyChangedEventManager(); public static void AddListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); private void OnPropertyChanged(object sender, PropertyChangedEventArgs args); private void PrivateAddListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); private void PrivateRemoveListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); protected override bool Purge(object source, object data, bool purgeAll); public static void RemoveListener(INotifyPropertyChanged source, IWeakEventListener listener, string propertyName); protected override void StartListening(object source); protected override void StopListening(object source); // Properties private static PropertyChangedEventManager CurrentManager { get; }}</pre><p>Basically, <code>AddListener</code> access the private <code>CurrentManager</code> singleton and subscribes the given listener to <code>OnPropertyChanged</code>. Fortunately for us, there&#8217;s a flaw in th the implementation of <code>OnPropertyChanged</code>. What it does is it gets the list of listeners based on the sender and raises their event with the given sender and args. The problem here is that it doesn&#8217;t verify that the object raising the event is actually the sender! That is to say, we should be able to send a fake PropertyChanged event through another object acting as a surrogate. All we need to do is add that object to the PropertyChangedEvenManager&#8217;s list and start impersonating.</p><p>To that end, I added this private class to <code>BindableBase</code> to lazily add the <code>INotifyPropertyChanged</code> proxy object to the <code>PropertyChangedEventManager</code>. Since we&#8217;re not actually interested in the events, I made a stub implementation of <code>IWeakEventListener</code> that returns false constantly to indicate it&#8217;s not handling the event. Finally, I hold onto both of these references to keep them from being garbage collected.</p><pre class="brush:csharp">private class PropertyChangedEventManagerProxy {// We need to hold on to these refs to keep it from getting GC'd private readonly NotifyPropertyChangedProxy _notifyPropertyChangedProxy; private readonly IWeakEventListener _weakEventListener; private PropertyChangedEventManagerProxy() {_notifyPropertyChangedProxy = new NotifyPropertyChangedProxy(); _weakEventListener = new WeakListenerStub(); PropertyChangedEventManager.AddListener(_notifyPropertyChangedProxy, _weakEventListener, string.Empty); }public void RaisePropertyChanged(object sender, string propertyName) {_notifyPropertyChangedProxy.Raise(sender, new PropertyChangedEventArgs(propertyName)); }private static PropertyChangedEventManagerProxy _instance; public static PropertyChangedEventManagerProxy Instance { get { return _instance ?? (_instance = new PropertyChangedEventManagerProxy()); } } private class NotifyPropertyChangedProxy : INotifyPropertyChanged {public event PropertyChangedEventHandler PropertyChanged = delegate { }; public void Raise(object sender, PropertyChangedEventArgs e) {PropertyChanged(sender, e); }} private class WeakListenerStub : IWeakEventListener {public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { return false; }} }</pre><p>The only thing left to do is add the coerce value function as an optional parameter on <code>SetProperty</code> and hook it up:</p><pre class="brush:csharp">protected void SetProperty&lt;T&gt;( ref T backingStore, T value, string propertyName, Action onChanged = null, Action&lt;T&gt; onChanging = null, Func&lt;T, T&gt; coerceValue = null) {VerifyCallerIsProperty(propertyName); var effectiveValue = coerceValue != null ? coerceValue(value) : value; if (EqualityComparer&lt;T&gt;.Default.Equals(backingStore, effectiveValue)) {// If we coerced this value and the coerced value is not equal to the original, we need to // send a fake PropertyChanged event to notify WPF that this value isn't what it thinks it is. if (coerceValue != null &amp;&amp; !EqualityComparer&lt;T&gt;.Default.Equals(value, effectiveValue)) PropertyChangedEventManagerProxy.Instance.RaisePropertyChanged(this, propertyName); return; }if (onChanging != null) onChanging(effectiveValue); OnPropertyChanging(propertyName); backingStore = effectiveValue; if (onChanged != null) onChanged(); OnPropertyChanged(propertyName); }</pre><p>And there you have it. All the benefits of dependency property coercion, and the same short, sweet <code>SetProperty</code> syntax.</p><p>As before, everything is on <a href="https://github.com/danielmoore/InpcTemplate">GitHub</a> so you can take a look at the whole thing and fork it if you see something to be improved.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/coercing-viewmodel-values-with-inotifypropertychanged/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>The Right Way to do INotifyPropertyChanged</title>
			<link>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/</link>
			<comments>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/#comments</comments>
			<pubDate>Sun, 20 Feb 2011 22:35:12 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[Uncategorized]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Extension Methods]]></category>
			<category><![CDATA[INotifyPropertyChanged]]></category>
			<category><![CDATA[Lambda]]></category>
			<category><![CDATA[patterns]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=397</guid>
			<description><![CDATA[It&#8217;s sad how much controversy there is in doing something as simple as raising property change notification to our subscribers. It seems to me that we should have settled on something by now and moved on to bigger problems, yet, still, I see developers at every level of experience doing it differently. I want to [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s sad how much controversy there is in doing something as simple as raising property change notification to our subscribers. It seems to me that we should have settled on something by now and moved on to bigger problems, yet, still, I see developers at every level of experience doing it differently.</p><p>I want to inform you all that <a href="http://xkcd.com/386/">you&#8217;re doing it wrong</a>.<span id="more-397"></span></p><h2>The Problem</h2><p>Most projects choose to implement <code>INotifyPropertyChanged</code> instead of extending <code>DependencyObject</code> for the sole reason that dependency properties are an enormous pain to write. Having worked on a large project that used the latter approach, I&#8217;ve entirely sworn it off, and I don&#8217;t care what kind of tooling you say makes life better. It&#8217;s just too complicated. On top of that, it&#8217;s really difficult to subscribe to changes programmatically. Sure you can go through <code>DependencyPropertyDescriptor</code> and subscribe yourself, but that&#8217;s a hell of a lot harder than <code>+=</code>. So that leaves some people with properties that look like this:</p><pre class="brush:csharp">private int _myValue; public int MyValue {get { return _myValue; }set { _myValue = value; OnPropertyChanged("MyValue"); }}</pre><p>Not bad, perhaps. It just doesn&#8217;t do much. What about <code>INotifyPropertyChanging</code>? How do I do things internally when that property changes other than subscribing to my own <code>PropertyChanged</code> event?</p><p>These things could almost be overlooked. The real kicker is that this isn&#8217;t actually a proper implementation of <code>INotifyPropertyChanged</code>. <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx">According to MSDN</a>, the <code>PropertyChanged</code> event is described as, &#8220;Occurs when a property value changes,&#8221; and this code will raise an event even if the value doesn&#8217;t. Their implementation looks like this:</p><pre class="brush: csharp">private string customerNameValue = String.Empty; public string CustomerName {get {return this.customerNameValue; }set {if (value != this.customerNameValue) {this.customerNameValue = value; NotifyPropertyChanged("CustomerName"); }} }</pre><p>Aside from their code style (or lack thereof), allow me to point out a few things. First &#8211; and foremost &#8211; they&#8217;re comparing string equality with operators, no mere venial sin in my book. Secondly, this puts the onus of figuring out how to compare two types on the property writer ad-hoc, rather than using something more intelligent. Finally, does anyone else think that 17 lines is a few too many for a <em>dirt simple</em> property? It&#8217;s crazy.</p><h2>The Trouble with Lambda</h2><p>Some very smart programmers I know like to have their <code>NotifyPropertyChanged</code> method take an Expression&lt;Func&lt;TProp&gt;&gt; so you can do something like:</p><pre class="brush: csharp">private int _myValue; public int MyValue {get { return _myValue; }set { _myValue = value; NotifyPropertyChanged(() =&gt; MyValue); }}</pre><p>They say it improves type checking and the ease of refactoring. But as it turns out, <a href="http://blog.quantumbitdesigns.com/2010/01/26/mvvm-lambda-vs-inotifypropertychanged-vs-dependencyobject/">it&#8217;s god-awful for performance</a>, which can run you into a lot of problems if you don&#8217;t keep track of even moderate update bursts.</p><p>I&#8217;d almost be willing to accept the performance trade-off if it weren&#8217;t for the fact that the only place that&#8217;s calling it is <em>inside the property setter</em>. When you&#8217;re refactoring, I don&#8217;t see it as too much effort to go ahead and fix the string in the underlying property setter while you&#8217;re there; you have to fix the backing member anyway.</p><p>Really what we need is lambdas for subscription. All those places out in your code that subscribe to <code>PropertyChanged</code> and then you check the property name with a string! That&#8217;s the real refactoring nightmare. What I want to do is <code>myViewModel.SubscribeToPropertyChanged(vm =&gt; vm.Foo, OnFooChanged);</code></p><p>The implementation isn&#8217;t that complex at all:</p><pre class="brush:csharp">public static IDisposable SubscribeToPropertyChanged&lt;TSource, TProp&gt;( this TSource source, Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector, Action onChanged) where TSource : INotifyPropertyChanged {if (source == null) throw new ArgumentNullException("source"); if (propertySelector == null) throw new ArgumentNullException("propertySelector"); if (onChanged == null) throw new ArgumentNullException("onChanged"); var subscribedPropertyName = GetPropertyName(propertySelector); PropertyChangedEventHandler handler = (s, e) =&gt; {if (string.Equals(e.PropertyName, subscribedPropertyName, StringComparison.InvariantCulture)) onChanged(); }; source.PropertyChanged += handler; return Disposable.Create(() =&gt; source.PropertyChanged -= handler); }public static IDisposable SubscribeToPropertyChanging&lt;TSource, TProp&gt;( this TSource source, Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector, Action onChanging) where TSource : INotifyPropertyChanging {if (source == null) throw new ArgumentNullException("source"); if (propertySelector == null) throw new ArgumentNullException("propertySelector"); if (onChanging == null) throw new ArgumentNullException("onChanged"); var subscribedPropertyName = GetPropertyName(propertySelector); PropertyChangingEventHandler handler = (s, e) =&gt; {if (string.Equals(e.PropertyName, subscribedPropertyName, StringComparison.InvariantCulture)) onChanging(); }; source.PropertyChanging += handler; return Disposable.Create(() =&gt; source.PropertyChanging -= handler); }private static string GetPropertyName&lt;TSource, TProp&gt;(Expression&lt;Func&lt;TSource, TProp&gt;&gt; propertySelector) {var memberExpr = propertySelector.Body as MemberExpression; if (memberExpr == null) throw new ArgumentException("must be a member accessor", "propertySelector"); var propertyInfo = memberExpr.Member as PropertyInfo; if (propertyInfo == null || propertyInfo.DeclaringType != typeof(TSource)) throw new ArgumentException("must yield a single property on the given object", "propertySelector"); return propertyInfo.Name; }</pre><h2>The Best Solution</h2><p>This leaves me with a pretty explicit spec for implementing <code>INotifyPropertyChanged</code>:</p><ol><li>It will take no more lines than a basic backing field setter.</li><li>It will raise INotifyPropertyChanged and INotifyPropertyChanging.</li><li>It will only raise the properties if the value has changed.</li><li>it will provide an easy way to have internal property changed subscriptions.</li><li>It will not use Lambdas to identify the property.</li></ol><p>My solution allows you to do this:</p><pre class="brush: csharp">private int _myValue; public int MyValue {get { return _myValue; }set { SetProperty(ref _myValue, value, OnMyValueChanged, OnMyValueChanging); }} private void OnMyValueChanged() { } private void OnMyValueChanging(int newValue) { }</pre><p>Isn&#8217;t that nice? SetProperty looks like this:</p><pre class="brush:csharp">protected void SetProperty( ref T backingStore, T value, string propertyName, Action onChanged = null, Action onChanging = null) {VerifyCallerIsProperty(propertyName); if (EqualityComparer&lt;T&gt;.Default.Equals(backingStore, value)) return; if (onChanging != null) onChanging(value); OnPropertyChanging(propertyName); backingStore = value; if (onChanged != null) onChanged(); OnPropertyChanged(propertyName); }[Conditional("DEBUG")] private void VerifyCallerIsProperty(string propertyName) {var stackTrace = new StackTrace(); var frame = stackTrace.GetFrames()[2]; var caller = frame.GetMethod(); if (!caller.Name.Equals("set_" + propertyName, StringComparison.InvariantCulture)) throw new InvalidOperationException( string.Format("Called SetProperty for {0} from {1}", propertyName, caller.Name)) }</pre><p>The default parameters on <code>SetProperty</code> allow you to specify the changed callback or the changing callbacks in any permutation with the usual syntax and the stack trace analysis happens at debug time to make sure that the string you provide actually represents the property it&#8217;s being called from.</p><p>So how do we update dependent properties? The one thing you don&#8217;t want to do is <strong>ever</strong> have external property changing logic directly in your set method. It&#8217;s better to call out to a <code>OnMyPropertyChanging</code> event and have that method update your dependent method. The syntax is a little verbose, but it&#8217;s the most readable and extensible way to do it:</p><pre class="brush: csharp">private int _foo; public int Foo {get { return _foo; }set { SetProperty(ref _foo, value, "Foo", OnFooChanged); }} private int _bar; public int Bar {get { return _bar; }set { SetProperty(ref _bar, value, "Bar", OnBarChanged); }} private int _foobar; public int Foobar {get { return _foobar; }private set { SetProperty(ref _foobar, value, "Foobar"); }} private void OnFooChanged() { UpdateFoobar(); }private void OnBarChanged() { UpdateFoobar(); }private void UpdateFoobar() { Foobar = _foo + _bar; }</pre><p>In general you should <strong>never</strong> call <code>OnProeprtyChanged</code>; that decision is best left to the property and its underlying helper.</p><p>I hope this clears the water  for some people new to WPF and provides reasons for the veterans to change their tune. If you think I&#8217;m wrong, feel free to try and prove it to me in the comments section. After all, duty calls.</p><p>The source and XML documentation for all this and a few tests is on <a href="https://github.com/danielmoore/InpcTemplate">github</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2011/the-right-way-to-do-inotifypropertychanged/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		</item>
		<item>
			<title>How to Actually Change the System Theme in WPF</title>
			<link>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/</link>
			<comments>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/#comments</comments>
			<pubDate>Sun, 05 Dec 2010 22:21:22 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Reflection]]></category>
			<category><![CDATA[Styles]]></category>
			<category><![CDATA[Themes]]></category>
			<category><![CDATA[WPF]]></category>
			<category><![CDATA[XAML]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=372</guid>
			<description><![CDATA[When I first started working with WPF professionally, it wasn&#8217;t very long before I realized I needed to change the system theme of WPF to give my users a consistent experience across platforms. Not to mention that Vista&#8217;s theme was much improved over XP and even more so over the classic theme. Conceptually, this should [...]]]></description>
			<content:encoded><![CDATA[<p>When I first started working with WPF professionally, it wasn&#8217;t very long before I realized I needed to change the system theme of WPF to give my users a consistent experience across platforms. Not to mention that Vista&#8217;s theme was <em>much</em> improved over XP and even more so over the classic theme. Conceptually, this should be feasible, since WPF has its own rendering engine, as opposed to WinForms relying on GDI.<span id="more-372"></span></p><p>Naturally, the first thing I did was to <a href="http://www.google.com/search?q=wpf+force+vista+theme">Google the answer</a>. The <a href="http://arbel.net/blog/archive/2006/11/03/Forcing-WPF-to-use-a-specific-Windows-theme.aspx">first result</a> looked pretty good so I implemented that:</p><pre class="brush: xml">&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/PresentationFramework.Aero;V4.0.0.0;31bf3856ad364e35;component/themes/aero.normalcolor.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt;</pre><p>This worked great up until I started styling things. Any time I created a style for one of the system controls, it&#8217;d change the underlying style back to the original system them, rather than the one I wanted. It turns out that naturally styles are based on the system theme, rather than implicit style (for reasons we&#8217;ll get into later). So the way to base a theme off of the implicit style is like this:</p><pre class="brush: xml">&lt;Style x:Key="GreenButtonStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"&gt; &lt;Setter Property="Background" Value="Green"/&gt; &lt;Setter Property="Foreground" Value="White"/&gt; &lt;/Style&gt;</pre><p>Maybe a little inconvenient, but it gets the job done:﻿</p><p><a href="http://northhorizon.net/wp-content/uploads/2010/12/dictionary-based-theme-change.png"><img class="aligncenter size-full wp-image-383" title="Dictionary Based Theme Change" src="http://northhorizon.net/wp-content/uploads/2010/12/dictionary-based-theme-change.png" alt="" width="525" height="350" /></a></p><p>All was well up until I needed to make a new style based off of the default theme. Like many WPF applications, we had some default styles defined to give our controls a clean, consistent look. But in my particular case, I needed to make a whole new visual &#8220;branch,&#8221; using the default theme as the &#8220;trunk.&#8221; If I used my <code>BasedOn</code> workaround, I&#8217;d just get my implicit style; if I didn&#8217;t I&#8217;d get that nasty classic theme.</p><p>The more I thought about this, the more I realized that all of these problems were being caused by the fact that I was applying a system theme (aero.normalcolor) as a style on top of the actual system theme, rather than <em>actually</em> changing it. So I set off on a journey in Reflector to find out how WPF picks the current theme. This sounds hard, and it&#8217;s actually a lot harder than it sounds. After a dozen or so hours (spread out over a few weeks) and a some guidance by <a href="http://learnwpf.com/Posts/Post.aspx?postId=3f1f4b8b-b91a-442d-a531-919de70ac225">a blog that got really close</a> (unfortunately, my link is now dead), I found out that however WPF calls a native method in uxtheme.dll to get the actual system theme, then stores the result in <code>MS.Win32.UxThemeWrapper</code>, an internal static class (of course). Furthermore, the properties on the class are read only (and also marked internal), so the best way to change it was by directly manipulating the private fields. My solution looks like this:</p><pre class="brush: csharp">public partial class App : Application {public App() {SetTheme("aero", "normalcolor"); }/// &lt;summary&gt; /// Sets the WPF system theme. /// &lt;/summary&gt; /// &lt;param name="themeName"&gt;The name of the theme. (ie "aero")&lt;/param&gt; /// &lt;param name="themeColor"&gt;The name of the color. (ie "normalcolor")&lt;/param&gt; public static void SetTheme(string themeName, string themeColor) {const BindingFlags staticNonPublic = BindingFlags.Static | BindingFlags.NonPublic; var presentationFrameworkAsm = Assembly.GetAssembly(typeof(Window)); var themeWrapper = presentationFrameworkAsm.GetType("MS.Win32.UxThemeWrapper"); var isActiveField = themeWrapper.GetField("_isActive", staticNonPublic); var themeColorField = themeWrapper.GetField("_themeColor", staticNonPublic); var themeNameField = themeWrapper.GetField("_themeName", staticNonPublic); // Set this to true so WPF doesn't default to classic. isActiveField.SetValue(null, true); themeColorField.SetValue(null, themeColor); themeNameField.SetValue(null, themeName); }}</pre><p>I call the method in the <code>App</code> constructor so it sets the values after WPF does its detection, but before the system theme is loaded for rendering.</p><p>Here&#8217;s what I got back:</p><p><img class="aligncenter size-full wp-image-384" title="Basic Reflection Theme Change" src="http://northhorizon.net/wp-content/uploads/2010/12/basic-reflection-theme-change.png" alt="" width="525" height="350" />Success!</p><p>There&#8217;s still a couple downsides to this approach. First, I can&#8217;t change the theme whenever I want to, and secondly, if the user changes their Windows theme while the application is running, the theme I set gets wiped out.</p><p>Wait a minute. If Windows can change the application theme, I can too!</p><p>Poking around a little more, I found out that when WPF wants to find a system resource, it also calls <code>System.Windows.SystemResources.EnsureResourceChangeListener()</code> which makes sure there&#8217;s a listener attached to the Windows message pump, ready to interpret events like a theme change.</p><pre class="brush:csharp">[SecurityCritical, SecurityTreatAsSafe] private static void EnsureResourceChangeListener() {if (_hwndNotify == null) {HwndWrapper wrapper = new HwndWrapper(0, -2013265920, 0, 0, 0, 0, 0, "SystemResourceNotifyWindow", IntPtr.Zero, null); _hwndNotify = new SecurityCriticalDataClass&lt;HwndWrapper&gt;(wrapper); _hwndNotify.Value.Dispatcher.ShutdownFinished += new EventHandler(SystemResources.OnShutdownFinished); _hwndNotifyHook = new HwndWrapperHook(SystemResources.SystemThemeFilterMessage); _hwndNotify.Value.AddHook(_hwndNotifyHook); }}</pre><p>The handler looks like this:</p><pre class="brush: csharp">[SecurityTreatAsSafe, SecurityCritical] private static IntPtr SystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {WindowMessage message = (WindowMessage) msg; switch (message) {// abridged case WindowMessage.WM_THEMECHANGED: SystemColors.InvalidateCache(); SystemParameters.InvalidateCache(); OnThemeChanged(); InvalidateResources(false); break; }return IntPtr.Zero; }</pre><p>So the plan was to remove the hook so the message pump couldn&#8217;t change the theme out from under me and then call the handler whenever <em>I</em> want. As it turns out, it&#8217;s even easier than that. Because the list of hooks is implemented with a WeakReferenceList, all I need to do is null out the private <code>_hwndNotifyHook</code> field. There&#8217;s just one problem here: killing the handler prevents us from receiving system notifications for the other messages like device changes, power updates, etc. So we really need to inject a filter into the pipeline and pass along everything except the ThemeChanged event.</p><p>Fair warning: if you get queasy around reflection, you should probably stop reading here.</p><pre class="brush: csharp">public static class ThemeHelper {private const BindingFlags InstanceNonPublic = BindingFlags.Instance | BindingFlags.NonPublic; private const BindingFlags StaticNonPublic = BindingFlags.Static | BindingFlags.NonPublic; private const int ThemeChangedMessage = 0x31a; private static readonly MethodInfo FilteredSystemThemeFilterMessageMethod =typeof(ThemeHelper).GetMethod("FilteredSystemThemeFilterMessage", StaticNonPublic); private static readonly Assembly PresentationFramework =Assembly.GetAssembly(typeof(Window)); private static readonly Type ThemeWrapper =PresentationFramework.GetType("MS.Win32.UxThemeWrapper"); private static readonly FieldInfo ThemeWrapper_isActiveField =ThemeWrapper.GetField("_isActive", StaticNonPublic); private static readonly FieldInfo ThemeWrapper_themeColorField =ThemeWrapper.GetField("_themeColor", StaticNonPublic); private static readonly FieldInfo ThemeWrapper_themeNameField =ThemeWrapper.GetField("_themeName", StaticNonPublic); private static readonly Type SystemResources =PresentationFramework.GetType("System.Windows.SystemResources"); private static readonly FieldInfo SystemResources_hwndNotifyField =SystemResources.GetField("_hwndNotify", StaticNonPublic); private static readonly FieldInfo SystemResources_hwndNotifyHookField =SystemResources.GetField("_hwndNotifyHook", StaticNonPublic); private static readonly MethodInfo SystemResources_EnsureResourceChangeListener =SystemResources.GetMethod("EnsureResourceChangeListener", StaticNonPublic); private static readonly MethodInfo SystemResources_SystemThemeFilterMessageMethod =SystemResources.GetMethod("SystemThemeFilterMessage", StaticNonPublic); private static readonly Assembly WindowsBase =Assembly.GetAssembly(typeof(DependencyObject)); private static readonly Type HwndWrapperHook =WindowsBase.GetType("MS.Win32.HwndWrapperHook"); private static readonly Type HwndWrapper =WindowsBase.GetType("MS.Win32.HwndWrapper"); private static readonly MethodInfo HwndWrapper_AddHookMethod =HwndWrapper.GetMethod("AddHook"); private static readonly Type SecurityCriticalDataClass =WindowsBase.GetType("MS.Internal.SecurityCriticalDataClass`1") .MakeGenericType(HwndWrapper); private static readonly PropertyInfo SecurityCriticalDataClass_ValueProperty =SecurityCriticalDataClass.GetProperty("Value", InstanceNonPublic); /// &lt;summary&gt; /// Sets the WPF system theme. /// &lt;/summary&gt; /// &lt;param name="themeName"&gt;The name of the theme. (ie "aero")&lt;/param&gt; /// &lt;param name="themeColor"&gt;The name of the color. (ie "normalcolor")&lt;/param&gt; public static void SetTheme(string themeName, string themeColor) {SetHwndNotifyHook(FilteredSystemThemeFilterMessageMethod); // Call the system message handler with ThemeChanged so it // will clear the theme dictionary caches. InvokeSystemThemeFilterMessage(IntPtr.Zero, ThemeChangedMessage, IntPtr.Zero, IntPtr.Zero, false); // Need this to make sure WPF doesn't default to classic. ThemeWrapper_isActiveField.SetValue(null, true); ThemeWrapper_themeColorField.SetValue(null, themeColor); ThemeWrapper_themeNameField.SetValue(null, themeName); }public static void Reset() {SetHwndNotifyHook(SystemResources_SystemThemeFilterMessageMethod); InvokeSystemThemeFilterMessage(IntPtr.Zero, ThemeChangedMessage, IntPtr.Zero, IntPtr.Zero, false); }private static void SetHwndNotifyHook(MethodInfo method) {var hookDelegate = Delegate.CreateDelegate(HwndWrapperHook, FilteredSystemThemeFilterMessageMethod); // Note that because the HwndwWrapper uses a WeakReference list, we don't need // to remove the old value. Simply killing the reference is good enough. SystemResources_hwndNotifyHookField.SetValue(null, hookDelegate); // Make sure _hwndNotify is set! SystemResources_EnsureResourceChangeListener.Invoke(null, null); // this does SystemResources._hwndNotify.Value.AddHook(hookDelegate) var hwndNotify = SystemResources_hwndNotifyField.GetValue(null); var hwndNotifyValue = SecurityCriticalDataClass_ValueProperty.GetValue(hwndNotify, null); HwndWrapper_AddHookMethod.Invoke(hwndNotifyValue, new object[] { hookDelegate }); }private static IntPtr InvokeSystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, bool handled) {return (IntPtr)SystemResources_SystemThemeFilterMessageMethod.Invoke(null, new object[] { hwnd, msg, wParam, lParam, handled }); }private static IntPtr FilteredSystemThemeFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {if (msg == ThemeChangedMessage) return IntPtr.Zero; return InvokeSystemThemeFilterMessage(hwnd, msg, wParam, lParam, handled); }}</pre><p>What a mess! What&#8217;s really annoying is that this entire process could have (and, I argue, should have) been made public to user code. In the very least, I&#8217;d like to be able to decorate my assembly with an attribute declaring which theme I&#8217;d like to run under, but I think it&#8217;s completely reasonable to have an public static class provide the same API I have here.</p><p>The whole test suite is available <del><a href="http://northhorizon.net/wp-content/uploads/2010/12/SystemThemeChangeTest.zip">here</a></del> on <a href="https://github.com/danielmoore/SystemThemeChange">GitHub</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/how-to-actually-change-the-system-theme-in-wpf/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		</item>
		<item>
			<title>The Extension Method Pack</title>
			<link>http://northhorizon.net/2010/the-extension-method-pack/</link>
			<comments>http://northhorizon.net/2010/the-extension-method-pack/#comments</comments>
			<pubDate>Thu, 27 May 2010 12:19:26 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Coding]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Dependency Object]]></category>
			<category><![CDATA[Extension Methods]]></category>
			<category><![CDATA[Hash Table]]></category>
			<category><![CDATA[Lambda]]></category>
			<category><![CDATA[WPF]]></category>
			<category><![CDATA[XMP]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=220</guid>
			<description><![CDATA[Since .NET 3.0 came out, I&#8217;ve been enjoying taking advantage of extension methods and the ability to create my own. The thing I&#8217;ve noticed is that a handful of them are useful to almost any application, above and beyond what Microsoft provides in System.Linq. So over the last few days I took the time to [...]]]></description>
			<content:encoded><![CDATA[<p>Since .NET 3.0 came out, I&#8217;ve been enjoying taking advantage of extension methods and the ability to create my own. The thing I&#8217;ve noticed is that a handful of them are useful to almost any application, above and beyond what Microsoft provides in <code>System.Linq</code>. So over the last few days I took the time to gather these methods together, unit test them, and run them through FXCop to make a high-quality package ready to go in any application with a little re-namespacing.</p><p>I&#8217;ve broken each code sample into independent blocks wherein all necessary dependencies are contained, so you can take any extension method <em>a la carte</em> or you can get everything from the <a href="http://northhorizon.net/wp-content/uploads/2010/05/Extension-Method-Pack.zip">attached zip file</a>. My solution was built in .NET 4.0 in Visual Studio 2010, but everything should work just fine in .NET 3.5 with Visual Studio 2008.</p><p>Also included in the zip file are my unit tests, which may help you understand usage of some of the more esoteric extensions, such as ChainGet, and XML comments for your IntelliSense and XML documentation generator.</p><p><strong>Edit:</strong> The whole solution is now available on <a href="https://github.com/danielmoore/Extension-Method-Pack">github</a>!</p><p><span id="more-220"></span></p><p>Here&#8217;s the table of contents, so you can jump around more easily:<br /><a name="toc"></a></p><ul><li>IEnumerable<ul><li><a href="#IEnumerable.Foreach">ForEach</a></li><li><a href="#IEnumerable.Append">Append</a></li><li><a href="#IEnumerable.Prepend">Prepend</a></li><li><a href="#IEnumerable.AsObservable">AsObservable</a></li><li><a href="#IEnumerable.AsHashSet">AsHashSet</a></li><li><a href="#IEnumerable.ArgMax">ArgMax</a></li><li><a href="#IEnumerable.ArgMin">ArgMin</a></li></ul></li><li>ICollection<ul><li><a href="#ICollection.AddAll">AddAll</a></li><li><a href="#ICollection.RemoveAll">RemoveAll</a></li></ul></li><li>IDictionary<ul><li><a href="#IDictionary.Add">Add</a></li><li><a href="#IDictionary.AddAll">AddAll</a></li><li><a href="#IDictionary.Remove">Remove</a></li><li><a href="#IDictionary.RemoveAll">RemoveAll</a></li><li><a href="#IDictionary.RemoveAndClean">RemoveAndClean</a></li><li><a href="#IDictionary.RemoveAllAndClean">RemoveAllAndClean</a></li><li><a href="#IDictionary.Clean">Clean</a></li></ul></li><li>Object<ul><li><a href="#Object.As">As</a></li><li><a href="#Object.AsValueType">AsValueType</a></li><li><a href="#Object.ChainGet">ChainGet</a></li></ul></li><li>DependencyObject<ul><li><a href="#DependencyObject.SafeGetValue">SafeGetValue</a></li><li><a href="#DependencyObject.SafeSetValue">SafeSetValue</a></li></ul></li></ul><h2>IEnumerable</h2><p><a name="IEnumerable.ForEach"></a><code>ForEach</code> is pretty straightforward. It mimics <code>List&lt;T&gt;.ForEach</code>, but for all <code>IEnumerable</code>, both generic and weakly typed.</p><pre class="brush: csharp">public static void ForEach&lt;T&gt;( this IEnumerable&lt;T&gt; collection, Action&lt;T&gt; action) {if (collection == null) throw new ArgumentNullException("collection"); if (action == null) throw new ArgumentNullException("action"); foreach (var item in collection) action(item); }</pre><pre class="brush: csharp">public static void ForEach( this IEnumerable collection, Action&lt;object&gt; action) {if (collection == null) throw new ArgumentNullException("collection"); if (action == null) throw new ArgumentNullException("action"); foreach (var item in collection) action(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.Append"></a><a name="IEnumerable.Prepend"></a><code>Append</code> and <code>Prepend</code> simply take an item and return a a new <code>IEnumerable&lt;T&gt;</code> with that item on the end or beginning, respectively. <code>Prepend</code> is the equivalent of the <code><a href="http://en.wikipedia.org/wiki/cons" title="cons" >cons</a></code> operation to a list.</p><pre class="brush: csharp">public static IEnumerable&lt;T&gt; Append&lt;T&gt;( this IEnumerable&lt;T&gt; collection, T item) {if (collection == null) throw new ArgumentNullException("collection"); if (item == null) throw new ArgumentNullException("item"); foreach (var colItem in collection) yield return colItem; yield return item; }</pre><pre class="brush: csharp">public static IEnumerable&lt;T&gt; Prepend&lt;T&gt;( this IEnumerable&lt;T&gt; collection, T item) {if (collection == null) throw new ArgumentNullException("collection"); if (item == null) throw new ArgumentNullException("item"); yield return item; foreach (var colItem in collection) yield return colItem; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.AsObservable"></a><a name="IEnumerable.AsHashSet"></a><code>AsObservable</code> and <code>AsHashSet</code> yield their respective data structures, but check to see if they are already what you want, saving valuable time when dealing with interfaces.</p><pre class="brush: csharp">public static ObservableCollection&lt;T&gt; AsObservable&lt;T&gt;( this IEnumerable&lt;T&gt; collection) {if (collection == null) throw new ArgumentNullException("collection"); return collection as ObservableCollection&lt;T&gt; ?? new ObservableCollection&lt;T&gt;(collection); }</pre><pre class="brush: csharp">public static HashSet&lt;T&gt; AsHashSet&lt;T&gt;(this IEnumerable&lt;T&gt; collection) {if (collection == null) throw new ArgumentNullException("collection"); return collection as HashSet&lt;T&gt; ?? new HashSet&lt;T&gt;(collection); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IEnumerable.ArgMax"></a><a name="IEnumerable.ArgMin"></a><code><a href="http://en.wikipedia.org/wiki/Arg max" title="Arg max" >ArgMax</a></code> and <code>ArgMin</code> are corollaries to <code>Max</code> and <code>Min</code> in the <code>System.Linq</code> namespace, but return the item in the list that produced the highest value from <code>Max</code> or least value from <code>Min</code>, respectively.</p><pre class="brush: csharp">public static T ArgMax&lt;T, TValue&gt;( this IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function) where TValue : IComparable&lt;TValue&gt; {return ArgComp(collection, function, GreaterThan); }private static bool GreaterThan&lt;T&gt;(T first, T second) where T : IComparable&lt;T&gt; {return first.CompareTo(second) &gt; 0; }public static T ArgMin&lt;T, TValue&gt;( this IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function) where TValue : IComparable&lt;TValue&gt; {return ArgComp(collection, function, LessThan); }private static bool LessThan&lt;T&gt;(T first, T second) where T : IComparable&lt;T&gt; {return first.CompareTo(second) &lt; 0; }private static T ArgComp&lt;T, TValue&gt;( IEnumerable&lt;T&gt; collection, Func&lt;T, TValue&gt; function, Func&lt;TValue, TValue, bool&gt; accept) where TValue : IComparable&lt;TValue&gt; {if (collection == null) throw new ArgumentNullException("collection"); if (function == null) throw new ArgumentNullException("function"); var isSet = false; var maxArg = default(T); var maxValue = default(TValue); foreach (var item in collection) {var value = function(item); if (!isSet || accept(value, maxValue)) {maxArg = item; maxValue = value; isSet = true; }} return maxArg; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>ICollection</h2><p><a name="ICollection.AddAll"></a><code>AddAll</code> imitates <code>List&lt;T&gt;.AddRange</code>.</p><pre class="brush: csharp">public static void AddAll&lt;T&gt;( this ICollection&lt;T&gt; collection, IEnumerable&lt;T&gt; additions) {if (collection == null) throw new ArgumentNullException("collection"); if (additions == null) throw new ArgumentNullException("additions"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); foreach (var item in additions) collection.Add(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="ICollection.RemoveAll"></a><code>RemoveAll</code> imitates <code>List&lt;T&gt;.RemoveAll</code>. A second overload allows you to specify the removals if you already have them.</p><pre class="brush: csharp">public static IEnumerable&lt;T&gt; RemoveAll&lt;T&gt;( this ICollection&lt;T&gt; collection, Predicate&lt;T&gt; predicate) {if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); // we can't possibly remove more than the entire list. var removals = new List&lt;T&gt;(collection.Count); // this is an O(n + m * k) operation where n is collection.Count, // m is removals.Count, and K is the removal operation time. Because // we know n &gt;= m, this is an O(n + n * k) operation or just O(n * k). foreach (var item in collection) if (predicate(item)) removals.Add(item); foreach (var item in removals) collection.Remove(item); return removals; }</pre><pre class="brush: csharp">public static void RemoveAll&lt;T&gt;( this ICollection&lt;T&gt; collection, IEnumerable&lt;T&gt; removals) {if (collection == null) throw new ArgumentNullException("collection"); if (removals == null) throw new ArgumentNullException("removals"); if (collection.IsReadOnly) throw new InvalidOperationException("collection is read only"); foreach (var item in removals) collection.Remove(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>IDictionary</h2><p>All of these methods have to do with <a href="http://en.wikipedia.org/wiki/Hash table" title="Hash table" >hash tables</a>. I use them pretty frequently and these methods are able to make life a lot easier.</p><p><a name="IDictionary.Add"></a><a name="IDictionary.AddAll"></a><code>Add</code> and <code>AddAll</code> insert the key and a new collection into the dictionary if the key doesn&#8217;t already exist and then adds the item or items to the collection.</p><pre class="brush: csharp">public static void Add&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt;, new() {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) {if (col.IsReadOnly) throw new InvalidOperationException("bucket is read only"); }else dictionary.Add(key, col = new TCol()); col.Add(item); }</pre><pre class="brush: csharp">public static void AddAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; additions) where TCol : ICollection&lt;TItem&gt;, new() {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (additions == null) throw new ArgumentNullException("additions"); TCol col; if (!dictionary.TryGetValue(key, out col)) dictionary.Add(key, col = new TCol()); foreach (var item in additions) col.Add(item); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.Remove"></a><a name="IDictionary.RemoveAll"></a><code>Remove</code> and <code>RemoveAll</code> simply remove items from the collection associated with the specified key, if there is one. For the predicate overloads, you need to explicitly construct your <code>Predicate&lt;T&gt;</code> delegate because the C# compiler has trouble doing the type inference.</p><pre class="brush: csharp">public static void Remove&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) col.Remove(item); }</pre><pre class="brush: csharp">public static void RemoveAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; removals) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (removals == null) throw new ArgumentNullException("removals"); TCol col; if (dictionary.TryGetValue(key, out col)) foreach (var item in removals) col.Remove(item); }</pre><pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAll&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, Predicate&lt;TItem&gt; predicate) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (predicate == null) throw new ArgumentNullException("predicate"); var removals = new List&lt;TItem&gt;(); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in col) if (predicate(item)) removals.Add(item); foreach (var item in removals) col.Remove(item); }return removals; }// Usage: Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary; myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.RemoveAndClean"></a><a name="IDictionary.RemoveAllAndClean"></a><code>RemoveAndClean</code> and <code>RemoveAllAndClean</code> both remove items from the collection associated with the specified key and if the resulting collection is empty, they remove the key from the dictionary as well. These come in both predicate and list forms.</p><pre class="brush: csharp">public static void RemoveAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, TItem item) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); TCol col; if (dictionary.TryGetValue(key, out col)) {col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }}</pre><pre class="brush: csharp">public static void RemoveAllAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, IEnumerable&lt;TItem&gt; removals) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (removals == null) throw new ArgumentNullException("removals"); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in removals) col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }}</pre><pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAllAndClean&lt;TKey, TCol, TItem&gt;( this IDictionary&lt;TKey, TCol&gt; dictionary, TKey key, Predicate&lt;TItem&gt; predicate) where TCol : ICollection&lt;TItem&gt; {if (dictionary == null) throw new ArgumentNullException("dictionary"); if (key == null) throw new ArgumentNullException("key"); if (predicate == null) throw new ArgumentNullException("predicate"); var removals = new List&lt;TItem&gt;(); TCol col; if (dictionary.TryGetValue(key, out col)) {foreach (var item in col) if (predicate(item)) removals.Add(item); foreach (var item in removals) col.Remove(item); if (col.Count == 0) dictionary.Remove(key); }return removals; }// Usage: Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary; myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="IDictionary.Clean"></a><code>Clean</code> simply goes through all the keys and removes entries with empty collections.</p><pre class="brush: csharp">public static void Clean&lt;TKey, TCol&gt;(this IDictionary&lt;TKey, TCol&gt; dictionary) where TCol : ICollection {if (dictionary == null) throw new ArgumentNullException("dictionary"); var keys = dictionary.Keys.ToList(); foreach (var key in keys) if (dictionary[key].Count == 0) dictionary.Remove(key); }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>Object</h2><p><a name="Object.As"></a>As casts an object to a specified type, executes an action with it, and returns whether or not the cast was successful.</p><pre class="brush: csharp">public static bool As&lt;T&gt;(this object obj, Action&lt;T&gt; action) where T : class {if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); var target = obj as T; if (target == null) return false; action(target); return true; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="Object.AsValueType"></a><code>AsValueType</code> does the same thing as <code>As</code>, but for value types.</p><pre class="brush: csharp">public static bool AsValueType&lt;T&gt;(this object obj, Action&lt;T&gt; action) where T : struct {if (obj == null) throw new ArgumentNullException("obj"); if (action == null) throw new ArgumentNullException("action"); if (obj is T) {action((T)obj); return true; }return false; }</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><p><a name="Object.ChainGet"></a><code>ChainGet</code> attempts to resolve a chain of member accesses and returns the result or <code>default(TValue)</code>. Since <code>TValue</code> could be a value type, there is also an overload that has an out parameter indicating whether the value was obtained.</p><p>Be careful with this extension. Since it uses reflection, it&#8217;s a bit slow. For discrete usage, each call is under 1 ms, but if you use it in a loop with many items, the performance hit will become more tangible.</p><pre class="brush: csharp">public static TValue ChainGet&lt;TRoot, TValue&gt;( this TRoot root, Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression) {bool success; return ChainGet(root, getExpression, out success); }public static TValue ChainGet&lt;TRoot, TValue&gt;( this TRoot root, Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression, out bool success) {// it's ok if root is null! if (getExpression == null) throw new ArgumentNullException("getExpression"); var members = new Stack&lt;MemberAccessInfo&gt;(); Expression expr = getExpression.Body; while (expr != null) {if (expr.NodeType == ExpressionType.Parameter) break; var memberExpr = expr as MemberExpression; if (memberExpr == null) throw new ArgumentException( "Given expression is not a member access chain.", "getExpression"); members.Push(new MemberAccessInfo(memberExpr.Member)); expr = memberExpr.Expression; }object node = root; foreach (var member in members) {if (node == null) {success = false; return default(TValue); }node = member.GetValue(node); }success = true; return (TValue)node; }private class MemberAccessInfo {private PropertyInfo _propertyInfo; private FieldInfo _fieldInfo; public MemberAccessInfo(MemberInfo info) {_propertyInfo = info as PropertyInfo; _fieldInfo = info as FieldInfo; }public object GetValue(object target) {if (_propertyInfo != null) return _propertyInfo.GetValue(target, null); else if (_fieldInfo != null) return _fieldInfo.GetValue(target); else throw new InvalidOperationException(); }} // Usage: var myValue = obj.ChainGet(o =&gt; o.MyProperty.MySubProperty.MySubSubProperty.MyValue);</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p><h2>DependencyObject</h2><p><a name="DependencyObject.SafeGetValue"></a><a name="DependencyObject.SafeSetValue"></a>These extensions work just like their non-safe counterparts on <code>DependencyObject</code>, but will call <code>Dispatcher.Invoke</code> to do operations if the current thread isn&#8217;t a UI thread.</p><pre class="brush: csharp">public static object SafeGetValue( this DependencyObject obj, DependencyProperty dp) {if (obj == null) throw new ArgumentNullException("obj"); if (dp == null) throw new ArgumentNullException("dp"); if (obj.CheckAccess()) return obj.GetValue(dp); var self = new Func &lt;DependencyObject, DependencyProperty, object&gt; (SafeGetValue); return Dispatcher.Invoke(self, obj, dp); }</pre><pre class="brush: csharp">public static void SafeSetValue( this DependencyObject obj, DependencyProperty dp, object value) {if (obj == null) throw new ArgumentNullException("obj"); if (dp == null) throw new ArgumentNullException("dp"); if (obj.CheckAccess()) obj.SetValue(dp, value); else {var self = new Action &lt;DependencyObject, DependencyProperty, object&gt; (SafeSetValue); Dispatcher.Invoke(self, obj, dp, value); }}</pre><pre class="brush: csharp">public static void SafeSetValue( this DependencyObject obj, DependencyPropertyKey key, object value) {if (obj == null) throw new ArgumentNullException("obj"); if (key == null) throw new ArgumentNullException("key"); if (obj.CheckAccess()) obj.SetValue(key, value); else {var self = new Action &lt;DependencyObject, DependencyPropertyKey, object&gt; (SafeSetValue); Dispatcher.Invoke(self, obj, key, value); }}</pre><p><a class="more-link alignright" href="#toc">Table of Contents</a></p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/the-extension-method-pack/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
		<item>
			<title>Getting to New York</title>
			<link>http://northhorizon.net/2010/getting-to-new-york-part-2/</link>
			<comments>http://northhorizon.net/2010/getting-to-new-york-part-2/#comments</comments>
			<pubDate>Wed, 07 Apr 2010 14:00:46 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Life in NYC]]></category>
			<category><![CDATA[C#]]></category>
			<category><![CDATA[Interviews]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=203</guid>
			<description><![CDATA[Continued from Part I. Part II. On the Phone Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled [...]]]></description>
			<content:encoded><![CDATA[<p><em>Continued from <a href="http://northhorizon.net/2010/getting-to-new-york-part-1/">Part I</a>.<a href="http://northhorizon.net/2010/getting-to-new-york-part-1/"><br /></a></em></p><h2>Part II. On the Phone</h2><p>Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled off my bookshelf my trusty copy of <a href="http://www.amazon.com/CLR-via-Dev-Pro-Jeffrey-Richter/dp/0735627045">CLR via C#</a>, which is, in my opinion, the best book you can read if you really want to take your understanding of C# and .NET from “intermediate” to “expert”. C#  Developers: no excuses, read this book cover to cover. As it turns out, my interviewer, Nick, must be a fan of the same book. When he called me that Monday morning, after introducing himself, Nick threw me a couple softballs before turning up the heat. I was queried at length about generics, delegates, anonymous methods, and the garbage collector (among other things), all of which I was more than happy to explicate in the greatest of detail, having refreshed myself on their inner workings the night before. Nick’s attention then turned to the newer .NET 3.5 features, which I had been using for almost two years, and I was more than happy to talk about those, too. I must admit, he stumped me on a concept called “attached behaviors”. I was familiar with attached properties, but it wasn’t until recently that I’ve become fully aware of attached behaviors. I’ll have another article discussing what I learned in the future.</p><p>After Nick finished grilling me for information, I had my turn to ask him questions. I seem to remember having a list of things to talk about, but I was suffering from some strange variant of vertigo, so I went with my usual developer talking points. For the record, Nick is one of the nicest guys ever. As I would find out later, Lab49 is composed solely of superb people. You may be thinking that I’m generalizing or hyperbolizing, but in all seriousness, I have yet to find a single bad apple or even mildly distasteful person at Lab49. Every time I think I’ve found one, they prove me wrong. Even the Java guys are top notch, and that’s saying something. In any case, I finished the interview enjoying a discussion of the usual programmer minutiae, talking about podcasts and developer philosophy. I’m not sure if it’s normal for one to feel a sense of camaraderie with his interviewer, but I know I sure did.<span id="more-203"></span></p><p>Later that day, I received an email from James, a Recruitment Coordinator at Lab49, asking for a “telephone conversation” with Nemo, the Director of Recruitment. I figured it was one of those psychological profiles one of my friends had been subjected to in a recent interview. I don’t think I could have been more wrong. The next morning, Nemo called, introduced himself, asked for clarification on a few points of my résumé, and opened himself up for questions. I asked him the usual questions on how Lab49 was structured, the promotion strategy, and what Lab49 does in general.</p><p>Nemo explained to me that Lab49 is somewhat loosely structured, with no real middle management. As projects start and finish, you report to the project manager and engagement manager, but every project is custom-tailored to the clients’ needs. I pressed Nemo to explain how a successful company works without the infrastructure almost every company of equal size has. Nemo couldn’t really explain how it worked, but only that it did, and quite well. Some may say, “when the cat’s away,” but I might interject that maybe without the threat of imminent death, a mouse might be more free to do something more constructive with its time than cower for its life.</p><p>Coming from a consulting background, I could really tell Lab49 really is a consulting firm in the greatest sense of the term. The answer to everything is, “it depends,” and, “what the client needs,” which is clearly working out well for them, but can be frustrating trying to pin down something concrete on which to make a decision. In general, Labbers work on-site with the clients to best make use of human and information resources. In my opinion, there’s definitely a beneficial side effect to it: when Lab49 is working side-by-side with the client, the work has a face, rather than some unknown bunch of people dropping code in a folder every week or two.</p><p>Nemo continued by telling me that Lab49 has titles out of necessity, but they don’t play as much of a role as in other companies. I really appreciated that. Being a young guy, it’s typically difficult for me to get my ideas out in a space where I’ve got a title that’s easily negligible. I can say with authority that’s not been the case at Lab49. Every day I work with guys who have decades of experience on me, but are interested to hear what I have to say. It’s not about seniority; it’s about being the best at what you do and bringing new and innovative ideas to the table. For that very reason, I prefer to keep my title to myself. There’s no real company policy on the publicity of your title, but it’s not on my business card and I certainly wouldn’t wear it on my sleeve.</p><p>Nemo concluded the interview by saying that Daniel Chait, one of the founders of Lab49 would want to talk to me over Skype before an in-person interview. That was the first time anyone had said anything about an in-person interview, and while I had expected it at some point, I couldn’t help but be excited to see some light at the end of the tunnel. I confidently told Nemo that I was available for the remainder of the day, which might have caught him a bit off-guard. He said Daniel was a busy guy and he’d see when he was available. I was confirmed for later that afternoon by email not too long after hanging up.</p><p>I’m not sure if it was then or later that I started feeling extremely skeptical of this Lab49 place. I remember telling my friend, Chris, that, “I know Nirvana Corp burned down, but Lab49 makes me wonder,” quoting from an <a href="http://www.tv.com/video/15935/the-competition">episode</a> of <em>Dilbert, The Animated Series</em>.  I found it difficult to believe that such a place could exist, so little was my faith in humanity, let alone developers.</p><p>I then realized I was about to have my fourth communiqué with a company in three business days, whereas almost no Dallas-based company had insomuch as replied in a week.  <em>These guys really don’t mess around</em>, I remember thinking.</p><p>At 3:00 PM and after a few quirky Skype issues, I was on webcam with Daniel Chait, now fully appreciating the extra money I’d spent on a <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E1682610407">nice webcam</a>. Chait went over my experience thoroughly, fully examining the roles I had played on each team. I’m not sure why, but at times I felt very intimidated. It’s perplexing because going over the conversation in my head Daniel wasn’t in the least bit condescending nor indirect in his questions. We discussed my work in WPF and LINQ and lambda expressions. Having taken Advanced Programming Languages and feeling like (but by no means) an expert in functional languages, I was glad to be on more solid ground. I had a compulsion to share with Daniel a couple extension methods I had written to succinctly state an equation in lambda. Unfortunately, since it was a compulsion I wasn’t prepared at all with the code snippet. I brought up my Machine Learning projects folder, which I knew it was in but couldn’t remember exactly which project I had written the extension for. Fumbling around, I must have spent a full five minutes of awkward silence finding the thing, which seemed anti-climactic for such a long wait, and even more so for me, since it felt like an eternity.</p><p>Afterward, I told my roommate that I wasn’t sure how that interview had gone. It was without a doubt by my estimation my weakest interview, and likewise the most important. I spent a little while going over the events, trying to find out why I felt I had done so poorly. All I can say is that I feel very confident of my technical skills and far less strongly about my experience, which was a major focus of Chait’s interview. That and that awkward silence.  I told myself that if they wanted a guy with more experience, that was a perfectly legitimate reason not to go forward, and I shouldn’t be worried about it. And if they rejected me outright for not having that bit of code on hand, they could go to Hell.</p><p>I was glad some of my friends wanted to go out that night so I could get my mind off the whole thing. When I got back, there was an email from James waiting for me, inviting me to New York for an in-person interview. I slept well that night.</p><p>The next day I made reservations airfare and lodging and ran both by James, as Lab49 kindly picked up the tab. It might be standard operating procedure for companies, but the fact is that they don’t have to do it, and I would have paid for the ticket myself if they hadn’t. Now all that was left to do was wait out the week and familiarize myself as best I could with my travel plans.</p><p>Clearly this company had their act together and was vigorously pursuing this discovery period. I was also reacquainting myself with the ever-greater possibility of leaving everything for New York. My father was supportive, and because he’s not usually too keen on my adventures, I took it for a good sign. That being the case, I started warming my close family and friends up to the idea that I might end up in New York. Most of them were surprised, marveling at the apparent spontaneity and haste in the whole process. Only months before had I told them I’d be staying in Dallas for the “foreseeable future” as a consultant writing software for my own company.</p><p>Who knew the foreseeable future was so short?</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/getting-to-new-york-part-2/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		</item>
		<item>
			<title>Getting to New York</title>
			<link>http://northhorizon.net/2010/getting-to-new-york-part-1/</link>
			<comments>http://northhorizon.net/2010/getting-to-new-york-part-1/#comments</comments>
			<pubDate>Thu, 11 Mar 2010 05:09:34 +0000</pubDate>
			<dc:creator>Daniel</dc:creator>
			<category><![CDATA[Life in NYC]]></category>
			<category><![CDATA[Gestault]]></category>
			<category><![CDATA[Interviewing]]></category>
			<category><![CDATA[Lab49]]></category>
			<category><![CDATA[NYC]]></category>
			<category><![CDATA[WPF]]></category>
			<guid isPermaLink="false">http://northhorizon.net/?p=186</guid>
			<description><![CDATA[A number of people have asked me how in the world I ended up in New York City. Here is the story, to the best of my memory. The entire series of events takes place over three or four weeks, so I will break it up into multiple parts. Part I. The Call I had [...]]]></description>
			<content:encoded><![CDATA[<p>A number of people have asked me how in the world I ended up in New York City. Here is the story, to the best of my memory. The entire series of events takes place over three or four weeks, so I will break it up into multiple parts.</p><h2>Part I. The Call</h2><p>I had been consulting for right about a year and a half, and things were looking pretty good. Chris and I, under the company name of Gestault Solutions, had managed to architect and implement a complete resource scheduling system for outpatient healthcare centers. We were not without the help and business guidance of Randall, who is perhaps one of the most intelligent and honorable businessmen I will ever meet.  I’ll be the first to admit, it was an incredible undertaking for such a small team in such a short time, and I while I may wince at a few spots in the codebase, I’m proud to have worked with Chris and Randall on it.<span id="more-186"></span></p><p>Of course, every company has problems, and while ours weren’t so much in the codebase, but in those pesky people we call “clients,” who seem to be the most disorganized and incoherent bunch of people under a roof. I really hate business politics. Our main client, to whom we were very dependent upon for revenue decided that they wanted to fork our legacy product, iOrder, and use their staff to continue incremental feature improvements on it. We had concluded several months earlier that while iOrder was doing very well for when it was written and the circumstances thereof, that it was outdated and had several architectural flaws that hampered further development. Fortunately, Chris and I were both very adept at the suite of new .NET technologies, notably WPF and very quickly WCF, so we were able to leverage both of those frameworks to get well-designed software out the door orders of magnitude faster than teams using older technologies.</p><p>Our client’s team was expecting to make a release in September of 2009 with a pittance of feature improvements. Since we were brought on to help their team transition, we had a good idea of how things were progressing, and it was our professional opinions at the time that their chances of success were slim to none, based on the skill sets of their developers and architectural choices. It’s worth pointing out that these guys were accustomed to maintaining software, making tweaks and small changes and this was new development, which requires a whole different set of skills. It may not surprise you then that as of this writing, they still haven’t finished their handful of upgrades.</p><p>Around the same time as the client’s stated release date, we were testing our completely new WPF user interface with a good bit of success. There were some initial bugs, but that’s to be expected. Despite having blown their own release date and given the opportunity to ditch their ailing project and purchase our finished one, our client (if you could call them that at this point) decided to persist with their team with a slightly revised schedule. I’m not sure how many deadlines they had, but they are now aiming for a June 2010 release. From what I’ve seen, a pig with a model rocket strapped to its back has a better chance of getting off the ground.</p><p>We continued working on our project, albeit at a lower rate through the end of 2009 and beginning of 2010, but it was looking like we were not going to pick up again anytime soon. Randall had found a second client to bring onboard, but they weren’t in a hurry to do anything either. I had just graduated in December and was looking to kick off my career, but every week things became a bit grimmer, despite Randall&#8217;s best efforts to show our main client reason.</p><p>I wasn’t really worried until Chris started interviewing. That was when I got my résumé in order and started making phone calls. The job market wasn’t looking very interesting to me; there was a lot of web work, internal management systems, so forth and so on, but very little WPF work or companies on the cutting edge looking for employees. I was also looking for a senior position, which may seem a bit audacious for my age and credentials, but I was more than willing to prove to anybody that I wasn’t wasting their time with my job application. A recruiter called me and introduced me to a particular FedEx/Kinkos project designing some kiosk interface with a bunch of contracted developers. I was pretty skeptical, since without strong project leadership, success becomes a fleeting goal, and I’d hate to have my name pinned to a failed project, even if it wasn’t my fault.</p><p>On Friday, 5 January, I was called by a guy who introduced himself as Ryan Elberg from Lab49, a software consulting company. He noted, “I saw your résumé on Dice and that you were available for relocation.”</p><p>“Depends on the job,” I quickly replied. “Where are you located?”</p><p>“New York. Are you interested?”</p><p>I had marked the “Available for Relocation” checkbox on Dice, the monster.com of IT, in case a company in Houston, Austin, or San Antonio was looking for a programmer.</p><p>Not really knowing what to say, I went with my previous remark, “Depends on the job. Which part of New York?” It could have been Albany, for all I knew.</p><p>“Downtown New York City.”</p><p>At this point I was just stalling for time. I had no real intention of moving to New York, but there are a lot of premier software companies in NYC, so why waste a good job opportunity? I quickly decided that I’d go through the interview process, which would surely include a face-to-face interview, at which time I could decide whether I wanted to be there or not.</p><p>Ryan asked me when I would be available for a quick pre-screening test. I told him I was ready immediately, so he commenced with a little multiple choice test over the phone. Apparently, I did quite well, so he set up another phone interview with a developer named Nick for the following Monday.</p><p>After I hung up, I couldn’t help but feel a bit exhilarated. It’s not everyday people quiz me on CLR garbage collection and such. At the same time, I was filled with dread toward to idea of leaving my friends and family behind in my beloved Texas, a bastion of freedom and conservativism, for New York, a place with neither family nor friends, except my Uncle far upstate in Rome. And New York City was recently in the news for Mayor Bloomberg’s thoughts on how someone with a concealed handgun license could shoot up a movie theater. Not exactly the kind of rhetoric I was accustomed to in Texas.</p><p>I decided to procrastinate on figuring out what I wanted to do. Being fresh out of college, I was an expert at putting things off until later. Maybe something would happen along the interview process where I could find an out and not end up moving. It’d be interesting to say that someone called me from New York thinking I’d be great for their team, but I turned <em>them</em> down because they didn’t have it together.</p><p>I was in for a surprise.</p><p><em>Continued in <a href="http://northhorizon.net/2010/getting-to-new-york-part-2/">Part II</a></em>.</p>]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/getting-to-new-york-part-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
