<?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>NorthHorizon &#187; C#</title>
	<atom:link href="http://northhorizon.net/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://northhorizon.net</link>
	<description></description>
	<lastBuildDate>Sun, 29 Aug 2010 21:19:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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.<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" target="_blank"  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" target="_blank"  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" target="_blank"  title="Hash table" >hash tables</a>. I use them pretty frequently and these methods are able to make life a lot easier.</p>
<p><a name="IDictionary.Add"></a><a name="IDictionary.AddAll"></a><code>Add</code> and <code>AddAll</code> insert the key and a new collection into the dictionary if the key doesn&#8217;t already exist and then adds the item or items to the collection.</p>
<pre class="brush: csharp">public static void Add&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	TItem item)
	where TCol : ICollection&lt;TItem&gt;, new()
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	TCol col;
	if (dictionary.TryGetValue(key, out col))
	{
		if (col.IsReadOnly)
			throw new InvalidOperationException("bucket is read only");
	}
	else
		dictionary.Add(key, col = new TCol());

	col.Add(item);
}
</pre>
<pre class="brush: csharp">public static void AddAll&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	IEnumerable&lt;TItem&gt; additions)
	where TCol : ICollection&lt;TItem&gt;, new()
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	if (additions == null)
		throw new ArgumentNullException("additions");

	TCol col;
	if (!dictionary.TryGetValue(key, out col))
		dictionary.Add(key, col = new TCol());

	foreach (var item in additions)
		col.Add(item);
}
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<p><a name="IDictionary.Remove"></a><a name="IDictionary.RemoveAll"></a><code>Remove</code> and <code>RemoveAll</code> simply remove items from the collection associated with the specified key, if there is one. For the predicate overloads, you need to explicitly construct your <code>Predicate&lt;T&gt;</code> delegate because the C# compiler has trouble doing the type inference.</p>
<pre class="brush: csharp">public static void Remove&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	TItem item)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	TCol col;
	if (dictionary.TryGetValue(key, out col))
		col.Remove(item);
}
</pre>
<pre class="brush: csharp">public static void RemoveAll&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	IEnumerable&lt;TItem&gt; removals)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	if (removals == null)
		throw new ArgumentNullException("removals");

	TCol col;
	if (dictionary.TryGetValue(key, out col))
		foreach (var item in removals)
			col.Remove(item);
}
</pre>
<pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAll&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	Predicate&lt;TItem&gt; predicate)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	if (predicate == null)
		throw new ArgumentNullException("predicate");

	var removals = new List&lt;TItem&gt;();

	TCol col;
	if (dictionary.TryGetValue(key, out col))
	{
		foreach (var item in col)
			if (predicate(item))
				removals.Add(item);

		foreach (var item in removals)
			col.Remove(item);
	}

	return removals;
}

// Usage:
Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary;
myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<p><a name="IDictionary.RemoveAndClean"></a><a name="IDictionary.RemoveAllAndClean"></a><code>RemoveAndClean</code> and <code>RemoveAllAndClean</code> both remove items from the collection associated with the specified key and if the resulting collection is empty, they remove the key from the dictionary as well. These come in both predicate and list forms.</p>
<pre class="brush: csharp">public static void RemoveAndClean&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	TItem item)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	TCol col;
	if (dictionary.TryGetValue(key, out col))
	{
		col.Remove(item);

		if (col.Count == 0)
			dictionary.Remove(key);
	}
}
</pre>
<pre class="brush: csharp">public static void RemoveAllAndClean&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	IEnumerable&lt;TItem&gt; removals)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	if (removals == null)
		throw new ArgumentNullException("removals");

	TCol col;
	if (dictionary.TryGetValue(key, out col))
	{
		foreach (var item in removals)
			col.Remove(item);

		if (col.Count == 0)
			dictionary.Remove(key);
	}
}
</pre>
<pre class="brush: csharp">public static IEnumerable&lt;TItem&gt; RemoveAllAndClean&lt;TKey, TCol, TItem&gt;(
	this IDictionary&lt;TKey, TCol&gt; dictionary,
	TKey key,
	Predicate&lt;TItem&gt; predicate)
	where TCol : ICollection&lt;TItem&gt;
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	if (key == null)
		throw new ArgumentNullException("key");

	if (predicate == null)
		throw new ArgumentNullException("predicate");

	var removals = new List&lt;TItem&gt;();

	TCol col;
	if (dictionary.TryGetValue(key, out col))
	{
		foreach (var item in col)
			if (predicate(item))
				removals.Add(item);

		foreach (var item in removals)
			col.Remove(item);

		if (col.Count == 0)
			dictionary.Remove(key);
	}

	return removals;
}

