<?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; Coding</title>
	<atom:link href="http://northhorizon.net/category/coding/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>Alpha-Blending Colors in PowerShell</title>
		<link>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/</link>
		<comments>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 19:40:07 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Lab49]]></category>
		<category><![CDATA[colors]]></category>
		<category><![CDATA[pipelining]]></category>
		<category><![CDATA[powershell]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=299</guid>
		<description><![CDATA[The other day I was given the task of converting a particularly poorly designed VisualBrush into a LinearGradientBrush. One of the problems I came across very quickly was the use of semi-transparent colors layered on top of each other, and, of course, I needed a &#8220;flattened&#8221; color for my GradientStop. Now, I could have used [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was given the task of converting a particularly poorly designed VisualBrush into a LinearGradientBrush. One of the problems I came across very quickly was the use of semi-transparent colors layered on top of each other, and, of course, I needed a &#8220;flattened&#8221; color for my GradientStop. Now, I could have used Paint.NET or GIMP or Photoshop to put out a couple layers of colors, set the transparencies and used the color dropper to get the result. Of course, since I&#8217;m not a designer, I don&#8217;t have any of those things installed on my work computer, so I decided to just find the equation to blend the channels myself. It didn&#8217;t take long, and Wikipedia delivered the goods. According to <a href="http://en.wikipedia.org/wiki/http://en.wikipedia.org/wiki/Alpha_compositing" target="_blank"  title="http://en.wikipedia.org/wiki/Alpha_compositing" >the article</a>, the formula to merge two colors, <img src='http://s.wordpress.com/latex.php?latex=C_a&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_a' title='C_a' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=C_b&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_b' title='C_b' class='latex' />, into some output color, <img src='http://s.wordpress.com/latex.php?latex=C_o&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_o' title='C_o' class='latex' />, looks like this:</p>
<p style="text-align: center;"><img src='http://s.wordpress.com/latex.php?latex=C_o%20%3D%20C_a%5Calpha_a%2BC_b%5Calpha_b%281-%5Calpha_a%29&#038;bg=T&#038;fg=000000&#038;s=0' alt='C_o = C_a\alpha_a+C_b\alpha_b(1-\alpha_a)' title='C_o = C_a\alpha_a+C_b\alpha_b(1-\alpha_a)' class='latex' /></p>
<p>Since a color can be thought of as a three-tuple of its R, G, and B channels, the formula is easily distributed to each of these values.</p>
<p>At this point, I decided I could probably just pull out a calculator and crunch the numbers. But maybe, in about the same time, I could also whip something together, say in PowerShell, to do it for me. Since I&#8217;m still learning PowerShell, I figured the learning experience would be worth at least something.<span id="more-299"></span></p>
<p>So the first thing I needed was the ability to parse an ARGB hex code into a hashtable with each channel separated out. Here&#8217;s what I got.</p>
<pre class="brush: powershell">function Blend-Colors ([string[]] $colors) {
    # $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#'
    # and assign them to groups named a, r, g, and b for each channel, respectively.
    $argbHexColorRegex = "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$"

    foreach($colorHex in $colors) {
        if($colorHex -match $argbHexColorRegex) {
            $color = @{
                a = [int]::Parse($matches.a, 'AllowHexSpecifier')
                r = [int]::Parse($matches.r, 'AllowHexSpecifier');
                g = [int]::Parse($matches.g, 'AllowHexSpecifier');
                b = [int]::Parse($matches.b, 'AllowHexSpecifier');
            }

            $color | ft
        } else {
            throw "Invalid color: $colorHex"
        }
    }
}</pre>
<p>Ok, not too shabby. If you&#8217;re wondering where <code>$matches</code> came from, as a side effect of the <code>-match</code> operation, the <code>$matches</code> hashtable is set with all the matched groups defined. I just prefer to use the object syntax in this case over the index syntax.</p>
<p>So, I&#8217;m not real happy with the amount of repetition going on in the assignment of my hashtable. My first attempt to clean it up looked like this:</p>
<pre class="brush: powershell; gutter: false">$color = ('a','r','g','b') | % { @{ $_ = [int]::Parse($matches.$_, 'AllowHexSpecifier') } }</pre>
<p>But that just gave me an array of hashtables with one attribute in each. I asked <a href="http://www.dougfinke.com/">Doug Finke</a> what he thought and he recommended this modification:</p>
<pre class="brush: powershell; gutter: false">('a','r','g','b') | % { $color = @{} } { $color.$_ = [int]::Parse($matches.$_, 'AllowHexSpecifier') }</pre>
<p>Cool! It seems a little obvious now, though.</p>
<p>Next on the agenda was to translate the blending equation into PowerShell. Since the equation is a little more involved, I decided to abstract it out into a subfunction like so:</p>
<pre class="brush: powershell">function Merge-Channel ($c0, $c1, $c) {
	$a0 = $c0.a / 255
	$a1 = $c1.a / 255
	return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0)
}</pre>
<p><code>$c0</code> and <code>$c1</code> are color hashtables and <code>$c</code> is the name of the channel to blend. I had to divide the alpha channels by 255 to produce a value compatible with the equation, namely, between 0 and 1.</p>
<p>The reason I chose to accept the entire color and desired channel, rather than a more terse definition accepting the specific channel values and related alpha values was to make calling the code a little more elegant:</p>
<pre class="brush: powershell; gutter: false">('r','g','b') | % `
	{ $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `
	{ $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }</pre>
<p>When blending, the alpha channels simply sum, so I put that in my hashtable initializer and just iterated over the color channels.</p>
<p>Now the final step is to return our value back in hex form. Fortunately, the formatting styles for <code>int</code> make this really easy:</p>
<pre class="brush: powershell; gutter: false">return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f (('a','r','g','b') | % { [int][Math]::Round($baseColor.$_, 0) })</pre>
<p>I&#8217;m rounding to ensure the highest accuracy to the blended color, as opposed to simply truncating.</p>
<p>Putting it all together, I decided to create two array constants, <code>$argb</code> and <code>$rgb</code> to alias arrays of the channels. While I was at it, I also promoted my <code>$argbHexColorRegex</code> to a constant just for good measure. Finally, I made the base color white, so there would be something to blend against. The result looks like this:</p>
<pre class="brush: powershell">function Blend-Colors ([Parameter(Mandatory=$true)] [string[]] $colors) {
    # $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#'
    # and assign them to groups named a, r, g, and b for each channel, respectively.
    Set-Variable argbHexColorRegex -Option Constant `
        -Value "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$"
    Set-Variable argb -Option Constant -Value 'a','r','g','b'
    Set-Variable rgb -Option Constant -Value 'r','g','b'

    function Merge-Channel ($c0, $c1, $c) {
        $a0 = $c0.a / 255
        $a1 = $c1.a / 255
        return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0)
    }

    $argb | % { $outColor = @{} } { $outColor.$_ = 255 } # set $outColor to white (#FFFFFFFF)

    foreach($color in $colors) {
        if(-not ($color -match $argbHexColorRegex)) {
            throw "Invalid color: $color"
        }

        $argb | % { $addColor = @{} } { $addColor.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }

        $rgb | % `
            { $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `
            { $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }

        $outColor = $mergeColor
    }

    return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f ($argb | % { [int][Math]::Round($outColor.$_, 0) })
}</pre>
<p>This is looking really good, and, really, I might have just stopped here. The only things I was missing at this point were pipelining and documentation, and since my solution had become completely over-engineered as it was, I decided I  might as well go for broke.</p>
<p>The first thing I wanted to do was abstract out my initialization of <code>$outColor</code> to a parameter. Since I&#8217;d have to parse the string, I&#8217;d also need to abstract my color hex parser.</p>
<pre class="brush: powershell">function Parse-Color ([string] $hex) {
	if($hex -match $argbHexColorRegex) {
		$argb | % { $color = @{} } { $color.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }
		return $color;
	} else {
		return $null;
	}
}</pre>
<p>The reason I decided to return null instead of throwing an error immediately is because I wanted to treat errors differently in both places. Specifically, if an invalid string is passed in to the <code>-background</code>, I want to throw an argument exception, and if something invalid comes in over the pipeline, I just want to write the error to the error output and keep on trucking.</p>
<p>I tried a few <a href="http://huddledmasses.org/writing-better-script-functions-for-the-powershell-pipeline/">different approaches</a> to being able to both accept input over the parameter list and I finally found out about <code>[Parameter(ValueFromPipeline=$true)]</code>. Here is my test setup:</p>
<pre class="brush: powershell">function Get-Range([int]$max) {
    for($i=0; $i -lt $max; $i++) {
        Write-Host "pushing $i to pipeline"
        Write-Output $i
    }
}

function Test-Pipeline([Parameter(ValueFromPipeline=$true)][int[]]$vals = $null) {
    process {
        foreach($item in @($vals)){
            Write-Host "processing $item from pipeline"
        }
    }
}</pre>
<p>And my test output:</p>
<pre class="brush: plain; gutter: false">&gt; Get-Range 3 | Test-Pipeline
pushing 0 to pipeline
processing 0 from pipeline
pushing 1 to pipeline
processing 1 from pipeline
pushing 2 to pipeline

&gt; Test-Pipeline ('1','2','3')
processing 1 from pipeline
processing 2 from pipeline
processing 3 from pipeline</pre>
<p>Notice the <code>@($vals)</code> in my <code>foreach</code>? That&#8217;s to protect against null inputs by ensuring <code>$vals</code> is a list.</p>
<p>Now that I&#8217;ve got all my pieces together, I just need to put everything in place with a splash of <a href="http://technet.microsoft.com/en-us/magazine/ff458353.aspx">documentation</a>.</p>
<pre class="brush: powershell">&lt;#
    .SYNOPSIS
    Takes a list of ARGB hex values and blends them in order against a specified background.

    .PARAMETER background
    The background color to blend against, defaults to white.

    .PARAMETER colors
    A list of ARGB hex color strings, can be pushed from the pipeline.

    .EXAMPLE
    Blend-Colors '#ff121212', '#705F6A87'

    .LINK

http://en.wikipedia.org/wiki/Alpha_compositing

#&gt;
function Blend-Colors (
    [string] $background = '#FFFFFFFF',
    [Parameter(ValueFromPipeline = $true)] [string[]] $colors = $null) {
    begin {
        # $argbHexColorRegex should recognize all 4-byte hex color strings prefixed with a '#'
        # and assign them to groups named a, r, g, and b for each channel, respectively.
        Set-Variable argbHexColorRegex -Option Constant `
            -Value "(?i)^#(?'a'[0-9A-F]{2})(?'r'[0-9A-F]{2})(?'g'[0-9A-F]{2})(?'b'[0-9A-F]{2})$"

        Set-Variable argb -Option Constant -Value 'a','r','g','b'
        Set-Variable rgb -Option Constant -Value 'r','g','b'

        function Parse-Color ([string] $hex) {
            if($hex -match $argbHexColorRegex) {
                $argb | % { $color = @{} } { $color.$_ =  [int]::Parse($matches.$_, 'AllowHexSpecifier') }
                return $color;
            } else {
                return $null;
            }
        }

        function Merge-Channel ($c0, $c1, $c) {
            $a0 = $c0.a / 255
            $a1 = $c1.a / 255
            return $a0 * $c0.$c + $a1 * $c1.$c * (1 - $a0)
        }

        $outColor = Parse-Color $background
        if(-not $outColor) {
            throw (New-Object ArgumentException -ArgumentList "Invalid color: '$background'", 'background')
        }
    }
    process {
        foreach($color in @($colors)){
            $addColor = Parse-Color $color
            if(-not $addColor) {
                Write-Error "Invalid input color: $_"
                break
            }

            $rgb | % `
                { $mergeColor = @{ a = [Math]::Min(255, $outColor.a + $addColor.a) } } `
                { $mergeColor.$_ = Merge-Channel $addColor $outColor $_ }

            $outColor = $mergeColor
        }
    }
    end {
        return '#{0:x2}{1:x2}{2:x2}{3:x2}' -f ($argb | % { [int][Math]::Round($outColor.$_, 0) })
    }
}</pre>
<p>Now all you have to do is save it in %userprofile%\My Documents\WindowsPowerShell\Modules\UITools as UITools.psm1 and call <code>Import-Module UITools</code> to bring in this function.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/alpha-blending-colors-in-powershell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>Single Instance ClickOnce</title>
		<link>http://northhorizon.net/2010/single-instance-clickonce/</link>
		<comments>http://northhorizon.net/2010/single-instance-clickonce/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 17:49:12 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Lab49]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=170</guid>
		<description><![CDATA[I&#8217;m currently working on a project where the client wants to be able to click on a link and bring up a WPF UI with relevant information and available actions. Furthermore, the client wants to be able to keep clicking links and continue to reuse the same instance of the WPF UI. We decided our [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a project where the client wants to be able to click on a link and bring up a WPF UI with relevant information and available actions. Furthermore, the client wants to be able to keep clicking links and continue to reuse the same instance of the WPF UI. We decided our best option would be to go with a ClickOnce deployment, but we were unsure of how to get the web page to talk to our application.<span id="more-170"></span></p>
<p>Getting the first instance open was easy. MSDN has a <a href="http://msdn.microsoft.com/en-us/library/ms172242.aspx">great article</a> on how to get a query string out of your URI. Straight from the article:</p>
<pre class="brush: csharp">private NameValueCollection GetQueryStringParameters()
{
    NameValueCollection nameValueTable = new NameValueCollection();

    if (ApplicationDeployment.IsNetworkDeployed)
    {
        string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
        nameValueTable = HttpUtility.ParseQueryString(queryString);
    }

    return (nameValueTable);
}</pre>
<p>I was also aware that you can use a <a href="http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx">Mutex</a> to synchronize your processes. It&#8217;s a much more elegant solution than a process table search. The only question was how do we pass data from one instance of my application to another? A common solution I saw was to defer to native methods and pass strings around that way, but I felt this was too inflexible of a solution, and it requires full trust to boot. Our particular application requires full trust anyway, but in the spirit of getting things done right, we decided to give WCF <a href="http://en.wikipedia.org/wiki/Inter-process communication" target="_blank"  title="Inter-process communication" >IPC</a> a shot, and it definitely paid off.</p>
<p>My first proof of concept was much more messy than this, but I&#8217;ll spare you the clutter and discuss my better organized version. In any case, you will need to reference System.Deployment, System.ServiceModel, and System.Web.</p>
<p>I decided that I wanted to completely encapsulate the WCF and process synchronization logic, so I setup a class called <code>ApplicationInstanceMonitor&lt;T&gt; : IApplicationMonitor&lt;T&gt;</code>, where <code>T</code> is the type of the message you want to send with IPC. I decorated it with the following service behavior so we can use a singleton instance. Usually I&#8217;d go with a re-entrant concurrency mode, but since we won&#8217;t be handling very many requests, one at a time is sufficient.</p>
<pre class="brush: csharp">[ServiceBehavior(
	InstanceContextMode = InstanceContextMode.Single,
	ConcurrencyMode = ConcurrencyMode.Single)]</pre>
<p>Its implemented interface is pretty simple:</p>
<pre class="brush: csharp">[ServiceContract]
public interface IApplicationInstanceMonitor&lt;T&gt;
{
	[OperationContract(IsOneWay = true)]
	void NotifyNewInstance(T message);
}
</pre>
<p>Next I created a method to deal with the Mutex, take action to setup IPC as necessary, and report its status.</p>
<pre class="brush: csharp">private readonly string _mutexName; // Set by constructor
private Mutex _processLock;

public bool Assert()
{
	if (_processLock != null)
		throw new InvalidOperationException("Assert() has already been called.");

	bool created;
	_processLock = new Mutex(true, _mutexName, out created);

	if (created)
		StartIpcServer();
	else
		ConnectToIpcServer();

	return created;
}
</pre>
<p>For the WCF setup, I simply needed a URI to bind to (set or generated by the constructor) and a binding:</p>
<pre class="brush: csharp">_binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport);</pre>
<p>So connecting to WCF was rudimentary:</p>
<pre class="brush: csharp">private readonly Uri _ipcUri; // Set by constructor
private readonly NetNamedPipeBinding _binding; // Set as above
private ServiceHost _ipcServer;
private ChannelFactory&lt;IApplicationInstanceMonitor&lt;T&gt;&gt; _channelFactory;
private IApplicationInstanceMonitor _ipcChannel;

private void StartIpcServer()
{
	_ipcServer = new ServiceHost(this, _ipcUri);
	_ipcServer.AddServiceEndpoint(typeof(IApplicationInstanceMonitor), _binding, _ipcUri);

	_ipcServer.Open();

	_ipcChannel = this;
}

private void ConnectToIpcServer()
{
	_channelFactory = new ChannelFactory&lt;IApplicationInstanceMonitor&lt;T&gt;&gt;(
		_binding, new EndpointAddress(_ipcUri));
	_ipcChannel = _channelFactory.CreateChannel();
}
</pre>
<p>Now all that&#8217;s left to do in our class is expose out the useful methods. I use an explicitly implemented service contract interface to deal with the server-side, since that&#8217;s what WCF will call into and the regular implementation for the client side.</p>
<pre class="brush: csharp">public event EventHandler&lt;NewInstanceCreatedEventArgs&lt;T&gt;&gt; NewInstanceCreated;

// NOTE: This is not a subclass, but here for ease of viewing.
public class NewInstanceCreatedEventArgs&lt;T&gt; : EventArgs
{
	public NewInstanceCreatedEventArgs(T message)
		: base()
	{
		Message = message;
	}

	public T Message { get; private set; }
}

public void NotifyNewInstance(T message)
{
	// Client side

	if (_ipcChannel == null)
		throw new InvalidOperationException("Not connected to IPC Server.");

	_ipcChannel.NotifyNewInstance(message);
}

void IApplicationInstanceMonitor.NotifyNewInstance(T message)
{
	// Server side

	if (NewInstanceCreated != null)
		NewInstanceCreated(this, new NewInstanceCreatedEventArgs(message));
}
</pre>
<p>There it is! Now all we need to hook it up is in our App.xaml.cs (assuming you&#8217;re doing WPF)</p>
<pre class="brush: csharp">private Window1 _window; // Set by constructor
protected override void OnStartup(StartupEventArgs e)
{
	if (_instanceMonitor.Assert())
	{
		// This is the only instance.

		_instanceMonitor.NewInstanceCreated += OnNewInstanceCreated;

		_window.Show();
	}
	else
	{
		// Defer to another instance.

		_instanceMonitor.NotifyNewInstance(new MyMessage { QueryString = GetQueryString() });

		Shutdown();
	}
}

private void OnNewInstanceCreated(object sender, NewInstanceCreatedEventArgs e)
{
	// Handle your message here

	_window.Activate();
}

public string GetQueryString()
{
	return ApplicationDeployment.IsNetworkDeployed ?
		ApplicationDeployment.CurrentDeployment.ActivationUri.Query :
		string.Empty;
}

public void HandleQueryString(string query)
{
	var args = HttpUtility.ParseQueryString(query);

	_window.Message = args["message"] ?? "No message provided";
}

[Serializable]
public class MyMessage
{
	public string QueryString { get; set; }
}
</pre>
<p>And now we&#8217;re done. Just a bit of HTML and you&#8217;ll be communicating with your ClickOnce in no time!</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/single-instance-clickonce/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Qualifications for Writing Textbooks</title>
		<link>http://northhorizon.net/2009/the-qualifications-for-writing-textbooks/</link>
		<comments>http://northhorizon.net/2009/the-qualifications-for-writing-textbooks/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 19:48:37 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Textbooks]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=122</guid>
		<description><![CDATA[It&#8217;s certainly true that there are many unqualified authors that the self-taught programmer has to look out for, but what about the textbooks we read at universities? I won&#8217;t argue for a second that tenured professors are the least bit unqualified to discuss the intricacies of algorithms and abstract data structures, but who writes the [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s certainly true that there are many <a href="http://video.google.com/videoplay?docid=-4408250627226363306">unqualified authors</a> that the self-taught programmer has to look out for, but what about the textbooks we read at universities? I won&#8217;t argue for a second that tenured professors are the least bit unqualified to discuss the intricacies of algorithms and abstract data structures, but who writes the book on using real world implementations? Who is qualified to write the book on Java or SQL Server? I&#8217;d want to see someone who has been using the technology for several years or a good portion of the technology&#8217;s life if it&#8217;s relatively new. Unfortunately, I find this is rarely the case.<span id="more-122"></span> I think publishers could run a pitch like this:</p>
<blockquote><p>From the people who confused you with the most elementary algorithms comes a series of things you really need to know to do your job! Watch, mystified, as the book which you have a test on in eight hours <em>invents</em> symbols to explain the details of single digit addition! You might have been top of your class in high school and showed promise through your core and basic classes, but just you wait! Our authors have learned and mastered techniques to simultaneously insult your intelligence and dumbfound you with a needless amount of abstraction and complexity! All this can be yours for the low-low price of $280 for our 120 page full color, hardcover book!</p></blockquote>
<p><span>I&#8217;ve always been upset with textbook publishers, ever since my days in Computer Science 1, sophomore year in high school. The authors of that poorly constructed book (the binding literally only lasted about six months before self-destructing) took some kind of sadistic enjoyment in coming up with unintelligible vocabulary, patterns, and practices in which to subject students. In those days our teacher was our savior; no matter how mind-gratingly stupid and dull the book was, Mr. Patterson invariably sorted things out and never hesitated to say the book was moronic. I have to thank him for saving my sanity or, at least, staving off the inevitable future.</span></p>
<p>This semester, I draw particular complaint with <a href="http://www.amazon.com/Fundamentals-Database-Systems-Ramez-Elmasri/dp/0321369572/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1238532060&amp;sr=8-1">the book in my databases class</a>, inappropriately named &#8220;Fundamentals of Database Systems (5e),&#8221;  by <span>Ramez Elmasri and Shamkant B. Navathe. I&#8217;ve been writing SQL for about four years now, but it wasn&#8217;t untill my last job that I think I really learned the full potential of a database system. My old boss was an absolute <em>god </em>in writing SQL and I  made certain that the learning experience more than accounted for the pay. It was under his tutelage that I learned how well-designed database systems were made and how to retrieve amazing data no one thought possible. I wouldn&#8217;t consider myself a sage in designing databases, but I think that I&#8217;m definitely qualified to pass judgment on most designs, especially the ones that would be considered &#8220;fundamental.&#8221;</span></p>
<p><span>During the early stages of my class, my professor discussed the all-important topic of table keys. (For my non-programmer friends, you use database keys to look up data in a particular table. Since some tables can have millions of rows, you have to choose a key that is unique and is as small as possible for quick lookup.) It&#8217;s a well-held practice in modern databases that the database is really the best agent to tell you what the keys are, so in general, what you want to do is tell it what your data is, and, like a coat-check, it gives you a little token (a 32-bit signed integer) to get your data again. Because the database chooses the key, you can be assured that it is both unique and small enough to quickly look things up. This is known as an auto-increment integer primary key column, mainly because the integer that you&#8217;re given is 1 (or some increment) more than the key that was given out last. Even though it&#8217;s not a traditional mechanism in database research, every major database (MSSQL, Oracle, MySQL, Protegé) has some incarnation of it. Traditionally, the programmer chooses one or more fields that combined are unique. While this is effective, it takes significantly longer for the server to prepare the key to look up the data and the number of fields that must be duplicated on tables so the original data can be found becomes tremendous. My database professor still disagrees with me, but I have faith that he&#8217;ll have an epiphiny sometime and understand and regret the error of his ways.</span></p>
<p><span>So why is it that these authors, from whom my professor quotes, have got it all wrong? In lieu of real research, I did some investigative Googling to find the qualifications of these men.</span></p>
<h3><span>Ramez Elmarsi</span></h3>
<ul>
<li>B.S., Electrical Engineering, Alexandria University (Egypt, 1972)</li>
<li>M.S., Ph.D., Computer Science, Stanford University (1980)</li>
</ul>
<p>Elmarsi has spent the bulk of his life in research while consulting for Honeywell developing a distributed database testbed and associated tools from 1982 to 1987. He now teaches at the University of Texas at Arlington and consults for various law firms.</p>
<h6>Source: <a href="http://ranger.uta.edu/~elmasri/">http://ranger.uta.edu/~elmasri/</a></h6>
<h3>Shamkant B. Navathe</h3>
<ul>
<li>Ph.D., Industrial and Operations Engineering, University of Michigan (1976)</li>
<li>M.S., Computer and Information Science, Ohio State University (1970)</li>
<li>B.E., Electrical Communications Engineering, Indian Institute of Science (1968)</li>
<li>B.Sc., Physics, Mathematics, University of Poona (India,	1965)</li>
</ul>
<p>Navathe was a Systems Engineer for IBM from 1968-1969 before working for Electronic Data Systems in 1971. Starting in 1975, Navathe began teaching at NYU as an associate professor and then moved to the University of Florida for a few years until he ultimately settled at the Georgia Institute of Technology, where he teaches now.</p>
<h6>Source: <a href="http://www.cc.gatech.edu/computing/Database/faculty/sham/">http://www.cc.gatech.edu/computing/Database/faculty/sham/</a></h6>
<p>There&#8217;s no doubt that these men have the academic prowess demanded by their degrees and both have an extensive list of published works. But what really disturbs me is their professional résumé. Navathe stopped working professionally in 1971 and Elmarsi has never worked as a full-time employee at <em>any</em> company. This is when I understood exactly why my book is heavy on unintuitive mathematical symbols wielded like a bat with barbed wire and light on intelligence or edifying information. This field changes dramatically every couple years and unless you can keep up to date on the very latest technology, you are willing yourself into obsolescence. But yet some <span style="text-decoration: line-through;">charlatans</span> authors have the audacity to publish texts advising the unsuspecting student to continue using the old technologies of yore, rather than using what is new and efficient. Perhaps even more inexcusable is the book selection committee at my university choosing textbooks no one can read, let alone understand to remind all of us undergrad students that we&#8217;re not Ph.D.&#8217;s and we haven&#8217;t joined their elite clique.</p>
<p>I think this problem is far more widespread than I have broached here. A year or so ago, I wrote a letter I never delivered to my dean, more or less as a venting exercise. I think I&#8217;m going to clean it up and discuss my points here, in the event someone who can do something stumbles upon my humble blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/the-qualifications-for-writing-textbooks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Definition of Computer Science</title>
		<link>http://northhorizon.net/2009/the-definition-of-computer-science/</link>
		<comments>http://northhorizon.net/2009/the-definition-of-computer-science/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 05:37:24 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=106</guid>
		<description><![CDATA[What is Computer Science? It&#8217;s always interesting to see how different people answer the question. Especially people who have or plan to have degrees in it. Dictionary.com defines it as: the science that deals with the theory and methods of processing information in digital computers, the design of computer hardware and software, and the applications [...]]]></description>
			<content:encoded><![CDATA[<p>What is Computer Science?</p>
<p>It&#8217;s always interesting to see how different people answer the question. Especially people who have or plan to have <em>degrees</em> in it. Dictionary.com defines it as:</p>
<blockquote><p>the science that deals with the theory and methods of processing information in digital computers, the design of computer hardware and software, and the applications of computers.</p></blockquote>
<p>I see this broken down into:</p>
<ul>
<li>Science</li>
<li>Theory</li>
<li>Design of hardware and software</li>
<li>Applications for computation</li>
</ul>
<p>Normally, I&#8217;d say fighting the dictionary on definitions would be rather fruitless, but this is by far one of the most vague definitions I&#8217;ve ever seen. I think a good analog for CS is math and physics. In that much more mature field, mathematics provides laws that say <em>x</em> should exist. It is then up to the applied physicist to prove in a lab that the theory is true. Even <em>then</em>, it is up to a company and its engineers to productize and actually use the fruits of science. Computer Science, in stark contrast according to this definition, is all of those things rolled up into one. It&#8217;s no wonder why no one in this field knows what it means.<span id="more-106"></span></p>
<p>To me, the entire term &#8220;Computer Science&#8221; is a huge misnomer. It&#8217;s certainly not science. Science, at least to me, involves creating a hypothesis, setting up an experiment, and proving the truth of your assumptions. Last time I checked, there was no such thing in CS. Nobody sits around and hypothesizes about algorithms, let alone commercial programs. I think upper management would have a conniption if their products were experiments.</p>
<p>So what about computers? Surely you use computers in CS! I suppose most of my professors didn&#8217;t get that memo, and, historically, that really hasn&#8217;t been the case either. Edsger Dijkstra, one of the most renowned computer scientists in our short history, never used a computer. Even his musings, as late as 2001, were handwritten. Dijkstra had a very particular view of CS. To him, Computer Science was purely theory &#8211; really quite close to a real science in terms of algorithm design and such. It was his opinion that all these programs we run on our computers are perversions of computation. In the spirit of our forerunner, my professor in Advanced Data Structures forwent computers in favor of the more conventional pencil and paper. To be fair, I&#8217;m almost certain he <em>was</em> a machine, based upon his ability to do the most tedious and mundane calculations <em>ad nauseum</em> with the patience of any of Intel&#8217;s creations.</p>
<p>Since it seems my degree is almost as ambiguous as a Liberal Arts degree, I will posit my suggestions for changing it. Fortunately, unlike my comparison, <em>my</em> degree is both useful and salvageable.</p>
<p>My university has done a good job of trying to distill the ideas that I&#8217;ve covered here, and, for that, I commend them. It is, however, nothing short of unprovidential that they&#8217;ve managed to distill one form of mud into two forms of mud. The school offers degrees in Computer Science and Software Engineering. Despite what you might think, SE is hardly its namesake. What they ended up with is a theory-application mix (CS) and a application-business mix (SE). At least it&#8217;s a step in the right direction.</p>
<p>I think we need three degrees, as you have probably noticed that I&#8217;ve been hinting all along:</p>
<ol>
<li>Theoretical Computation</li>
<li>Software Engineering</li>
<li>Software Management</li>
</ol>
<p>Theoretical Computation would focus on algorithm design and computability, as its name suggests. It&#8217;s not a science, and it has no computers in it &#8211; just <em>computability</em>, or the ability for something to be derived from calculations and deterministic processes.</p>
<p>Software Engineering would actually live up to its name. Programming would be king, like the pencil is to the artist. Software architecture would be a major emphasis, as well as applied algorithm design, which could reach over into Theoretical Computation.</p>
<p>Finally comes Software Management. Because software planning is a huge issue for any company that writes software, be it boxed or internally distributed, we need people who are trained to help the process along. These people need to be business savvy to communicate deadlines and goals to the non-technical arm(s) of the company. Furthermore, Software Management majors have to be technical enough to be able to choose good employees.</p>
<p>A lot of people in the field feel that there will be a strong resistance to change for such a degree plan, even if it makes sense. I can understand the impetus, but at the same time the degree itself hasn&#8217;t existed for forty years, so there is always hope for reorganization.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/the-definition-of-computer-science/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>W3C Validation and the Web</title>
		<link>http://northhorizon.net/2009/w3c-validation-and-the-web/</link>
		<comments>http://northhorizon.net/2009/w3c-validation-and-the-web/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 14:00:57 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Browser]]></category>
		<category><![CDATA[Coding Horror]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[W3C]]></category>
		<category><![CDATA[W3C Validation]]></category>
		<category><![CDATA[Web Standards]]></category>
		<category><![CDATA[XHTML]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=98</guid>
		<description><![CDATA[I try to keep up on several blogs, one of which is Jeff Atwood&#8217;s Coding Horror. Recently, he chose the topic of W3 Validation and its necessity, or lack thereof. I also seem to have made a few statements on a similar topic, so perhaps my view is nothing short of expected. What is strange, [...]]]></description>
			<content:encoded><![CDATA[<p>I try to keep up on several blogs, one of which is Jeff Atwood&#8217;s <a href="http://codinghorror.com">Coding Horror</a>. Recently, he chose the topic of W3 Validation and its necessity, or lack thereof. I also seem to have made a <a href="http://northhorizon.net/2009/browser-compatibility-and-the-sanity-of-web-developers/">few statements</a> on a similar topic, so perhaps my view is nothing short of expected. What <em>is</em> strange, however, is Jeff&#8217;s point of view, considering he and I are kindred spirits in the world of .NET and C#.<span id="more-98"></span></p>
<p>Jeff&#8217;s argument is pretty simple:</p>
<ul>
<li>The web is a forgiving place.</li>
<li>Many big-name websites don&#8217;t pass validation.</li>
<li>James Bennett doesn&#8217;t like XHTML.</li>
<li>CSS isn&#8217;t as intuitive as HTML-embedded properties.</li>
<li>Validity is relative to your standards.</li>
</ul>
<p>Since Jeff &#8220;vehemently agrees&#8221; with Mr. Bennett, I decided to investigate <a href="http://www.b-list.org/weblog/2008/jun/18/html/">his article</a> as well, to try and understand where Atwood was coming from. Benett&#8217;s argument is even more basic:</p>
<ul>
<li>No real advantages.</li>
<li>Markup errors are fatal.</li>
<li>There is some CSS/DOM incompatibility between HTML 4.01 and XHTML.</li>
</ul>
<p>The majority of these points, are, in my opinion, rooted in ignorance and xenophobia, both of which are disastrously fatal in our industry, <em>especially</em> on the Web. It is true the Web is very forgiving, but only because it must be so. HTML is a novel language, in the sense that you don&#8217;t move from line to line, from procedure to procedure, but rather declare the structure of how something looks and let the renderer (IE, Firefox, Safari) choose the best way to view it. A good example is when Firefox switched from an iterative to a recursive implementation in its third version and also reimplemented its graphics engine. Because of the declarative nature of HTML, websites weren&#8217;t adversely impacted. However, like all new things, HTML has its quirks. Namely, it&#8217;s not very easy for computers to understand. In fact, sometimes it&#8217;s not all that easy for even humans to understand &#8211; maybe a sort of inverted Turing test.</p>
<p>Like all the triumphs in Computer Science, someone identified the problems that exist in HTML and created a far more flexible and extensible language called XML. XML is now one of the best containers for information because of its well-designed and understandable structure and its infinite flexibility. While that&#8217;s great for data storage, what about the Web? Well, that&#8217;s where XHTML 1.0 came in, as a statically defined language like HTML, but a machine-understandable and consistent language, like XML. XHTML, is, at its very essence, the best of both worlds.</p>
<p>I think Atwood and Bennett had a similar reaction to XHTML <a href="http://northhorizon.net/2009/browser-compatibility-and-the-sanity-of-web-developers/">as I did</a>:</p>
<blockquote><p>Back when XHTML went 1.0, I was somewhat surprised to see that they had actually removed elements and attributes from the specification. Usually, moving to a new product means that you get more, not less.</p></blockquote>
<p>The difference here is that they refused, either consciously or unconsciously to adapt to and understand where the Web was &#8211; and still is &#8211; going. The W3C is going for a very specific separation of concerns for websites. XHTML is designed to be the static structure of a website. It contains data (text and such), and some hints on how to present it (whether it be in paragraphs, tabular, or a list), but nothing else. This is where CSS comes in. CSS decorates the XHTML, quantifying distances, sizes, backgrounds, and organization. Finally, JavaScript gives the client a smooth feel, dynamically altering the web page to best suit the client, and, as of late, retrieve data on the fly through AJAX and JSON. This is why HTML attributes are almost all deprecated in XHTML &#8211; the static structure doesn&#8217;t care how wide things are or how tall they are. One of the best examples that I can think of to demonstrate the division of power between XHTML and CSS is <a href="http://www.csszengarden.com/">CSS Zen Garden</a>. The opening page is modest enough, but choose one of the designs on the right sidebar and the entire layout changes. The only difference between the default and new design is a new CSS style sheet. You&#8217;ll notice it has all the same text, all the same navigation, but a completely different look. Why is this useful or important? Well, as a form of broadcast media, it is salient to shape the way your website looks based on the viewer. For instance, if you go to a website on an web-enabled cellphone, I&#8217;d want to strip out as many ancillary graphics as possible and conserve as much width as possible. If you&#8217;re vision impaired, I want to be able to deliver to you a web page that a TTY device can easily understand. Or, perhaps, you&#8217;re a search engine and I want to get straight to the point so you can index better. This should all be easily accomplished by specifying the use and intention of each style sheet and allowing the user to choose the one that best suits their purpose.</p>
<p>Of course, someone always brings up the fact that many name-brand websites aren&#8217;t valid at all. I&#8217;d also like to point out that many big-name trading firms are going bankrupt. Just because they don&#8217;t care doesn&#8217;t mean you shouldn&#8217;t. The argument itself is infantile. I&#8217;m not trying to inflate my ego any (trust me, that&#8217;d be a bad idea), but I find writing XHTML 1.1 (which is by far the strictest) to be very easy. When Marlene and I drew up the static format for this website (that is, before we plugged in all the WordPress stuff), I had about three validation errors, all of which were quelled very easily. Personally, I was a little disappointed I had <em>any</em>, but I suppose perfection was never a trait I had.</p>
<p>Jeff also wonders whether CSS validation is possible. I&#8217;m not entirely sure why he didn&#8217;t bother to <a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=zyV&amp;newwindow=1&amp;q=css+validation&amp;btnG=Search">check Google</a>. Of course CSS validation exists, and I&#8217;m proud to say this website&#8217;s CSS is valid as well.</p>
<p>It&#8217;s unfortunate that XHTML markup errors are indeed fatal (and the errors aren&#8217;t always very helpful), but as a C# developer, I&#8217;m used to having compiled code. If I messed up and miscommunicated with the machine (again, perfection is not one of my virtues), I want the machine to tell me that it doesn&#8217;t understand, rather than acting like my girlfriend, misinterpreting what I said, and summarily stating that I don&#8217;t love her anymore. Obviously it&#8217;s simply untrue; I will always love my computer. Girlfriends are a bit different.</p>
<p>So, perhaps the most important question is, why do we need standards? The need for validation clearly hinges upon the need for standards; without validation, how can one tell if standards are being upheld? And without standards, the Internet would be far more segmented than it is already. Jeff is right that most people don&#8217;t understand the W3 Valid &#8220;stickers&#8221; some webmasters (like myself) have on their websites in various locations. This doesn&#8217;t really bother me, though. Most people don&#8217;t notice half the validations on many of the products they use everyday. On the inside of the battery cover of your cellphone, there exist a multitude of symbols, each representing a different standards body that approved this device to work with the network. Yet millions of people blithely continue on, blissfully ignorant of the years of effort that go into making such a device. Such is the thankless life of an engineer. No one notices when you make amazing accomplishments (and a W3C valid website is hardly a major feat), but everyone complains when the slightest flaw presents itself.</p>
<p>I suppose we just learn to deal with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/w3c-validation-and-the-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Respond in blue ink: Requiring Tools in Computer Science</title>
		<link>http://northhorizon.net/2009/respond-in-blue-ink-requiring-tools-in-computer-science/</link>
		<comments>http://northhorizon.net/2009/respond-in-blue-ink-requiring-tools-in-computer-science/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 22:46:13 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Grading]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JUDE]]></category>
		<category><![CDATA[Object Oriented Analysis and Design]]></category>
		<category><![CDATA[Object Oriented Programming Systems]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Visio]]></category>
		<category><![CDATA[Waterfall]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=82</guid>
		<description><![CDATA[This semester I&#8217;m taking several electives to finish up my degree. One of the courses I&#8217;m taking is Object Oriented Programming Systems, formerly Object Oriented Analysis and Design. I have yet to find a suitable explanation as to why OOaD was cut and reformed at the graduate level, but I&#8217;m assuming it was because it [...]]]></description>
			<content:encoded><![CDATA[<p>This semester I&#8217;m taking several electives to finish up my degree. One of the courses I&#8217;m taking is Object Oriented Programming Systems, formerly Object Oriented Analysis and Design. I have yet to find a suitable explanation as to why OOaD was cut and reformed at the graduate level, but I&#8217;m assuming it was because it was a bit too advanced for <span style="text-decoration: line-through;">some</span> many of the people I find in my major. In its stead, we now have a much more aptly abbreviated course.</p>
<p>In any case, my professor is a big proponent of Java, the Waterfall <a href="http://en.wikipedia.org/wiki/Software Development Life Cycle" target="_blank"  title="Software Development Life Cycle" >SDLC</a> (which he dubs &#8220;the generic SDLC.&#8221; I wasn&#8217;t aware wet sand was considered &#8220;the generic foundation&#8221;) and, of course, all the misery that comes with it.<span id="more-82"></span></p>
<p>For one of our more recent homework assignments, we were given the trivial task of converting a four Java classes from a previous assignment into UML diagrams. We were obviously applying what we learned in class by putting the cart in front of the horse. Our assignment was to be done in <a href="http://en.wikipedia.org/wiki/Jude (UML Tool)" target="_blank"  title="Jude (UML Tool)" >JUDE</a> of <a href="http://jude.change-vision.com/jude-web/product/img/er_index_en.jpg">all things</a>. In the interests of full disclosure, I am completely spoiled in terms of tools to use. Microsoft, through its godsend of <a href="http://en.wikipedia.org/wiki/MSDNAA" target="_blank"  title="MSDNAA" >MSDNAA</a> makes Christmas just about every day of the year for me. Sure I know it&#8217;s a form of product marketing &#8211; analogous to giving crack to kids &#8211; but have you <em>used</em> their stuff? It&#8217;s head and shoulders above <em>everything</em> else, and in many cases is the paradigm to which the industry <strong>only seeks to make parity with</strong>. With that being said, I&#8217;m hoping you&#8217;ll understand my&#8230; disposition against Fischer Price&#8217;s JUDE product. Instead of trudging through the installation of a clearly inferior product, ripping my hair out trying to understand the UI, and eventually producing a diagram that my 5-year-old cousin could have drawn better, I decided that I would use Visio instead. I made my diagrams down to the letter and they looked <em>beautiful</em>. I spent extra time making sure that the positioning of each class reduced the nmber of times connections intersected and made especially sure that everything was clear. I saved it out as a PDF, so as to be platform agnostic, and submitted it.</p>
<p>I wasn&#8217;t nearly as surprised as I was <em>livid </em>when I found out that I had been deducted 50% credit on the <em>sole</em> basis of, &#8220;it&#8217;s not a .jude file.&#8221; <em>That</em> is the kind of <a href="http://www.wsu.edu/~brians/errors/churchill.html">arrant pedantry</a> up with which I will not put. To me, it&#8217;s really the equivalent of me asking you to write a paper on Shakespeare in blue ink. I&#8217;d suppose a lot of people would remark, &#8220;well, I write in blue ink anyway, so it&#8217;s not a big deal,&#8221; and continue on. Still more would say, &#8220;normally I write in black ink, but I&#8217;ll comply because it seems like a trivial request, and not worth the fight.&#8221; This would probably leave me by myself stating emphatically that it is <em>unreasonable</em> to be concerned with the color of the ink that I write in juxtaposed against the magnitude of writing a paper on Shakespeare. Of course, I&#8217;d comply if the reasoning for the requirement of blue ink was enumerated, so long as it wasn&#8217;t arbitrary.</p>
<p>Perhaps even more important than the freedom aspect of the scenario is the abject <em>insanity</em> that revolves around diagrams. Who cares if your diagram was written in Visio, JUDE, Rhapsody, or on a whiteboard? <strong><em>It&#8217;s a diagram</em></strong>. The concept of <a href="http://en.wikipedia.org/wiki/WYSIWYG" target="_blank"  title="WYSIWYG" >WYSIWYG</a> is almost an understatement. It might be argued that JUDE is an &#8220;enterprise application&#8221; and my good professor is trying to do me a favor by showing me a tool that&#8217;s used in the &#8220;real world.&#8221; I don&#8217;t think I would ever want to work for an employer that says, &#8220;We see  UML on your résumé, but while we think you&#8217;re smart enough to work on our codebase, we don&#8217;t think you&#8217;re smart enough to learn to use the UML tool we have.&#8221;</p>
<p>I think it&#8217;s more important to state the objectives of any assignment, be it professional or educational, and let the person doing the work choose the best way to accomplish it. Nobody likes a micromanager. Especially me.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/respond-in-blue-ink-requiring-tools-in-computer-science/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Browser Compatibility and the Sanity of Web Developers</title>
		<link>http://northhorizon.net/2009/browser-compatibility-and-the-sanity-of-web-developers/</link>
		<comments>http://northhorizon.net/2009/browser-compatibility-and-the-sanity-of-web-developers/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 16:47:31 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Browser]]></category>
		<category><![CDATA[Chrome]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[CSS floats]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[IE]]></category>
		<category><![CDATA[Opera]]></category>
		<category><![CDATA[Safari]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=47</guid>
		<description><![CDATA[Since I&#8217;ve decided to get this blog rolling, one of my primary objectives was to ensure a consistent, high quality experience for any platform visitors come from. Obviously, it&#8217;s impossible to test the myriad of browsers out there, but I think it&#8217;s useful to at least test on the top three engines, namely Trident (Internet [...]]]></description>
			<content:encoded><![CDATA[<p>Since I&#8217;ve decided to get this blog rolling, one of my primary objectives was to ensure a consistent, high quality experience for any platform visitors come from. Obviously, it&#8217;s impossible to test the myriad of browsers out there, but I think it&#8217;s useful to at least test on the top three engines, namely Trident (Internet Explorer), Gecko (Firefox), and WebKit (Safari / Chrome). I also test on Opera, even though it has <a href="http://arstechnica.com/microsoft/news/2009/02/january-2009.ars">little market share</a>. Hopefully I&#8217;ll get my traffic statistics going again soon, so  I can prove more definitively that sixty something percent of the ten people who come here use Firefox anyway.</p>
<p>So that leave three or so of you guys using IE. Well, I hate to break it to you, but your browser sucks. It really does. Web developers everywhere have been rejecting Microsoft&#8217;s browser for some time now, which has given rise to the healthy market share Firefox has had.</p>
<p>How does this affect you and me, you may be wondering. Well, let&#8217;s do a case study on the site you&#8217;re looking at right now, since I&#8217;m fixing it up anyway.<span id="more-47"></span> For those of you not using a W3C compliant browser (read: IE), the website is supposed to have some blocks of color of varying height below each of the navigation links, which highlight to orange and a main body text that wraps around the sidebar on the right.</p>
<div id="attachment_59" class="wp-caption aligncenter" style="width: 160px"><a href="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ff.png"><img class="size-thumbnail wp-image-59" title="northhorizon-ff" src="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ff-150x150.png" alt="northhorizon-ff" width="150" height="150" /></a><p class="wp-caption-text">My post about hashing as seen in Firefox.</p></div>
<p>Beautiful. Everything looks just like it should in Firefox, Safari, Chrome, and Opera. But what happens when we look at it in IE?</p>
<div id="attachment_61" class="wp-caption aligncenter" style="width: 160px"><a href="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ie7.png"><img class="size-thumbnail wp-image-61" title="northhorizon-ie7" src="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ie7-150x150.png" alt="northhorizon-ie7" width="150" height="150" /></a><p class="wp-caption-text">The same post as seen by Internet Explorer 7</p></div>
<p>Oh wow. Not what I was going for at all. This is quite common for web developers to experience: write a website and make it perfect for the W3C compliant browsers and then try and get it to work in IE, because in all honesty, IE makes very little sense in terms of expected results. On another project, I instructed the browser to move an object 6 pixels left and 10 pixels down. Firefox was happy to oblige, but IE only moved it 3 pixels left and 8 pixels down.</p>
<p>So what&#8217;s going on here at the root, so we can fix it? Well, if you inspect my CSS, you&#8217;ll find this tidbit:</p>
<pre lang="css">#sidebar {
	float: right;
	width: 250px;
	list-style: none outside;
	background: white;
	margin: 0 0 0 10px;
	padding: 5px;
	padding-left: 20px;
}</pre>
<p>Most notably, I&#8217;m using CSS floats to put the Sidebar on the right. By doing so, I&#8217;m instructing the browser to make some space for it and to wrap text around it. IE obviously doesn&#8217;t care about my floated <code>div</code>, so it just disregards the instruction. That leaves me in a precarious position. Should I abandon my floats, which lead to nicer, cleaner XHTML in favor of tables because of one non-compliant browser? Of course not! Instead I have a little function that tells me what browser you&#8217;re using called <a href="http://us3.php.net/manual/en/function.get-browser.php"><code>get_browser()</code></a>. The code looks like this:</p>
<pre lang="php">$browscap = get_browser();
define('IE', ($browscap-&gt;browser == 'IE'));</pre>
<div id="attachment_64" class="wp-caption alignright" style="width: 160px"><a href="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ie7-fixed.png"><img class="size-thumbnail wp-image-64" title="northhorizon-ie7-fixed" src="http://northhorizon.net/wp-content/uploads/2009/02/northhorizon-ie7-fixed-150x150.png" alt="northhorizon-ie7-fixed" width="150" height="150" /></a><p class="wp-caption-text">The same post in Internet Explorer 7 with my fixes.</p></div>
<p>This gives me a global constant, <code>IE</code> that allows me to change how the website looks if you&#8217;re running IE. With this in mind, I actually insert in a table in the middle of the page to force the sidebar to stay on the right. Problem solved.</p>
<p>As I was doing all this, I wondered if IE8 would give me any relief. I was somewhat surprised to find that it does, in fact, respect floating <code>div</code>s, and even respects the :after pseudo classes that allow me to add those blocks under the navigation links. Just not the hovering. <em>Sigh</em>. Anyway, all I needed to do was modify my IE code to check the major version number of the browser to say that IE8+ was <span style="text-decoration: line-through;">really</span> mostly W3C compliant.</p>
<pre lang="php">$browscap = get_browser();
define('IE', ($browscap-&gt;browser == 'IE' &amp;&amp; $browscap-&gt;majorver &lt; 8));</pre>
<p>So why is IE this way fundamentally? I don&#8217;t have any real code or facts to base these assumptions on, but my speculation is based on working with both XHTML and CSS as well as C# / WinForms / WPF. I assert to you that Microsoft has misunderstood the Web since its inception. With things like <a href="http://en.wikipedia.org/wiki/ActiveX">ActiveX</a> (now, thankfully, deprecated) it seems like Microsoft has always wanted to bring Windows to the web &#8211; literally. In Windows Forms (the battleship gray programs we all used to know), each visual element is a very unique item. Buttons don&#8217;t behave very much like Panels which don&#8217;t behave very much like CheckBoxes. It follows that you can&#8217;t really apply properties that relate to a Button to a Panel. Sensible enough. Unlees you&#8217;re dealing with XHTML and CSS. Back when XHTML went 1.0, I was somewhat surprised to see that they had actually <em>removed</em> elements and attributes from the specification. Usually, moving to a new product means that you get <em>more</em>, not less. It took some time, but I eventually realized that the Web isn&#8217;t like WinForms at all. Each element on the web (with the exception of form controls like ComboBoxes and CheckBoxes) is really the same. Almost everything can be broken down into a div or a span, and really if you change the display attribute on them, you end up with one amorphous panel.</p>
<p>This is the fundamental difference between IE and the W3C triad. Microsoft insists that floats and hovers really shouldn&#8217;t apply to things like divs, because they come from two seperate branches in the object tree. Really, until Microsoft realizes this, throws the existing codebase out, and tries again, IE will never be able to keep up with the rest. It&#8217;s a matter of understanding the nature of the Web and using an appropriate architecture to interpret it.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2009/browser-compatibility-and-the-sanity-of-web-developers/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>
