<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[i-think Twenty-Two]]></title>
  <link href="http://i-think22.net/atom.xml" rel="self"/>
  <link href="http://i-think22.net/"/>
  <updated>2019-05-30T21:09:52+10:00</updated>
  <id>http://i-think22.net/</id>
  <author>
    <name><![CDATA[Rhys Parry]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Build notification light using Redis and a Delcom Visual Indicator]]></title>
    <link href="http://i-think22.net/archives/2014/04/02/build-notification-light-using-redis-and-a-delcom-visual-indicator/"/>
    <updated>2014-04-02T17:46:00+10:00</updated>
    <id>http://i-think22.net/archives/2014/04/02/build-notification-light-using-redis-and-a-delcom-visual-indicator</id>
    <content type="html"><![CDATA[<p>A while back I ordered a <a href="http://www.delcomproducts.com/products_USBLMP.asp">Visual Signal Indicator</a> from <a href="http://www.delcomproducts.com">Delcom</a>. I had
great plans to make it flash when I received a call on Lync, and to generally
help me keep track of the health of the project I was working on. I looked at
the <a href="http://www.delcomproducts.com/productdetails.asp?ProductNum=890640">C# example code</a> provided by Delcom and initially was hesitant to get
started. I was already planning out how I would need to write a library that
would simplify the madness of unravelling the various settings the example
provided. All the commands were wrapped to Click events in a Windows Form app
which led me to not get a start on the project as quickly as I had hoped.</p>

<p>Recently I have just started working on a new project and as we were blessed
with a build server and a mostly working build I was reminded of this project
that had been put on the back burner. This time I approached it with a far
more pragmatic mindset and just wanted to get something working. I wasn&rsquo;t
looking to win any UI awards and I didn&rsquo;t want to architect it any further
than what I needed to get the job done.</p>

<p>This is what the light can do:</p>

<ul>
<li>Turn on any of three colours at various power levels</li>
<li>Flash lights on a timing interval</li>
<li>Make beeping sounds</li>
<li>Accept input (the light itself is a button)</li>
</ul>


<p>I still haven&rsquo;t quite worked out exactly how the button works on the light,
but I was able to easily set it so it would beep if I pushed the button
thanks to a built in setting. This however wasn&rsquo;t something that I especially
needed anyway.</p>

<p>My needs however were simple. I had three colours to choose from, red, green
and yellow. I also wanted to be able to make the light flash while a build was
running and continue to show the colour of the previous build result.</p>

<h2>A Redis interface to the light</h2>

<p>Another technology I have been looking into recently is <a href="http://redis.io">Redis</a>. It&rsquo;s a key
value store which lets you hold some simple data structures. It also has an
excellent publish/subscribe model which allows messages to be broadcast to
interested clients.</p>

<p>After using this to store some configuration information for some tests to
great success I thought about using <a href="http://redis.io">Redis</a> to provide an interface into the
inner workings of my build light. By holding the desired state of the light in
<a href="http://redis.io">Redis</a> all I would need is to signal that a change had been made and all
would be well.</p>

<p>Rather than starting from scratch I chose to extend the existing example code
as it was already working well. The work I needed to do involved automating the
interaction with the UI, a task I was already familiar with and to do it within
the application itself, a breeze. Working this way also provided full visibility
into what settings were being sent to the light.</p>

<p>The changes I needed to make were:</p>

<ul>
<li>Opening a connection to the light on startup</li>
<li>Ensuring that the light&rsquo;s state on startup matched the state stored in <a href="http://redis.io">Redis</a></li>
<li>Applying styling to the On/Off/Flash lights to better indicate the current state</li>
<li>Listening to a channel on <a href="http://redis.io">Redis</a> for changes to the light state</li>
<li>Updating the light state as applicable</li>
</ul>


<p>I decided to leave the buzzer and switch control as an exercise for another day
as these were not essential to my plans (and the buzzer would likely annoy me).</p>

<p>I decided to use a <a href="http://redis.io">Redis</a> hash (a Dictionary) to store information about the
desired state of the light. In <a href="http://redis.io">Redis</a>, hashes can have individual fields
changed making it fairly easy to work with. I chose to set up the following
fields for each colour light:</p>

<ul>
<li><code>state</code> with <code>0</code> representing off, <code>1</code> on, and <code>2</code> flashing</li>
<li><code>power</code> representing the power level or intensity of the light</li>
<li><code>onduty</code> specifying a time interval for the light to be on when flashing</li>
<li><code>offduty</code> specifying a time interval for the light to be off when flashing</li>
<li><code>offset</code> specifying an offset when flashing so that the flashing of lights
could be synchronised (e.g. flashing between red and green)</li>
</ul>


<p>These all corresponded to appropriate controls in the example application.</p>

<p>The code for the solution can be found in my <a href="https://github.com/rhysparry/HIDVIWINCS">HIDVIWINCS</a> repository on
GitHub.</p>

<h2>Getting the build status</h2>

<p>Of course, this was only part of the battle. Fortunately obtaining the status
of the latest build was reasonably straightforward. First, I set up an <code>Enum</code>
to keep track of the light&rsquo;s current colour.</p>

<figure class='code'><figcaption><span>LightColour.cs </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">namespace</span> <span class="nn">ConsoleBuildMonitor</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">public</span> <span class="k">enum</span> <span class="n">LightColour</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="n">Off</span><span class="p">,</span>
</span><span class='line'>    <span class="n">Red</span><span class="p">,</span>
</span><span class='line'>    <span class="n">Yellow</span><span class="p">,</span> <span class="c1">// On my light it is yellow, on others, blue</span>
</span><span class='line'>    <span class="n">Green</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>With this simple task out of the way I could set up individual methods to
update the appropriate hashes in <a href="http://redis.io">Redis</a>. The library I used in the build
monitor was Booksleeve, a slightly older version than the client I used in
<a href="https://github.com/rhysparry/HIDVIWINCS">HIDVIWINCS</a>. Setting the colour of the light was as simple as folows:</p>

<figure class='code'><figcaption><span>Program.cs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">SetLight</span><span class="p">(</span><span class="n">LightColour</span> <span class="n">colour</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="kt">var</span> <span class="n">db</span> <span class="p">=</span> <span class="kt">int</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisDatabase&quot;</span><span class="p">]);</span>
</span><span class='line'>  <span class="k">using</span> <span class="p">(</span>
</span><span class='line'>      <span class="kt">var</span> <span class="n">conn</span> <span class="p">=</span> <span class="k">new</span> <span class="n">RedisConnection</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisHost&quot;</span><span class="p">],</span>
</span><span class='line'>          <span class="kt">int</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisPort&quot;</span><span class="p">])))</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Hashes</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="n">db</span><span class="p">,</span> <span class="s">&quot;red&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span><span class="n">color</span> <span class="p">==</span> <span class="n">LightColour</span><span class="p">.</span><span class="n">Red</span> <span class="p">?</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">1</span> <span class="p">:</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">0</span> <span class="p">});</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Hashes</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="n">db</span><span class="p">,</span> <span class="s">&quot;blueyellow&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span><span class="n">color</span> <span class="p">==</span> <span class="n">LightColour</span><span class="p">.</span><span class="n">Yellow</span> <span class="p">?</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">1</span> <span class="p">:</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">0</span> <span class="p">});</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Hashes</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="n">db</span><span class="p">,</span> <span class="s">&quot;green&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span><span class="n">color</span> <span class="p">==</span> <span class="n">LightColour</span><span class="p">.</span><span class="n">Green</span> <span class="p">?</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">1</span> <span class="p">:</span> <span class="p">(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">0</span> <span class="p">});</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Publish</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisUpdateChannel&quot;</span><span class="p">],</span> <span class="s">&quot;1&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="n">lightColour</span> <span class="p">=</span> <span class="n">colour</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then to make the light flash I simply needed to make sure that the state was
set appropriate for the current light.</p>

<figure class='code'><figcaption><span>Program.cs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">Flash</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="kt">var</span> <span class="n">db</span> <span class="p">=</span> <span class="kt">int</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisDatabase&quot;</span><span class="p">]);</span>
</span><span class='line'>  <span class="k">using</span> <span class="p">(</span>
</span><span class='line'>      <span class="kt">var</span> <span class="n">conn</span> <span class="p">=</span> <span class="k">new</span> <span class="n">RedisConnection</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisHost&quot;</span><span class="p">],</span>
</span><span class='line'>          <span class="kt">int</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisPort&quot;</span><span class="p">])))</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Open</span><span class="p">();</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Hashes</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="n">db</span><span class="p">,</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="n">lightColour</span> <span class="p">==</span> <span class="n">LightColour</span><span class="p">.</span><span class="n">Red</span> <span class="p">?</span> <span class="s">&quot;red&quot;</span> <span class="p">:</span> <span class="k">this</span><span class="p">.</span><span class="n">lightColor</span> <span class="p">==</span> <span class="n">LightColour</span><span class="p">.</span><span class="n">Green</span> <span class="p">?</span> <span class="s">&quot;green&quot;</span> <span class="p">:</span> <span class="s">&quot;blueyellow&quot;</span><span class="p">,</span>
</span><span class='line'>        <span class="s">&quot;state&quot;</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{(</span><span class="kt">byte</span><span class="p">)</span> <span class="m">2</span><span class="p">});</span>
</span><span class='line'>    <span class="n">conn</span><span class="p">.</span><span class="n">Publish</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;RedisUpdateChannel&quot;</span><span class="p">],</span> <span class="s">&quot;1&quot;</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It is worth noting that the message sent on the update channel doesn&rsquo;t actually
matter at this point in time as it is simple the receipt of the message that
triggers an update to the light&rsquo;s status.</p>

<p>Finally the code required to check the build status is reasonably straightforward:</p>