// Usage:
Dictionary&lt;int, List&lt;int&gt;&gt; myDictionary;
myDictionary.RemoveAll(4, new Predicate&lt;int&gt;(i =&gt; i &lt; 42));
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<p><a name="IDictionary.Clean"></a><code>Clean</code> simply goes through all the keys and removes entries with empty collections.</p>
<pre class="brush: csharp">public static void Clean&lt;TKey, TCol&gt;(this IDictionary&lt;TKey, TCol&gt; dictionary)
	where TCol : ICollection
{
	if (dictionary == null)
		throw new ArgumentNullException("dictionary");

	var keys = dictionary.Keys.ToList();

	foreach (var key in keys)
		if (dictionary[key].Count == 0)
			dictionary.Remove(key);
}
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<h2>Object</h2>
<p><a name="Object.As"></a>As casts an object to a specified type, executes an action with it, and returns whether or not the cast was successful.</p>
<pre class="brush: csharp">public static bool As&lt;T&gt;(this object obj, Action&lt;T&gt; action)
	where T : class
{
	if (obj == null)
		throw new ArgumentNullException("obj");

	if (action == null)
		throw new ArgumentNullException("action");

	var target = obj as T;
	if (target == null)
		return false;

	action(target);
	return true;
}
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<p><a name="Object.AsValueType"></a><code>AsValueType</code> does the same thing as <code>As</code>, but for value types.</p>
<pre class="brush: csharp">public static bool AsValueType&lt;T&gt;(this object obj, Action&lt;T&gt; action)
	where T : struct
{
	if (obj == null)
		throw new ArgumentNullException("obj");

	if (action == null)
		throw new ArgumentNullException("action");

	if (obj is T)
	{
		action((T)obj);
		return true;
	}

	return false;
}
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<p><a name="Object.ChainGet"></a><code>ChainGet</code> attempts to resolve a chain of member accesses and returns the result or <code>default(TValue)</code>. Since <code>TValue</code> could be a value type, there is also an overload that has an out parameter indicating whether the value was obtained.</p>
<p>Be careful with this extension. Since it uses reflection, it&#8217;s a bit slow. For discrete usage, each call is under 1 ms, but if you use it in a loop with many items, the performance hit will become more tangible.</p>
<pre class="brush: csharp">public static TValue ChainGet&lt;TRoot, TValue&gt;(
	this TRoot root,
	Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression)
{
	bool success;
	return ChainGet(root, getExpression, out success);
}

public static TValue ChainGet&lt;TRoot, TValue&gt;(
	this TRoot root,
	Expression&lt;Func&lt;TRoot, TValue&gt;&gt; getExpression,
	out bool success)
{
	// it's ok if root is null!

	if (getExpression == null)
		throw new ArgumentNullException("getExpression");

	var members = new Stack&lt;MemberAccessInfo&gt;();

	Expression expr = getExpression.Body;
	while (expr != null)
	{
		if (expr.NodeType == ExpressionType.Parameter)
			break;

		var memberExpr = expr as MemberExpression;
		if (memberExpr == null)
			throw new ArgumentException(
				"Given expression is not a member access chain.",
				"getExpression");

		members.Push(new MemberAccessInfo(memberExpr.Member));

		expr = memberExpr.Expression;
	}

	object node = root;
	foreach (var member in members)
	{
		if (node == null)
		{
			success = false;
			return default(TValue);
		}

		node = member.GetValue(node);
	}

	success = true;
	return (TValue)node;
}

private class MemberAccessInfo
{
	private PropertyInfo _propertyInfo;
	private FieldInfo _fieldInfo;

	public MemberAccessInfo(MemberInfo info)
	{
		_propertyInfo = info as PropertyInfo;
		_fieldInfo = info as FieldInfo;
	}

	public object GetValue(object target)
	{
		if (_propertyInfo != null)
			return _propertyInfo.GetValue(target, null);
		else if (_fieldInfo != null)
			return _fieldInfo.GetValue(target);
		else
			throw new InvalidOperationException();
	}
}

// Usage:
var myValue = obj.ChainGet(o =&gt; o.MyProperty.MySubProperty.MySubSubProperty.MyValue);
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
<h2>DependencyObject</h2>
<p><a name="DependencyObject.SafeGetValue"></a><a name="DependencyObject.SafeSetValue"></a>These extensions work just like their non-safe counterparts on <code>DependencyObject</code>, but will call <code>Dispatcher.Invoke</code> to do operations if the current thread isn&#8217;t a UI thread.</p>
<pre class="brush: csharp">public static object SafeGetValue(
	this DependencyObject obj,
	DependencyProperty dp)
{
	if (obj == null)
		throw new ArgumentNullException("obj");

	if (dp == null)
		throw new ArgumentNullException("dp");

	if (obj.CheckAccess())
		return obj.GetValue(dp);

	var self = new Func
		&lt;DependencyObject, DependencyProperty, object&gt;
		(SafeGetValue);

	return Dispatcher.Invoke(self, obj, dp);
}
</pre>
<pre class="brush: csharp">public static void SafeSetValue(
	this DependencyObject obj,
	DependencyProperty dp,
	object value)
{
	if (obj == null)
		throw new ArgumentNullException("obj");

	if (dp == null)
		throw new ArgumentNullException("dp");

	if (obj.CheckAccess())
		obj.SetValue(dp, value);
	else
	{
		var self = new Action
			&lt;DependencyObject, DependencyProperty, object&gt;
			(SafeSetValue);
		Dispatcher.Invoke(self, obj, dp, value);
	}
}
</pre>
<pre class="brush: csharp">public static void SafeSetValue(
	this DependencyObject obj,
	DependencyPropertyKey key,
	object value)
{
	if (obj == null)
		throw new ArgumentNullException("obj");

	if (key == null)
		throw new ArgumentNullException("key");