<figure class='code'><figcaption><span>Program.cs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">ExecuteLoop</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="kt">var</span> <span class="n">buildStatus</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Dictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="n">BuildStatus</span><span class="p">&gt;();</span>
</span><span class='line'>  <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">collection</span> <span class="p">=</span> <span class="k">new</span> <span class="n">TfsTeamProjectCollection</span><span class="p">(</span><span class="k">new</span> <span class="n">Uri</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;TfsProjectCollectionUrl&quot;</span><span class="p">])))</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="n">collection</span><span class="p">.</span><span class="n">Authenticate</span><span class="p">();</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">bs</span> <span class="p">=</span> <span class="n">collection</span><span class="p">.</span><span class="n">GetService</span><span class="p">&lt;</span><span class="n">IBuildServer</span><span class="p">&gt;();</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">re</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Regex</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;BuildPattern&quot;</span><span class="p">]);</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">ls</span> <span class="p">=</span>
</span><span class='line'>        <span class="n">bs</span><span class="p">.</span><span class="n">QueryBuildDefinitions</span><span class="p">(</span><span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;TfsProject&quot;</span><span class="p">])</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Where</span><span class="p">(</span><span class="n">d</span> <span class="p">=&gt;</span> <span class="n">re</span><span class="p">.</span><span class="n">IsMatch</span><span class="p">(</span><span class="n">d</span><span class="p">.</span><span class="n">Name</span><span class="p">)).</span><span class="n">ToList</span><span class="p">();</span>
</span><span class='line'>    <span class="k">do</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>      <span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">b</span> <span class="k">in</span> <span class="n">ls</span><span class="p">)</span>
</span><span class='line'>      <span class="p">{</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">latestBuild</span> <span class="p">=</span> <span class="n">bs</span><span class="p">.</span><span class="n">QueryBuilds</span><span class="p">(</span><span class="n">b</span><span class="p">).</span><span class="n">OrderBy</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span> <span class="n">x</span><span class="p">.</span><span class="n">StartTime</span><span class="p">).</span><span class="n">LastOrDefault</span><span class="p">();</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">latestBuild</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="k">continue</span><span class="p">;</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(!</span><span class="n">buildStatus</span><span class="p">.</span><span class="n">ContainsKey</span><span class="p">(</span><span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span> <span class="p">||</span> <span class="n">buildStatus</span><span class="p">[</span><span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">]</span> <span class="p">!=</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">Status</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>          <span class="k">switch</span> <span class="p">(</span><span class="n">latestBuild</span><span class="p">.</span><span class="n">Status</span><span class="p">)</span>
</span><span class='line'>          <span class="p">{</span>
</span><span class='line'>            <span class="k">case</span> <span class="n">BuildStatus</span><span class="p">.</span><span class="n">Failed</span><span class="p">:</span>
</span><span class='line'>              <span class="n">SetLight</span><span class="p">(</span><span class="n">LightColour</span><span class="p">.</span><span class="n">Red</span><span class="p">);</span>
</span><span class='line'>              <span class="n">Log</span><span class="p">.</span><span class="n">Error</span><span class="p">(</span><span class="s">&quot;Build {Build} Failed ({RequestedFor}) - {BuildId}&quot;</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span>
</span><span class='line'>                <span class="n">latestBuild</span><span class="p">.</span><span class="n">RequestedFor</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">BuildNumber</span><span class="p">);</span>
</span><span class='line'>              <span class="k">break</span><span class="p">;</span>
</span><span class='line'>            <span class="k">case</span> <span class="n">BuildStatus</span><span class="p">.</span><span class="n">PartiallySucceeded</span><span class="p">:</span>
</span><span class='line'>              <span class="n">SetLight</span><span class="p">(</span><span class="n">LightColour</span><span class="p">.</span><span class="n">Yellow</span><span class="p">);</span>
</span><span class='line'>              <span class="n">Log</span><span class="p">.</span><span class="n">Warning</span><span class="p">(</span><span class="s">&quot;Build {Build} Partially Succeeded ({RequestedFor}) - {BuildId}&quot;</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span>
</span><span class='line'>                <span class="n">latestBuild</span><span class="p">.</span><span class="n">RequestedFor</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">BuildNumber</span><span class="p">);</span>
</span><span class='line'>              <span class="k">break</span><span class="p">;</span>
</span><span class='line'>            <span class="k">case</span> <span class="n">BuildStatus</span><span class="p">.</span><span class="n">InProgress</span><span class="p">:</span>
</span><span class='line'>              <span class="n">Flash</span><span class="p">();</span>
</span><span class='line'>              <span class="n">Log</span><span class="p">.</span><span class="n">Information</span><span class="p">(</span><span class="s">&quot;Build {Build} In Progress ({RequestedFor}) - {BuildId}&quot;</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span>
</span><span class='line'>                <span class="n">latestBuild</span><span class="p">.</span><span class="n">RequestedFor</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">BuildNumber</span><span class="p">);</span>
</span><span class='line'>              <span class="k">break</span><span class="p">;</span>
</span><span class='line'>            <span class="k">case</span> <span class="n">BuildStatus</span><span class="p">.</span><span class="n">Succeeded</span><span class="p">:</span>
</span><span class='line'>              <span class="n">SetLight</span><span class="p">(</span><span class="n">LightColour</span><span class="p">.</span><span class="n">Green</span><span class="p">);</span>
</span><span class='line'>              <span class="n">Log</span><span class="p">.</span><span class="n">Information</span><span class="p">(</span><span class="s">&quot;Build {Build} {Status} ({RequestedFor}) - {BuildId}&quot;</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span>
</span><span class='line'>                <span class="n">latestBuild</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">RequestedFor</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">BuildNumber</span><span class="p">);</span>
</span><span class='line'>              <span class="k">break</span><span class="p">;</span>
</span><span class='line'>            <span class="k">default</span><span class="p">:</span>
</span><span class='line'>              <span class="n">Log</span><span class="p">.</span><span class="n">Information</span><span class="p">(</span><span class="s">&quot;Build {Build} {Status} ({RequestedFor}) - {BuildId}&quot;</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span>
</span><span class='line'>                <span class="n">latestBuild</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">RequestedFor</span><span class="p">,</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">BuildNumber</span><span class="p">);</span>
</span><span class='line'>              <span class="k">break</span><span class="p">;</span>
</span><span class='line'>          <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>          <span class="n">buildStatus</span><span class="p">[</span><span class="n">b</span><span class="p">.</span><span class="n">Name</span><span class="p">]</span> <span class="p">=</span> <span class="n">latestBuild</span><span class="p">.</span><span class="n">Status</span><span class="p">;</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>      <span class="n">Task</span><span class="p">.</span><span class="n">Delay</span><span class="p">(</span><span class="m">5000</span><span class="p">,</span> <span class="n">_cancellationToken</span><span class="p">).</span><span class="n">Wait</span><span class="p">(</span><span class="n">_cancellationToken</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span> <span class="k">while</span> <span class="p">(!</span><span class="n">_cancellationToken</span><span class="p">.</span><span class="n">IsCancellationRequested</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The code required to integrate the light to the build monitor was actually the
simplest bit of code in the whole thing. Indeed I haven&rsquo;t shown the most complex
part of the code because it still needs work, but it handles restarting the loop
if it fails and shutting the whole thing down cleanly.</p>

<p>Importantly it means that the monitoring tools are well separated from the
actual control of the light. They no longer need to even exist on the same
computer. Indeed during my initial testing I had <a href="http://redis.io">Redis</a> hosted on one computer,
the light on another and I was using a <a href="http://redis.io">Redis</a> client on a third.</p>

<p>Photos and videos of the build light in action!</p>


<p><section class="flickr-set"><figure class="flickr-thumbnail" style="width: 240px;"><a href="https://live.staticflickr.com/3675/13577769995_cde766a02b_z.jpg" class="fancybox" data-title-id="flickr-photo-13577769995" data-media="photo" rel="flickr-set-72157643300507474"><img src="https://live.staticflickr.com/3675/13577769995_cde766a02b_m.jpg" title="Build Succeeded" style="width: 240px; height: 180px;"/></a><figcaption id="flickr-photo-13577769995"><h1><a class="flickr-link" href="https://www.flickr.com/photos/i-think22/13577769995">Build Succeeded</a> by i-think Twenty-Two</h1><div class="description">Both the build and the tests have passed. This makes me happy. :-D</div></figcaption></figure><figure class="flickr-thumbnail" style="width: 240px;"><a href="https://live.staticflickr.com/7276/13578151994_821022658a_z.jpg" class="fancybox" data-title-id="flickr-photo-13578151994" data-media="photo" rel="flickr-set-72157643300507474"><img src="https://live.staticflickr.com/7276/13578151994_821022658a_m.jpg" title="Partially Succeeded" style="width: 240px; height: 180px;"/></a><figcaption id="flickr-photo-13578151994"><h1><a class="flickr-link" href="https://www.flickr.com/photos/i-think22/13578151994">Partially Succeeded</a> by i-think Twenty-Two</h1><div class="description">This is what the build light looks like when tests fail.</div></figcaption></figure><figure class="flickr-thumbnail" style="width: 240px;"><a href="https://live.staticflickr.com/7424/13578154184_d3697ee2b4_z.jpg" class="fancybox" data-title-id="flickr-photo-13578154184" data-media="photo" rel="flickr-set-72157643300507474"><img src="https://live.staticflickr.com/7424/13578154184_d3697ee2b4_m.jpg" title="Build Failure" style="width: 240px; height: 180px;"/></a><figcaption id="flickr-photo-13578154184"><h1><a class="flickr-link" href="https://www.flickr.com/photos/i-think22/13578154184">Build Failure</a> by i-think Twenty-Two</h1><div class="description">Here the code doesn&rsquo;t even compile. This makes me sad. :-(</div></figcaption></figure><figure class="flickr-thumbnail video-preview" style="width: 240px;"><a href="https://www.flickr.com/photos/i-think22/13578271464" class="fancybox" data-title-id="flickr-photo-13578271464" data-media="video" data-content-id="#flickr-video-content-13578271464" rel="flickr-set-72157643300507474"><img src="https://live.staticflickr.com/7032/13578271464_57eb405ef2_m.jpg" title="Building..." style="width: 240px; height: 135px;"/><span class="video-icon">&#x25b6;</span></a><figcaption id="flickr-photo-13578271464"><h1><a class="flickr-link" href="https://www.flickr.com/photos/i-think22/13578271464">Building&hellip;</a> by i-think Twenty-Two</h1><div class="description">While the build server is building the latest check-in and running tests the build light flashes.</div></figcaption></figure><div style='display:none'><div id='flickr-video-content-13578271464'><object type="application/x-shockwave-flash" width="640" height="360" data="http://www.flickr.com/apps/video/stewart.swf?v=109786" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&amp;photo_secret=57eb405ef2&amp;photo_id=13578271464"/><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=109786"/><param name="bgcolor" value="#000000"/><param name="allowFullScreen" value="true"/><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=109786" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&amp;photo_secret=57eb405ef2&amp;photo_id=13578271464" width="640" height="360"/></object></div></div><figure class="flickr-thumbnail" style="width: 240px;"><a href="https://live.staticflickr.com/3708/13613804804_cc0e58132a_z.jpg" class="fancybox" data-title-id="flickr-photo-13613804804" data-media="photo" rel="flickr-set-72157643300507474"><img src="https://live.staticflickr.com/3708/13613804804_cc0e58132a_m.jpg" title="HDIWINCS" style="width: 240px; height: 92px;"/></a><figcaption id="flickr-photo-13613804804"><h1><a class="flickr-link" href="https://www.flickr.com/photos/i-think22/13613804804">HDIWINCS</a> by i-think Twenty-Two</h1><div class="description">The super snazzy UI</div></figcaption></figure></section></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Boosting productivity with F# discriminated unions and pattern matching]]></title>
    <link href="http://i-think22.net/archives/2014/01/24/boosting-productivity-with-f-number-discriminated-unions-and-pattern-matching/"/>
    <updated>2014-01-24T09:00:00+10:00</updated>
    <id>http://i-think22.net/archives/2014/01/24/boosting-productivity-with-f-number-discriminated-unions-and-pattern-matching</id>
    <content type="html"><![CDATA[<p>So I&rsquo;ve been working on some on some <a href="http://www.projecteuler.net/">Project Euler</a> problems to make sure I&rsquo;m
as ready as possible for some upcoming job interviews. If you aren&rsquo;t already aware
of <a href="http://www.projecteuler.net/">Project Euler</a> go and check it out.</p>

<p>I have been using a mixture of C# and <a href="http://j.mp/fsharp">F#</a> to solve the problems. I have been wanting
to expand my <a href="http://j.mp/fsharp">F#</a> knowledge for some time now, so my strategy so far is to re-implement
re-usable components that I had written in C# into <a href="http://j.mp/fsharp">F#</a>. Because I&rsquo;m a huge fan of
recursion many of these re-implementations were extremely straightforward as I was
already following a common functional pattern.</p>

<p>Eventually I came across <a href="http://projecteuler.net/problem=57">Problem 57</a>. The problem involves evalutating an expanding
formula into the appropriate fractional result. Nb: Code found in this post provides a
partial solution to this problem.</p>

<p>These are the first four iterations as described in the problem:</p>

<pre><code>1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
</code></pre>

<p>So I am essentially working with a tree of operations. Each iteration can be based on
the one preceding it. The problem requires that each of these is able to be reduced to
a single fraction. Therefore the pieces that I need are:</p>

<ul>
<li>A data structure to hold the expression</li>
<li>A function to reduce the expression to a fraction</li>
<li>A function to determine the next iteration of the expression</li>
</ul>


<p>I won&rsquo;t be looking at the last of these three pieces here (I&rsquo;ll leave that as an exercise
for you).</p>

<p>Also, it would be kind of nice if I had a function to show me a string representation of
my expression so that I could easily check I&rsquo;m on the right track (because that is
generally easier than trying to understand an object graph plus I already had a string
representation to target).</p>

<p>So when it came to picking the data structure I was reminded of <a href="http://msdn.microsoft.com/en-us/library/dd233226.aspx">discriminated unions</a> in
<a href="http://j.mp/fsharp">F#</a>. These allowed you to define different but related structures. The relationship
could then be used to enable pattern matching to deal with a specific case.</p>

<p>The expressions that I needed to support were quite simple, add, divide and of course a
constant value. In this case I&rsquo;ll throw caution to the wind and use an integer.</p>

<figure class='code'><figcaption><span>Problem57.fs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='fsharp'><span class='line'><span class="k">type</span> <span class="nc">Expression</span> <span class="o">=</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Constant</span> <span class="k">of</span> <span class="n">int</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Add</span> <span class="k">of</span> <span class="n">Expression</span> <span class="o">*</span> <span class="n">Expression</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span> <span class="k">of</span> <span class="n">Expression</span> <span class="o">*</span> <span class="n">Expression</span>
</span></code></pre></td></tr></table></div></figure>


<p></p>

<p>Here my constant values are stored in a <code>Constant</code> object which is itself an expression.
<code>Add</code> and <code>Divide</code> are both comprised of a pair of expressions.
<code>Expression</code> is a recursive type and can either have constant leaf nodes of branches
which perform an operation.</p>

<p>I could have made a simplification as in the values I was constructing the left operand
of <code>Add</code> and <code>Divide</code> would always be a constant, but this more flexible structure generally
felt better.</p>

<p>I could now easily construct the first iteration like so:</p>

<figure class='code'><figcaption><span>Problem57.fs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='fsharp'><span class='line'><span class="k">let</span> <span class="nv">root</span> <span class="o">=</span> <span class="n">Add</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="mi">1</span><span class="o">),</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="mi">1</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="mi">2</span><span class="o">)))</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is rather verbose and difficult to read and is only going to become more difficult as
we increment the value. So the next thing I&rsquo;m going to do is create a function which will
create a string version of the expression so that I can review it by hand.</p>

<p>Now when I am thinking about the string function (I&rsquo;m going to call it <code>stringify</code>)
I can think of the various types:</p>

<ul>
<li><code>Constant</code> will just be a <code>ToString()</code> call on the value.</li>
<li><code>Add</code> and <code>Divide</code> will be recursive and call the <code>stringify</code> function of both expressions
and separate the results with the appropriate operator.</li>
<li>Also we want to surround the denominator in brackets if the denominator is not just
a constant.</li>
</ul>


<p>Putting these into practice becomes extremely straightforward (ignoring that I haven&rsquo;t used
a <code>StringBuilder</code>).</p>

<figure class='code'><figcaption><span>Problem57.fs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='fsharp'><span class='line'><span class="k">let</span> <span class="nv">rec</span> <span class="n">stringify</span> <span class="n">v</span> <span class="o">=</span>
</span><span class='line'>  <span class="k">match</span> <span class="n">v</span> <span class="k">with</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Constant</span><span class="o">(</span><span class="n">x</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">x</span><span class="o">.</span><span class="n">ToString</span><span class="bp">()</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Add</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="n">y</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">stringify</span> <span class="n">x</span><span class="o">)</span> <span class="o">+</span> <span class="s">&quot;+&quot;</span> <span class="o">+</span> <span class="o">(</span><span class="n">stringify</span> <span class="n">y</span><span class="o">)</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="n">Constant</span><span class="o">(</span><span class="n">y</span><span class="o">))</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">stringify</span> <span class="n">x</span><span class="o">)</span> <span class="o">+</span> <span class="s">&quot;/&quot;</span> <span class="o">+</span> <span class="n">y</span><span class="o">.</span><span class="n">ToString</span><span class="bp">()</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="n">y</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="n">stringify</span> <span class="n">x</span><span class="o">)</span> <span class="o">+</span> <span class="s">&quot;/(&quot;</span> <span class="o">+</span> <span class="o">(</span><span class="n">stringify</span> <span class="n">y</span><span class="o">)</span> <span class="o">+</span> <span class="s">&quot;)&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>What struck me as awesome was the amazing simplicity of this code. Using pattern
matching I was able to easily address my special case for including brackets and
give the other cases in a straightforward manner as well. The <a href="http://j.mp/fsharp">F#</a> compiler
even helped by ensuring that I matched all possible patterns (it uses wizardry
known as type inference to determine that <code>v</code> is an <code>Expression</code>
type).</p>

<p>I could then execute my <code>stringify</code> function on root to check that everything worked
as intended. The delightful part at this point was that it did. The next step was
to reduce one of these expressions down to its smallest possible form. This too
would prove to be trivial. Here&rsquo;s the code I came up with:</p>

<figure class='code'><figcaption><span>Problem57.fs (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='fsharp'><span class='line'><span class="k">let</span> <span class="nv">rec</span> <span class="n">reduce</span> <span class="n">v</span> <span class="o">=</span>
</span><span class='line'>  <span class="k">match</span> <span class="n">v</span> <span class="k">with</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Constant</span><span class="o">(</span><span class="n">c</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">Constant</span><span class="o">(</span><span class="n">c</span><span class="o">)</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Add</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">a</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="n">b</span><span class="o">))</span> <span class="o">-&gt;</span> <span class="n">Constant</span><span class="o">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">)</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">a</span><span class="o">),</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">b</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="n">c</span><span class="o">)))</span> <span class="o">-&gt;</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">a</span> <span class="o">*</span> <span class="n">c</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="n">b</span><span class="o">))</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Add</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">a</span><span class="o">),</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(</span><span class="n">b</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="n">c</span><span class="o">)))</span> <span class="o">-&gt;</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">((</span><span class="n">a</span> <span class="o">*</span> <span class="n">c</span><span class="o">)</span> <span class="o">+</span> <span class="n">b</span><span class="o">),</span> <span class="n">Constant</span><span class="o">(</span><span class="n">c</span><span class="o">))</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Add</span><span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">Add</span><span class="o">(</span><span class="n">reduce</span> <span class="n">a</span><span class="o">,</span> <span class="n">reduce</span> <span class="n">b</span><span class="o">)</span> <span class="o">|&gt;</span> <span class="n">reduce</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span><span class="o">(</span><span class="n">Constant</span><span class="o">(_),</span> <span class="n">Constant</span><span class="o">(_))</span> <span class="o">-&gt;</span> <span class="n">v</span>
</span><span class='line'>  <span class="o">|</span> <span class="n">Divide</span><span class="o">(</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">Divide</span><span class="o">(</span><span class="n">reduce</span> <span class="n">a</span><span class="o">,</span> <span class="n">reduce</span> <span class="n">b</span><span class="o">)</span> <span class="o">|&gt;</span> <span class="n">reduce</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here I looked at the sort of smaller patterns I was dealing with and repeatedly
called reduce until I achieved a desirable pattern. Again, the simplicity of each
pattern and its resulting reduction really drove home the incredible benefit
provided by pattern matching.</p>

<p>Pattern matching is a technique that I really miss when I use languages like C#.
For this reason alone I would really like to see <a href="http://j.mp/fsharp">F#</a> become more widely adopted
so it may be finally possible to use it in projects where we are currently
confined to a single language.</p>

<p>I have written a number of code generating tools over the years, especially
focussing on the generation of SQL from some sort of structure. Looking at how
easily I was able to solve the problem above using <a href="http://j.mp/fsharp">F#</a> I wish that I had some
of these techniques at my disposal then.</p>

<p>Finally, I made a slight modification in the code above which will prevent it
from being used verbatim to solve the <a href="http://www.projecteuler.net/">Euler</a> problem.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Paste on the console]]></title>
    <link href="http://i-think22.net/archives/2013/04/09/paste-on-the-console/"/>
    <updated>2013-04-09T19:14:00+10:00</updated>
    <id>http://i-think22.net/archives/2013/04/09/paste-on-the-console</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve already alluded to the fact that I love working on the console and in
Windows, PowerShell is my console of choice. I get to throw all sort of things
through it&rsquo;s object based pipeline and play with them in fun and exciting ways.</p>

<p>I also have added to my path a large number of the <a href="http://gnuwin32.sourceforge.net/">GnuWin32</a> tools which
are sometimes better at dealing with raw text like <code>sed</code> and occasionally
<code>grep</code> instead of PowerShell&rsquo;s <code>Select-String</code>. By having these utilities in my
path I can better deal with being stuck in pure <code>cmd.exe</code>.</p>

<p>Anyway, one of my favourite utilities is <code>Clip.exe</code>. It comes out of the box in
Windows 7 and presumably Windows Vista. I rolled my own for Windows XP although
I believe that it may be available as part of a resource kit. In case it isn&rsquo;t
immediately obvious, what <code>Clip.exe</code> does is takes whatever is fed to Standard
Input and saves it to the clipboard. Very useful indeed.</p>

<p>The clipboard is a great place for storing some data temporarily and I quite
frequently find that I want to process it in various ways. I have a bunch of
command line utilities that are perfect at this, but I have to save the
contents to a file and pass that file to the utility. That sounds like busy
work. Fortunately the <a href="http://gnuwin32.sourceforge.net/">GnuWin32</a> utilities and PowerShell both read from
standard input. What I need is a tool that does the opposite of <code>Clip.exe</code> and
writes the contents of the clipboard to standard input. What I need is
<code>Paste.exe</code>. So I wrote it.</p>

<div><script src='https://gist.github.com/3615260.js?file=Paste.cs'></script>
<noscript><pre><code>namespace ConsolePaste
{
    using System;
    using System.Linq;
    using System.Threading;
    using System.Windows.Forms;

    public class Paste 
    {
        [STAThread]
        public static void Main(string[] args)
        {
            var raw = args.Contains(&quot;-r&quot;);
            if (Clipboard.ContainsText())
            {
                if (raw)
                {
                    Console.Out.Write(Clipboard.GetText());
                    return;
                }

                foreach (var line in Clipboard.GetText().Split(new [] {&quot;\r\n&quot;, &quot;\n&quot;}, StringSplitOptions.None ))
                {
                    Console.Out.WriteLine(line);
                }
            }
            else if (Clipboard.ContainsFileDropList())
            {
                if (raw)
                {
                    Console.Out.Write(string.Join(Environment.NewLine, Clipboard.GetFileDropList().Cast&lt;string&gt;()));
                    return;
                }

                foreach (var file in Clipboard.GetFileDropList())
                {
                    Console.Out.WriteLine(file);
                }
            }
        }
    }
}
</code></pre></noscript></div>


<p>A simple compile&hellip;</p>

<pre><code>$ csc .\Paste.cs
</code></pre>

<p>And after copying to my Utilities folder (which is in my path) I&rsquo;m good to go.</p>

<p>An added bonus is that I handle files copied in Windows Explorer. These will be
returned as a list of filenames.</p>

<p>By default I add an extra <code>Environment.NewLine</code> and the end of the content as
it tends to make the whole thing neater in the console. If this is causing you
hassles use the <code>-r</code> switch which will paste the contents in their raw form.</p>

<h2>Paste in Action</h2>

<p>I use paste to quickly view the clipboard contents:</p>

<pre><code>$ paste
</code></pre>

<p>To strip formatting in the clipboard:</p>

<pre><code>$ paste | clip
</code></pre>

<p>To filter clipboard contents:</p>

<pre><code>$ paste | grep -i batman
</code></pre>

<p>As subjects of a PowerShell ForEach-Object:</p>

<pre><code>$ paste | % { $_.Length }
</code></pre>

<p>If you find a common pattern, share it in the comments below.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Apple TV and Automatic Downloads]]></title>
    <link href="http://i-think22.net/archives/2013/04/08/apple-tv-and-automatic-downloads/"/>
    <updated>2013-04-08T18:03:00+10:00</updated>
    <id>http://i-think22.net/archives/2013/04/08/apple-tv-and-automatic-downloads</id>
    <content type="html"><![CDATA[<p>Lately there has been some peculiar activity on the iTunes Australia store.
Some of my favourite shows are becoming available only a day after being aired
in either the USA or Britain. For the record, these shows are:</p>

<ul>
<li>Doctor Who</li>
<li>Game of Thrones</li>
<li>Mad Men</li>
</ul>


<p>Both <em>Game of Thrones</em> and <em>Mad Men</em> have season passes available for just over
$30. Oh, and that&rsquo;s HD. A quick look and you are looking at about $50 for a
Blu-Ray of season 2.</p>

<p>So suddenly we have an influx of shows that are timely and cheap (relatively
speaking). Sure, they encumbered with the iTunes DRM and you have to use iTunes
but I like to think that this is a good sign. It seems like Australia has
become a test bed for online distribution.</p>

<p>Aside from the DRM (and the fact that you are restricted to Apple devices)
there is one glaring omission, communication. The scheduling of when shows will
be available is largely hidden until they are released. So right now I&rsquo;m going
on faith that the prompt deliveries will continue for the remainder of the
season but obviously have no guarantee that they will. Even if some insight was
given into when the next episode will be released that would be an excellent
start.</p>

<p>The next issue is the overall experience. I have a setup with a Mac Mini and an
Apple TV connected to my television. It&rsquo;s a shame that I kind of need both. The
Mac Mini has been delegated as the storage server and it can hold all my iTunes
downloads. However the full screen experience is somewhat lacking and generally
requires fiddling around with a trackpad and keyboard. The Apple TV on the
other hand delivers a fantastic (if somewhat limited) full screen experience as
you would expect. However there is no way to <em>reliably</em> cache your shows on it
so as to avoid disturbances due to issues involved in communicating with
Apple&rsquo;s servers. The device itself has a substantial buffer, but to buffer an
entire show generally involves starting it, hitting pause and waiting for it to
download completely without looking at anything else in the meantime.</p>

<p>So this is where the Mac Mini comes into its own. I can open up iTunes and
download the shows I have purchased and share them with my Apple TV through the
Home Sharing feature. Unfortunately the Apple TV interface for Home Sharing
isn&rsquo;t as slick as the regular TV interface, but once you get going it doesn&rsquo;t
really matter. The Apple TV also serves as a great way to browse the iTunes
store and purchasing items is <em>really</em> easy.</p>

<p>And with this ease comes a small snag. It appears (and has been confirmed by
a support request with Apple) that when you purchase a season pass on an Apple
TV you cannot set up iTunes to automatically download new episodes as they
become available. You <em>can</em> still download these episodes manually though, so
the limitation won&rsquo;t stop you from downloading your purchase shows, but it does
make it just a little bit harder.</p>

<p>The workaround of course is to perform the actual purchase via iTunes on the
machine that you want to download the episodes to. So unfortunately for the
moment the keyboard and trackpad attached to my Mac Mini are there to stay.</p>

<p>Fortunately iTunes does send an email when a new episode of a show you&rsquo;ve
subscribed to is released, so this acts as a prompt to kick off the manual
download.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mercurial: Configure a Graphical Diff Tool]]></title>
    <link href="http://i-think22.net/archives/2013/04/07/mercurial-configure-a-graphical-diff-tool/"/>
    <updated>2013-04-07T09:16:00+10:00</updated>
    <id>http://i-think22.net/archives/2013/04/07/mercurial-configure-a-graphical-diff-tool</id>
    <content type="html"><![CDATA[<p>I love the command line. Very rarely do I ever not have a console window open.
Consequently I tend to do all my source control activities from the command
line. However I&rsquo;m not a command line bigot. I know when the console has reached
its limit and I have to resort to a more graphical tool. With <a href="http://mercurial.selenic.com">Mercurial</a> this
hits hard when doing complicated diffs and of course the dreaded three way
merge. Fortunately Mercurial has been configured out of the box to recognise my
<a href="http://www.scootersoftware.com">merge tool of choice</a> so when Mercurial finds a conflict during a merge it
can show me a GUI based tool that will help me get on with my work.</p>

<p>But what about the times when I want to review the changes that I&rsquo;ve made? This
is especially important when I&rsquo;m about to push changes and inflict my work on
other developers. It&rsquo;s also a great opportunity to spot issues which may result
in broken builds.</p>

<p>For small changes I still stick with the console and run:</p>

<pre><code>$ hg diff
</code></pre>

<p>This gives me a fairly simple diff of my changes. I can make this even better
by enabling the <a href="http://mercurial.selenic.com/wiki/ColorExtension">color extension</a> which will spruce up my command line
output by adding colour to a myriad of different commands, but importantly for
this case, diff. By marking insertions in green and deletions in red I can get
a very quick overview of the changes I have made. To enable this extension I
just add the following to my <code>mercurial.ini</code> file.</p>

<figure class='code'><figcaption><span>mercurial.ini (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='ini'><span class='line'><span class="k">[extensions]</span>
</span><span class='line'><span class="na">color</span> <span class="o">=</span>
</span></code></pre></td></tr></table></div></figure>


<p>However a basic diff is somewhat limited. It generally won&rsquo;t take the filetype
into consideration and a small change to a big line can be difficult to spot.
Fortunately there are a number of great diff tools out there. The one I use is
<a href="http://www.scootersoftware.com">Beyond Compare 3</a> (you&rsquo;ll need the Professional version if you want its
excellent three way merge feature). It isn&rsquo;t free, but for a tool I use <em>every</em>
day I feel that it has been worth it many times over.</p>

<p>These instructions should work with any diff tool capable of understanding
command line parameters and able to compare two folders.</p>

<p>To integrate our graphical diff tool with Mercurial we&rsquo;ll turn to another
extension, <a href="http://mercurial.selenic.com/wiki/ExtdiffExtension">Extdiff</a>. This extension helps you use a graphical diff tool to
compare two different changesets (or a changeset with the current work in
progress). Importantly it also makes sure that if you make any changes to the
working copy they will be propagated back when you are done. So if your diff
tool is good at moving changes from one file to another and editing files in
place you can very easily clean up your changes. Enabling the extension is
straightforward.</p>

<figure class='code'><figcaption><span>mercurial.ini (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='ini'><span class='line'><span class="k">[extensions]</span>
</span><span class='line'><span class="na">color</span> <span class="o">=</span>
</span><span class='line'><span class="na">extdiff</span> <span class="o">=</span>
</span></code></pre></td></tr></table></div></figure>


<p>This has however only enabled the <code>extdiff</code> command in Mercurial. If we want
to configure our diff tool of choice we have to make one final change.</p>

<figure class='code'><figcaption><span>mercurial.ini (excerpt) </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ini'><span class='line'><span class="k">[extensions]</span>
</span><span class='line'><span class="na">color</span> <span class="o">=</span>
</span><span class='line'><span class="na">extdiff</span> <span class="o">=</span>
</span><span class='line'>
</span><span class='line'><span class="k">[extdiff]</span>
</span><span class='line'><span class="na">cmd.vdiff</span> <span class="o">=</span> <span class="s">C:\Program Files (x86)\Beyond Compare 3\BCompare.exe</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here I&rsquo;ve added the <code>extdiff</code> section and created a new command <code>vdiff</code> which
will use Beyond Compare as my diff tool. So now to use Beyond Compare to view
my changes I just need to run the following:</p>

<pre><code>$ hg vdiff
</code></pre>

<p>I can create as many of these commands as I like if I want to enable different
diff tools. It is also possible to parse arguments to the diff tool. For
instructions check out the <a href="http://mercurial.selenic.com/wiki/ExtdiffExtension">Extdiff documentation page</a> on the Mercurial
wiki.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mercurial: Taming Multiple Heads with Bookmarks]]></title>
    <link href="http://i-think22.net/archives/2013/04/03/mercurial-taming-multiple-heads-with-bookmarks/"/>
    <updated>2013-04-03T19:03:00+10:00</updated>
    <id>http://i-think22.net/archives/2013/04/03/mercurial-taming-multiple-heads-with-bookmarks</id>
    <content type="html"><![CDATA[<p>I&rsquo;m a huge fan of version control. I have fond memories of first learning
Subversion and setting up a source control server. I also remember the pain
involved every time I wanted to create a new repository. Sure, I had a good
process and it wasn&rsquo;t <em>that</em> bad, but it was still something. For a long time
I really thought that nothing could be better. Then I was introduced to this:</p>

<pre><code>$ hg init .
</code></pre>

<p>That one line changed my life forever. Pretty soon I had just about everything
I was actively working on managed by source control. It truly was a golden age.
At this time I was generally working inside my own repositories sheltered from
the rest of the world. Even for a single user <a href="http://mercurial.selenic.com/">Mercurial</a> came to my aid by
protecting me from myself. Coupled with an <a href="http://www.scootersoftware.com/">awesome diff tool</a> I felt
unstoppable. I was able to better break down problems and experiment more
knowing that I could easily get back to a known good state and easily examine
exactly what I&rsquo;d just changed.</p>

<p>Of course as these things go it was only a matter of time before I was able to
really dive into a repository that was actively maintained by other users. Here
I was finally able to see if Mercurial was worthy of all the hype that I had
read having consumed plenty of documentation (and forgetting all the things I
wasn&rsquo;t using on a regular basis).</p>

<p>And I was generally happy. But one thing continued to niggle at me. The number
of &ldquo;Merge&rdquo; commits seemed extremely unnecessary. So I looked into the
<a href="http://mercurial.selenic.com/wiki/RebaseExtension">rebase extension</a>. Now I was able to graft my changes at the end of
everyone else&rsquo;s history. Most of my changes were fairly isolated and there were
rarely any conflicts (and when there were easily resolved with a simple <a href="http://www.scootersoftware.com/">three
way merge</a>).</p>

<p>And so again, life was good. But as time moved on I became wary of all this
rewriting of history. One instance of sending duplicate changesets to the
&lsquo;master&rsquo; repository will quickly identify how easy it is to do the wrong thing.
Wasn&rsquo;t Mercurial supposed to save me from all this? I lost faith and began to
look elsewhere, learnt the ins and outs of <a href="http://git-scm.com/">Git</a> and really came to like
the light weight branching it offered. This seemed to be perfect for what I
wanted. I could have feature branches on bits of work that I might do and then
merge them into the trunk when I&rsquo;m done. Suddenly the merges didn&rsquo;t seem so
bad as each served a specific purpose of bringing a feature to the main line.</p>

<p>So I looked into <a href="http://mercurial.selenic.com/">Mercurial</a> branches. Branches in Mercurial aren&rsquo;t as
lightweight as in <a href="http://git-scm.com/">Git</a>. And even when they are closed traces of them seem
to last forever. That might be fine for some cases, but for the work I was
doing I didn&rsquo;t want to worry about coming up with unique names for my branches
<em>and</em> have those choices persisted for all eternity.</p>

<p>So I went for a search to find how other <a href="http://mercurial.selenic.com/">Mercurial</a> users tackle this
apparent shortfall. The answer was to maintain multiple heads <em>and</em> to use
bookmarks to manage each head.</p>

<p>When I was first learning about <a href="http://mercurial.selenic.com/">Mercurial</a> I suppose I gave myself the
impression that multiple heads were bad and whenever there was more than one
head you <em>need</em> to merge. This is of course completely wrong.</p>

<p><a href="http://mercurial.selenic.com/">Mercurial</a> quite happily chugs along with multiple heads and indeed it is
fairly fundamental to how it works. When it comes time to <em>push</em> your changes
you might run into issues, but even here we can work around them.</p>

<h2>How I use bookmarks to manage multiple heads</h2>

<p>When you have multiple heads to work with it becomes evident fairly quickly
that you will need to have a good way to switch between these heads. This
is where <a href="http://mercurial.selenic.com/wiki/Bookmarks">bookmarks</a> come into play. So let&rsquo;s look at an example of how this
works:</p>

<p>I&rsquo;ve opened up my trusty console window and have updated my repository.</p>

<pre><code>$ hg pull -u
</code></pre>

<p>I&rsquo;ve used the <code>-u</code> switch here to update the repository at the same time as
pulling the latest changes. I don&rsquo;t have any bookmarks set yet so I&rsquo;m going
to create one now so that I can easily track the &lsquo;tip&rsquo; from the &lsquo;master&rsquo;
repository. I&rsquo;m going to call it &lsquo;master&rsquo; because that&rsquo;s easy to remember.</p>

<pre><code>$ hg book master
</code></pre>

<p>I&rsquo;ve shortened the <code>bookmarks</code> command to <code>book</code> because <code>book</code> is easier to
type and still gets the point across without being too cryptic. Now I&rsquo;m going
to start working on a fairly major change. I want to be able to commit often as
I know that I will get things into a partially working state frequently but
don&rsquo;t want to share my changes until I&rsquo;m completely done. So I&rsquo;ll create a new
bookmark to keep track of these changes:</p>

<pre><code>$ hg book batman
</code></pre>

<p>So now I have two bookmarks that both point to the same changeset. Importantly
the <em>active</em> bookmark is <code>batman</code> because it&rsquo;s the last bookmark I used. You
can only have one active bookmark at a time. To see the bookmarks that I have I
can just run the <code>book</code> command with no parameters.</p>

<pre><code>$ hg book
 * batman               34:7f6c4f9e45fb
   master               34:7f6c4f9e45fb
</code></pre>

<p>Looks good. The <code>*</code> indicates which bookmark is currently active. Note that
they both point to the same changeset. Now I&rsquo;m going to make some changes and
commit:</p>

<pre><code>$ hg commit -m "Improved grapple."
</code></pre>

<p>Now if I look at my bookmarks I&rsquo;ll see that <code>batman</code> has moved with my new
changeset and <code>master</code> has stayed put.</p>

<pre><code>$ hg book
 * batman               35:63a4549bc962
   master               34:7f6c4f9e45fb
</code></pre>

<p>This is generally the point where someone might interrupt me with an urgent
change. This time I know it is a simple change and we need to get it into the
<code>master</code> ASAP. I don&rsquo;t want to risk my improved grapple though and this change
is unrelated anyway so I&rsquo;ll start back at the master bookmark.</p>

<pre><code>$ hg update master
1 file updated, 0 files merged, 0 files removed, 0 files unresolved
$ hg book robin
$ hg book
   batman               35:63a4549bc962
   master               34:7f6c4f9e45fb
 * robin                34:7f6c4f9e45fb
</code></pre>

<p>Now I can make my change and commit.</p>

<pre><code>$ hg commit -m "Reduce brightness of Robin costume."
$ hg book
   batman               35:63a4549bc962
   master               34:7f6c4f9e45fb
 * robin                36:9832ab432fec
</code></pre>

<p>Now I can see that the <code>robin</code> bookmark has moved, the <code>batman</code> bookmark
stays in place and the <code>master</code> bookmark still points to the last changeset I
pulled from the master repository. At this point I technically have two heads.</p>

<pre><code>$ hg heads .
changeset:   35:63a4549bc962
bookmark:    batman
user:        Rhys Parry &lt;rhys@example.com&gt;
date:        Wed Apr 3 20:40:12 2013 +1000
summary:     Improved grapple.

changeset:  36:9832ab432fec
bookmark:   robin
tag:        tip
user:       Rhys Parry &lt;rhys@example.com&gt;
date:       Wed Apr 3 20:52:19 2013 +1000
summary:    Reduce brightness of Robin costume.
</code></pre>

<p>Because we have bookmarks for these changesets we can quickly switch between
them. Here you can also see that the <code>robin</code> changeset also is regarded as the
<code>tip</code> of the repository. Because this change is urgent I want to push it to the
master repository ASAP. So first I&rsquo;ll check if there is anything new in the
master repository.</p>

<pre><code>$ hg in
comparing with B:\Batcave
searching for changes
changeset:   37: f33b6a00e172
tag:         tip
user:        Alfred Pennyworth &lt;alfred@example.com&gt;
date:        Wed Apr 3 20:38:19 2013 +1000
summary:     Improve delivery of hot cocoa.
</code></pre>

<p>Here we can see that there has been a change since I started working. If I want
to push this change I&rsquo;ll need to merge my changes. But first I&rsquo;ll make updating
as simple as possible.</p>

<pre><code>$ hg update master
1 file updated, 0 files merged, 0 files removed, 0 files unresolved
$ hg pull -u
</code></pre>

<p>This will pull in Alfred&rsquo;s changes and leave us with three heads. Importantly
when we used <code>hg update master</code> Mercurial knew we were switching to a bookmark
so it set it as the <em>active</em> bookmark. When we pulled in Alfred&rsquo;s changes the
bookmark followed the update so now <code>master</code> is pointing where we were
expecting it to.</p>

<pre><code>$ hg book
   batman               35:63a4549bc962
 * master               37:f33b6a00e172
   robin                36:9832ab432fec
</code></pre>

<p>Now we just need to merge the <code>robin</code> branch into <code>master</code> and we&rsquo;ll be in a
position to start pushing our changes. Again, this is straightforward.</p>

<pre><code>$ hg merge robin
$ hg commit -m "Merge Robin costume improvements."
</code></pre>

<p>This time I can easily come up with a merge message because I know that there
is a common theme to what I am merging. The same would apply if I was merging
one hundred changesets. I can also now think of the merge as a true change and
not just a nasty side effect of my choice of version control system. Finally I
am ready to push my changes to the master repository. Because I don&rsquo;t want the
changes from my <code>batman</code> bookmark going up I&rsquo;ll take a bit more care and do the
following:</p>

<pre><code>$ hg push -r master
</code></pre>

<p>This will push the <code>master</code> bookmark and all its descendants (which now includes
the <code>robin</code> changes as well but <em>not</em> the <code>batman</code> changes). If you want to
preview what changesets you will be sending to the master repository you can
always run the following command first:</p>

<pre><code>$ hg out -r master
</code></pre>

<p>Sometimes you might forget to include the <code>-r</code> flag. If you do Mercurial will
kindly refuse your push and none of your changes will be pushed. By default
Mercurial isn&rsquo;t keen on letting you push extra heads to other repositories.</p>

<p>With this in mind we can feel a little safer knowing that Mercurial will
prevent us from inflicting our unfinished changes on others before their time.
We can of course force these changes if we want:</p>

<pre><code>$ hg push --force -B master -B batman backup
</code></pre>

<p>Here I&rsquo;ve forced these extra heads to be pushed to my own backup repository
so that if my machine fails all my changes, including the bookmarks (which are
not pushed by default).</p>

<p>So that&rsquo;s a peak at one of the ways I use Mercurial on a daily basis. I&rsquo;m sure
there are many improvements to the way I am currently working and I relish the
opportunity to explore more of Mercurial&rsquo;s functionality.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[More thoughts on Google+]]></title>
    <link href="http://i-think22.net/archives/2011/07/08/more-thoughts-on-google-plus/"/>
    <updated>2011-07-08T06:15:23+10:00</updated>
    <id>http://i-think22.net/archives/2011/07/08/more-thoughts-on-google-plus</id>
    <content type="html"><![CDATA[<p>So it seems as though I forgot a couple of points in last night&rsquo;s blog post
(<a href="http://www.i-think22.net/archives/2011/07/07/first-impressions-of-google-plus/">First Impressions of Google+</a>).</p>

<h3>I should be able to sort my circles</h3>

<p>While you can create new circles there doesn&rsquo;t appear to be any way to sort them.
Unfortunately this means that my extreme circles (close friends and fringe) are right next
to each other and that&rsquo;s just not right. However the problem really becomes evident with
the menu list of your streams. Only your first custom circle is shown in the list (when
you have added more than two custom circles). These are also sorted alphabetically after
the predefined circles, which is a little odd, but I can see why it might be the case.</p>

<h3>Preliminary conclusion</h3>

<p>I think that at least in my case, Google+ is more likely to displace Twitter than
Facebook. That said I&rsquo;m not overly active on Facebook, but I find using twitter is a great
way to keep up to date with the people I actually care about and a little industry stuff
as well. I think Google+ is well targeted for that particular purpose. Like Twitter though
you only know who is actually listening, not how much they care about what you say.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[First Impressions of Google+]]></title>
    <link href="http://i-think22.net/archives/2011/07/07/first-impressions-of-google-plus/"/>
    <updated>2011-07-07T21:16:43+10:00</updated>
    <id>http://i-think22.net/archives/2011/07/07/first-impressions-of-google-plus</id>
    <content type="html"><![CDATA[<p>Well, I managed to get on to Google+ today. My first impression is it feels
like the love child of Facebook and Twitter. It may look a lot like Facebook
when you are viewing your &lsquo;Streams&rsquo;, but the model feels much more like how
Twitter would be if you could tweet to specific groups of people. I won&rsquo;t bore
you with the details of Circles and how they work, instead I&rsquo;ll point out the
things I really like and the missing features that I hope are filled in soon.</p>

<h3>The Stream</h3>

<p>Well, this is all pretty standard. So all the things from your circles that your circle
friends have deemed you worthy to see appear here. What I would like to see here is the
ability to exclude feeds from certain circles from appearing in the stream. This would
allow your default view to be void of noise but still provide ready access to these
people.</p>

<h3>Circles and Sets</h3>

<p>I have no doubt that this is a feature the guys at Google are keen to push out (the math
nerds that they are). Basically what is needed is the ability to define composite circles,
that is circles that use standard set operations (union, intersection and subtraction) to
define their members. Of course they would have to explain it better than me, but some
Venn diagrams should make it clear enough to just about anybody.</p>

<h3>Suggestions that are smarter about multiple email addresses</h3>

<p>Because the suggestions are based partly on the entire contents of you Gmail address book
I&rsquo;ve found that I get suggestions for people I&rsquo;ve already added (but have multiple email
accounts). One suggestion was even to add myself. Where I&rsquo;ve told Google that I have
multiple addresses I would hope that it could prune some of that for me.</p>

<p>I do like the multiple personality approach that Google+ gives you. I&rsquo;m glad
that even though set functionality isn&rsquo;t available yet that by using circles
you can model some pretty complex social hierarchies. Whether enough people
will make the switch remains to be seen. I&rsquo;m not holding my breath, because
unless Google rapidly expands their trial interest may just fizzle. So,
hopefully Google can bring wave after wave of improvements while the buzz is
still in the air.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Pipe Character '|' on Windows Phone 7]]></title>
    <link href="http://i-think22.net/archives/2011/02/07/the-pipe-character-on-windows-phone-7/"/>
    <updated>2011-02-07T19:48:23+10:00</updated>
    <id>http://i-think22.net/archives/2011/02/07/the-pipe-character-on-windows-phone-7</id>
    <content type="html"><![CDATA[<p>Recently I decided to put a bit of Powershell in a reply to a tweet. I was
using my fancy shmancy new Windows Phone 7. Well, needless to say I ran into a
few problems when I tried to insert the pipe character. I suppose it isn&rsquo;t too
commonly used, but I really wanted it to get my message across (whilst I could
have probably used a capital I to get my point across, some fonts won&rsquo;t do
that and it wouldn&rsquo;t be able to be pasted, so that wouldn&rsquo;t do).</p>

<p>After holding down what felt like every button ((On the English (UK)
keyboard)) to see what special characters they revealed (like the iPhone, the
&deg; symbol is hidden under the &lsquo;0&rsquo; key) the pipe character still eluded me.
However Windows Phone 7 also comes with a special smiley keyboard which has a
wide array of smileys to choose from, including the flat :| smiley. Knowing
that was the pipe character right there it became easy, simply insert the :|
smiley, move the cursor between the colon and the pipe, hit the backspace key
and move the cursor back to the end of the line.</p>

<p>It couldn&rsquo;t be simpler&hellip;</p>

<p>Actually, maybe it could. Pipe symbol please!?!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Installing multiple MSI files using msiexec.exe and Powershell]]></title>
    <link href="http://i-think22.net/archives/2011/02/06/installing-multiple-msi-files-using-msiexec-exe-and-powershell/"/>
    <updated>2011-02-06T19:36:09+10:00</updated>
    <id>http://i-think22.net/archives/2011/02/06/installing-multiple-msi-files-using-msiexec-exe-and-powershell</id>
    <content type="html"><![CDATA[<p>I use Powershell scripts to update test environments and when I can I prefer
to use the MSI files that we would ship to a customer rather than hacking
together an xcopy deployment. Recently I worked on a script that did the
following:</p>

<ol>
<li>Check if an MSI already exists in a folder I designated as holding the current installation files (I called it &lsquo;Current&rsquo;).</li>
<li>If the MSI exists, execute the uninstall process for the MSI, and remove the MSI from the &lsquo;Current&rsquo; folder.</li>
<li>Copy the new installation file from the build drop folder and put it in the &lsquo;Current&rsquo; folder.</li>
<li>Execute the install process on the MSI in the &lsquo;Current&rsquo; folder.</li>
</ol>


<p>However I soon ran into a problem in that when I called msiexec.exe it would
not block the script, so it would try to run multiple instances on Windows
Installer and if you&rsquo;ve had any experience with Windows Installer you know
that just doesn&rsquo;t work (and for good reason).</p>

<p>A quick search on the interwebs revealed that I could simply wait for the
msiexec.exe process to finish. Rather than doing some sort of convoluted
monitoring of the process inside Powershell I decided to use the the <code>Start-Process</code>
commandlet (inspired by <a href="http://blogs.msdn.com/b/heaths/">Heath Stewart</a>&rsquo;s post &lsquo;<a href="http://blogs.msdn.com/b/heaths/archive/2005/11/15/493236.aspx">Waiting for msiexec to Finish</a>&rsquo;).</p>

<p><code>Start-Process</code> is a little bit different from &lsquo;start&rsquo; especially in how it
passes the parameters (through the <code>-ArgumentList</code> argument/parameter). But
fortunately the <code>-Wait</code> parameter was exactly what I was looking for. Here&rsquo;s
the final line:</p>

<pre><code>Start-Process -FilePath msiexec -ArgumentList /i, $installer, /quiet -Wait
</code></pre>

<p>This let everything nicely chain together and now deployments are super easy,
as they should be.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Disabling the debug trace output in Coded UI Tests]]></title>
    <link href="http://i-think22.net/archives/2011/01/24/disabling-the-debug-trace-output-in-coded-ui-tests/"/>
    <updated>2011-01-24T19:26:39+10:00</updated>
    <id>http://i-think22.net/archives/2011/01/24/disabling-the-debug-trace-output-in-coded-ui-tests</id>
    <content type="html"><![CDATA[<p>The Coded UI tests in Visual Studio 2010 are pretty cool. For the last few
months I&rsquo;ve been using the framework to completely automate a sophisticated
web application, with lots of drag and drop and crazy design surfaces.</p>

<p>But the test details page has always looked a little verbose. The default
Debug trace is full of so much stuff that I find it completely unusable, and
what it does have is barely legible anyway. So usually I just collapse the
section and move on to my own less verbose logging and the stack trace.</p>

<p>Unfortunately all this information comes at a bit of a price and I have seen
machines run into the good ol' <code>OutOfMemoryException</code> more than once while
working with the log. So to eliminate that cause from the list of possible
culprits I hit the net and went searching for how to disable the debug trace
in Coded UI Tests.</p>

<p>Unfortunately I didn&rsquo;t find much (other than how to enable, and usually by
editing the test agent configuration). I wanted to find a solution that I
could add to my solution (damn overloaded words) that would just work no
matter what machine I ran the tests on. Fortunately it was really easy. I just
added an <code>App.config</code> file with the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;</span>
</span><span class='line'><span class="nt">&lt;configuration&gt;</span>
</span><span class='line'>  <span class="nt">&lt;system.diagnostics&gt;</span>
</span><span class='line'>    <span class="nt">&lt;switches&gt;</span>
</span><span class='line'>      <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">&quot;EqtTraceLevel&quot;</span> <span class="na">value=</span><span class="s">&quot;0&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/switches&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/system.diagnostics&gt;</span>
</span><span class='line'><span class="nt">&lt;/configuration&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>It did the trick and it is making my life a whole lot easier. Hopefully it
helps someone else too. (You could also try other values for the level, but
I&rsquo;m an all or nothing kind of guy).</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[I don't need no stinking third dimension]]></title>
    <link href="http://i-think22.net/archives/2010/10/01/i-dont-need-no-stinking-third-dimension/"/>
    <updated>2010-10-01T10:27:49+10:00</updated>
    <id>http://i-think22.net/archives/2010/10/01/i-dont-need-no-stinking-third-dimension</id>
    <content type="html"><![CDATA[<p>They are all the rage these days. Movies in 3D. Soon it will be hard to see a
movie at a cinema without having to wear those silly glasses. It&rsquo;s also a new
excuse to add to the ticket price. But in reality it is all just a gimmick,
yes, even for those ultra-gimicky movies like <em>Avatar</em>.</p>

<p>That&rsquo;s right. I&rsquo;ve said it. I didn&rsquo;t really enjoy <em>Avatar</em>. It went on and on
and frankly I&rsquo;m kind of annoyed that the humans didn&rsquo;t wipe out the blue guys.
Sure the movie was visually very fancy and there were lots of ooing and ahing
about the 3D visuals (which I agree were spectacular), but in adding the third
dimension to the visuals the movie lost one of the most important dimensions,
substance.</p>

<p>And that&rsquo;s where the problem really lies. The addition of 3D to the movie
world has just given the movie makers of today yet another distraction from
actually making a good movie. You know, one where you actually care about the
characters.</p>

<p><img class="right" src="http://i-think22.net/a/2010-10-01-i-dont-need-no-stinking-third-dimension/DSC01543_1024o-300x225.jpg" width="300" height="225" title="Me, Will and Dave sporting 3D glasses" >
The other thing that bugs me about movies in 3D is that it can make it very
difficult to focus on what is going on. Although I will give credit to <em>The
Last Airbender</em> which made only very subtle use of 3D and I could actually
read the text when it appeared without straining. <em>Piranha</em> on the other hand
made the text almost impossible to read.</p>

<p>I seriously question the need for presenting films in three dimensions. Movie
makers have been using a simple two dimensional screen for years and doing
just fine. They use lighting, shadows and other fancy tricks to provide the
illusion of depth and when you are caught up in the movie you don&rsquo;t even
really notice. So I think that&rsquo;s where the problem really is. In 3D movies all
I notice is that it is in 3D and it becomes harder to recognise and interpret
the story that is actually happening on the screen. It sounds odd, but I find
it harder to actually immerse myself in a 3D film.</p>

<p>I suppose one big reason the studios might be pushing for more 3D film
releases apart from the increased ticket prices is that it might be a way to
thwart some camcorder piracy of their movies. Although It would probably be
fairly simple to put a filter on the camera so that&rsquo;s probably a stupid
reason.</p>

<p>And if the kids out there want to really play with the whole three dimensional
thing, I suggest placing two objects one behind the other. Close one eye and
line up your sight so that the back object is obscured. Now alternately close
and open each eye. It&rsquo;s like magic.</p>

<p>Photo courtesy of <a href="http://omegadelta.net/">William Denniss</a>. Used with permission.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[On Google Chrome omitting the http:// from the Omnibox]]></title>
    <link href="http://i-think22.net/archives/2010/09/10/on-google-chrome-omitting-the-http-from-the-omnibox/"/>
    <updated>2010-09-10T09:10:07+10:00</updated>
    <id>http://i-think22.net/archives/2010/09/10/on-google-chrome-omitting-the-http-from-the-omnibox</id>
    <content type="html"><![CDATA[<p><img class="left" src="http://i-think22.net/a/2010-09-10-on-google-chrome-omitting-the-http-from-the-omnibox/chrome_logo.gif" title="Google Chrome Logo" >
Recently a Google Chrome update removed the &lsquo;<a href="http://">http://</a>&rsquo; from the Omnibox (aka the
address/search bar). When the change was originally introduced in the development branch
of Google Chrome in April this year there was massive backlash (~150 comments on a bug,
specifically <a href="http://code.google.com/p/chromium/issues/detail?id=41467">Bug 41467</a>). Of course within about 5 days the comments died down and
everyone moved on with their lives. The Chromium team have marked the &lsquo;bug&rsquo; as &lsquo;Won&rsquo;t
fix&rsquo;.</p>

<p>Now the feature has hit the main release. If you still aren&rsquo;t sure what I&rsquo;m talking about,
here&rsquo;s a screenshot:</p>

<p><img src="http://i-think22.net/a/2010-09-10-on-google-chrome-omitting-the-http-from-the-omnibox/omnibox_sans_http.png" alt="The Omnibox sans 'http://'" /></p>

<p>Personally I like the change, and here&rsquo;s why:</p>

<ul>
<li>Copy and Paste use cases still work (at least they do on my machine).</li>
<li>Because I read left to right I don&rsquo;t have to skip 7 characters to get to the domain name.</li>
<li>I consider my browser to be primarily an HTTP client. I expect HTTP to be the default protocol and don&rsquo;t need this information exposed.</li>
<li>My own personal biases.</li>
</ul>


<p>Of course, HTTPS urls display differently.</p>

<p><img src="http://i-think22.net/a/2010-09-10-on-google-chrome-omitting-the-http-from-the-omnibox/omnibox_https.png" alt="Omnibox with https://" /></p>

<p>So this could be a little confusing, but it does further highlight the fact
that the connection is secured.</p>

<p>Nevertheless one of the reasons I do include Chrome as part of my browser
cycle is because it is different. This change is different from the other
browsers, but it is exactly this difference that I like.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[VSMDI Normalizer]]></title>
    <link href="http://i-think22.net/archives/2010/02/11/vsmdi-normalizer/"/>
    <updated>2010-02-11T20:11:35+10:00</updated>
    <id>http://i-think22.net/archives/2010/02/11/vsmdi-normalizer</id>
    <content type="html"><![CDATA[<p>Have you noticed that your Visual Studio test lists always seem to get re-
ordered? Make sense of this randomness with the VSMDI Normalizer.</p>

<p>It works by sorting your test lists and tests by name, creating a consistent
ordering, allowing better merging and comparison of test lists. It&rsquo;s a command
line tool so it can integrate with automated processes really well.</p>

<p>It works in two modes:</p>

<ol>
<li>Target Mode: Specify the VSMDI file as the first argument and the target output file as the second. If the target exists it will be overwritten. This is ideal if not everyone is using VSMDI Normalizer. Some file comparison tools accept external converter tools (such as Beyond Compare).</li>
<li>In Place Mode: The VSMDI file will be normalized in place. This would be a good operation to run prior to check in. Just specify the VSMDI file as the first and only argument at the command line.</li>
</ol>


<p><a href="https://bitbucket.org/rhysparry/vsmdi-normalizer/downloads">Download VSMDI Normalizer</a></p>

<p>For support, visit our <a href="https://bitbucket.org/rhysparry/vsmdi-normalizer/issues">support page</a>.</p>

<p>VSMDI Normalizer is free for personal and commercial use. It comes with no
warranty, explicit or implicit.</p>

<p>To use VSMDI Normalizer with Beyond Compare:</p>

<ol>
<li>Open Beyond Compare</li>
<li>Select Tools > File Formats</li>
<li>Click New</li>
<li>Enter *.vsmdi as the mask</li>
<li>In the Conversion Tab, select &ldquo;External program (Unicode filenames)&rdquo;.</li>
<li>Browse for the VSMDI Normalizer tool (for the Loading field).</li>
<li>Append the following to the Loading path: &ldquo; %s %t&rdquo; (without the quotes).</li>
<li>Check Disable editing</li>
<li>Click Save and Close</li>
</ol>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Windows Easy Transfer: Easy when you know how]]></title>
    <link href="http://i-think22.net/archives/2009/10/06/windows-easy-transfer-easy-when-you-know-how/"/>
    <updated>2009-10-06T06:18:00+10:00</updated>
    <id>http://i-think22.net/archives/2009/10/06/windows-easy-transfer-easy-when-you-know-how</id>
    <content type="html"><![CDATA[<p>I recently installed Windows 7 RTM on my laptop. Knowing that Asus didn&rsquo;t
supply 64-bit drivers for my laptop I installed the 32-bit version. After all,
I only had 2GiB of RAM anyway.</p>

<p>Working from home the last few weeks has put more stress on my laptop than it
has previously and I was constantly hitting my 2GiB limit leaving my hard
drive thrashing as Windows struggled to swap pages in and out of memory.</p>

<p>I was surprised when I installed Windows 7 that I didn&rsquo;t need to download any
drivers from my manufacturer (Asus). My graphics drivers were installed
through Windows Update and everything else worked out of the box.
((Unfortunately this didn&rsquo;t include my Bluetooth drivers, but as I am now
using the Microsoft Explorer Mouse this doesn&rsquo;t seem like such a loss.))</p>

<p>So, after some encouragement from a <a href="http://buffered.io">friend on twitter</a> I
decided to try installing the 64-bit version of Windows 7 and if it worked,
move up to 4GiB of RAM.</p>

<p>I already had the 64-bit image ready to go on Windows Deployment Services, but
I had just recently finished setting up my machine perfectly. I was
particularly worried about having to reconfigure Outlook and set up new PST
file. Now I could have tried copying my user profile and transferring that
way, but instead I figured that I&rsquo;d give Windows Easy Transfer a try. Once I
passed the initial welcome screen I was confronted with the following options:</p>

<p><img src="http://www.i-think22.net/wp-%0Acontent/uploads/2009/10/EasyTransferCable.png" alt="An Easy Transfer cable" /></p>

<p>I guess this is a good idea for people who don&rsquo;t have a wired home network. I
didn&rsquo;t have one of these cables (and I don&rsquo;t think looping it back to the same
computer would work right) so I moved to the next option.</p>

<p><img src="http://www.i-think22.net/wp-%0Acontent/uploads/2009/10/NetworkTransfer.png" alt="A network" /></p>

<p>Surely this was the option I wanted. After all, I wanted to copy the files to
my network server. Unfortunately, no. This option migrates directly to the new
computer. This wasn&rsquo;t right either.</p>

<p><img src="http://www.i-think22.net/wp-%0Acontent/uploads/2009/10/RemovableDiskTransfer.png" alt="RemovableDiskTransfer" /></p>

<p>An external hard disk or USB flash drive? That sounds very specific.
Fortunately this includes network drives too. In fact, it just brings up a
standard file dialog so you could likely store the migration file anywhere you
want.</p>

<p>Then it was just a case of following the on-screen directions. It not only
backed up the Documents folder, but it grabbed other folders on the disk and
on different partitions. Unfortunately it doesn&rsquo;t grab the settings for all
applications, but it covered enough for my needs.</p>

<p>Once you&rsquo;ve migrated back you get this handy migration report which you can
use as a guide to see what applications you still have to install:</p>

<p><img src="http://www.i-think22.net/wp-%0Acontent/uploads/2009/10/PreviouslyInstalledApplications.png" alt="Previously Installed Applications" /></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[LINQ to SQL and tables with no Primary Key]]></title>
    <link href="http://i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key/"/>
    <updated>2009-07-24T06:24:39+10:00</updated>
    <id>http://i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key</id>
    <content type="html"><![CDATA[<p>I ran into an interesting issue with LINQ to SQL yesterday. I had to update a
table with no Primary Key. As I expected, LINQ to SQL wasn&rsquo;t too happy with
this scenario. Unfortunately LINQ to SQL will only throw an exception when you
try to Insert or Delete a record with no primary key. Updates fail silently.</p>

<p>It&rsquo;s actually quite obvious when you look into what is happening. To do an
update you would usually do something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="kt">var</span> <span class="n">update</span> <span class="p">=</span> <span class="p">(</span><span class="k">from</span> <span class="n">v</span> <span class="k">in</span> <span class="n">db</span><span class="p">.</span><span class="n">SimpleRecords</span>
</span><span class='line'>              <span class="k">where</span> <span class="n">v</span><span class="p">.</span><span class="n">identifier</span> <span class="p">==</span> <span class="m">12</span>
</span><span class='line'>              <span class="k">select</span> <span class="n">v</span><span class="p">).</span><span class="n">First</span><span class="p">();</span>
</span><span class='line'><span class="n">update</span><span class="p">.</span><span class="k">value</span> <span class="p">=</span> <span class="s">&quot;new value&quot;</span><span class="p">;</span>
</span><span class='line'><span class="n">db</span><span class="p">.</span><span class="n">SubmitChanges</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>Of course, nothing happens. Here&rsquo;s the code (slightly edited for readability)
that is generated by the LINQ to SQL classes:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="na">[Table(Name=&quot;dbo.SimpleRecord&quot;)]</span>
</span><span class='line'><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">SimpleRecord</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>   <span class="k">private</span> <span class="kt">int</span> <span class="n">_identifier</span><span class="p">;</span>
</span><span class='line'>      
</span><span class='line'>   <span class="k">private</span> <span class="kt">string</span> <span class="n">_value</span><span class="p">;</span>
</span><span class='line'>      
</span><span class='line'>      <span class="k">public</span> <span class="nf">SimpleTable</span><span class="p">()</span>
</span><span class='line'>      <span class="p">{</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'><span class="na">     </span>
</span><span class='line'><span class="na">      [Column(Storage=&quot;_identifier&quot;, AutoSync=AutoSync.Always,</span>
</span><span class='line'><span class="na">         DbType=&quot;Int NOT NULL IDENTITY&quot;, IsDbGenerated=true)]</span>
</span><span class='line'>      <span class="k">public</span> <span class="kt">int</span> <span class="n">identifier</span>
</span><span class='line'>      <span class="p">{</span>
</span><span class='line'>         <span class="k">get</span>
</span><span class='line'>         <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">_identifier</span><span class="p">;</span>
</span><span class='line'>         <span class="p">}</span>
</span><span class='line'>         <span class="k">set</span>
</span><span class='line'>         <span class="p">{</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">_identifier</span> <span class="p">!=</span> <span class="k">value</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>               <span class="k">this</span><span class="p">.</span><span class="n">_identifier</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>         <span class="p">}</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'><span class="na">     </span>
</span><span class='line'><span class="na">      [Column(Storage=&quot;_value&quot;, DbType=&quot;VarChar(50)&quot;)]</span>
</span><span class='line'>      <span class="k">public</span> <span class="kt">string</span> <span class="k">value</span>
</span><span class='line'>      <span class="p">{</span>
</span><span class='line'>         <span class="k">get</span>
</span><span class='line'>         <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="n">_value</span><span class="p">;</span>
</span><span class='line'>         <span class="p">}</span>
</span><span class='line'>         <span class="k">set</span>
</span><span class='line'>         <span class="p">{</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="n">_value</span> <span class="p">!=</span> <span class="k">value</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>               <span class="k">this</span><span class="p">.</span><span class="n">_value</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>         <span class="p">}</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Without a primary key the two following interfaces aren&rsquo;t emitted:
<code>INotifyPropertyChanging</code> and <code>INotifyPropertyChanged</code></p>

<p>Therefore LINQ to SQL doesn&rsquo;t know that your record has changed (so can&rsquo;t warn
you that it can&rsquo;t update).</p>

<p>Now that you understand the problem the solution is simple: Define a primary
key in your table.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Workplace Instant Messaging Etiquette]]></title>
    <link href="http://i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette/"/>
    <updated>2009-07-04T18:35:19+10:00</updated>
    <id>http://i-think22.net/archives/2009/07/04/workplace-instant-messaging-etiquette</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve been getting progressively more and more annoyed at the use of Instant
Messaging in the workplace. Don&rsquo;t get me wrong, I think it is a fantastic way
to get quick messages across to people and for communicating across boundaries
(such as across the other side of the building), but I feel that there are a
few rules that should be followed if Instant Messaging is going to be an
effective form of communication.</p>

<p><strong>1. If you want something or are asking a question put it in your first message.</strong></p>

<p>Every time I am interrupted by an instant message that just says &ldquo;Hi&rdquo; or
&ldquo;Rhys&rdquo; I scream a little inside. This &ldquo;handshaking protocol&rdquo; has broken my
concentration and I am now trying to work out what the person wants. I can
even see that they are feverously trying to type their actual message. Why
waste my previous cycles by forcing me to process a single useless &ldquo;header&rdquo;
and wait for the actual body. Send the header and the body at the same time!!
As an example:</p>

<blockquote><p>Hi Rhys, do you have time for a quick test review?</p></blockquote>

<p>This message is concise, expresses the point and can easily be responded to,
like so:</p>

<blockquote><p>I&rsquo;m busy. Go away.</p></blockquote>

<p>Ok, in reality it would probably be more like this:</p>

<blockquote><p>Sure</p></blockquote>

<p>Or if I really am busy:</p>

<blockquote><p>Can it wait? I am in the middle of something and should be ready in about 20
minutes.</p></blockquote>

<p><strong>2. Send complete messages</strong></p>

<p>The last example leads us into the next rule, send complete messages. Don&rsquo;t
leave the recipient of your message guessing. Sure, you can&rsquo;t answer all
possible questions at once, but at least answer the most obvious ones. Empower
the person you are communicating with by giving them the information they
need to make a decision so that the conversation can end quickly.</p>

<p><strong>3. Don&rsquo;t let conversations drag on</strong></p>

<p>If an Instant Messaging conversation is going on too long it is a good
indication that the process has broken down. If possible it may be time to get
up and speak to the person the old fashioned way. You&rsquo;ll be able to get more
information processed more quickly. If you can&rsquo;t speak in person, use a
telephone or if there is just a lot of information that you need to pass,
write an email.</p>

<p><strong>Final words</strong></p>

<p>I&rsquo;m sure there are more rules that could be applied, but I know that if
everyone could follow the first rule I&rsquo;d be much much happier.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[LINQ Talk from Queensland MSDN User Group]]></title>
    <link href="http://i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/"/>
    <updated>2009-05-07T06:23:52+10:00</updated>
    <id>http://i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group</id>
    <content type="html"><![CDATA[<p>Last month I did a talk on LINQ at the Queensland MSDN User Group. For your
viewing pleasure the talk is available on Live Meeting. Check it out here:</p>

<p><a href="https://www112.livemeeting.com/cc/microsoft/view?cn=&amp;id=59CJFS&amp;pw=">LINQ: Powerful Stuff (QMSDNUG)</a></p>

<p>You may need to skip the first 5 minutes.</p>

<p>Slides are available here: <a href="http://linq.i-think22.net/LinqApril2009.pdf">http://linq.i-think22.net/LinqApril2009.pdf</a></p>

<p>Demos will be available soon.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Writing XML with XElement]]></title>
    <link href="http://i-think22.net/archives/2009/02/27/writing-xml-with-xelement/"/>
    <updated>2009-02-27T08:39:00+10:00</updated>
    <id>http://i-think22.net/archives/2009/02/27/writing-xml-with-xelement</id>
    <content type="html"><![CDATA[<p>In my last post we looked at <a href="http://i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/">how you can use LINQ to XML and XElement to parse XML</a>.
But what if you want to create XML files programmatically? Or
modify an existing XML document?</p>

<p>Let&rsquo;s start by looking at how we might add a new entry to our blog. Here is
the XML file again:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
</span><span class='line'><span class="nt">&lt;Blog&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Entries&gt;</span>
</span><span class='line'>      <span class="nt">&lt;Entry</span> <span class="na">Archived=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Title&gt;</span>My First Post<span class="nt">&lt;/Title&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Body&gt;</span>I love LINQ. It&#39;s the best<span class="nt">&lt;/Body&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Comments&gt;</span>
</span><span class='line'>            <span class="c">&lt;!-- TODO: Shouldn&#39;t comments have authors? --&gt;</span>
</span><span class='line'>            <span class="nt">&lt;Comment&gt;</span>I love LINQ more<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>            <span class="nt">&lt;Comment&gt;</span>LINQ is the way of the future.<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>         <span class="nt">&lt;/Comments&gt;</span>
</span><span class='line'>      <span class="nt">&lt;/Entry&gt;</span>
</span><span class='line'>   <span class="nt">&lt;/Entries&gt;</span>
</span><span class='line'><span class="nt">&lt;/Blog&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>So we want to add a new Entry under the Entries element. We&rsquo;ll also assume
that our XML file has been parsed into an <code>XElement</code> variable <code>blog</code>.</p>

<p>We&rsquo;ll start by creating our entry first:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="kt">var</span> <span class="n">entry</span> <span class="p">=</span> <span class="k">new</span> <span class="n">XElement</span><span class="p">(</span><span class="s">&quot;Entry&quot;</span><span class="p">);</span>
</span><span class='line'><span class="n">entry</span><span class="p">.</span><span class="n">SetAttributeValue</span><span class="p">(</span><span class="s">&quot;Archived&quot;</span><span class="p">,</span> <span class="k">false</span><span class="p">);</span>
</span><span class='line'><span class="n">entry</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">XElement</span><span class="p">(</span><span class="s">&quot;Title&quot;</span><span class="p">,</span> <span class="s">&quot;My Second Post&quot;</span><span class="p">));</span>
</span><span class='line'><span class="n">entry</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">XElement</span><span class="p">(</span><span class="s">&quot;Body&quot;</span><span class="p">,</span> <span class="s">&quot;Just a quick post.&quot;</span><span class="p">));</span>
</span><span class='line'><span class="n">entry</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">XElement</span><span class="p">(</span><span class="s">&quot;Comments&quot;</span><span class="p">));</span>
</span></code></pre></td></tr></table></div></figure>


<p>We started by creating the element, set the &ldquo;Archived&rdquo; attribute, then added
the other necessary elements. I&rsquo;ve still added the Comments element even
though it will be empty. Depending on the rules that have been set about how I
should layout the XML it might be optional.</p>

<p>To check that my code worked I plugged it into <a href="http://www.linqpad.net/">LINQPad</a> and dumped the value of entry like so:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="n">entry</span><span class="p">.</span><span class="n">ToString</span><span class="p">().</span><span class="n">Dump</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>The results showed me the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;Entry</span> <span class="na">Archived=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Title&gt;</span>My Second Post<span class="nt">&lt;/Title&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Body&gt;</span>Just a quick post.<span class="nt">&lt;/Body&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Comments</span> <span class="nt">/&gt;</span>
</span><span class='line'><span class="nt">&lt;/Entry&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Wow, that&rsquo;s exactly what we want. Even though we used a <code>Boolean</code> value
instead of a <code>String</code> for the attribute, <code>XElement</code> was smart enough to
display its value as a human readable string. The XML is also nicely formatted
and readable. I added the call to <code>ToString()</code> to emphasise that it wasn&rsquo;t
LINQPad that was responsible for the improved formatting.</p>

<p>What we have done here is generate an XML fragment. Sometimes it is easier to
think of large XML files as smaller fragments that can be handled
independently.</p>

<p>So now all we have to do is find the Entries element and add our <code>entry</code>
<code>XElement</code> to it like so.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="n">blog</span><span class="p">.</span><span class="n">Element</span><span class="p">(</span><span class="s">&quot;Entries&quot;</span><span class="p">).</span><span class="n">Add</span><span class="p">(</span><span class="n">entry</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will leave us with the final XML looking like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;Blog&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Entries&gt;</span>
</span><span class='line'>     <span class="nt">&lt;Entry</span> <span class="na">Archived=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Title&gt;</span>My First Post<span class="nt">&lt;/Title&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Body&gt;</span>I love LINQ. It&#39;s the best<span class="nt">&lt;/Body&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Comments&gt;</span>
</span><span class='line'>         <span class="c">&lt;!-- TODO: Shouldn&#39;t comments have authors? --&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Comment&gt;</span>I love LINQ more<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Comment&gt;</span>LINQ is the way of the future.<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>       <span class="nt">&lt;/Comments&gt;</span>
</span><span class='line'>     <span class="nt">&lt;/Entry&gt;</span>
</span><span class='line'>     <span class="nt">&lt;Entry</span> <span class="na">Archived=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Title&gt;</span>My Second Post<span class="nt">&lt;/Title&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Body&gt;</span>Just a quick post.<span class="nt">&lt;/Body&gt;</span>
</span><span class='line'>       <span class="nt">&lt;Comments</span> <span class="nt">/&gt;</span>
</span><span class='line'>     <span class="nt">&lt;/Entry&gt;</span>
</span><span class='line'>   <span class="nt">&lt;/Entries&gt;</span>
</span><span class='line'><span class="nt">&lt;/Blog&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<h3>What about our XML declaration?</h3>

<p>You might be wondering why the <code>ToString()</code> method of <code>XElement</code> doesn&rsquo;t
include the XML declaration. Because XElement represents a fragment of XML
which could appear anywhere in an XML document. If it included the XML
declaration it would lose this flexibility. However there is a workaround if
you are outputting to a final file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="kt">var</span> <span class="n">blogDump</span> <span class="p">=</span> <span class="k">new</span> <span class="n">StringBuilder</span><span class="p">();</span>
</span><span class='line'><span class="n">blog</span><span class="p">.</span><span class="n">Save</span><span class="p">(</span><span class="k">new</span> <span class="n">StringWriter</span><span class="p">(</span><span class="n">blogDump</span><span class="p">));</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>Save()</code> method on <code>XElement</code> automatically adds an appropriate XML
declaration, which is probably a good idea as it sorts out the complicated
things like the encoding and XML version (which I&rsquo;ve never seen as anything
other than 1.0 to date). The <code>Save()</code> method can take either the name of a
file (as a <code>String</code>), an <code>XmlWriter</code> or <code>TextWriter</code>. In the example above
I&rsquo;ve used a <code>StringWriter</code> (which is a subclass of <code>TextWriter</code>) to save XML
to a <code>StringBuilder</code> object which I could then use to build a string
containing the XML. <code>Save()</code> also takes a second parameter, <code>SaveOptions</code>
which allows you to save your XML file without the extra whitespace that I&rsquo;ve
shown above. If you want to save those bytes it might be worth looking at this
option.</p>

<h3>Where do we go from here?</h3>

<p>I haven&rsquo;t yet decided what my next LINQ post will cover (although LINQ to
Entities is high on the agenda), so I won&rsquo;t promise anything here now. I have
much more to say still about LINQ, so feel free to post in the comments
suggestions for areas to cover in future posts and the areas you would like to
see covered in more detail. So far this has been fairly introductory and we&rsquo;ll
be building towards more advanced topics over the coming weeks.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[XML Made Easy with LINQ to XML]]></title>
    <link href="http://i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/"/>
    <updated>2009-02-25T08:58:00+10:00</updated>
    <id>http://i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml</id>
    <content type="html"><![CDATA[<p>XML is a fantastic way to structure information. Here are the two things I
like most about XML.</p>

<ol>
<li>It&rsquo;s fundamental concepts are simple, making many XML files readable by regular humans.</li>
<li>The formalised structure enables re-use of a more generalised XML parser.</li>
</ol>


<p>Projects can certainly suffer from too much XML or XML is used when a better
option exists. Once your XML files become too difficult to read in a text
editor it may be better to look at another option (or better design your XML
schema).</p>

<h3>A lightning fast introduction to XML</h3>

<p>Skip this section if you already know XML, but take time to look at this XML
sample as it will be used throughout the article.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
</span><span class='line'><span class="nt">&lt;Blog&gt;</span>
</span><span class='line'>   <span class="nt">&lt;Entries&gt;</span>
</span><span class='line'>      <span class="nt">&lt;Entry</span> <span class="na">Archived=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Title&gt;</span>My First Post<span class="nt">&lt;/Title&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Body&gt;</span>I love LINQ. It&#39;s the best<span class="nt">&lt;/Body&gt;</span>
</span><span class='line'>         <span class="nt">&lt;Comments&gt;</span>
</span><span class='line'>            <span class="c">&lt;!-- TODO: Shouldn&#39;t comments have authors? --&gt;</span>
</span><span class='line'>            <span class="nt">&lt;Comment&gt;</span>I love LINQ more<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>            <span class="nt">&lt;Comment&gt;</span>LINQ is the way of the future.<span class="nt">&lt;/Comment&gt;</span>
</span><span class='line'>         <span class="nt">&lt;/Comments&gt;</span>
</span><span class='line'>      <span class="nt">&lt;/Entry&gt;</span>                  
</span><span class='line'>   <span class="nt">&lt;/Entries&gt;</span>
</span><span class='line'><span class="nt">&lt;/Blog&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Above is an example of a simple XML file. XML files follow a structured
pattern called a <strong>schema</strong>. The schema defines the rules for what is allowed
where and generally defines the structure of your file. Fortunately you don&rsquo;t
need to write a formal schema to get started with XML. Instead you can just
start laying out your data. That&rsquo;s where the &ldquo;X&rdquo; in XML comes from, because it
is <strong>eXtensible</strong>.</p>

<p>So the sample XML above is being used to store the contents of a simple blog.
XML isn&rsquo;t the best way to do this, but a blog is a simple well understood
concept. If you read my article on <a href="http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/">LINQ to SQL</a> you might notice that this is very
similar to the database example I used there.</p>

<p>Every XML document <em>should</em> start with what is known as an <strong>XML
declaration</strong>. It&rsquo;s in the first line of the XML and defines the version of
the XML as well as the encoding of the file. If you are using notepad you can
select the encoding when you save the file. The topic of encodings is out of
the scope of this article.</p>

<p>The next important element that all XML files need is a <strong>root node</strong>. In this
example our root node is called &ldquo;Blog&rdquo; and it holds all of our other elements.
There can only be one root node in an XML document so if we wanted another
blog we would have to put it in another XML file or redesign our XML to have a
new root node (such as BlogCollection).</p>

<p>From there we can see that our XML document is made up of two key parts,
elements and attributes. <strong>Elements</strong> are the things in angle brackets (called
<strong>tags</strong>) and an element continues until it is closed with a matching closing
tag. <strong>Closing tags</strong> are different from regular tags as they have a forward
slash (/) before the name of the tag. We will use the term element to describe
everything from the opening tag (a regular tag) to the closing tag, and a tag
as the bit with the angle brackets.</p>

<p>There is also a special kind of tag called a <strong>self-closing tag</strong> that is both
an opening tag and a closing tag. These tags have a forward slash before the
closing angle bracket. For example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;SelfClosingTag</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The space before the forward slash is optional (and stems back to
compatibility with HTML). Personally I like keeping the space there, but your
project may have different rules.</p>

<p>The other important concept is attributes. <strong>Attributes</strong> go inside the tag to
provide more information about a tag. Attributes can only be used once per
element (but one element can have multiple attributes). In the example above,
we have given the entry tag the Archived attribute.</p>

<p>Sometimes it can be difficult to determine whether data should be expressed as
an attribute or as a <strong>child element</strong> (an element inside another element).
Typically the rule of thumb is that an attribute should be describing
metadata, that is extra information about the element itself and how it might
be interpreted. Occasionally this doesn&rsquo;t clear things up at all. If you are
still confused, consider the complexity of the data and whether multiple
instances of the data will be required. Complex and repeating data is a sure
sign that you want to use an element.</p>

<p>Importantly elements can contain other elements which can in turn contain more
elements (and so on). XML follows a very strict hierarchy (which makes it easy
to navigate) so an element must be closed inside the element that it was
opened in. This means that any element (except the root node of course) has
one and only one <strong>parent element</strong>. If you are modelling structured data it
is unlikely you&rsquo;ll run into troubles.</p>

<p>Finally I&rsquo;ve also added a comment to remind me to add authors to the comments.
We won&rsquo;t actually be doing this, it was merely there to demonstrate how you
can include <strong>comments</strong> in your XML documents. Comments should be ignored
when parsing an XML file as they are unrelated to the data. Comments begin
with <code>&lt;!--</code> and end with <code>--&gt;</code>.</p>

<p>Ok, so by now you should know enough about XML to understand how we can parse
this XML file and pull the necessary elements.</p>

<h3>Now for the exciting stuff</h3>

<p>LINQ to XML is a set of classes designed to work well with LINQ. It provides a
very simple API that allows XML to be read and written with ease.</p>

<p>The centre of your LINQ to XML world is <code>XElement</code>. Through <code>XElement</code> we can
access all of the important information in the sample above. Let&rsquo;s start by
writing a query that can help us get the Blog entries to display on the front
page. We&rsquo;ll assume I&rsquo;ve loaded the XML as a string into a variable called
<code>blogXml</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="kt">var</span> <span class="n">blog</span> <span class="p">=</span> <span class="n">XElement</span><span class="p">.</span><span class="n">Parse</span><span class="p">(</span><span class="n">blogXml</span><span class="p">);</span>
</span><span class='line'><span class="kt">var</span> <span class="n">frontPage</span> <span class="p">=</span> <span class="k">from</span> <span class="n">e</span> <span class="k">in</span> <span class="n">blog</span><span class="p">.</span><span class="n">Descendants</span><span class="p">(</span><span class="s">&quot;Entry&quot;</span><span class="p">)</span>
</span><span class='line'>                <span class="k">where</span> <span class="n">e</span><span class="p">.</span><span class="n">Attribute</span><span class="p">(</span><span class="s">&quot;Archived&quot;</span><span class="p">).</span><span class="n">Value</span> <span class="p">==</span> <span class="s">&quot;false&quot;</span>
</span><span class='line'>                <span class="k">select</span> <span class="n">e</span><span class="p">;</span>
</span><span class='line'><span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">entry</span> <span class="k">in</span> <span class="n">frontPage</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>   <span class="n">WriteBlogTitle</span><span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">Element</span><span class="p">(</span><span class="s">&quot;Title&quot;</span><span class="p">).</span><span class="n">Value</span><span class="p">);</span>
</span><span class='line'>   <span class="n">WriteBlogBody</span><span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">Element</span><span class="p">(</span><span class="s">&quot;Body&quot;</span><span class="p">).</span><span class="n">Value</span><span class="p">);</span>
</span><span class='line'>   <span class="n">WriteBlogCommentCount</span><span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">Descendants</span><span class="p">(</span><span class="s">&quot;Comment&quot;</span><span class="p">).</span><span class="n">Count</span><span class="p">());</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This example does absolutely no error checking (something you&rsquo;ll definitely
want to do if you are working with real XML) but demonstrates how simple it is
to find particular elements inside XML. Additionally you can use <code>XElement</code>
objects to pass XML fragments around your application. We could have made our
LINQ query return an anonymous type that pulled out the Title, Body and
Comment count for each entry, but instead we just pulled out the <code>XElement</code>
itself. From there we were able count the comments inside our loop.</p>

<p>There is nothing preventing you from using these fantastic classes without
having to use LINQ queries as well. In fact, most of the XML parsing code I&rsquo;ve
written lately doesn&rsquo;t use LINQ queries at all to find elements, just the
methods of the XElement class. Let&rsquo;s look at the ones you&rsquo;ll likely use most.
Don&rsquo;t worry that these parameters take an XName as their parameter, strings
are automatically cast to a XName. You&rsquo;ll need to use XName if you are dealing
with namespaces (which I&rsquo;ll discuss in a future post).</p>

<ul>
<li><strong><code>Element(XName name)</code></strong> returns the first <strong>immediate</strong> child element with the given name. If the element does not exist it returns <code>null</code>.</li>
<li><strong><code>Elements()</code></strong> returns an <code>IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements. So against Blog the enumeration would yield a single &ldquo;Entries&rdquo; <code>XElement</code>. If there are no child elements the enumeration will be empty.</li>
<li><strong><code>Elements(XName name)</code></strong> returns an <code>IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements with the given name. If no elements with the name exist it will return an empty enumeration.</li>
<li><strong><code>Attribute(XName name)</code></strong> returns an <code>XAttribute</code> that is the attribute with the specified name. If the attribute does not exist it returns <code>null</code>.</li>
</ul>


<p>To match the <code>Element()</code> and <code>Elements()</code> methods there are also a set of
<code>Descendant()</code> and <code>Descendants()</code> methods. These work in the same way except
that they return all elements under the node. We used this method when we were
finding the Entry element as we didn&rsquo;t care about the rest of the document&rsquo;s
hierarchy.</p>

<p>Because these methods return null if the element (or attribute) is not found
it is important to check that the value is not null unless you are using a
method which returns an <code>IEnumerable&lt;T&gt;</code> object.</p>

<h3>Where to from here?</h3>

<p>You now know all the important classes needed to parse XML files (perhaps to
load up some strongly typed objects). In my next post I&rsquo;ll be discussing how
you can use this same class to build complex XML structures. In the meantime,
check out the <a href="http://msdn.microsoft.com/">MSDN</a> documentation for <code>XElement</code>.</p>
]]></content>
  </entry>
  
</feed>