	if (obj.CheckAccess())
		obj.SetValue(key, value);
	else
	{
		var self = new Action
			&lt;DependencyObject, DependencyPropertyKey, object&gt;
			(SafeSetValue);
		Dispatcher.Invoke(self, obj, key, value);
	}
}
</pre>
<p><a class="more-link alignright" href="#toc">Table of Contents</a></p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/the-extension-method-pack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting to New York</title>
		<link>http://northhorizon.net/2010/getting-to-new-york-part-2/</link>
		<comments>http://northhorizon.net/2010/getting-to-new-york-part-2/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 14:00:46 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Life in NYC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Interviews]]></category>
		<category><![CDATA[Lab49]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=203</guid>
		<description><![CDATA[Continued from Part I. Part II. On the Phone Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled [...]]]></description>
			<content:encoded><![CDATA[<p><em>Continued from <a href="http://northhorizon.net/2010/getting-to-new-york-part-1/">Part I</a>.<a href="http://northhorizon.net/2010/getting-to-new-york-part-1/"><br />
</a></em></p>
<h2>Part II. On the Phone</h2>
<p>Sunday evening, January 18, I decided it might be a good idea to brush up on my .NET framework knowledge to prepare for my interview the next morning. Judging by the latter questions of Lab49’s “preliminary screening test,” these guys really didn’t mess around. I pulled off my bookshelf my trusty copy of <a href="http://www.amazon.com/CLR-via-Dev-Pro-Jeffrey-Richter/dp/0735627045">CLR via C#</a>, which is, in my opinion, the best book you can read if you really want to take your understanding of C# and .NET from “intermediate” to “expert”. C#  Developers: no excuses, read this book cover to cover. As it turns out, my interviewer, Nick, must be a fan of the same book. When he called me that Monday morning, after introducing himself, Nick threw me a couple softballs before turning up the heat. I was queried at length about generics, delegates, anonymous methods, and the garbage collector (among other things), all of which I was more than happy to explicate in the greatest of detail, having refreshed myself on their inner workings the night before. Nick’s attention then turned to the newer .NET 3.5 features, which I had been using for almost two years, and I was more than happy to talk about those, too. I must admit, he stumped me on a concept called “attached behaviors”. I was familiar with attached properties, but it wasn’t until recently that I’ve become fully aware of attached behaviors. I’ll have another article discussing what I learned in the future.</p>
<p>After Nick finished grilling me for information, I had my turn to ask him questions. I seem to remember having a list of things to talk about, but I was suffering from some strange variant of vertigo, so I went with my usual developer talking points. For the record, Nick is one of the nicest guys ever. As I would find out later, Lab49 is composed solely of superb people. You may be thinking that I’m generalizing or hyperbolizing, but in all seriousness, I have yet to find a single bad apple or even mildly distasteful person at Lab49. Every time I think I’ve found one, they prove me wrong. Even the Java guys are top notch, and that’s saying something. In any case, I finished the interview enjoying a discussion of the usual programmer minutiae, talking about podcasts and developer philosophy. I’m not sure if it’s normal for one to feel a sense of camaraderie with his interviewer, but I know I sure did.<span id="more-203"></span></p>
<p>Later that day, I received an email from James, a Recruitment Coordinator at Lab49, asking for a “telephone conversation” with Nemo, the Director of Recruitment. I figured it was one of those psychological profiles one of my friends had been subjected to in a recent interview. I don’t think I could have been more wrong. The next morning, Nemo called, introduced himself, asked for clarification on a few points of my résumé, and opened himself up for questions. I asked him the usual questions on how Lab49 was structured, the promotion strategy, and what Lab49 does in general.</p>
<p>Nemo explained to me that Lab49 is somewhat loosely structured, with no real middle management. As projects start and finish, you report to the project manager and engagement manager, but every project is custom-tailored to the clients’ needs. I pressed Nemo to explain how a successful company works without the infrastructure almost every company of equal size has. Nemo couldn’t really explain how it worked, but only that it did, and quite well. Some may say, “when the cat’s away,” but I might interject that maybe without the threat of imminent death, a mouse might be more free to do something more constructive with its time than cower for its life.</p>
<p>Coming from a consulting background, I could really tell Lab49 really is a consulting firm in the greatest sense of the term. The answer to everything is, “it depends,” and, “what the client needs,” which is clearly working out well for them, but can be frustrating trying to pin down something concrete on which to make a decision. In general, Labbers work on-site with the clients to best make use of human and information resources. In my opinion, there’s definitely a beneficial side effect to it: when Lab49 is working side-by-side with the client, the work has a face, rather than some unknown bunch of people dropping code in a folder every week or two.</p>
<p>Nemo continued by telling me that Lab49 has titles out of necessity, but they don’t play as much of a role as in other companies. I really appreciated that. Being a young guy, it’s typically difficult for me to get my ideas out in a space where I’ve got a title that’s easily negligible. I can say with authority that’s not been the case at Lab49. Every day I work with guys who have decades of experience on me, but are interested to hear what I have to say. It’s not about seniority; it’s about being the best at what you do and bringing new and innovative ideas to the table. For that very reason, I prefer to keep my title to myself. There’s no real company policy on the publicity of your title, but it’s not on my business card and I certainly wouldn’t wear it on my sleeve.</p>
<p>Nemo concluded the interview by saying that Daniel Chait, one of the founders of Lab49 would want to talk to me over Skype before an in-person interview. That was the first time anyone had said anything about an in-person interview, and while I had expected it at some point, I couldn’t help but be excited to see some light at the end of the tunnel. I confidently told Nemo that I was available for the remainder of the day, which might have caught him a bit off-guard. He said Daniel was a busy guy and he’d see when he was available. I was confirmed for later that afternoon by email not too long after hanging up.</p>
<p>I’m not sure if it was then or later that I started feeling extremely skeptical of this Lab49 place. I remember telling my friend, Chris, that, “I know Nirvana Corp burned down, but Lab49 makes me wonder,” quoting from an <a href="http://www.tv.com/video/15935/the-competition">episode</a> of <em>Dilbert, The Animated Series</em>.  I found it difficult to believe that such a place could exist, so little was my faith in humanity, let alone developers.</p>
<p>I then realized I was about to have my fourth communiqué with a company in three business days, whereas almost no Dallas-based company had insomuch as replied in a week.  <em>These guys really don’t mess around</em>, I remember thinking.</p>
<p>At 3:00 PM and after a few quirky Skype issues, I was on webcam with Daniel Chait, now fully appreciating the extra money I’d spent on a <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E1682610407">nice webcam</a>. Chait went over my experience thoroughly, fully examining the roles I had played on each team. I’m not sure why, but at times I felt very intimidated. It’s perplexing because going over the conversation in my head Daniel wasn’t in the least bit condescending nor indirect in his questions. We discussed my work in WPF and LINQ and lambda expressions. Having taken Advanced Programming Languages and feeling like (but by no means) an expert in functional languages, I was glad to be on more solid ground. I had a compulsion to share with Daniel a couple extension methods I had written to succinctly state an equation in lambda. Unfortunately, since it was a compulsion I wasn’t prepared at all with the code snippet. I brought up my Machine Learning projects folder, which I knew it was in but couldn’t remember exactly which project I had written the extension for. Fumbling around, I must have spent a full five minutes of awkward silence finding the thing, which seemed anti-climactic for such a long wait, and even more so for me, since it felt like an eternity.</p>
<p>Afterward, I told my roommate that I wasn’t sure how that interview had gone. It was without a doubt by my estimation my weakest interview, and likewise the most important. I spent a little while going over the events, trying to find out why I felt I had done so poorly. All I can say is that I feel very confident of my technical skills and far less strongly about my experience, which was a major focus of Chait’s interview. That and that awkward silence.  I told myself that if they wanted a guy with more experience, that was a perfectly legitimate reason not to go forward, and I shouldn’t be worried about it. And if they rejected me outright for not having that bit of code on hand, they could go to Hell.</p>
<p>I was glad some of my friends wanted to go out that night so I could get my mind off the whole thing. When I got back, there was an email from James waiting for me, inviting me to New York for an in-person interview. I slept well that night.</p>
<p>The next day I made reservations airfare and lodging and ran both by James, as Lab49 kindly picked up the tab. It might be standard operating procedure for companies, but the fact is that they don’t have to do it, and I would have paid for the ticket myself if they hadn’t. Now all that was left to do was wait out the week and familiarize myself as best I could with my travel plans.</p>
<p>Clearly this company had their act together and was vigorously pursuing this discovery period. I was also reacquainting myself with the ever-greater possibility of leaving everything for New York. My father was supportive, and because he’s not usually too keen on my adventures, I took it for a good sign. That being the case, I started warming my close family and friends up to the idea that I might end up in New York. Most of them were surprised, marveling at the apparent spontaneity and haste in the whole process. Only months before had I told them I’d be staying in Dallas for the “foreseeable future” as a consultant writing software for my own company.</p>
<p>Who knew the foreseeable future was so short?</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/getting-to-new-york-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Variable-length Integers</title>
		<link>http://northhorizon.net/2009/variable-length-integers/</link>
		<comments>http://northhorizon.net/2009/variable-length-integers/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 20:34:21 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Site News]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Chord]]></category>
		<category><![CDATA[Coursework]]></category>
		<category><![CDATA[Hashing]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=14</guid>
		<description><![CDATA[Wow. So it definitely took me long enough to get this blog going. A lot has happened since I got this site up and running, so hopefully there will be no shortage of thoughts to write about. This semester I&#8217;ve finally qualified to take the CS Senior Design Project, which, this semester, is to design [...]]]></description>
			<content:encoded><![CDATA[<p>Wow. So it definitely took me long enough to get this blog going. A lot has happened since I got this site up and running, so hopefully there will be no shortage of thoughts to write about.</p>
<p>This semester I&#8217;ve finally qualified to take the CS Senior Design Project, which, this semester, is to design a <a href="http://en.wikipedia.org/wiki/Chord_project">Chord</a> client. At the heart of the system is the <em>identifier</em>, which is essentially a glorified hash. We decided to go with SHA-256, partially because the instructor mentioned it was in the class of his favorite hashes. It didn&#8217;t really matter to me, since C# supports it just as easily as anything else.</p>
<p>Identifiers have two essential purposes, comparison and addition, from which every method can be derived. I wasn&#8217;t particularly intrigued by either of these topics, since almost without exception, you can rely on existing structures in the <a href="http://en.wikipedia.org/wiki/Framework_Class_Library">FCL</a> to do whatever you need to do, and it&#8217;s always better to do so. Now, I said &#8220;almost without exception,&#8221; namely because I stumbled upon the fact that these identifiers unequivocally are exceptions. The thing about using a SHA-256 hash &#8211; or any hash for that matter &#8211; is that it&#8217;s an enormous value &#8211; 256 bits to be precise. There aren&#8217;t any real 32 or even 64 bit hashes available (I doubt they&#8217;d be useful), so relying on the good ol&#8217; FCL goes out the window.<span id="more-14"></span></p>
<p>Other students, stuck in the abyss of Java, were having difficulty getting their socket implementations going, so mucking around in massive integer arithmetic was right out. I believe the professor advised them to take the 32 <a href="http://en.wikipedia.org/wiki/Most_significant_bit">MSB</a> and just rely on an unsigned integer. <em>(Side note: does Java even have unsigned integers?) </em>I considered a few similar options: taking the 64 <a href="http://en.wikipedia.org/wiki/Least_significant_bit">LSB</a> or separating the hash into several equal groups of 64-bits each and getting the xor result of the segments. Arrogantly I proceeded on, demanding that whatever I wrote work not only for SHA-256 but also SHA-512 or anything else using the full bit-length.</p>
<p>Comparison wasn&#8217;t difficult. Essentially, you start at the MSB in your array (which happens to be at <code>Length - 1</code>) and compare until you find a comparison <code>!= 0</code>:</p>
<pre class="brush: csharp">public int CompareTo(Identifier other)
{
	for (int i = _hash.Length - 1; i &amp;gt;= 0; i--)
	{
		int compare = _hash[i].CompareTo(other._hash[i]);

		if (compare != 0)
			return compare;
	}

	return 0;
}</pre>
<p>Now comes the fun part. First, I wrote a little method called <code>Pad(byte[] list, int size)</code> which pads the MSB of an array with 0&#8242;s until it&#8217;s the proper length. After several iterations, I finally ended up with this:</p>
<pre class="brush: csharp">public static byte[] Add(byte[] a, byte[] b)
{
	if (a.Length &gt; b.Length)
		b = Pad(b, a.Length);
	else if (a.Length &lt; b.Length)
		a = Pad(a, b.Length);

	byte[] result = new byte[a.Length];

	int carry = 0;
	for (int i = 0; i &lt; a.Length; i++)
	{
		int value = carry + a[i] + b[i];

		// get the bottom part of the bits
		result[i] = (byte)value;

		// knock off the bottom bits that we already got and
		// put the rest into carry.
		carry = (value - result[i]) / byte.MaxValue;
	}

	return result;
}</pre>
<p>The data holder for carry has to be large enough for the worst case scenario <code>0xFF + 0xFF + carry 1</code>, which is why I chose an <code>int</code> rather than a <code>byte</code> (although a short could have worked just as well, I suppose).</p>
<p>Subtraction was more difficult. Consider the way you subtract, with carrying, etc. Carrying on its own is a recursive process, and I can&#8217;t imagine writing it out. It was at that time that I remembered how the <a href="http://en.wikipedia.org/wiki/Arithmetic_logic_unit">ALU</a> does subtraction- by taking the two&#8217;s compliment of the second operand and doing addition. So I followed suit:</p>
<pre class="brush: csharp">public static byte[] Subtract(byte[] a, byte[] b)
{
    if (a.Length &gt; b.Length)
        b = Pad(b, a.Length);
    else if (a.Length &lt; b.Length)
        a = Pad(a, b.Length);

	byte[] twoscomp = new byte[b.Length];

	// get the 1's compliment
	for (int i = 0; i &lt; b.Length; i++)
		twoscomp[i] = (byte)(byte.MaxValue - b[i]);

	// add 1
	twoscomp = Add(twoscomp, new byte[] { 1 });

	// NOTE: twoscomp is now the two's compliment of b.

	return Add(a, twoscomp);
}</pre>
<p>I also needed multiplication, but I&#8217;m still working on the solution. I&#8217;ve got a working draft, but I&#8217;m not entirely sure I&#8217;m happy with it just yet. I&#8217;ll keep you notified.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/variable-length-integers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
