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

  <title><![CDATA[Jake Ginnivan's blog]]></title>
  <link href="http://jake.ginnivan.net/atom.xml" rel="self"/>
  <link href="http://jake.ginnivan.net/"/>
  <updated>2015-07-28T11:48:07+08:00</updated>
  <id>http://jake.ginnivan.net/</id>
  <author>
    <name><![CDATA[Jake Ginnivan]]></name>
    <email><![CDATA[jake@ginnivan.net]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[GitVersion v3.0.0!]]></title>
    <link href="http://jake.ginnivan.net/blog/2015/07/28/gitversion-v3/"/>
    <updated>2015-07-28T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2015/07/28/gitversion-v3</id>
    <content type="html"><![CDATA[<p>Today GitVersion v3.0.0 has been released. For me it has been a long time coming, with 4 beta releases and incorporating a lot of feedback between each release. It all started with <a href="https://github.com/GitTools/GitVersion/pull/338">this pull request</a> which replaced the existing approach of each git workflow being hard coded with a class responsible for calculating each branch type.</p>

<p>This meant that GitFlow and GitHubFlow had completely separate code paths with very little shared, it also meant that things like commit counting varied on different branches. v3 changed all that and now is entirely driven by configuration. This initial pull request weighed in at 78 commits, 196 files, changed 2,500 lines of code and deleted another 700. 106 pull requests later we are shipping.</p>

<p>This configuration based approach has been really important for a number of reasons:</p>

<ol>
<li>Understanding/documenting what GitVersion is doing.</li>
<li>When we had bug reports of a version being incorrectly calculated there was never a generic fix.</li>
<li>The logic for every branch was different and inconsistent. Then GitFlow and GitHubFlow worked quite differently in some respects</li>
<li>It was hard to get GitVersion to work with nightlies and publishing CI builds to NuGet</li>
<li>This meant that getting GitVersion working with Octopus deploy was not great</li>
</ol>


<p>A number of long standing bugs were fixed with the changes made in v3, some of the highlights of the new features</p>

<ul>
<li><code>GitVersion init</code> is a configuration tool which allows you to make GitVersion work the way you want it to</li>
<li>Decent documentation!

<ul>
<li>Check it out at <a href="http://gitversion.readthedocs.org/en/latest">http://gitversion.readthedocs.org/en/latest</a></li>
</ul>
</li>
<li>Configurable version incrementing

<ul>
<li><a href="http://gitversion.readthedocs.org/en/latest/reference/continuous-delivery/">Continuous Delivery</a> (default) means GitVersion will only increment the version when you release and tag, this works great for some scenarios and not well for otherwise</li>
<li><a href="http://gitversion.readthedocs.org/en/latest/reference/continuous-deployment/">Continuous Deployment</a>, meaning each commit will produce a <em>different</em> SemVer</li>
<li>Read more at [<a href="http://gitversion.readthedocs.org/en/latest/more-info/version-increments/">http://gitversion.readthedocs.org/en/latest/more-info/version-increments/</a>]</li>
</ul>
</li>
<li>Better error reporting - when things go wrong (which should be a lot less often now) we try to give you decent information including:

<ul>
<li>Dumping out a cleaned git history graph which you can paste into an issue so we can reproduce the issue</li>
<li>Logging out all decisions and sources for versions</li>
</ul>
</li>
</ul>


<h2>Whats next</h2>

<p>There are a few features which will be released in 3.1 which will make GitVersion nicer to get started. v4 hopefully will be not too far down the road when we rethink the command line usage and fix a few other things which have got a bit complex over time.</p>

<h2>Give it a go</h2>

<p>All the links you need are on our GitHub page at <a href="https://github.com/GitTools/GitVersion#gitversion">https://github.com/GitTools/GitVersion#gitversion</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ReactJS Popout window]]></title>
    <link href="http://jake.ginnivan.net/blog/2015/05/27/react-popout-window/"/>
    <updated>2015-05-27T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2015/05/27/react-popout-window</id>
    <content type="html"><![CDATA[<p>Recently I had a requirement to have a chat history panel which could be popped out into it&rsquo;s own window and that window needed to have live updates. I figured I had two ways of doing it, I could open a new window which initialised itself and had it&rsquo;s own connection to the server to get updates or I could keep with the React way and have the components which pop out simply flow updates to the window via props.</p>

<p>The component which needs to support popping out is the <code>ChatHistory</code> component which takes a set of items which get rendered.</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='js'><span class='line'><span class="o">&lt;</span><span class="nx">ChatHistory</span> <span class="nx">messages</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">chat</span><span class="p">.</span><span class="nx">messages</span><span class="p">}</span> <span class="o">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>A simplified implementation looks 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>
<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>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kr">class</span> <span class="nx">ChatHistory</span> <span class="kr">extends</span> <span class="nx">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">constructor</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kr">super</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">popout</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">popout</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="k">this</span><span class="p">)</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">state</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">poppedOut</span><span class="o">:</span> <span class="kc">false</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="nx">popout</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">poppedOut</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">(</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>        <span class="o">&lt;</span><span class="nx">Graphicon</span> <span class="nx">style</span><span class="o">=</span><span class="p"></span> <span class="nx">icon</span><span class="o">=</span><span class="s1">&#39;popout&#39;</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">popout</span><span class="p">}</span> <span class="o">/&gt;</span>
</span><span class='line'>        <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">messages</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">msg</span> <span class="o">=&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>            <span class="p">{</span><span class="nx">msg</span><span class="p">.</span><span class="nx">date</span><span class="p">}</span>
</span><span class='line'>            <span class="o">&lt;</span><span class="nx">pre</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">msg</span><span class="p">.</span><span class="nx">text</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/pre&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="err">/div&gt;</span>
</span><span class='line'>        <span class="p">)}</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="err">/div&gt;</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>Next is how do I pop this content out. First I create a <code>PoppedOutChatHistory</code> component:</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>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kr">class</span> <span class="nx">PoppedOutChatHistory</span> <span class="kr">extends</span> <span class="nx">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">constructor</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">{</span> <span class="kr">super</span><span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">(</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>        <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">messages</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">msg</span> <span class="o">=&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>            <span class="p">{</span><span class="nx">item</span><span class="p">.</span><span class="nx">date</span><span class="p">}</span>
</span><span class='line'>            <span class="o">&lt;</span><span class="nx">pre</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">msg</span><span class="p">.</span><span class="nx">text</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/pre&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="err">/div&gt;</span>
</span><span class='line'>        <span class="p">)}</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="err">/div&gt;</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>Then I introduced a <code>Popout</code> react component into the <code>ChatHistory</code> render function:</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>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">render</span><span class="p">()</span> <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="nx">state</span><span class="p">.</span><span class="nx">isPoppedOut</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">(</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">Popout</span> <span class="nx">title</span><span class="o">=</span><span class="s1">&#39;Window title&#39;</span> <span class="nx">onClosing</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">popupClosed</span><span class="p">}</span><span class="o">&gt;</span>
</span><span class='line'>        <span class="o">&lt;</span><span class="nx">PoppedOutChatHistory</span> <span class="nx">messages</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">messages</span><span class="p">}</span> <span class="o">/&gt;</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="err">/Popout&gt;</span>
</span><span class='line'>    <span class="p">);</span>
</span><span class='line'>  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="p">(</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">span</span> <span class="nx">style</span><span class="o">=</span><span class="p"></span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">popout</span><span class="p">}</span> <span class="nx">className</span><span class="o">=</span><span class="s2">&quot;buttonGlyphicon glyphicon glyphicon-export&quot;</span><span class="o">&gt;&lt;</span><span class="err">/span&gt;</span>
</span><span class='line'>        <span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">messages</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">msg</span> <span class="o">=&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="nx">div</span><span class="o">&gt;</span>
</span><span class='line'>            <span class="p">{</span><span class="nx">msg</span><span class="p">.</span><span class="nx">date</span><span class="p">}</span>
</span><span class='line'>            <span class="o">&lt;</span><span class="nx">pre</span><span class="o">&gt;</span><span class="p">{</span><span class="nx">msg</span><span class="p">.</span><span class="nx">text</span><span class="p">}</span><span class="o">&lt;</span><span class="err">/pre&gt;</span>
</span><span class='line'>          <span class="o">&lt;</span><span class="err">/div&gt;</span>
</span><span class='line'>        <span class="p">)}</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="err">/div&gt;</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><span class='line'><span class="nx">popupClosed</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span> <span class="nx">poppedOut</span><span class="o">:</span> <span class="kc">false</span> <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>Popout</code> component is quite simple, when <code>show</code> is set to true then it will render the content in a new popout window. The nice thing about having this as a React component is that the <code>Popout</code> window&rsquo;s lifecycle is tied to the lifecycle of the owning component. So when the History component is unmounted the <code>Popout</code> will close the popup it might have had opened.</p>

<h2>Summary</h2>

<p>I am pretty happy with the result of this Component, I can continue to flow props and handle events. For instance if I wanted to pop up a input form:</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='js'><span class='line'><span class="nx">render</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="p">(</span>
</span><span class='line'>    <span class="o">&lt;</span><span class="nx">Popout</span> <span class="nx">title</span><span class="o">=</span><span class="s1">&#39;Window title&#39;</span> <span class="nx">onClosing</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">popupClosed</span><span class="p">}</span><span class="o">&gt;</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">type</span><span class="o">=</span><span class="s1">&#39;text&#39;</span> <span class="nx">onChange</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">textChanged</span><span class="p">}</span> <span class="o">/&gt;</span>
</span><span class='line'>      <span class="o">&lt;</span><span class="nx">input</span> <span class="nx">type</span><span class="o">=</span><span class="s1">&#39;button&#39;</span> <span class="nx">onClick</span><span class="o">=</span><span class="p">{</span><span class="k">this</span><span class="p">.</span><span class="nx">submit</span><span class="p">}</span> <span class="o">/&gt;</span>
</span><span class='line'>    <span class="o">&lt;</span><span class="err">/Popout&gt;</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>


<h3>Source and install</h3>

<blockquote><p>npm install react-popup &ndash;save</p></blockquote>

<p><a href="https://github.com/JakeGinnivan/react-popout">Source on GitHub</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Improving the carnac codebase and Rx usage (Part 3)]]></title>
    <link href="http://jake.ginnivan.net/blog/carnac-improvements/part-3/"/>
    <updated>2015-02-02T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/carnac-improvements/improving-carnacs-code-part-3</id>
    <content type="html"><![CDATA[<p>Parts one and two have covered the InterceptKeys class which exposes a feed of raw keyboard events and the MessageProvider which turns key presses into messages to display on the screen. There is a class between those two, the KeyProvider which I am not going to actually blog about as it doesn&rsquo;t introduce any new concepts which I have not covered in parts 1 and 2 of this blog series.</p>

<p><a href="http://jake.ginnivan.net/blog/carnac-improvements/part-1/">Part 1 - Refactoring the InterceptKeys class </a> <br/>
<a href="http://jake.ginnivan.net/blog/carnac-improvements/part-2/">Part 2 - Refactoring the MessageProvider class</a><br/>
Part 3 - Introducing the MessageController class<br/>
Part 4 - Removing state mutation from the stream</p>

<p>Instead we will dive into the MessageController class which brings the streams from the KeyProvider and MessageProvider together then maintains the list of Messages displayed on the screen. The requirements are:</p>

<ul>
<li>Add any new messages into the messages collection</li>
<li>After 5 seconds set a flag on the message which triggers an animation</li>
<li>1 second after that the message is removed from the messages collection</li>
<li>If a message is updated the 5 second countdown should start again.</li>
</ul>


<h2>Old implementation</h2>

<p>The previous implementation was quite simple but it was hard to test. Also Rx can solve this problem very nicely, so why not.</p>

<ul>
<li>New messages were added to the messages list</li>
<li>A timer fired once a second, the callback did:

<ul>
<li>A foreach loop over every item which had a LastUpdated property more than 5 seconds go, then set the IsDeleting flag to true</li>
<li>A foreach loop over every item which had a LastUpdated property more than 6 seconds go, then removed it from the list</li>
</ul>
</li>
</ul>


<p>Lets rewrite this into Rx</p>

<!-- more -->


<h1>Implementing in Rx</h1>

<h2>Messages stream</h2>

<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='csharp'><span class='line'><span class="n">IObservable</span><span class="p">&lt;</span><span class="n">KeyPress</span><span class="p">&gt;</span> <span class="n">keyStream</span> <span class="p">=</span> <span class="n">keyProvider</span><span class="p">.</span><span class="n">GetKeyStream</span><span class="p">();</span>
</span><span class='line'><span class="n">IObservable</span><span class="p">&lt;</span><span class="n">Message</span><span class="p">&gt;</span> <span class="n">messageStream</span> <span class="p">=</span> <span class="n">messageProvider</span><span class="p">.</span><span class="n">GetMessageStream</span><span class="p">(</span><span class="n">keyStream</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Step one is to get the messages subscription. Nothing much to see here except the variable names and types.</p>

<h2>Adding messages</h2>

<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='csharp'><span class='line'><span class="kt">var</span> <span class="n">addMessageSubscription</span> <span class="p">=</span> <span class="n">messageStream</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">message</span> <span class="p">=&gt;</span> <span class="n">messages</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">message</span><span class="p">));</span>
</span></code></pre></td></tr></table></div></figure>


<p>Also not much to see here, we subscribe to the messages stream and when a new value is yeilded we add that into the message into the messages collection.</p>

<h2>Fading messages out</h2>

<p>Now is where things become a little more interesting. Lets start off with simply setting the flag after 5 seconds</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageSubscription</span> <span class="p">=</span> <span class="n">messageStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Delay</span><span class="p">(</span><span class="n">FiveSeconds</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">m</span> <span class="p">=&gt;</span> <span class="n">m</span><span class="p">.</span><span class="n">IsDeleting</span> <span class="p">=</span> <span class="k">true</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Great, but this does not take into account the updates. Here is the problem we want to solve visualised.</p>

<p>Each - represents a second, | is a completed stream</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='csharp'><span class='line'><span class="n">a</span><span class="p">--------</span><span class="n">b</span><span class="p">---------</span><span class="n">a</span><span class="p">----*</span><span class="n">ab</span><span class="p">----</span>
</span><span class='line'><span class="p">-----</span><span class="n">a</span><span class="p">|</span>
</span><span class='line'>         <span class="p">-----</span><span class="n">b</span><span class="p">|</span>
</span><span class='line'>                   <span class="p">---------</span><span class="n">ab</span><span class="p">|</span>
</span><span class='line'><span class="p">-----</span><span class="n">a</span><span class="p">--------</span><span class="n">b</span><span class="p">-------------</span><span class="n">ab</span>
</span></code></pre></td></tr></table></div></figure>


<p>This shows us that we need a nested stream of some sort. Lets rewrite the fade out query into something that will create an inner stream.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageStream</span> <span class="p">=</span> <span class="n">messageStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">SelectMany</span><span class="p">(</span><span class="n">message</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="c1">// the inner stream goes here</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageSubscription</span> <span class="p">=</span> <span class="n">fadeOutMessageStream</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">m</span> <span class="p">=&gt;</span> <span class="n">m</span><span class="p">.</span><span class="n">IsDeleting</span> <span class="p">=</span> <span class="k">true</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we need to write the inner stream. Once again lets visualise the problem (x is an update, @ is the start of an observable.Timer(), o is the stream yeilding a value)</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='csharp'><span class='line'><span class="n">x</span><span class="p">---</span><span class="n">x</span><span class="p">----</span><span class="n">x</span><span class="p">-----</span>
</span><span class='line'><span class="err">@</span><span class="p">---|</span>
</span><span class='line'>    <span class="err">@</span><span class="p">----|</span>
</span><span class='line'>         <span class="err">@</span><span class="p">-----</span><span class="n">o</span><span class="p">|</span>
</span><span class='line'><span class="p">---------------</span><span class="n">x</span><span class="p">|</span>
</span></code></pre></td></tr></table></div></figure>


<p>The thing that is changing and we are reacting to in this query is the updates of the message. A message has a property with signature <code>IObservable&lt;Unit&gt; Updates { get; }</code> which we can subscribe to for updates to that message. We also want to kick off right away when we subscribe (otherwise the timer will not start until an update happens). With this in mind, the start of the inner query is:</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='csharp'><span class='line'><span class="k">return</span> <span class="n">message</span><span class="p">.</span><span class="n">Updated</span>
</span><span class='line'>    <span class="p">.</span><span class="n">StartWith</span><span class="p">(</span><span class="n">Unit</span><span class="p">.</span><span class="n">Default</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we need to introduce a timer of some sort. Because each update has it&rsquo;s own timeout we need another nested stream. The marble diagram shows the nested screen pattern off really nicely. To get the nested stream we just do a <code>.Select()</code> which give us:</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">return</span> <span class="n">message</span><span class="p">.</span><span class="n">Updated</span>
</span><span class='line'>    <span class="p">.</span><span class="n">StartWith</span><span class="p">(</span><span class="n">Unit</span><span class="p">.</span><span class="n">Default</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Timer</span><span class="p">(</span><span class="n">FiveSeconds</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>The return type of that select is actually <code>IObservable&lt;IObservable&lt;long&gt;&gt;</code> which is the nested stream. In the marble diagram above you will notice that when we get an update and start a timer we close the previous timer stream. In Rx this is known as the <code>.Switch()</code> statement. When the outer observable yeilds a new inner observable, switch will dispose the last inner observable and subscribe to the new stream instead. Now the code is:</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">return</span> <span class="n">message</span><span class="p">.</span><span class="n">Updated</span>
</span><span class='line'>    <span class="p">.</span><span class="n">StartWith</span><span class="p">(</span><span class="n">Unit</span><span class="p">.</span><span class="n">Default</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Timer</span><span class="p">(</span><span class="n">FiveSeconds</span><span class="p">))</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Switch</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>We are not finished yet, switch returns us a single stream of type <code>IObservable&lt;long&gt;</code>. We need a stream of messages 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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageStream</span> <span class="p">=</span> <span class="n">messageStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">SelectMany</span><span class="p">(</span><span class="n">message</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">message</span><span class="p">.</span><span class="n">Updated</span>
</span><span class='line'>            <span class="p">.</span><span class="n">StartWith</span><span class="p">(</span><span class="n">Unit</span><span class="p">.</span><span class="n">Default</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Timer</span><span class="p">(</span><span class="n">FiveSeconds</span><span class="p">))</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Switch</span><span class="p">()</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">message</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>We now are back showing the code which includes the outer stream. Our select we have just added simply ignores what it gets given and returns the message passed by the outer query.</p>

<p>Going back to our marble diagram you will notice there is one thing missing:</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='csharp'><span class='line'><span class="n">a</span><span class="p">--------</span><span class="n">b</span><span class="p">---------</span><span class="n">a</span><span class="p">----*</span><span class="n">ab</span><span class="p">----</span>
</span><span class='line'><span class="p">-----</span><span class="n">a</span><span class="p">|</span>
</span><span class='line'>         <span class="p">-----</span><span class="n">b</span><span class="p">|</span>
</span><span class='line'>                   <span class="p">---------</span><span class="n">ab</span><span class="p">|</span>
</span><span class='line'><span class="p">-----</span><span class="n">a</span><span class="p">--------</span><span class="n">b</span><span class="p">-------------</span><span class="n">ab</span>
</span></code></pre></td></tr></table></div></figure>


<p>After each inner stream yeilds a value, it immediately terminates. This is an easy fix, we just append <code>.Take(1)</code> to the inner query giving us:</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageStream</span> <span class="p">=</span> <span class="n">messageStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">SelectMany</span><span class="p">(</span><span class="n">message</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">message</span><span class="p">.</span><span class="n">Updated</span>
</span><span class='line'>            <span class="p">.</span><span class="n">StartWith</span><span class="p">(</span><span class="n">Unit</span><span class="p">.</span><span class="n">Default</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Timer</span><span class="p">(</span><span class="n">FiveSeconds</span><span class="p">))</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Switch</span><span class="p">()</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="n">message</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">Take</span><span class="p">(</span><span class="m">1</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="kt">var</span> <span class="n">fadeOutMessageSubscription</span> <span class="p">=</span> <span class="n">fadeOutMessageStream</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">m</span> <span class="p">=&gt;</span> <span class="n">m</span><span class="p">.</span><span class="n">IsDeleting</span> <span class="p">=</span> <span class="k">true</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Onto the <a href="https://www.youtube.com/watch?v=Rre3zgL7eMk#t=56">Next song</a></p>

<h2>Removing messages</h2>

<p>The nice thing about Rx is that you can just build on other streams. So we just take our <code>fadeOutMessageStream</code>, apply a 1 second delay then subscribe.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">removeMessageStream</span> <span class="p">=</span> <span class="n">fadeOutMessageStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Delay</span><span class="p">(</span><span class="n">OneSecond</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">m</span> <span class="p">=&gt;</span> <span class="n">messages</span><span class="p">.</span><span class="n">Remove</span><span class="p">(</span><span class="n">m</span><span class="p">));</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Next steps</h2>

<p>One thing all of these streams rely on is that each of them receive the <em>same instance</em> of each message. It is no good to us if each of them are working on a different messages. This is an easy fix using an operator we saw in Part 1 of this series, <code>.Publish()</code>.</p>

<p>But this time we will not use <code>.RefCount()</code> as we want to set up our queries then turn them on all at the same time, otherwise we have race conditions that messages might be added but never removed. We want all 3 of our subscriptions to start simultanously.</p>

<p>Lets zoom out to the method level and have a look what the <code>MessageController.Start</code> method looks like after we publish the stream.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">readonly</span> <span class="n">SerialDisposable</span> <span class="n">stopCarnacDisposable</span> <span class="p">=</span> <span class="k">new</span> <span class="n">SerialDisposable</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">Start</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">keyStream</span> <span class="p">=</span> <span class="n">keyProvider</span><span class="p">.</span><span class="n">GetKeyStream</span><span class="p">();</span>
</span><span class='line'>    <span class="n">IConnectableObservable</span><span class="p">&lt;</span><span class="n">Message</span><span class="p">&gt;</span> <span class="n">messageStream</span> <span class="p">=</span> <span class="n">messageProvider</span><span class="p">.</span><span class="n">GetMessageStream</span><span class="p">(</span><span class="n">keyStream</span><span class="p">).</span><span class="n">Publish</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">IDisposable</span> <span class="n">addMessageSubscription</span> <span class="p">=</span> <span class="p">...;</span>
</span><span class='line'>    <span class="n">IDisposable</span> <span class="n">fadeOutMessageSubscription</span> <span class="p">=</span> <span class="p">...;</span>
</span><span class='line'>    <span class="n">IDisposable</span> <span class="n">removeMessageSubscription</span> <span class="p">=</span> <span class="p">...;</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">IDisposable</span> <span class="n">underlyingMessageSubscription</span> <span class="p">=</span> <span class="n">messageStream</span><span class="p">.</span><span class="n">Connect</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">stopCarnacDisposable</span><span class="p">.</span><span class="n">Disposable</span> <span class="p">=</span> <span class="k">new</span> <span class="n">CompositeDisposable</span><span class="p">(</span>
</span><span class='line'>        <span class="n">underlyingMessageSubscription</span><span class="p">,</span>
</span><span class='line'>        <span class="n">addMessageSubscription</span><span class="p">,</span>
</span><span class='line'>        <span class="n">fadeOutMessageSubscription</span><span class="p">,</span>
</span><span class='line'>        <span class="n">removeMessageStream</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>MessageController</code> will use two different types of Rx Disposables. They are:</p>

<ul>
<li><code>SerialDisposable</code> - If the .Disposable property is set multiple times the current value is Disposed before it is updated to the latest value.
I use this so if <code>.Start</code> is called multiple times we will create a new subscription but it makes sure the previous subscription is disposed.</li>
<li><code>CompositeDisposable</code> - Takes any number of IDisposable&rsquo;s as constructor parameters, when it is disposed all disposables passed into the ctor will be disposed</li>
</ul>


<p>The new <code>CompositeDisposable</code> which takes all our of subscriptions is assigned to the <code>stopCarnacDisposable.Disposable</code> property before exiting the <code>Start</code> method. When the <code>MessageProvider</code> class is disposed <code>stopCarnacDisposable.Dispose()</code> will be called disposing any subscription which has been started by <code>Start</code>.</p>

<p>To walk through what we see above, I publish the message stream, create the three subscriptions and then I call <code>.Connect()</code> on the messageStream (which is now of type <code>IConnectableObservable&lt;Message&gt;</code>).</p>

<p>This allows me to explicitly control the underlying stream, when disposing I simply dispose the underlying stream then all of my other streams and everything is cleaned up nicely.</p>

<h3>Specifying Schedulers</h3>

<p>One part of the code I have ommited is explicitly specifying on what Scheduler everything will run on. I have introduced an <code>IConcurrencyService</code> which abstracts me from the static Rx schedulers (allowing me to write tests, which is coming up next!). When using Rx you should always specify what schedulers you want your code to run on, in carnac&rsquo;s case we want everything to run on the UI Thread. Normally this is bad but because we are modifying messages which are bound to by the UI we have to. Maybe a future blog post can be how we made carnacs Rx streams immutable, but not now.</p>

<p>We do that by adding these two lines before every <code>.Subscribe()</code> call in this class.</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='csharp'><span class='line'><span class="p">.</span><span class="n">ObserveOn</span><span class="p">(</span><span class="n">concurrencyService</span><span class="p">.</span><span class="n">MainThreadScheduler</span><span class="p">)</span>
</span><span class='line'><span class="p">.</span><span class="n">SubscribeOn</span><span class="p">(</span><span class="n">concurrencyService</span><span class="p">.</span><span class="n">MainThreadScheduler</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Error handling</h3>

<p>I wanted to call our error handling explicitly, carnac has <em>none</em>. It didn&rsquo;t before this refactor and it didn&rsquo;t after. There is a GitHub issue open at the time of writing this blog post to sort this out.</p>

<h2>Testing</h2>

<p>I mentioned at the start of this post that this would be easier to test, lets put that to the test and write some tests. First off the simplest case.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[Fact]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">MessagesAreAddedIntoKeysColletion</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">message</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Message</span><span class="p">(</span><span class="n">A</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">sut</span><span class="p">.</span><span class="n">Start</span><span class="p">();</span>
</span><span class='line'>    <span class="n">ProvideMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">keysCollection</span><span class="p">.</span><span class="n">ShouldContain</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'>    <span class="n">message</span><span class="p">.</span><span class="n">IsDeleting</span><span class="p">.</span><span class="n">ShouldBe</span><span class="p">(</span><span class="k">false</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>A is a property which returns a KeyPress and ProvideMessage simply yields that message to the messageStream which the KeyProvider subscribes to. Now we have an simple example test, here is a more complex 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>
<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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[Fact]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">MessagesAreFlaggedAsDeletingAfter5Seconds</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">message</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Message</span><span class="p">(</span><span class="n">A</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">sut</span><span class="p">.</span><span class="n">Start</span><span class="p">();</span>
</span><span class='line'>    <span class="n">ProvideMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'>    <span class="n">testScheduler</span><span class="p">.</span><span class="n">AdvanceBy</span><span class="p">(</span><span class="n">TimeSpan</span><span class="p">.</span><span class="n">FromSeconds</span><span class="p">(</span><span class="m">5</span><span class="p">).</span><span class="n">Ticks</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">message</span><span class="p">.</span><span class="n">IsDeleting</span><span class="p">.</span><span class="n">ShouldBe</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this test we have made use of our ICurrencyService by making it always return a <code>TestScheduler</code>. The <code>TestScheduler</code> is in the Rx.Testing NuGet library and is <strong>very</strong> useful. Because Rx abstracts time we can write tests which rely on time very quickly and they also execute very fast.</p>

<p>The above test provides a message to the messageStream and then moves time forward by 5 seconds and makes sure that our message has been flagged for deletion, which it has. Lets push this a little harder and make sure that we do not expire when that message has been updated.</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='csharp'><span class='line'><span class="na">[Fact]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">MessageTimeoutIsStartedAgainIfMessageIsUpdated</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">message</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Message</span><span class="p">(</span><span class="n">A</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">sut</span><span class="p">.</span><span class="n">Start</span><span class="p">();</span>
</span><span class='line'>    <span class="n">ProvideMessage</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'>    <span class="n">testScheduler</span><span class="p">.</span><span class="n">AdvanceBy</span><span class="p">(</span><span class="n">TimeSpan</span><span class="p">.</span><span class="n">FromSeconds</span><span class="p">(</span><span class="m">3</span><span class="p">).</span><span class="n">Ticks</span><span class="p">);</span>
</span><span class='line'>    <span class="n">message</span><span class="p">.</span><span class="n">Merge</span><span class="p">(</span><span class="k">new</span> <span class="n">Message</span><span class="p">(</span><span class="n">A</span><span class="p">));</span> <span class="c1">// Update message</span>
</span><span class='line'>    <span class="n">testScheduler</span><span class="p">.</span><span class="n">AdvanceBy</span><span class="p">(</span><span class="n">TimeSpan</span><span class="p">.</span><span class="n">FromSeconds</span><span class="p">(</span><span class="m">3</span><span class="p">).</span><span class="n">Ticks</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">message</span><span class="p">.</span><span class="n">IsDeleting</span><span class="p">.</span><span class="n">ShouldBe</span><span class="p">(</span><span class="k">false</span><span class="p">);</span>
</span><span class='line'>    <span class="n">keysCollection</span><span class="p">.</span><span class="n">ShouldContain</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see the code to test our Rx queries is really simply.</p>

<h1>Summary</h1>

<p>The MessageController is quite a small class and reasonably simple once you are familiar with Rx concepts but it has some interesting problems which many applications have and demonstrates how they can be easily solved and tested.</p>

<p>Part 4 will remove the mutation of existing messages from the stream. Any sort of mutation of state inside an Rx stream is likely to be a source of bugs and make the application very hard to reason about and debug. Unlike the first 3 posts in this series part 4 will be changing overall architecture and introducing some new concepts into the carnac codebase.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Improving the carnac codebase and Rx usage (Part 2)]]></title>
    <link href="http://jake.ginnivan.net/blog/carnac-improvements/part-2/"/>
    <updated>2015-02-01T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/carnac-improvements/improving-carnacs-code-part-2</id>
    <content type="html"><![CDATA[<p>This post is the second part in a series covering a series of improvements in the carnac codebase, specifically to improve the usage of Rx. The next class I will be rewriting is the MessageProvider.</p>

<p><a href="http://jake.ginnivan.net/blog/carnac-improvements/part-1/">Part 1 - Refactoring the InterceptKeys class</a><br/>
Part 2 - Refactoring the MessageProvider class<br/>
<a href="http://jake.ginnivan.net/blog/carnac-improvements/part-3/">Part 3 - Introducing the MessageController class</a><br/>
Part 4 - Removing state mutation from the stream</p>

<p>As a bit of background, in carnac a <code>KeyPress</code> is not directional and it also contains information about if modifiers were pressed at the same time. For Instance <code>ctrl + r</code> would be a KeyPress. A <code>Message</code> is what is shown on the screen.</p>

<p>The message provider as it is does the following:</p>

<ul>
<li>Is <code>IObserver&lt;KeyPress&gt;</code></li>
<li>It aggregates multiple KeyPresses into logical messages with the following rules:

<ul>
<li>Shortcuts are always shown in their own message</li>
<li>If there has been more than a second between the last keypress a new message is created</li>
<li>If the key presses were entered into different applications a new messsage is created</li>
</ul>
</li>
<li>Apply &lsquo;Only show shortcuts&rsquo; filter</li>
</ul>


<p>Here is what the code looked like before the refactor.</p>

<!-- more -->




<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>
<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>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
<span class='line-number'>64</span>
<span class='line-number'>65</span>
<span class='line-number'>66</span>
<span class='line-number'>67</span>
<span class='line-number'>68</span>
<span class='line-number'>69</span>
<span class='line-number'>70</span>
<span class='line-number'>71</span>
<span class='line-number'>72</span>
<span class='line-number'>73</span>
<span class='line-number'>74</span>
<span class='line-number'>75</span>
<span class='line-number'>76</span>
<span class='line-number'>77</span>
<span class='line-number'>78</span>
<span class='line-number'>79</span>
<span class='line-number'>80</span>
<span class='line-number'>81</span>
<span class='line-number'>82</span>
<span class='line-number'>83</span>
<span class='line-number'>84</span>
<span class='line-number'>85</span>
<span class='line-number'>86</span>
<span class='line-number'>87</span>
<span class='line-number'>88</span>
<span class='line-number'>89</span>
<span class='line-number'>90</span>
<span class='line-number'>91</span>
<span class='line-number'>92</span>
<span class='line-number'>93</span>
<span class='line-number'>94</span>
<span class='line-number'>95</span>
<span class='line-number'>96</span>
<span class='line-number'>97</span>
<span class='line-number'>98</span>
<span class='line-number'>99</span>
<span class='line-number'>100</span>
<span class='line-number'>101</span>
<span class='line-number'>102</span>
<span class='line-number'>103</span>
<span class='line-number'>104</span>
<span class='line-number'>105</span>
<span class='line-number'>106</span>
<span class='line-number'>107</span>
<span class='line-number'>108</span>
<span class='line-number'>109</span>
<span class='line-number'>110</span>
<span class='line-number'>111</span>
<span class='line-number'>112</span>
<span class='line-number'>113</span>
<span class='line-number'>114</span>
<span class='line-number'>115</span>
<span class='line-number'>116</span>
<span class='line-number'>117</span>
<span class='line-number'>118</span>
<span class='line-number'>119</span>
<span class='line-number'>120</span>
<span class='line-number'>121</span>
<span class='line-number'>122</span>
<span class='line-number'>123</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">MessageProvider</span> <span class="p">:</span> <span class="n">IMessageProvider</span><span class="p">,</span> <span class="n">IObserver</span><span class="p">&lt;</span><span class="n">KeyPress</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">readonly</span> <span class="n">Subject</span><span class="p">&lt;</span><span class="n">Message</span><span class="p">&gt;</span> <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Subject</span><span class="p">&lt;</span><span class="n">Message</span><span class="p">&gt;();</span>
</span><span class='line'>    <span class="k">private</span> <span class="k">readonly</span> <span class="n">IShortcutProvider</span> <span class="n">shortcutProvider</span><span class="p">;</span>
</span><span class='line'>    <span class="k">private</span> <span class="n">IDisposable</span> <span class="n">keyStream</span><span class="p">;</span>
</span><span class='line'>    <span class="k">private</span> <span class="k">readonly</span> <span class="n">PopupSettings</span> <span class="n">settings</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="nf">MessageProvider</span><span class="p">(</span><span class="n">IKeyProvider</span> <span class="n">keyProvider</span><span class="p">,</span> <span class="n">IShortcutProvider</span> <span class="n">shortcutProvider</span><span class="p">,</span> <span class="n">ISettingsProvider</span> <span class="n">settingsProvider</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">shortcutProvider</span> <span class="p">=</span> <span class="n">shortcutProvider</span><span class="p">;</span>
</span><span class='line'>        <span class="n">settings</span> <span class="p">=</span> <span class="n">settingsProvider</span><span class="p">.</span><span class="n">GetSettings</span><span class="p">&lt;</span><span class="n">PopupSettings</span><span class="p">&gt;();</span>
</span><span class='line'>        <span class="n">keyStream</span> <span class="p">=</span> <span class="n">keyProvider</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">Message</span> <span class="n">CurrentMessage</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">private</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">IDisposable</span> <span class="nf">Subscribe</span><span class="p">(</span><span class="n">IObserver</span><span class="p">&lt;</span><span class="n">Message</span><span class="p">&gt;</span> <span class="n">observer</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">subject</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">observer</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="k">void</span> <span class="nf">OnNext</span><span class="p">(</span><span class="n">KeyPress</span> <span class="k">value</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">Message</span> <span class="n">message</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="kt">var</span> <span class="n">currentKeyPress</span> <span class="p">=</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span><span class="k">value</span><span class="p">};</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">keyPresses</span> <span class="p">=</span> <span class="n">CurrentMessage</span> <span class="p">==</span> <span class="k">null</span> <span class="p">?</span> <span class="n">currentKeyPress</span> <span class="p">:</span> <span class="n">CurrentMessage</span><span class="p">.</span><span class="n">Keys</span><span class="p">.</span><span class="n">Concat</span><span class="p">(</span><span class="n">currentKeyPress</span><span class="p">).</span><span class="n">ToArray</span><span class="p">();</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">possibleShortcuts</span> <span class="p">=</span> <span class="n">GetPossibleShortcuts</span><span class="p">(</span><span class="n">keyPresses</span><span class="p">).</span><span class="n">ToList</span><span class="p">();</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">possibleShortcuts</span><span class="p">.</span><span class="n">Any</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">shortcut</span> <span class="p">=</span> <span class="n">possibleShortcuts</span><span class="p">.</span><span class="n">FirstOrDefault</span><span class="p">(</span><span class="n">s</span> <span class="p">=&gt;</span> <span class="n">s</span><span class="p">.</span><span class="n">IsMatch</span><span class="p">(</span><span class="n">keyPresses</span><span class="p">));</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">shortcut</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="n">message</span> <span class="p">=</span> <span class="n">CurrentMessage</span> <span class="p">??</span> <span class="n">CreateNewMessage</span><span class="p">(</span><span class="k">value</span><span class="p">);</span>
</span><span class='line'>                <span class="n">message</span><span class="p">.</span><span class="n">AddKey</span><span class="p">(</span><span class="k">value</span><span class="p">);</span>
</span><span class='line'>                <span class="n">message</span><span class="p">.</span><span class="n">ShortcutName</span> <span class="p">=</span> <span class="n">shortcut</span><span class="p">.</span><span class="n">Name</span><span class="p">;</span>
</span><span class='line'>                <span class="c1">//Have duplicated as it was easier for now, this should be cleaned up</span>
</span><span class='line'>                <span class="k">return</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="c1">// Haven&#39;t matched a Chord, try just the last keypress</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">keyShortcuts</span> <span class="p">=</span> <span class="n">GetPossibleShortcuts</span><span class="p">(</span><span class="n">currentKeyPress</span><span class="p">).</span><span class="n">ToList</span><span class="p">();</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">keyShortcuts</span><span class="p">.</span><span class="n">Any</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">shortcut</span> <span class="p">=</span> <span class="n">keyShortcuts</span><span class="p">.</span><span class="n">FirstOrDefault</span><span class="p">(</span><span class="n">s</span> <span class="p">=&gt;</span> <span class="n">s</span><span class="p">.</span><span class="n">IsMatch</span><span class="p">(</span><span class="n">currentKeyPress</span><span class="p">));</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">shortcut</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="c1">//For matching last keypress, we want a new message</span>
</span><span class='line'>                <span class="n">message</span> <span class="p">=</span> <span class="n">CreateNewMessage</span><span class="p">(</span><span class="k">value</span><span class="p">);</span>
</span><span class='line'>                <span class="n">message</span><span class="p">.</span><span class="n">AddKey</span><span class="p">(</span><span class="k">value</span><span class="p">);</span>
</span><span class='line'>                <span class="n">message</span><span class="p">.</span><span class="n">ShortcutName</span> <span class="p">=</span> <span class="n">shortcut</span><span class="p">.</span><span class="n">Name</span><span class="p">;</span>
</span><span class='line'>                <span class="c1">//Have duplicated as it was easier for now, this should be cleaned up</span>
</span><span class='line'>                <span class="k">return</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="k">if</span> <span class="p">(!</span><span class="k">value</span><span class="p">.</span><span class="n">IsShortcut</span> <span class="p">&amp;&amp;</span> <span class="n">settings</span><span class="p">.</span><span class="n">DetectShortcutsOnly</span><span class="p">)</span>
</span><span class='line'>            <span class="k">return</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">ShouldCreateNewMessage</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="n">message</span> <span class="p">=</span> <span class="n">CreateNewMessage</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">else</span>
</span><span class='line'>            <span class="n">message</span> <span class="p">=</span> <span class="n">CurrentMessage</span> <span class="p">??</span> <span class="n">CreateNewMessage</span><span class="p">(</span><span class="k">value</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">message</span><span class="p">.</span><span class="n">AddKey</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><span class='line'>    <span class="k">private</span> <span class="n">Message</span> <span class="nf">CreateNewMessage</span><span class="p">(</span><span class="n">KeyPress</span> <span class="k">value</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">message</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Message</span>
</span><span class='line'>                              <span class="p">{</span>
</span><span class='line'>                                  <span class="n">StartingTime</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">,</span>
</span><span class='line'>                                  <span class="n">ProcessName</span> <span class="p">=</span> <span class="k">value</span><span class="p">.</span><span class="n">Process</span><span class="p">.</span><span class="n">ProcessName</span>
</span><span class='line'>                              <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">CurrentMessage</span> <span class="p">=</span> <span class="n">message</span><span class="p">;</span>
</span><span class='line'>        <span class="n">subject</span><span class="p">.</span><span class="n">OnNext</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">message</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="kt">bool</span> <span class="nf">ShouldCreateNewMessage</span><span class="p">(</span><span class="n">KeyPress</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">return</span>
</span><span class='line'>            <span class="n">CurrentMessage</span> <span class="p">==</span> <span class="k">null</span> <span class="p">||</span>
</span><span class='line'>            <span class="n">IsDifferentProcess</span><span class="p">(</span><span class="k">value</span><span class="p">)</span> <span class="p">||</span>
</span><span class='line'>            <span class="n">IsOlderThanOneSecond</span><span class="p">()</span> <span class="p">||</span>
</span><span class='line'>            <span class="n">LastKeyPressWasShortcut</span><span class="p">()</span> <span class="p">||</span>
</span><span class='line'>            <span class="k">value</span><span class="p">.</span><span class="n">IsShortcut</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="kt">bool</span> <span class="nf">LastKeyPressWasShortcut</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">CurrentMessage</span><span class="p">.</span><span class="n">Keys</span><span class="p">.</span><span class="n">Last</span><span class="p">().</span><span class="n">IsShortcut</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">KeyShortcut</span><span class="p">&gt;</span> <span class="n">GetPossibleShortcuts</span><span class="p">(</span><span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">KeyPress</span><span class="p">&gt;</span> <span class="n">keyPresses</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">shortcutProvider</span><span class="p">.</span><span class="n">GetShortcutsMatching</span><span class="p">(</span><span class="n">keyPresses</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="kt">bool</span> <span class="nf">IsOlderThanOneSecond</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">CurrentMessage</span><span class="p">.</span><span class="n">LastMessage</span> <span class="p">&lt;</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="n">AddSeconds</span><span class="p">(-</span><span class="m">1</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="kt">bool</span> <span class="nf">IsDifferentProcess</span><span class="p">(</span><span class="n">KeyPress</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">return</span> <span class="n">CurrentMessage</span><span class="p">.</span><span class="n">ProcessName</span> <span class="p">!=</span> <span class="k">value</span><span class="p">.</span><span class="n">Process</span><span class="p">.</span><span class="n">ProcessName</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="k">void</span> <span class="nf">OnError</span><span class="p">(</span><span class="n">Exception</span> <span class="n">error</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="k">void</span> <span class="nf">OnCompleted</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>
</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 first thing you will notice is that most of the methods in this class access and manipulate the property <code>CurrentMessage</code>. This makes this class really hard to follow and rationalise what is going on.</p>

<h1>Removing <code>IObservable&lt;T&gt;</code></h1>

<p>Like in the previous class we refactored, the first thing we need to do is to stop implementing IObservable<T>.</p>

<p>Our subscribe method will change from <code>IDisposable Subscribe(IObserver&lt;Message&gt; observer)</code> to <code>IObservable&lt;Message&gt; GetMessageStream(IObservable&lt;KeyPress&gt; keyStream)</code></p>

<p>This means consumers of this class can simply pass an observable in and get a new feed. It also makes this class easy to test.</p>

<h1>Visualising the requirements</h1>

<p>After looking at the current behaviour I decided that it would make more sense to not show a partial shortcut on the screen until it had either been completed or broken. With that in mind, we will start off with a series of key presses. a, b, ctrl+r, ctrl+r, ctrl+r, a, ↓, ↓ (↓ is the down arrow key). For these examples imagine we have a single shortcut which is ctrl+r, ctrl+r.</p>

<p>If we draw an ascii marble diagram it will look 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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">a</span><span class="p">----</span><span class="n">b</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">a</span><span class="p">----</span><span class="err">↓</span><span class="p">----</span><span class="err">↓</span>
</span></code></pre></td></tr></table></div></figure>


<p>The first requirement is that we batch shortcuts into a single message.</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='csharp'><span class='line'><span class="n">a</span><span class="p">----</span><span class="n">b</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">a</span><span class="p">-----------</span><span class="err">↓</span><span class="p">---</span><span class="err">↓</span>
</span><span class='line'><span class="n">a</span><span class="p">----</span><span class="n">b</span><span class="p">--------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">,</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">-------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">--</span><span class="n">a</span><span class="p">---</span><span class="err">↓</span><span class="p">---</span><span class="err">↓</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the above diagram we see that ctrl+r, ctrl+r is a completed shortcut so our second stream emits the completed shortcut. But when we have ctrl+r, &lsquo;a&rsquo; that is not a shortcut. It is instead a broken shortcut so the second stream emits two messages, one directly after the other. a, b and the arrow keys emit a completed message right away because they are not part of any potential shortcuts.</p>

<p>The next step is to merge messages together which we want to display on the screen together. In the above example we want to see this on the screen:</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">ab</span>
</span><span class='line'><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">,</span> <span class="n">ctrl</span><span class="p">+</span><span class="n">r</span> <span class="p">[</span><span class="n">Rename</span><span class="p">]</span>
</span><span class='line'><span class="n">crtl</span><span class="p">+</span><span class="n">r</span>
</span><span class='line'><span class="n">a</span><span class="err">↓</span> <span class="n">x</span> <span class="m">2</span>
</span></code></pre></td></tr></table></div></figure>


<p>Lets add that into our marble diagram. Items prefixed with * are new messages which will replace the messages it has been merged with</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">a</span><span class="p">----</span><span class="n">b</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">----</span><span class="n">a</span><span class="p">-----------</span><span class="err">↓</span><span class="p">----</span><span class="err">↓</span><span class="p">-------</span>
</span><span class='line'><span class="n">a</span><span class="p">----</span><span class="n">b</span><span class="p">--------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">,</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">-------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">--</span><span class="n">a</span><span class="p">---</span><span class="err">↓</span><span class="p">----</span><span class="err">↓</span><span class="p">-------</span>
</span><span class='line'><span class="n">a</span><span class="p">----*</span><span class="n">ab</span><span class="p">------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">,</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">-------------</span><span class="n">ctrl</span><span class="p">+</span><span class="n">r</span><span class="p">--</span><span class="n">a</span><span class="p">---*</span><span class="n">a</span><span class="err">↓</span><span class="p">--*</span><span class="n">ab</span><span class="err">↓</span> <span class="n">x</span> <span class="m">2</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we have an idea visually of what our streams will look like we can turn this into Rx.</p>

<h1>Writing the query</h1>

<p>In Rx when we want to reduce the number of items we have where we need some sort of aggregation function. In this case we want to use the <code>.Scan()</code> operator.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">return</span> <span class="n">keyStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Scan</span><span class="p">(</span><span class="k">new</span> <span class="n">ShortcutAccumulator</span><span class="p">(),</span> <span class="p">(</span><span class="n">acc</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">acc</span><span class="p">.</span><span class="n">ProcessKey</span><span class="p">(</span><span class="n">shortcutProvider</span><span class="p">,</span> <span class="n">key</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">c</span> <span class="p">=&gt;</span> <span class="n">c</span><span class="p">.</span><span class="n">HasCompletedValue</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">SelectMany</span><span class="p">(</span><span class="n">acc</span> <span class="p">=&gt;</span> <span class="n">acc</span><span class="p">.</span><span class="n">GetMessages</span><span class="p">())</span>
</span></code></pre></td></tr></table></div></figure>


<p>Scan calls your accumulation function for each item in the stream, but unlike <code>Aggregate</code> it will emit the new aggregated value. In this case we start off with an empty <code>ShortcutAccumulator</code>, then the <code>keyStream</code> yields a value it is passed to the current <code>ShortcutAccumulator</code> which returns either itself or a new <code>ShortcutAccumulator</code> which <code>.Scan</code> will yield.</p>

<p>The ShortcutAccumulator will check if that key press matches any shortcuts. If it doesn&rsquo;t, or that key completes the shortcut, it sets the HasCompletedValue property to true and returns itself. When a completed accumulator is asked to process a key it will simply create a new <code>ShortcutAccumulator</code>and get it to process the key and return that accumulator instead of itself.</p>

<p>Because <code>.Scan</code> will emit the <code>ShortcutAccumulator</code> after each key press, we can simply filter the accumulators which are not completed yet, then select many on each completed ShortcutAccumulator to get the messages it has accumulated. The reason for the select many is when a shortcut is broken we create a message for each accumulated key press. And our stream now matches the second line in our marble diagram.</p>

<p>To do the final line in our marble diagram we need another <code>Scan</code> which merges Messages which need to be merged.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">return</span> <span class="n">keyStream</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Scan</span><span class="p">(</span><span class="k">new</span> <span class="n">ShortcutAccumulator</span><span class="p">(),</span> <span class="p">(</span><span class="n">acc</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">acc</span><span class="p">.</span><span class="n">ProcessKey</span><span class="p">(</span><span class="n">shortcutProvider</span><span class="p">,</span> <span class="n">key</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">c</span> <span class="p">=&gt;</span> <span class="n">c</span><span class="p">.</span><span class="n">HasCompletedValue</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">SelectMany</span><span class="p">(</span><span class="n">c</span> <span class="p">=&gt;</span> <span class="n">c</span><span class="p">.</span><span class="n">GetMessages</span><span class="p">())</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Scan</span><span class="p">(</span><span class="k">new</span> <span class="n">Message</span><span class="p">(),</span> <span class="p">(</span><span class="n">previousMessage</span><span class="p">,</span> <span class="n">newMessage</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">messageMerger</span><span class="p">.</span><span class="n">MergeIfNeeded</span><span class="p">(</span><span class="n">previousMessage</span><span class="p">,</span> <span class="n">newMessage</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">m</span> <span class="p">=&gt;</span> <span class="p">!</span><span class="n">settings</span><span class="p">.</span><span class="n">DetectShortcutsOnly</span> <span class="p">||</span> <span class="n">m</span><span class="p">.</span><span class="n">IsShortcut</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Whether a message needs to be merged or not is no longer the responsibility of this class, it has been moved into our <code>MessageMerger</code> class. <code>MergeIfNeeded</code> will check for all the merge conditions like the key presses being over a second apart, from different processes, either message being a shortcut etc and if they can be merged the new message will be merged into the previous. Ideally our entire stream would be immutable but that will have to be a separate task, we are refactoring existing code after all.</p>

<p>Finally we apply the Shortcut Only setting and filter our list if that option is set.</p>

<h1>Summary</h1>

<p>The end result of the <code>MessageProvider</code> refactoring was a great improvement. The end result is a single method returning an Rx statement which forfills all of our requirements. The shortcut detection logic was moved into another class which has a single responsibility making it much easier to understand what is going on and follow.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Improving the carnac codebase and Rx usage (Part 1)]]></title>
    <link href="http://jake.ginnivan.net/blog/carnac-improvements/part-1/"/>
    <updated>2015-01-31T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/carnac-improvements/improving-carnacs-code</id>
    <content type="html"><![CDATA[<p><a href="http://carnackeys.com/">Carnac</a> is an open source project created as part of <a href="http://code52.org/">Code52</a>. It is a simple utility which overlays key presses on your screen as you type which is pretty handy for presentations. Carnac also ships with some keymaps for different applications so it understands when you are pressing shortcuts.</p>

<p>Recently Scott Hanselman blogged about a <a href="http://www.hanselman.com/blog/QuakeModeConsoleForVisualStudioOpenACommandPromptWithAHotkey.aspx">Quake Mode console</a> and mentioned carnac, this triggered Brendan Forster and myself to think about carnac again. When we started writing carnac there was not any Rx experience amongst the team and we did a pretty bad job. I think carnac is a <em>great</em> Rx problem and the code can be improved to take advantage of Rx and be a really good non-trivial Rx sample.
This blog series is all about the things we did wrong and the process I went through to refactor carnac into a much simpler code base and really leverage the power of Rx.</p>

<p>Part 1 - Refactoring the InterceptKeys class<br/>
<a href="http://jake.ginnivan.net/blog/carnac-improvements/part-2/">Part 2 - Refactoring the MessageProvider class</a><br/>
<a href="http://jake.ginnivan.net/blog/carnac-improvements/part-3/">Part 3 - Introducing the MessageController class</a><br/>
Part 4 - Removing state mutation from the stream</p>

<!-- more -->


<h1>Fixing the InterceptKeys class</h1>

<p>Carnac uses windows low level keyboard hooks to listen to key pressess. We have a class called <code>InterceptKeys</code> which is responsible for giving us an Rx stream of KeyEvents. This includes direction so if you press <code>ctrl+r</code> the stream would look like this:</p>

<ul>
<li>ctrl (down)</li>
<li>r (down)</li>
<li>r (up)</li>
<li>ctrl (up)</li>
</ul>


<p>That is all this class has to do. The only other thing to note is <code>InterceptKeys</code> is a singleton and should only ever have a single low level keyboard hook created.</p>

<p>Here is the original 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>
<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>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
<span class='line-number'>64</span>
<span class='line-number'>65</span>
<span class='line-number'>66</span>
<span class='line-number'>67</span>
<span class='line-number'>68</span>
<span class='line-number'>69</span>
<span class='line-number'>70</span>
<span class='line-number'>71</span>
<span class='line-number'>72</span>
<span class='line-number'>73</span>
<span class='line-number'>74</span>
<span class='line-number'>75</span>
<span class='line-number'>76</span>
<span class='line-number'>77</span>
<span class='line-number'>78</span>
<span class='line-number'>79</span>
<span class='line-number'>80</span>
<span class='line-number'>81</span>
<span class='line-number'>82</span>
<span class='line-number'>83</span>
<span class='line-number'>84</span>
<span class='line-number'>85</span>
<span class='line-number'>86</span>
<span class='line-number'>87</span>
<span class='line-number'>88</span>
<span class='line-number'>89</span>
<span class='line-number'>90</span>
<span class='line-number'>91</span>
<span class='line-number'>92</span>
<span class='line-number'>93</span>
<span class='line-number'>94</span>
<span class='line-number'>95</span>
<span class='line-number'>96</span>
<span class='line-number'>97</span>
<span class='line-number'>98</span>
<span class='line-number'>99</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[PermissionSet(SecurityAction.LinkDemand, Name = &quot;FullTrust&quot;)]</span>
</span><span class='line'><span class="na">[PermissionSet(SecurityAction.InheritanceDemand, Name=&quot;FullTrust&quot;)]</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">InterceptKeys</span> <span class="p">:</span> <span class="n">IObservable</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;,</span> <span class="n">IDisposable</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">static</span> <span class="n">InterceptKeys</span> <span class="n">current</span> <span class="p">=</span> <span class="k">new</span> <span class="n">InterceptKeys</span><span class="p">();</span>
</span><span class='line'>    <span class="k">readonly</span> <span class="n">Win32Methods</span><span class="p">.</span><span class="n">LowLevelKeyboardProc</span> <span class="n">callback</span><span class="p">;</span>
</span><span class='line'>    <span class="k">readonly</span> <span class="n">Subject</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;</span> <span class="n">subject</span><span class="p">;</span>
</span><span class='line'>    <span class="kt">bool</span> <span class="n">disposed</span><span class="p">;</span>
</span><span class='line'>    <span class="n">IntPtr</span> <span class="n">hookId</span> <span class="p">=</span> <span class="n">IntPtr</span><span class="p">.</span><span class="n">Zero</span><span class="p">;</span>
</span><span class='line'>    <span class="kt">decimal</span> <span class="n">subscriberCount</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">InterceptKeys</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">subject</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Subject</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;();</span>
</span><span class='line'>        <span class="n">callback</span> <span class="p">=</span> <span class="n">HookCallback</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="k">static</span> <span class="n">InterceptKeys</span> <span class="n">Current</span> <span class="p">{</span> <span class="k">return</span> <span class="n">current</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">Dispose</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
</span><span class='line'>        <span class="n">GC</span><span class="p">.</span><span class="n">SuppressFinalize</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">IDisposable</span> <span class="nf">Subscribe</span><span class="p">(</span><span class="n">IObserver</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;</span> <span class="n">observer</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">IDisposable</span> <span class="n">dispose</span> <span class="p">=</span> <span class="n">subject</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">observer</span><span class="p">);</span>
</span><span class='line'>        <span class="n">subscriberCount</span><span class="p">++;</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">subscriberCount</span> <span class="p">==</span> <span class="m">1</span><span class="p">)</span>
</span><span class='line'>            <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>        <span class="k">return</span> <span class="k">new</span> <span class="nf">DelegateDisposable</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>                                          <span class="p">{</span>
</span><span class='line'>                                              <span class="n">subscriberCount</span><span class="p">--;</span>
</span><span class='line'>                                              <span class="k">if</span> <span class="p">(</span><span class="n">subscriberCount</span> <span class="p">==</span> <span class="m">0</span><span class="p">)</span>
</span><span class='line'>                                                  <span class="n">Win32Methods</span><span class="p">.</span><span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>                                              <span class="n">dispose</span><span class="p">.</span><span class="n">Dispose</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">IntPtr</span> <span class="nf">HookCallback</span><span class="p">(</span><span class="kt">int</span> <span class="n">nCode</span><span class="p">,</span> <span class="n">IntPtr</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">IntPtr</span> <span class="n">lParam</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">nCode</span> <span class="p">&gt;=</span> <span class="m">0</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="cm">/* snip, not really important, just calculating the variabless used below. */</span>
</span><span class='line'>
</span><span class='line'>            <span class="kt">var</span> <span class="n">interceptKeyEventArgs</span> <span class="p">=</span> <span class="k">new</span> <span class="n">InterceptKeyEventArgs</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">keyDirection</span><span class="p">,</span> <span class="n">alt</span><span class="p">,</span> <span class="n">control</span><span class="p">,</span> <span class="n">shift</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="n">subject</span><span class="p">.</span><span class="n">OnNext</span><span class="p">(</span><span class="n">interceptKeyEventArgs</span><span class="p">);</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">interceptKeyEventArgs</span><span class="p">.</span><span class="n">Handled</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="k">return</span> <span class="p">(</span><span class="n">IntPtr</span><span class="p">)</span><span class="m">1</span><span class="p">;</span> <span class="c1">//handled</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="k">return</span> <span class="n">Win32Methods</span><span class="p">.</span><span class="n">CallNextHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">,</span> <span class="n">nCode</span><span class="p">,</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">static</span> <span class="n">IntPtr</span> <span class="nf">SetHook</span><span class="p">(</span><span class="n">Win32Methods</span><span class="p">.</span><span class="n">LowLevelKeyboardProc</span> <span class="n">proc</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">using</span> <span class="p">(</span><span class="n">Process</span> <span class="n">curProcess</span> <span class="p">=</span> <span class="n">Process</span><span class="p">.</span><span class="n">GetCurrentProcess</span><span class="p">())</span>
</span><span class='line'>        <span class="k">using</span> <span class="p">(</span><span class="n">ProcessModule</span> <span class="n">curModule</span> <span class="p">=</span> <span class="n">curProcess</span><span class="p">.</span><span class="n">MainModule</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">Win32Methods</span><span class="p">.</span><span class="n">SetWindowsHookEx</span><span class="p">(</span><span class="n">Win32Methods</span><span class="p">.</span><span class="n">WH_KEYBOARD_LL</span><span class="p">,</span> <span class="n">proc</span><span class="p">,</span>
</span><span class='line'>                                                  <span class="n">Win32Methods</span><span class="p">.</span><span class="n">GetModuleHandle</span><span class="p">(</span><span class="n">curModule</span><span class="p">.</span><span class="n">ModuleName</span><span class="p">),</span> <span class="m">0</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="k">protected</span> <span class="k">virtual</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">(</span><span class="kt">bool</span> <span class="n">disposing</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(!</span><span class="n">disposed</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">disposing</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="k">if</span> <span class="p">(</span><span class="n">subject</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
</span><span class='line'>                <span class="p">{</span>
</span><span class='line'>                    <span class="n">subject</span><span class="p">.</span><span class="n">Dispose</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">disposed</span> <span class="p">=</span> <span class="k">true</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="k">class</span> <span class="nc">DelegateDisposable</span> <span class="p">:</span> <span class="n">IDisposable</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">readonly</span> <span class="n">Action</span> <span class="n">dispose</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">public</span> <span class="nf">DelegateDisposable</span><span class="p">(</span><span class="n">Action</span> <span class="n">dispose</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">dispose</span> <span class="p">=</span> <span class="n">dispose</span><span class="p">;</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">public</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">()</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="n">dispose</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></code></pre></td></tr></table></div></figure>


<p>There are a lot of things we did wrong, lets look at them one at a time.</p>

<h1>DelegateDisposable class</h1>

<p>This is a simple win. Rx comes with a <em>heap</em> of really useful disposable types. We can delete our nested DelegateDisposable class and replace it&rsquo;s usage with <code>Disposable.Create()</code>. Quite an easy win.</p>

<h1>Implementing IObservable<InterceptKeyEventArgs></h1>

<p>When using Rx you should never have to implement <code>IObservable&lt;T&gt;</code> or <code>IObserver&lt;T&gt;</code>. If you do then you should be looking for a better way to do it.</p>

<p>Because we are implementing <code>IObservable</code> we have to provide a <code>.Subscribe</code> method. Lets have a look at that.</p>

<pre><code>public IDisposable Subscribe(IObserver&lt;InterceptKeyEventArgs&gt; observer)
{
    IDisposable dispose = subject.Subscribe(observer);
    subscriberCount++;
    if (subscriberCount == 1)
        hookId = SetHook(callback);
    return Disposable.Create(() =&gt;
                      {
                          subscriberCount--;
                          if (subscriberCount == 0)
                              Win32Methods.UnhookWindowsHookEx(hookId);
                          dispose.Dispose();
                      });
}
</code></pre>

<p>The first side effect of this is that we have to do subscription management ourselves now! The good news is we can make a very simple change to improve this.</p>

<ol>
<li>No longer inherit from <code>IObservable&lt;InterceptKeyEventArgs&gt;</code></li>
<li>Rename subscribe to <code>GetKeyStream</code> with this signature:<br/>
<code>IObservable&lt;InterceptKeyEventArgs&gt; GetKeyStream()</code></li>
<li>Make it compile again.</li>
</ol>


<p>To make it compile we need to create the observable that we are going to return. We will do that in the contructor of <code>InterceptKeys</code> so we always return the same observable to all callers (remember <code>InterceptKeys</code> is a singleton).</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">InterceptKeys</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">keyStream</span> <span class="p">=</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;(</span><span class="n">observer</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">dispose</span> <span class="p">=</span> <span class="n">subject</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">observer</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="n">Disposable</span><span class="p">.</span><span class="n">Create</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="n">Win32Methods</span><span class="p">.</span><span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>            <span class="n">dispose</span><span class="p">.</span><span class="n">Dispose</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 class="n">Publish</span><span class="p">().</span><span class="n">RefCount</span><span class="p">();</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">public</span> <span class="n">IObservable</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;</span> <span class="n">GetKeyStream</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">keyStream</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Ok this is looking better! We no longer are doing subscription management ourself. Lets look at the new Rx features we have used.</p>

<h3>Observable.Create</h3>

<p>If you ever need an observable, it is likely you want to use a static method off the <code>Observable</code> class. <code>Observable.Create</code> passes us an observable which we can call <code>.OnNext()</code>, <code>.OnError()</code> or <code>.OnComplete()</code> on to yield new values to any subscribers.</p>

<p>You then return an <code>IDisposable</code> which is called when the subscription is disposed by the subscriber.</p>

<h3>Publish()</h3>

<p>The next new thing is the <code>.Publish</code> extension method which is actually just a helper which calls the <code>.Multicast(Subject&lt;T&gt;)</code> extension. Multicast takes a subject (which is both a observer and an observable) and returns an <code>IConnectableObservable&lt;T&gt;</code>. When you subscribe to a connectable observable you are actually subscribing to the subject you passed into <code>.Multicast()</code>. <code>IConnectableObservable&lt;T&gt;</code> has a method called <code>Connect</code> on it, when you call connect it subscribes to the feed which you called <code>Multicast</code> on and passes in your Subject as the observer.</p>

<p>In effect <code>Multicast</code> means all subscribers actually share a single subscription, the subject simply determines the behaviour. Here are three examples:</p>

<ul>
<li><code>.Publish()</code> = <code>.Multicast(new Subject&lt;T&gt;)</code></li>
<li><code>.PublishLast()</code> = <code>.Multicast(new AsyncSubject&lt;T&gt;)</code></li>
<li><code>.Replay()</code> = <code>.Multicast(new ReplaySubject&lt;T&gt;)</code></li>
</ul>


<p>As a quick 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>
<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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">observable</span> <span class="p">=</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;(</span><span class="n">observer</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">Debug</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">&#39;</span><span class="n">Subscribed</span><span class="err">&#39;</span><span class="p">);</span>
</span><span class='line'>        <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">dispose</span> <span class="p">=</span> <span class="n">subject</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">observer</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="n">Disposable</span><span class="p">.</span><span class="n">Create</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="n">Debug</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">&#39;</span><span class="n">Unsubscribed</span><span class="err">&#39;</span><span class="p">);</span>
</span><span class='line'>            <span class="n">Win32Methods</span><span class="p">.</span><span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>            <span class="n">dispose</span><span class="p">.</span><span class="n">Dispose</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="c1">// Without Publish</span>
</span><span class='line'><span class="kt">var</span> <span class="n">subscription</span> <span class="p">=</span> <span class="n">observable</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="p">});</span> <span class="c1">// Prints &#39;Subscribed&#39;</span>
</span><span class='line'><span class="n">subscription</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span> <span class="c1">// Prints &#39;Unsubscribed&#39;</span>
</span><span class='line'><span class="kt">var</span> <span class="n">subscription2</span> <span class="p">=</span> <span class="n">observable</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="p">});</span> <span class="c1">// Prints &#39;Subscribed&#39;</span>
</span><span class='line'><span class="n">subscription2</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span> <span class="c1">// Prints &#39;Unsubscribed&#39;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// With Publish</span>
</span><span class='line'><span class="kt">var</span> <span class="n">published</span> <span class="p">=</span> <span class="n">observable</span><span class="p">.</span><span class="n">Publish</span><span class="p">();</span>
</span><span class='line'><span class="kt">var</span> <span class="n">subscription</span> <span class="p">=</span> <span class="n">published</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="p">});</span>
</span><span class='line'><span class="kt">var</span> <span class="n">subscription2</span> <span class="p">=</span> <span class="n">published</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">_</span> <span class="p">=&gt;</span> <span class="p">{</span> <span class="p">});</span>
</span><span class='line'><span class="kt">var</span> <span class="n">underlyingSubscription</span> <span class="p">=</span> <span class="n">observable</span><span class="p">.</span><span class="n">Connect</span><span class="p">();</span>   <span class="c1">// Prints &#39;Subscribed&#39;</span>
</span><span class='line'><span class="n">subscription</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span>
</span><span class='line'><span class="n">subscription2</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span>
</span><span class='line'><span class="n">underlyingSubscription</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span>  <span class="c1">// Prints &#39;Unsubscribed&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<h3>RefCount()</h3>

<p>Most of the time you do not want to manage the connection/disconnection of a connected observable yourself. This is where <code>RefCount</code> extension method comes in. It simply counts the number of subscribers and when the observable has subscribers it connects the underlying Published observable. Once all subscribers have Disposed it will disconnect the Published observable.</p>

<p>Now Rx is fully managing our subscriptions and will make sure we only ever have a single low-level keyboard hook!</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">observable</span> <span class="p">=</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;(</span><span class="n">observer</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">Debug</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">&#39;</span><span class="n">Subscribed</span><span class="err">&#39;</span><span class="p">);</span>
</span><span class='line'>        <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>        <span class="kt">var</span> <span class="n">dispose</span> <span class="p">=</span> <span class="n">subject</span><span class="p">.</span><span class="n">Subscribe</span><span class="p">(</span><span class="n">observer</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="n">Disposable</span><span class="p">.</span><span class="n">Create</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="n">Debug</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="err">&#39;</span><span class="n">Unsubscribed</span><span class="err">&#39;</span><span class="p">);</span>
</span><span class='line'>            <span class="n">Win32Methods</span><span class="p">.</span><span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>            <span class="n">dispose</span><span class="p">.</span><span class="n">Dispose</span><span class="p">();</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>    <span class="p">}).</span><span class="n">Publish</span><span class="p">().</span><span class="n">RefCount</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Cleanup</h2>

<p>Now that we have made this change, what else can be cleaned up?</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">decimal</span> <span class="n">subscriberCount</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">Dispose</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
</span><span class='line'>    <span class="n">GC</span><span class="p">.</span><span class="n">SuppressFinalize</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">protected</span> <span class="k">virtual</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">(</span><span class="kt">bool</span> <span class="n">disposing</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(!</span><span class="n">disposed</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">disposing</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">subject</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="n">subject</span><span class="p">.</span><span class="n">Dispose</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">disposed</span> <span class="p">=</span> <span class="k">true</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>We can delete all of this code now.</p>

<h1>Using <code>Subject&lt;InterceptKeyEventArgs&gt;</code></h1>

<p>The next warning sign we should be looking for in our Rx code is the use of Subjects. A subject is both a <code>IObservable&lt;T&gt;</code> AND an <code>IObserver&lt;T&gt;</code>. In this case we have a subject stored in a field which the Low Level Keyboard hook publishes to, inside our keyStream observable we have subscribed to the subject using the observer that <code>Observable.Create</code> gave to us.</p>

<p>To do this we have to move the low level keyboard hook into our <code>Observable.Create</code> so it can publish directly to the observer Rx has created us.</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>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">keyStream</span> <span class="p">=</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;(</span><span class="n">observer</span> <span class="p">=&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">Debug</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Subscribed to keys&quot;</span><span class="p">);</span>
</span><span class='line'>    <span class="n">IntPtr</span> <span class="n">hookId</span> <span class="p">=</span> <span class="n">IntPtr</span><span class="p">.</span><span class="n">Zero</span><span class="p">;</span>
</span><span class='line'>    <span class="c1">// Need to hold onto this callback, otherwise it will get GC&#39;d as it is an unmanged callback</span>
</span><span class='line'>    <span class="n">callback</span> <span class="p">=</span> <span class="p">(</span><span class="n">nCode</span><span class="p">,</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">)</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="n">nCode</span> <span class="p">&gt;=</span> <span class="m">0</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">eventArgs</span> <span class="p">=</span> <span class="n">CreateEventArgs</span><span class="p">(</span><span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">);</span>
</span><span class='line'>            <span class="n">observer</span><span class="p">.</span><span class="n">OnNext</span><span class="p">(</span><span class="n">eventArgs</span><span class="p">);</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="n">eventArgs</span><span class="p">.</span><span class="n">Handled</span><span class="p">)</span>
</span><span class='line'>                <span class="k">return</span> <span class="p">(</span><span class="n">IntPtr</span><span class="p">)</span><span class="m">1</span><span class="p">;</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="nf">CallNextHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">,</span> <span class="n">nCode</span><span class="p">,</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>    <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">Disposable</span><span class="p">.</span><span class="n">Create</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">Debug</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Unsubscribed from keys&quot;</span><span class="p">);</span>
</span><span class='line'>        <span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>        <span class="n">callback</span> <span class="p">=</span> <span class="k">null</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 class="n">Publish</span><span class="p">().</span><span class="n">RefCount</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is not the nicest code because of the API of <code>SetWindowsHookEx</code> but we have removed our Subject and the code is far easier to understand now.</p>

<h1>Summary</h1>

<p>After those refactorings we have a far more maintainable class and we have removed a number of Rx anti-patterns. This is what the class looks like after those refactorings:</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>
<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>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[PermissionSet(SecurityAction.LinkDemand, Name = &quot;FullTrust&quot;)]</span>
</span><span class='line'><span class="na">[PermissionSet(SecurityAction.InheritanceDemand, Name = &quot;FullTrust&quot;)]</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">InterceptKeys</span> <span class="p">:</span> <span class="n">IInterceptKeys</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">public</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">InterceptKeys</span> <span class="n">Current</span> <span class="p">=</span> <span class="k">new</span> <span class="n">InterceptKeys</span><span class="p">();</span>
</span><span class='line'>    <span class="n">LowLevelKeyboardProc</span> <span class="n">callback</span><span class="p">;</span>
</span><span class='line'>    <span class="k">readonly</span> <span class="n">IObservable</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;</span> <span class="n">keyStream</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="nf">InterceptKeys</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="n">keyStream</span> <span class="p">=</span> <span class="n">Observable</span><span class="p">.</span><span class="n">Create</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;(</span><span class="n">observer</span> <span class="p">=&gt;</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="n">Debug</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Subscribed to keys&quot;</span><span class="p">);</span>
</span><span class='line'>            <span class="n">IntPtr</span> <span class="n">hookId</span> <span class="p">=</span> <span class="n">IntPtr</span><span class="p">.</span><span class="n">Zero</span><span class="p">;</span>
</span><span class='line'>            <span class="c1">// Need to hold onto this callback, otherwise it will get GC&#39;d as it is an unmanged callback</span>
</span><span class='line'>            <span class="n">callback</span> <span class="p">=</span> <span class="p">(</span><span class="n">nCode</span><span class="p">,</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">)</span> <span class="p">=&gt;</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="k">if</span> <span class="p">(</span><span class="n">nCode</span> <span class="p">&gt;=</span> <span class="m">0</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">eventArgs</span> <span class="p">=</span> <span class="n">CreateEventArgs</span><span class="p">(</span><span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">);</span>
</span><span class='line'>                    <span class="n">observer</span><span class="p">.</span><span class="n">OnNext</span><span class="p">(</span><span class="n">eventArgs</span><span class="p">);</span>
</span><span class='line'>                    <span class="k">if</span> <span class="p">(</span><span class="n">eventArgs</span><span class="p">.</span><span class="n">Handled</span><span class="p">)</span>
</span><span class='line'>                        <span class="k">return</span> <span class="p">(</span><span class="n">IntPtr</span><span class="p">)</span><span class="m">1</span><span class="p">;</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>                <span class="k">return</span> <span class="nf">CallNextHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">,</span> <span class="n">nCode</span><span class="p">,</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">lParam</span><span class="p">);</span>
</span><span class='line'>            <span class="p">};</span>
</span><span class='line'>            <span class="n">hookId</span> <span class="p">=</span> <span class="n">SetHook</span><span class="p">(</span><span class="n">callback</span><span class="p">);</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">Disposable</span><span class="p">.</span><span class="n">Create</span><span class="p">(()</span> <span class="p">=&gt;</span>
</span><span class='line'>            <span class="p">{</span>
</span><span class='line'>                <span class="n">Debug</span><span class="p">.</span><span class="n">Write</span><span class="p">(</span><span class="s">&quot;Unsubscribed from keys&quot;</span><span class="p">);</span>
</span><span class='line'>                <span class="n">UnhookWindowsHookEx</span><span class="p">(</span><span class="n">hookId</span><span class="p">);</span>
</span><span class='line'>                <span class="n">callback</span> <span class="p">=</span> <span class="k">null</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 class="n">Publish</span><span class="p">().</span><span class="n">RefCount</span><span class="p">();</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">IObservable</span><span class="p">&lt;</span><span class="n">InterceptKeyEventArgs</span><span class="p">&gt;</span> <span class="n">GetKeyStream</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">keyStream</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">InterceptKeyEventArgs</span> <span class="nf">CreateEventArgs</span><span class="p">(</span><span class="n">IntPtr</span> <span class="n">wParam</span><span class="p">,</span> <span class="n">IntPtr</span> <span class="n">lParam</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="cm">/* snip, not really important, just calculating the variabless used below. */</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="k">new</span> <span class="nf">InterceptKeyEventArgs</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">keyDirection</span><span class="p">,</span> <span class="n">alt</span><span class="p">,</span> <span class="n">control</span><span class="p">,</span> <span class="n">shift</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">static</span> <span class="n">IntPtr</span> <span class="nf">SetHook</span><span class="p">(</span><span class="n">LowLevelKeyboardProc</span> <span class="n">proc</span><span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="c1">//TODO: This requires FullTrust to use the Process class - is there any options for doing this in MediumTrust?</span>
</span><span class='line'>        <span class="c1">//</span>
</span><span class='line'>        <span class="k">using</span> <span class="p">(</span><span class="n">Process</span> <span class="n">curProcess</span> <span class="p">=</span> <span class="n">Process</span><span class="p">.</span><span class="n">GetCurrentProcess</span><span class="p">())</span>
</span><span class='line'>        <span class="k">using</span> <span class="p">(</span><span class="n">ProcessModule</span> <span class="n">curModule</span> <span class="p">=</span> <span class="n">curProcess</span><span class="p">.</span><span class="n">MainModule</span><span class="p">)</span>
</span><span class='line'>        <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="nf">SetWindowsHookEx</span><span class="p">(</span><span class="n">WH_KEYBOARD_LL</span><span class="p">,</span> <span class="n">proc</span><span class="p">,</span> <span class="n">GetModuleHandle</span><span class="p">(</span><span class="n">curModule</span><span class="p">.</span><span class="n">ModuleName</span><span class="p">),</span> <span class="m">0</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></code></pre></td></tr></table></div></figure>


<p>Pretty good result in the end. We have reduced this file from 224 lines of code to 100 lines by not implmenting IObservable<T> ourselves, letting Rx manage our subscriptions (with <code>.Publish().RefCount()</code>) and making sure we use types provided by Rx (<code>Disposable.Create</code> instead of our own type).</p>

<p>Next in this series we will be rewriting the class which takes key presses (ctrl + f, a, b, space etc) and turns it into the messages carnac shows on the screen.</p>

<p><a href="http://jake.ginnivan.net/blog/carnac-improvements/part-2/">Check out part 2</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My Typical TeamCity build Setup]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/07/09/my-typical-teamcity-build-setup/"/>
    <updated>2014-07-09T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/07/09/my-typical-teamcity-build-setup</id>
    <content type="html"><![CDATA[<p>I posted <a href="http://jake.ginnivan.net/blog/2014/05/25/simple-versioning-and-release-notes/">Simple Versioning and Release Notes</a> a few weeks ago talking about how to simplify release notes and versioning. This post is a bit of a cheat sheet for how I set up my builds.</p>

<h2>Structure</h2>

<p>I normally have two but sometimes three builds for each project. The structure is something like this:</p>

<ul>
<li>TeamCity Project

<ol>
<li>CI</li>
<li>Acceptance/UI Tests (optional)</li>
<li>Release</li>
</ol>
</li>
</ul>


<p><code>1. CI</code> builds the solution with correctly versioned assemblies (update assembly info files with version before build), runs all unit tests then creates any packages which are required. This includes NuGet packages, Chocolatey packages, zipped binaries, clickonce installers etc.
This build monitors pull requests and is triggered automatically when there are new commits/branches.</p>

<p><code>2. Acceptance/UI Tests</code> is an extra I use when I have long running or UI tests, for example <a href="http://teamcity.ginnivan.net/project.html?projectId=TestStack_White&amp;tab=projectOverview">TestStack.White on TeamCity (sign in as guest)</a> has this build setup and it runs Whites UI tests.
The reason I separate it is for speed reasons, I want my CI build to fail fast and only if it is successful do I run this slow build.
This build triggers whenever <code>1. CI</code> succeeds</p>

<p><code>3. Release</code> (or 2. Release if there is no acceptance/ui test build) is run manually and it releases the artifacts build by <code>1. CI</code>, if that is a NuGet package it is pushed to NuGet.org, chocolatey packages get pushed to chocolatey.org, zip files get pushed as a GitHub release etc.
Once this build succeeds it should tag the VCS root and push that tag.</p>

<!-- more -->


<h2>Build Configuration</h2>

<h3>VCS Root</h3>

<p>First step is to create our VCS root.<br/>
<strong>Type: </strong> Git<br/>
<strong>VCS Root Name: </strong> Project Name (all branches + pull requests)<br/>
<strong>Default branch: </strong> master<br/>
<strong>Branch specifications: </strong></p>

<figure class='code'><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=''><span class='line'>+:refs/pull/*/merge
</span><span class='line'>+:refs/heads/*</span></code></pre></td></tr></table></div></figure>


<p>If you are using stash it would be</p>

<figure class='code'><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=''><span class='line'>+:refs/pull-requests/*/merge-clean
</span><span class='line'>+:refs/heads/*</span></code></pre></td></tr></table></div></figure>


<p>You should also put a username/password in to authenticate with the VCS root so we can tag in the release build</p>

<h3>1. CI</h3>

<p>This has two build steps, for this to work you should install GitVersion on your build server via chocolatey.</p>

<h4>Build steps</h4>

<ul>
<li><p><strong>GitVersion</strong><br/>
<strong>Runner Type:</strong> Command Line<br/>
<strong>Step Name:</strong> GitVersion<br/>
<strong>Run:</strong> Executable with parameters<br/>
<strong>Command executable:</strong> GitVersion<br/>
<strong>Command parameters:</strong> . /updateAssemblyInfo /output buildserver</p></li>
<li><p><strong>Build project</strong><br/>
This should be setup however you used to do it, build your solution, run your build scripts etc.</p></li>
</ul>


<h4>Triggers</h4>

<p>Add trigger <code>VCS Trigger</code> with the default settings which has a branch spec of <code>+:*</code></p>

<h4>Build Features</h4>

<p>I have the report status to GitHub plugin installed, this plugin tells github the build status of pull requests so it can display warnings if a pull request will break the build</p>

<h3>2. Acceptance test</h3>

<p>This build varies greatly, if you need this build it has the same triggers and dependencies setup as 3. Release. I won&rsquo;t repeat those settings here.</p>

<h3>3. Release</h3>

<h4>VCS Root</h4>

<p>The same VCS root which is referenced by 1. CI should also be referenced by this build</p>

<h4>Build steps</h4>

<p>Normally for me this just a NuGet push step. But whatever you normally do, use the artifact dependencies to get at the artifacts from your CI build to publish</p>

<h4>Build Features</h4>

<p>Add feature <code>VCS Labelling</code><br/>
<strong>Labeling pattern:</strong> %system.build.number%<br/>
<strong>Label builds in branches:</strong> <code>+:*</code> (we want to label any release)<br/>
Check <em>Label successful builds only</em></p>

<h4>Dependencies</h4>

<p>This is the important part, we want to setup a proper TeamCity build chain.
1. Add snapshot dependency for CI build and previous build in chain, so if you have 2. Acceptance tests then add a snapshot dependency for both CI and Acceptance test builds<br/>
Tick <em>Do not run new build if there is a suitable one</em> and <em>Only use successful builds from suitable ones</em><br/>
The snapshot dependency is really important, it means that you release the artifacts associated with a specific git commit. If you don&rsquo;t you can deploy artifacts which came from another branch =/
2. Add Artifact Dependency to CI Build with these settings:<br/>
<strong>Get artifacts from: </strong> Build from the same chain<br/>
<strong>Artifacts rules: </strong> MyPackage.*.nupkg (or whatever artifacts you need to publish</p>

<h4>General Settings</h4>

<p>I put this last because you need the dependencies setup before configuring this page.
<strong>Build Number Format:</strong> %dep.MyProject_Ci.build.number% (MyProject_Ci is the project ID of the CI build)</p>

<h2>Wrap up</h2>

<p>Hopefully this helps you get your TeamCity builds setup, I have found this setup works quite well and is easy to setup and keep running.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Updating Chocolateys release notes with GitReleaseNotes]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/06/26/updating-chocolateys-release-notes-with-gitreleasenotes/"/>
    <updated>2014-06-26T05:51:20+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/06/26/updating-chocolateys-release-notes-with-gitreleasenotes</id>
    <content type="html"><![CDATA[<p>Today I saw a tweet from Rob Reynolds today that <a href="https://twitter.com/ferventcoder/status/481816379340120064">Chocolatey 0.9.8.24 RC1 was released</a> so I clicked the link which was straight to the closed issues list on GitHub.</p>

<p>I also noticed that many of the RCs and betas were not tagged in Git so you can&rsquo;t see what was fixed each beta.</p>

<p>I have been working on a little utility to solve exactly this problem called <strong>GitReleaseNotes</strong>, the idea is that you install it via Chocolatey, then run <code>GitReleaseNotes /outputFile ReleaseNotes.md /allTags</code> and it will connect to your issue tracker (if the issue tracker is a REMOTE in your Git repository) fetch all the closed issues since it was last run and append them into your release notes. For public GitHub repos using GitHub issues these are the same so it just works, for Jira and YouTrack you will need to specify additional command line parameters</p>

<p>You then can manually edit, group and do whatever you want. All your modifications will not be changed when you run GitReleaseNotes again.</p>

<!-- more -->


<p>The first step was to change the formatting slightly, currently GitVersion assumes all release titles will start with <code># &lt;Release&gt;</code>, so I changed all of the <code>##1.2.3 (release date)</code> to <code># 1.2.3 (release date)</code>.</p>

<p>The next step was to tell GitReleaseNotes where to start from, to do this I needed to add the commit range of the last release, the most important one is the last sha. For this I just took when the release notes was updated last, then went back in the history until I found another major release. This gave me:</p>

<pre><code>Commits: [a32f1fc133...f15a8f3b52](https://github.com/chocolatey/chocolatey/compare/a32f1fc133...f15a8f3b52)
</code></pre>

<p>But this would work fine too</p>

<pre><code>Commits: a32f1fc133...f15a8f3b52
</code></pre>

<p>After I had done that I just ran <code>GitReleaseNotes /o CHANGELOG.md /allTags</code> and this was appended to the top of <code>CHANGELOG.md</code></p>

<figure class='code'><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>
</pre></td><td class='code'><pre><code class=''><span class='line'># vNext
</span><span class='line'>
</span><span class='line'> - [#493](https://github.com/chocolatey/chocolatey/issues/493) - [Enhancement] Chocolatey-Update cleanup
</span><span class='line'> - [#492](https://github.com/chocolatey/chocolatey/issues/492) - Error messages late in update of chocolatey itself
</span><span class='line'> - [#487](https://github.com/chocolatey/chocolatey/issues/487) - nuget.exe hangs for packages with many dependencies
</span><span class='line'> - [#486](https://github.com/chocolatey/chocolatey/pull/486) - Improve Chocolatey setup as administrator and add Test-ProcessAdminRights helper contributed by Jakub Berezanski ([jberezanski](https://github.com/jberezanski))
</span><span class='line'> - [#424](https://github.com/chocolatey/chocolatey/issues/424) - Update Contributing.md with link to mailing list
</span><span class='line'> - [#416](https://github.com/chocolatey/chocolatey/pull/416) - [Enhancement] added quiet parameter and forced write-host to honor that param (#411) contributed by Johan Leino ([jole78](https://github.com/jole78))
</span><span class='line'> - [#411](https://github.com/chocolatey/chocolatey/issues/411) - [Enhancement] absolute "quiet" mode - Allow shutting off "real" Write-Host
</span><span class='line'> - [#393](https://github.com/chocolatey/chocolatey/pull/393) - Resolve issue with DISM "missing" or with the 32-bit DISM being called on a 64-bit system contributed by Julian Easterling ([dcjulian29](https://github.com/dcjulian29))
</span><span class='line'> - [#379](https://github.com/chocolatey/chocolatey/issues/379) - [Enhancement] Update NuGet.exe to 2.8+ in Chocolatey install
</span><span class='line'>
</span><span class='line'>Commits: [c1ab0a6473...f541d8ca31](https://github.com/chocolatey/chocolatey/compare/c1ab0a6473...f541d8ca31)</span></code></pre></td></tr></table></div></figure>


<p>That was pretty easy, I submitted this as a pull request and Rob can just edit and next time generate the new release notes with easy. Including all the beta&rsquo;s.
You can view the pull request at <a href="https://github.com/chocolatey/chocolatey/pull/496">https://github.com/chocolatey/chocolatey/pull/496</a> - it may not be merged, but I figured this was a good guide of how you can start using GitReleaseNotes on your own project.
Feel free to post on issue on GitHub if you have issues with your project, it is still a work in progress tool after all!</p>

<p>You can also run <code>GitReleaseNotes /o releasenotes.md /allTags</code> to generate a complete new set of release notes since the start of the project with easy. Give that a go yourself and see what the output is.</p>

<h2>Next steps</h2>

<p>The next function of GitReleaseNotes will be to help you publish your release. This is <strong>not done yet</strong>, but you will be able to just go on a publish build:</p>

<p><code>GitReleaseNotes /publish /version 1.2.3</code> which will (hopefully):</p>

<ul>
<li>Push a GitHub release (which will cause the tag to be created)</li>
<li>Will automatically read the <em>vNext</em> section of your release notes and use that</li>
<li>Update the version in the release notes file, and push that</li>
</ul>


<p>Each of these steps will be able to be done individually. Then with this and <a href="https://github.com/Particular/GitVersion">GitVersion</a> I will be able to automate MUCH more of my release process.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using Approval text in tests]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/06/10/using-approval-text-in-tests/"/>
    <updated>2014-06-10T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/06/10/using-approval-text-in-tests</id>
    <content type="html"><![CDATA[<h2>Using Approval Text in tests</h2>

<p>I am currently using <a href="https://github.com/TestStack/TestStack.BDDfy">TestStack.BDDfy</a> as my BDD testing framework. v4 has some great changes which make BDDfy really really awesome.</p>

<p>One of the things I am testing is generated confirmation text based on a number of selected form inputs. I want the approved generated text to be put into the BDDfy output. First steps are to read the approved file, here is a quick snipped which does this:</p>

<pre><code>protected string GetApproved()
{
    var namer = new UnitTestFrameworkNamer();
    var basename = string.Format("{0}\\{1}", namer.SourcePath, namer.Name);
    var approvalFilename = new ApprovalTextWriter(string.Empty).GetApprovalFilename(basename);
    var approved = !File.Exists(approvalFilename) ? string.Empty : File.ReadAllText(approvalFilename);
    return approved;
}
</code></pre>

<p>Then I can just add my step in BDDfy <code>.Then(_ =&gt; ApprovedGeneratedConfirmationShouldMatch(sut.DealSummary.ToString()), string.Format("Approved generated confirmation should be:\r\n{0}", GetApproved()))</code></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Low friction Octopress/GitHub pages Setup]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/06/10/low-friction-octopress-github-pages-setup/"/>
    <updated>2014-06-10T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/06/10/low-friction-octopress-github-pages-setup</id>
    <content type="html"><![CDATA[<p>My blog uses <a href="http://octopress.org">Octopress</a> which is basically Jekyll plus a whole bunch of plug-ins preconfigured and it is hosted on <a href="https://pages.github.com">GitHub Pages</a>. But sometimes I really miss being able to simply create or edit posts online. I started looking around and found <a href="http://prose.io/">Prose.io</a>.</p>

<p>Prose is an <em>awesome</em> open source online Jekyll site editor for GitHub. Then if we setup TeamCity to automatically regenerate and deploy our blog when we make any commits we have a really simple way of making quick blog posts online.</p>

<!-- more -->


<p>Here is a quick rundown of creating a new post with Prose. If you are only interested in the automated TeamCity deployment just skip this section.</p>

<ol>
<li>Go into the _posts folder, then click New File<br/>
<img src="http://jake.ginnivan.net/assets/posts/Prose1.png" alt="New file" /></li>
<li>Add a title and write your post<br/>
<img src="http://jake.ginnivan.net/assets/posts/Prose2.png" alt="Write post" /></li>
<li>You can define your yaml metadata defaults for prose in your _config.yaml, giving you a nice UI<br/>
<img src="http://jake.ginnivan.net/assets/posts/Prose3.png" alt="Edit metadata" /></li>
</ol>


<p>When you hit save Prose will commit that file, pretty sweet. <strong>note</strong> if you do not create the file in the _posts folder you will not see the meta-data options. <strong>note2</strong> Image uploading is broken at the moment, hopefully this gets some love soon</p>

<h3>My Prose Config</h3>

<p>You can configure Prose by adding some additional metadata in your _config.yaml file. Here is mine:</p>

<pre><code># ----------------------- #
#   prose.io settings     #
# ----------------------- #
prose:
  rooturl: "source"
  site: "http://jake.ginnivan.net"
  media: "source/assets/posts"
  metadata:
    "source/_posts":
      - name: "layout"
        field:
          element: "hidden"
          value: "post"
      - name: "title"
        field:
          element: "text"
          value: "Title"
      - name: "comments"
        field:
          label: "Allow comments"
          element: "checkbox"
          value: true
      - name: "categories"
        field:
          element: "text"
          value: ""
      - name: "published"
        field:
          label: "Published"
          element: "checkbox"
          value: true
</code></pre>

<p>Read more about <a href="https://github.com/prose/prose/wiki/Prose-Configuration">Prose Configuration</a>.</p>

<h2>Setting up continuous deployment from TeamCity</h2>

<p>The next step is I want TeamCity to automatically regenerate my Octopress site and push it to GitHub. This also assumes you have your site setup as a <strong>user</strong> site</p>

<ol>
<li>Install everything you would need to get Octopress building locally on your build server</li>
<li>Create new build</li>
<li>Add VCS root pointing at <code>source</code></li>
<li>Set TeamCity Checkout mode to <em>checkout on agent</em></li>
<li>Add <code>Command Line</code> Build Step with Exe of <code>bundle</code> and Parameter of <code>install</code>. This will install all the dependencies Octopress needs</li>
<li><p>Next we need TeamCity to clone our repo into the <code>_deploy</code> directory, we can do this with another Command Line build step with the <em>Run</em> parameter set to Custom Script (the reason for <code>git checkout master</code> is that I have the source branch set as default, and the _deploy branch needs to be on master)</p>

<pre><code> if not exist _deploy (git clone https://%GithubUsername%:%GithubPassword%@github.com/%GithubUsername%/%GithubUsername%.github.io.git _deploy)
 cd _deploy
 git checkout master
 cd ..
</code></pre></li>
<li><p>The last build step is to regenerate and deploy our Octopress site. Add a <code>Rake</code> build step with the path set to <code>Rakefile</code> and the task set to <code>gen_deploy</code>. Make sure the <em>bundle exec</em> option is checked</p></li>
<li>Now setup a VCS build trigger so we deploy whenever anything changes</li>
<li>Finally go to the <em>Parameters</em> section of your build configuration. There will be two parameters needing values, <em>GitHubUsername</em> and <em>GitHubPassword</em>. <em>GitHubUsername</em> is easy, just put your username in.</li>
<li>For <em>GitHubPassword</em> click on <code>Edit</code> next to Spec, then set Display to Hidden and Type to Password. This will make sure your password does not show up in build logs and will be ****&rsquo;d out instead.</li>
</ol>


<p>Save your build configuration, and now whenever you push any updates to <code>source</code> your blog will be regenerated and deployed.</p>

<p>Enjoy!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Simple Versioning and release notes]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/25/simple-versioning-and-release-notes/"/>
    <updated>2014-05-25T17:05:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/25/simple-versioning-and-release-notes</id>
    <content type="html"><![CDATA[<p>I do <a href="http://jake.ginnivan.net/open-source-work">a lot of open source</a> and one common time sink across all projects is versioning and generating good release notes.</p>

<p>This post is about two new open source tools. <a href="https://github.com/Particular/GitVersion">GitVersion</a> and <a href="https://github.com/JakeGinnivan/GitReleaseNotes">GitReleaseNotes</a> which automate both of those things.</p>

<!-- more -->


<h2>Background</h2>

<p>About 7 months ago I was talking with <a href="https://github.com/simoncropp">Simon</a> about this pain. Simon and the guys at <a href="https://github.com/Particular">Particular (nServiceBus)</a> had already started on a tool which used the branching conventions of <a href="http://nvie.com/posts/a-successful-git-branching-model/">GitFlow</a> to infer the <a href="http://semver.org/">Semantic Version</a> of their software.</p>

<p>I was pretty excited about this, but did not want to convert all my projects to GitFlow just for versioning reasons. We had two choices, I could contribute <a href="https://guides.github.com/introduction/flow/index.html">GitHubFlow</a> support to GitFlowVersion or spin off a new project. After a discussion with Simon and <a href="https://github.com/andreasohlund">Andreas</a> we made the call that a separate project would be the way to start, then we can combine the best of both worlds later. <a href="https://github.com/JakeGinnivan/GitHubFlowVersion">GitHubFlowVersion</a> was born.</p>

<p>Since then, GitHubFlowVersion and GitFlowVersion have joined forces bringing the best ideas from both projects into <a href="https://github.com/Particular/GitVersion">GitVersion</a> which uses the conventions in common Git branching strategies to allow you to adopt <a href="http://semver.org">Semantic Versioning</a> in your project really easily. I will talk more about release notes a bit later.</p>

<h2>GitVersion in action</h2>

<p>I have created a simple repository on GitHub which I will use for this post at <a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases">JakeGinnivan/EasyVersioningAndReleases</a> and also <a href="http://teamcity.ginnivan.net/project.html?projectId=OpenSourceProjects_EasyVersioningAndReleases&amp;tab=projectOverview">setup a CI build</a> (login as guest).</p>

<p>In this example I am going to use <em>GitVersion.exe</em> from my &ldquo;build script&rdquo;, check out <a href="https://github.com/Particular/GitVersion/wiki/Command-Line-Tool">Command line usage</a> on the GitVersion wiki for more ways you can use GitVersion.exe. Also check out the MSBuild task and the Ruby Gem. When <em>GitVersion.exe</em> is run, it looks at your Git repository and infers the Semantic Version from previous tags, branch names and a few other things. The wiki covers how it does this. The goal though is that it should just work and do sensible things.</p>

<p>Here is my sample build script, all it does is call <em>GitVersion.exe</em>, parse the json that is returned and replace a <strong>version</strong> token in my powershell module.</p>

<pre><code>$currentDir = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

$output = . "$currentDir\GitVersion.1.0.0.0\tools\GitVersion.exe"

$joined = $output -join "`n"
$versionInfo = $joined | ConvertFrom-Json
$version = $versionInfo.SemVer

mkdir "$currentDir\Artifacts"

Copy-Item "$currentDir\src\UsefulStuff.psm1" "$currentDir\Artifacts\UsefulStuff.psm1"

(Get-Content "$currentDir\Artifacts\UsefulStuff.psm1") | 
    Foreach-Object {$_ -replace '__version__',"v$version"} |
    Out-File "$currentDir\Artifacts\UsefulStuff.psm1"

Write-Output "##teamcity[buildNumber '$version']"
</code></pre>

<p>The json returned from GitVersion is a collection of variables, here is an example of what GitVersion returns</p>

<pre><code>{
  "Major":1,
  "Minor":0,
  "Patch":0,
  "PreReleaseTag":"beta.1",
  "PreReleaseTagWithDash":"-beta.1",
  "BuildMetaData":431,
  "FullBuildMetaData":"431.Branch.release-1.0.0.Sha.c1b1f80cd5e3e8182aa208163e40b4df66461226",
  "MajorMinorPatch":"1.0.0",
  "SemVer":"1.0.0-beta.1",
  "LegacySemVer":"1.0.0-beta1",
  "LegacySemVerPadded":"1.0.0-beta0001",
  "AssemblySemVer":"1.0.0.0",
  "FullSemVer":"1.0.0-beta.1+431",
  "InformationalVersion":"1.0.0-beta.1+431.Branch.release-1.0.0.Sha.c1b1f80cd5e3e8182aa208163e40b4df66461226",
  "ClassicVersion":"1.0.0.431",
  "ClassicVersionWithTag":"1.0.0.431-beta.1",
  "BranchName":"release-1.0.0",
  "Sha":"c1b1f80cd5e3e8182aa208163e40b4df66461226",
  "AssemblyVersion":"1.0.0.0",
  "AssemblyFileVersion":"1.0.0.0",
  "OriginalRelease":"c1b1f80cd5e3e8182aa208163e40b4df66461226.2014-05-11 08:42:24Z"
}
</code></pre>

<p>The build metadata in the above example (+431) comes from the number of commits since the last tag/release. This means the SemVer is the same for each build, essentially making each CI build create a release candidate of the release. This works well with continuous delivery.</p>

<p>We then just copy our powershell module into the output folder and replace the version. The last command <code>Write-Output "##teamcity[buildNumber '$version']"</code> updates TeamCity&rsquo;s build number. Resulting in:</p>

<p><img src="http://jake.ginnivan.net/assets/posts/2014-05-13-simple-versioning-and-release-notes.png" alt="2014-05-13-simple-versioning-and-release-notes" /></p>

<h3>How to SemVer?</h3>

<p>Once we have GitVersion running, how do we get it to bump the SemVer?</p>

<p>GitVersion supports two Git branching strategies, <a href="https://guides.github.com/introduction/flow/index.html">GitHubFlow</a> (or the simple pull request model) and <a href="http://nvie.com/posts/a-successful-git-branching-model/">GitFlow</a>. I am going to use GitHubFlow as an example.</p>

<h4>Ways to bump the version</h4>

<ol>
<li>When you tag, the <em>patch</em> will automatically be bumped for the next build

<ul>
<li>So if you Tag 1.2.0, the next build will be 1.2.1</li>
</ul>
</li>
<li>Use NextVersion.txt when you want to bump major or minor

<ul>
<li>i.e &ldquo;2.0.0&rdquo; > NextVersion.txt  &ndash; will result in 2.0.0 being built</li>
</ul>
</li>
<li>Put the version number into a branch name and merge to master

<ul>
<li>For example if you want to bump major because of a breaking change, you can create a branch called <code>release-2.0.0</code>, which will build as <code>2.0.0-beta.1</code> automatically, once it is merged into master 2.0.0 stable will start being built</li>
</ul>
</li>
</ol>


<p>If you have other idea&rsquo;s on how we could bump the version, let us know. Some ideas are using Git notes or detecting specific phrases in your commit messages. Like <code>Breaking:</code> would cause major to be increased.</p>

<p>Check out the wiki for some additional info</p>

<ul>
<li><a href="https://github.com/Particular/GitVersion/wiki/Advantages-of-GitVersion">https://github.com/Particular/GitVersion/wiki/Advantages-of-GitVersion</a></li>
<li><a href="https://github.com/Particular/GitVersion/wiki/GitFlowExamples">https://github.com/Particular/GitVersion/wiki/GitFlowExamples</a></li>
<li><a href="https://github.com/Particular/GitVersion/wiki/GitHubFlowExamples">https://github.com/Particular/GitVersion/wiki/GitHubFlowExamples</a></li>
</ul>


<p>That is GitVersion in action. You can also just invoke it directly as the first step in you TeamCity build. It also supports a few other build servers.</p>

<h1>Generating release notes</h1>

<p>The next step in simplifying the maintenance of our open source (or internal) project is generating release notes.</p>

<p>There are two approaches you could take, try and keep your issue tracker and everything up to date so they can be generated from the issue tracker you use when you are release your software.</p>

<p>The second option is to keep your release notes in your repository, and you can edit and update them manually.
GitReleaseNotes works with either approach, but the recommended approach is the second one. Let&rsquo;s go through how you can use GitReleaseNotes.</p>

<p><strong>Note:</strong> these examples are with GitHub, but GitReleaseNotes works with Jira and YouTrack currenly. TFS will also be supported. The main requirement is that you use Git as your VCS.</p>

<h3>Step 1</h3>

<p>Install git release notes from Chocolatey, or download the zip and put into your PATH.</p>

<p><code>cinst GitReleaseNotes</code></p>

<h3>Step 2</h3>

<p>Change directory to any git directory, then run <code>GitReleaseNotes /o ReleaseNotes.md</code></p>

<p>This will generate some release notes:</p>

<ul>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/pull/11">#11</a> - Added function to load visual studio vars contributed by Jake Ginnivan (<a href="https://github.com/JakeGinnivan">JakeGinnivan</a>)</li>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/issues/10">#10</a> - Add function to load VS 2013 variables +enhancement</li>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/pull/9">#9</a> - Added project info contributed by Jake Ginnivan (<a href="https://github.com/JakeGinnivan">JakeGinnivan</a>)</li>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/issues/8">#8</a> - Create something to version</li>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/pull/7">#7</a> - Fixed header formatting contributed by Jake Ginnivan (<a href="https://github.com/JakeGinnivan">JakeGinnivan</a>)</li>
<li><a href="https://github.com/JakeGinnivan/EasyVersioningAndReleases/issues/1">#1</a> - Header formatted badly +fix</li>
</ul>


<p>Commits: d3620015c9&hellip;61862ed9e8</p>

<hr />

<p>Not sure about you, but I think this is pretty handy.. So what has GitReleaseNotes actually done?</p>

<ul>
<li>Seen that you have a Git remote pointing at GitHub</li>
<li>Connects to that remote (for example if upstream is Particular/GitVersion, it will use that repo) and fetches issues and pull requests

<ul>
<li>To connect to a private repo, you will need to login to GitHub and generate an application auth token then pass the auth token to GitReleaseNotes via a command line switch.</li>
</ul>
</li>
<li>Outputs the closed pull requests and issues <em>since the last tag</em> to the <em>release notes</em></li>
<li>If you have specified the <code>/alltags</code> switch then you will get issues grouped by release</li>
</ul>


<p>You get included:</p>

<ul>
<li>Link to the issue/pull request</li>
<li>Issue title</li>
<li>Tags (GitReleaseNotes follows <a href="http://www.semanticreleasenotes.org/">http://www.semanticreleasenotes.org/</a> which uses <code>+tag</code> after the title for tags/categories/labels.</li>
<li>Shout outs - a really important part of release notes, calling out the awesome people which have contributed to your project! Shout outs are only available for pull requests, and will only be the person who submitted the pull request</li>
<li>Commit range included in that release (this will become a link to the diff of those commits if supported by the site)</li>
</ul>


<p>As mentioned above, you could also be using another issue tracker and GitReleaseNotes would connect to it and fetch the issues!</p>

<h3>Step 3</h3>

<p>[Optional] Edit your release notes, if you only want to list pull requests just delete the issues. If you want to put both issue and pull request links in a single item, just do that. This can be improved as we go based on feedback to reduce the amount of manual work. You can also just leave it as is.</p>

<h3>Step 4</h3>

<p>If you are using the <code>/allTags</code> switch, then GitReleaseNotes will <em>append</em> new issues to your release notes. Meaning all your modifications will <em>not be changed</em> and new closed issues will simply be appended!</p>

<h2>Summary</h2>

<p>That&rsquo;s it, I would love feedback on both of these projects. I think they are massive time savers and I hope they save you some time!</p>

<p>I said I would come back to Particular&rsquo;s release note generator which can be found at <a href="https://github.com/Particular/GitHubReleaseNotes">https://github.com/Particular/GitHubReleaseNotes</a>.
It is much more strict and uses GitHub milestones and set tags to generate the release notes. Which allows high quality generated release notes. If you use GitHub milestones a lot for release planning, it might work better for you. Check it out.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cannot type capital V on Sculpt Keyboard]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/19/key-not-working-on-sculpt-keyboard/"/>
    <updated>2014-05-19T17:46:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/19/key-not-working-on-sculpt-keyboard</id>
    <content type="html"><![CDATA[<p>At the MVP summit last year I picked up a <a href="http://www.microsoft.com/hardware/en-gb/p/sculpt-ergonomic-desktop">Sculpt Ergonomic Desktop pack</a>, mainly because I cannot stand the UK keyboard layout and wanted to stay on the US layout while working in London.</p>

<p>I just had a very strange issue, I could not type a capital <strong>V</strong>, lowercase worked fine. Plugging into another machine showed the same issue.</p>

<p>One of the problems with the Sculpt is that the function keys get stuck. Apparently if the <code>F5</code> key gets stuck, then you can no longer type a capital V. If the <code>F2</code> key is stuck then you won&rsquo;t be able to type a capital C.</p>

<p>If you hit this random issue, hopefully you will read this post before returning your keyboard.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Disable thumbs.db]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/17/disable-thumbs-dot-db/"/>
    <updated>2014-05-17T18:43:14+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/17/disable-thumbs-dot-db</id>
    <content type="html"><![CDATA[<p>Thumbs.db is created by windows whenever a folder has images in it as a cache for the thumbnails for the images. But it gets locked and stops me switching branches in git and I have to restart my PC sometimes.</p>

<p>Save this as <code>KillThumbsDb.reg</code> and run it as administrator:</p>

<pre><code>Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Explorer]
"DisableThumbsDBOnNetworkFolders"=dword:00000001
</code></pre>

<p>I have no idea why thumbs.db is being created in local folders, but this fixes it for me.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Unknown git mergetool]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/15/unknown-git-mergetool/"/>
    <updated>2014-05-15T03:08:32+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/15/unknown-git-mergetool</id>
    <content type="html"><![CDATA[<p>Today my git mergetool stopped working. When I ran <code>git mergetool</code> I was greeted with:</p>

<pre><code>git config option merge.tool set to unknown tool: --global
Resetting to default...

This message is displayed because 'merge.tool' is not configured.
See 'git mergetool --tool-help' or 'git help config' for more details.
'git mergetool' will now attempt to use one of the following tools:
tortoisemerge emerge vimdiff
No known merge tool is available.
</code></pre>

<p>Somehow (seriously, I have <strong>no</strong> idea how I did this) I had created a setting in one of my repositories set my mergetool to <code>--global</code>.</p>

<p>If you happen to get yourself into the same issue, run <code>git config --list</code> to see what your config settings are.</p>

<p>For me, I had a rogue <code>merge.tool</code> entry, so I just had to run <code>git config --unset merge.tool</code> which deleted the entry and I was off again.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[BDDfy v4.0 Beta 1 Released]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/08/bddfy-v4-beta1/"/>
    <updated>2014-05-08T17:05:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/08/bddfy-v4-beta1</id>
    <content type="html"><![CDATA[<p>We are excited to announce v4 beta 1 of BDDfy! To give it a spin just change your NuGet settings to include pre-release and update. v4 has a bunch of new stuff included which takes BDDfy from not only the simplest BDD framework for .NET but also one of the most powerful!</p>

<p>Please give it a go and report any issues/feedback you have so can fix them before the final v4 release.</p>

<!-- more -->


<h2>New Features</h2>

<p>New features include:</p>

<ul>
<li>Cucumber Examples support

<ul>
<li>This was one of the biggest missing features of BDDfy. We support text based tables (to support easy migration from SpecFlow) and also examples in code which allows complex types rather than just basic types!</li>
<li>If you have not seen cucumber examples before check out <a href="https://github.com/cucumber/cucumber/wiki/Scenario-Outlines">https://github.com/cucumber/cucumber/wiki/Scenario-Outlines</a> for more information</li>
<li>See the <a href="http://jake.ginnivan.net/blog/2014/05/05/bddfy-examples-support/">examples blog post</a> for more information about examples and how they work in BDDfy</li>
</ul>
</li>
<li>Tags

<ul>
<li><code>.WithTags("Tag1", "Tag2")</code> will be seen in your reports. For example in text reporter you will get <code>Tags: Tag1, Tag2</code> under the test output. The HTML report will have tags boxes next to the step title</li>
<li>Tag functionality is really basic at the moment, and will be improved in v4.1</li>
</ul>
</li>
<li>Fluent: Step titles are prefixed with the step type

<ul>
<li>For example: <code>this.Given(_ =&gt; Something())</code> will result in a step title of <code>Given something</code></li>
</ul>
</li>
<li>Fluent: Removed restriction on order of step types. So you can create more complex tests (for acceptance/UI based tests). i.e <code>.Given().Then().When().Then().And().When().Then()</code> etc.</li>
<li>Added <em>But</em> step type, in beta 1 this is only available for the fluent syntax. It will be in reflective by the final release</li>
<li>New Metro HTML report</li>
<li>Classic HTML Report is now self contained with jQuery inlined in the report. CSS is also minified to make the report source easier to read.

<ul>
<li>You can switch to a CDN version of jQuery via configuration if you do not want it included in the report</li>
</ul>
</li>
<li>Inline assertions:

<ul>
<li><code>this.Given(() =&gt; { something = 5; }, "Something is 5")</code> so you do not have to create methods for steps if you do not want to.</li>
</ul>
</li>
<li>Title-only steps: you can have a title only step to explain the context more; e.g. Given(&ldquo;Given something&rdquo;)</li>
<li>StoryMetadata is made more generic to allow different story narratives; e.g. instead of As a &hellip;, I want &hellip;, So that &hellip; you can now have anything including So that &hellip;, As a &hellip;., I want &hellip;</li>
<li>Story title prefix is now customisable</li>
<li>Arguments passed to methods are now reported in steps much better, including:

<ul>
<li>Step titles are lazily evaluated, so if previous steps mutate state which is passed into a step then the value at step execution time will be reported</li>
<li>Support fields, properties and they will be reported as arguments in step title (i.e <code>this.Given(_ =&gt; Given(_three))</code> will be <code>Given 3</code></li>
<li>And a bunch of other improvements</li>
</ul>
</li>
<li><strong>BREAKING:</strong> A lot less namespaces to make the API easier to use.

<ul>
<li>Many of the namespaces that were necessary before, particularly for using fluent API and executable attributes, are removed and are now accessible via the root TestStack.BDDfy namespace.</li>
</ul>
</li>
<li><strong>BREAKING:</strong> A few types have been renamed to more accurately reflect their role and usage</li>
<li><strong>BREAKING:</strong> Removed story category from <code>.BDDFy</code> and <code>.LazyBDDfy</code> methods</li>
<li><strong>BREAKING:</strong> .net 3.5 support has been dropped, BDDfy now requires > .NET 4.0</li>
<li><em>Coming Soon:</em> ReSharper BDDfy plugin, which will stop ReSharper marking steps as unused. Check out it&rsquo;s progress at <a href="https://github.com/TestStack/TestStack.BDDfy.ReSharper">https://github.com/TestStack/TestStack.BDDfy.ReSharper</a> - Thanks heaps to Igal Tabachnik (@hmemcpy) for the work on this</li>
</ul>


<p>Check out the release notes at <a href="https://github.com/TestStack/TestStack.BDDfy/blob/release-4.0.0/release-notes.md">https://github.com/TestStack/TestStack.BDDfy/blob/release-4.0.0/release-notes.md</a></p>

<h2>Known issues</h2>

<ul>
<li>Add But to reflective API (<a href="https://github.com/TestStack/TestStack.BDDfy/issues/85">https://github.com/TestStack/TestStack.BDDfy/issues/85</a>)</li>
<li>Update diagnostics report to work with examples (<a href="https://github.com/TestStack/TestStack.BDDfy/issues/135">https://github.com/TestStack/TestStack.BDDfy/issues/135</a>)</li>
<li>Examples do not work with RunStepWithArgsAttribute (<a href="https://github.com/TestStack/TestStack.BDDfy/issues/136">https://github.com/TestStack/TestStack.BDDfy/issues/136</a>)</li>
</ul>


<h2>Feedback wanted</h2>

<p>This is an exciting release for BDDfy and we want to hear about any issues you hit</p>

<p>From the TestStack team (<a href="https://github.com/JakeGinnivan">Jake Ginnivan</a>, <a href="https://github.com/MehdiK">Mehdi Khalili</a>, <a href="https://github.com/mwhelan">Michael Whelan</a> and <a href="https://github.com/robdmoore">Rob Moore</a>)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[BDDfy v4.0 Examples Support]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/05/06/bddfy-examples-support/"/>
    <updated>2014-05-06T00:09:00+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/05/06/bddfy-examples-support</id>
    <content type="html"><![CDATA[<p>One of the major features in BDDfy v4 is the inclusion of examples</p>

<p><strong>Scenario:</strong> Successful rail card purchases<br/>
<strong>Given:</strong> the buyer is a <em>&lt;buyer category&gt;</em><br/>
<strong>And:</strong> the buyer selects a <em>&lt;fare&gt;</em><br/>
<strong>When:</strong> the buyer pays<br/>
<strong>Then:</strong> a sale occurs with an amount of <em>&lt;price&gt;</em></p>

<p>Examples:</p>

<pre><code>| Buyer Category | Fare          | Price |
| Student        | Monthly Pass  | $76   |
| Senior         | Monthly Pass  | $98   |
| Standard       | Monthly Pass  | $146  |
| Student        | Weekly Pass   | $23   |
| Senior         | Weekly Pass   | $30   |
| Standard       | Weekly Pass   | $44   |
| Student        | Day Pass      | $4    |
| Senior         | Day Pass      | $5    |
| Standard       | Day Pass      | $7    |
| Student        | Single Ticket | $1.5  |
| Senior         | Single Ticket | $2    |
| Standard       | Single Ticket | $3    |
</code></pre>

<p>This is an example of a Cucumber test with examples, for each row in the examples table the test will run effectively giving us a data driven BDD style test.</p>

<!-- more -->


<p>I have picked this test because it is a bit more complex than the standard <code>Given I have 3 beers in my fridge, When I drink 2, Then I have 1 beer left</code>.. Yay, how interesting..</p>

<p>In this example, I will use BDDfy&rsquo;s fluent API to write this test. First without examples:</p>

<pre><code>this.Given(_ =&gt; TheBuyerIsA(BuyerCategory.Student))
    .And(_ =&gt; TheBuyerSelectsA(new MonthlyPass()))
    .When(_ =&gt; TheBuyerPays())
    .Then(_ =&gt; ASaleOccursWithAnAmountOf(new Money(76)))
    .BDDfy("Successful rail card purchases");
</code></pre>

<p>Which gives us a nicely formatted output of</p>

<pre><code>Scenario: Successful rail card purchases
  The buyer is a Student
    The buyer selects a Monthly Pass
  The buyer pays
  A sale occurs with an amount of $76.00
</code></pre>

<p>The next step is to turn this into a test with examples.</p>

<h3>Step 1</h3>

<p>Create somewhere to put the examples, BDDfy supports private/public fields and properties as well as local variables in your test method. The following all work:</p>

<pre><code>private Fare fare;
private BuyerCategory _buyerCategory;
public Money Price { get; set; }

public void MyTest()
{
      var Fare = default(Fare);
}
</code></pre>

<p>Local variables are the cleanest and recommended approach, but feel free to use fields or properties when examples are shared between tests.</p>

<h3>Step 2</h3>

<p>Then we should replace the arguments we are passing to our steps to be the fields/properties</p>

<pre><code>var buyerCategory = default(BuyerCategory);
var fare = default(Fare);
var price = default(Money);

this.Given(_ =&gt; TheBuyerIsA(buyerCategory))
    .And(_ =&gt; TheBuyerSelectsA(fare))
    .When(_ =&gt; TheBuyerPays())
    .Then(_ =&gt; ASaleOccursWithAnAmountOf(Price))
    .BDDfy("Successful rail card purchases");
</code></pre>

<h3>Step 3</h3>

<p>Use the .WithExamples() extension method to pass your examples to BDDfy</p>

<pre><code>this.Given(_ =&gt; TheBuyerIsA(buyerCategory))
    .And(_ =&gt; TheBuyerSelectsA(fare))
    .When(_ =&gt; TheBuyerPays())
    .Then(_ =&gt; ASaleOccursWithAnAmountOf(price))
    .WithExamples(new ExampleTable(
        "Buyer Category", "Fare", "Price")
    {
        { BuyerCategory.Student, new MonthlyPass(), new Money(76) },
        { BuyerCategory.Senior, new MonthlyPass(), new Money(98) },
        { BuyerCategory.Standard, new MonthlyPass(), new Money(146) },
        { BuyerCategory.Student, new WeeklyPass(), new Money(23) },
        { BuyerCategory.Senior, new WeeklyPass(), new Money(30) },
        { BuyerCategory.Standard, new WeeklyPass(), new Money(44) },
        { BuyerCategory.Student, new DayPass(), new Money(4) },
        { BuyerCategory.Senior, new DayPass(), new Money(5) },
        { BuyerCategory.Standard, new DayPass(), new Money(7) },
        { BuyerCategory.Student, new SingleTicket(), new Money(1.5m) },
        { BuyerCategory.Senior, new SingleTicket(), new Money(2m) },
        { BuyerCategory.Standard, new SingleTicket(), new Money(3m) }
    })
    .BDDfy("Successful rail card purchases");
</code></pre>

<p>BDDfy supports two ways of providing examples, if you are migrating from SpecFlow and you are using simple types (unlike the example above where my examples are actually classes) then we support the normal text table:</p>

<pre><code>.WithExamples(@"
    | Header 1 | Header 2     | Header3    |
    | Value 1  | 2            | 3          |
    |          | 14 Mar 2010  | Transition |");
</code></pre>

<h3>Step 4</h3>

<p>Thats it, simply run your tests and the output will be something like this:</p>

<pre><code>Scenario: Successful rail card purchases
  The buyer is a &lt;Buyer Category&gt;        
    The buyer selects a &lt;Fare&gt;           
  The buyer pays                         
  A sale occurs with an amount of &lt;Price&gt;

Examples: 
| Buyer Category | Fare         | Price   |
| Student        | Monthly Pass | $76.00  |
| Senior         | Monthly Pass | $98.00  |
| Standard       | Monthly Pass | $146.00 |
| Student        | Weekly Pass  | $23.00  |
| Senior         | Weekly Pass  | $30.00  |
| Standard       | Weekly Pass  | $44.00  |
| Student        | Day Pass     | $4.00   |
| Senior         | Day Pass     | $5.00   |
| Standard       | Day Pass     | $7.00   |
| Student        | Day Pass     | $1.50   |
| Senior         | Day Pass     | $2.00   |
| Standard       | Day Pass     | $3.00   |
</code></pre>

<p>Errors will be reported against examples rather than steps when examples are used. For example:</p>

<pre><code>Examples: 
| Buyer Category | Fare         | Price   | Error                                                  |
| Student        | Monthly Pass | $76.00  |                                                        |
| Senior         | Monthly Pass | $98.00  |                                                        |
| Standard       | Monthly Pass | $146.00 |                                                        |
| Student        | Weekly Pass  | $23.00  | ChuckedAWobblyException: $24 should be $23 [Details 1] |
| Senior         | Weekly Pass  | $30.00  |                                                        |
| Standard       | Weekly Pass  | $44.00  |                                                        |
| Student        | Day Pass     | $4.00   |                                                        |
| Senior         | Day Pass     | $5.00   |                                                        |
| Standard       | Day Pass     | $7.00   |                                                        |
| Student        | Day Pass     | $1.50   |                                                        |
| Senior         | Day Pass     | $2.00   |                                                        |
| Standard       | Day Pass     | $3.00   |                                                        |

Exceptions:
1. ChuckedAWobblyException: $24 should be $23
&lt;stacktrace&gt;
</code></pre>

<p>This works with all of our built in reports. If you have custom reports then you will get a test for <em>each</em> example. Have a look at the built in reporters for examples on how to build custom reporters with examples support.</p>

<h2>Other things to note</h2>

<h3>Step names</h3>

<p>There are multiple ways to put placeholders in step names, the one shown above allows you to simply use the parameter on the step method. If it matches a column in your example table it will be substituted in the step name. If it doesn&rsquo;t match you will just get the value like you currently do.</p>

<p>We also support the following:</p>

<pre><code>GivenIHave__initialCount__Beers() # Then access the value from a field/property directly in the step
.Given(_ =&gt; InitialCount(), "Given I have &lt;initial count&gt; beers")
</code></pre>

<p>If you have more ideas on how we could make this even better, let us know!</p>

<h3>Errors</h3>

<p>BDDfy will try it&rsquo;s best to tell you when something is wrong, for example your test will fail if examples in your example table are not put anywhere. This is handy when you make a spelling mistake or refactor things and they no longer match.
We will also give you row and column information of values if they cannot be assigned, for example trying to assign &lsquo;null&rsquo; to a value type.</p>

<p>I really hope you enjoy using this feature, we have wanted to add this to BDDfy for a long time but it is a pretty massive feature so it has taken us a while. We also not only wanted to make it as good as the Gherkin first languages, but take advantage of the fact that BDDfy tests are written in code to allow complex types to be used in examples.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[nUnit 2.6.3, async and .net 4.0 broken]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/01/15/nunit-263-async-and-dotnet40-broken/"/>
    <updated>2014-01-15T02:55:09+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/01/15/nunit-263-async-and-dotnet40-broken</id>
    <content type="html"><![CDATA[<p>I am currently working on a <strong>.net 4.0</strong> project which uses async/await quite heavily. We also are using the old AsyncTargeting pack rather than the RTM because we do not have stats on how many clients currently have the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=3556">.net 4.0 KB 2468871 patch</a> which enables PCL support. These issues affect the RTM version as well.</p>

<p>Recently I have upgraded to nCrunch 2.2 beta and ReSharper 8.1 both which ship with the upgraded nUnit 2.6.3 runner. After I upgraded these tools I noticed tests which should have been failing were passing and passing tests were being reported as failing but showing stack traces from a different test..</p>

<p>Also I was getting different results in nCrunch, R# and nUnits console runner. Something was broken.</p>

<p><strong>NOTE</strong>: Async and TPL support is <em>not supported</em> in nUnit 2.x, but will be officially supported in v3.x and that it was a coincidence that it worked in 2.6.2. My discussions about the issues are at <a href="https://groups.google.com/forum/#!topic/nunit-discuss/McE95Cy2DlY">here on the nunit discussion board</a>.<br/>
As far as I can tell, there is no reason that 4.0 cannot be supported because to offer framework support does not need any new features OR the classes in the Async Targeting Pack or .NET 4.5. At a minimum tests returning <code>Task</code> should be supported as TPL was introduced into the CLR for net40.  <br/>
Recently I added async void and Task support to <a href="https://github.com/TestStack/TestStack.BDDfy/pull/32">BDDfy</a> which targets .NET 4.0, also xUnit 1.9.x supports Tasks in the current released version and has backported <code>async void</code> support to the 1.9.x codebase from the 2.0 and will be released if there is a need to release another patch release before 2.0 is released.</p>

<p><strong>.NET 4.5 is fully supported and works as expected with nUnit, it is only .net 4.0 which is affected</strong></p>

<!-- more -->


<p><img src="http://jake.ginnivan.net/assets/posts/2014-01-14-nunit-263,asyncandnet4.png" alt="2014-01-14-nunit-263,asyncandnet4" /></p>

<p>When I first saw this it really really confused me, so I have been diving into async, nUnit and trying all different things which is where my blog post on <a href="http://jake.ginnivan.net/blog/2014/01/10/on-async-and-sync-contexts/">async and synchronisation contexts</a> came from.</p>

<h2>So what&rsquo;s broken?</h2>

<p>But in 2.6.3 tests returning <code>Task</code> and <code>async void</code> tests will not wait for completion. In addition to that, nUnit 2.6.3 will flat out refuse to run tests which return <code>Task</code> and the console runner will return an error code. Other runners just silently skip the tests&hellip;</p>

<p>This means that if you use async/await <em>or</em> TPL and have upgraded to R# 8.1, nCrunch 2.2 or 2.3 beta, the nUnit.Runners NuGet project or any other tools which have upgraded to use the nUnit 2.6.3 runner internally your async tests will be completing <strong>unobserved</strong> and may be failing without your knowledge.</p>

<h3>Repro Solution</h3>

<p>I put together a sample solution showing the issues (and the screenshot above is from) the GitHub repo is available at <a href="https://github.com/JakeGinnivan/nUnit_net4.0AsyncIssues">https://github.com/JakeGinnivan/nUnit_net4.0AsyncIssues</a></p>

<p>Here are the test results from 2.6.2:</p>

<pre><code>Tests run: 3, Errors: 1, Failures: 0, Inconclusive: 0, Time: 1.4863562 seconds
  Not run: 0, Invalid: 0, Ignored: 0, Skipped: 0

Errors and Failures:
1) Test Error : ClassLibrary1.Class1Tests.Test1
   System.InvalidOperationException : Operation is not valid due to the current state of the object.

Server stack trace:
   at ClassLibrary1.Class1Tests.&lt;Test1&gt;d__0.MoveNext() in c:\Users\Jake\_Code\WpfApplication4\ClassLibrary1\Class1Tests.cs:line 19

Exception rethrown at [0]:
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.&lt;ThrowAsync&gt;b__0(Object state)
   at NUnit.Core.AsyncSynchronizationContext.AsyncOperationQueue.InvokePendingOperations()
   at NUnit.Core.AsyncSynchronizationContext.AsyncOperationQueue.InvokeAll()
   at NUnit.Core.NUnitAsyncTestMethod.RunVoidAsyncMethod(TestResult testResult)
</code></pre>

<p>And 2.6.3:</p>

<pre><code>Tests run: 2, Errors: 0, Failures: 0, Inconclusive: 0, Time: 0.676135209417321 seconds
  Not run: 1, Invalid: 1, Ignored: 0, Skipped: 0

Errors and Failures:

Tests Not Run:
1) NotRunnable : ClassLibrary1.Class1Tests.Test3
   Test method has non-void return type, but no result is expected
</code></pre>

<h2>What to do about it</h2>

<p>Luckily we can fix this and go back to a working version of nUnit (which as far as I can tell works perfectly for both <code>async void</code> and <code>Task</code> tests).</p>

<p>First you will need to <a href="http://launchpad.net/nunitv2/trunk/2.6.2/+download/NUnit-2.6.2.zip">download nUnit 2.6.2</a> and extract it to a known location</p>

<h3>Fixing ReSharper</h3>

<p>ReSharper is pretty easy as the options dialog allows you to override the runner it uses.</p>

<p>Go into the Resharper menu, then Options. Scroll down to <em>Unit Testing</em> under tools and select NUnit.</p>

<p>Then you can point ReSharper at the nUnit lib directory like so:
<img src="http://jake.ginnivan.net/assets/posts/2014-01-14-nunit-263,asyncandnet41.png" alt="2014-01-14-nunit-263,asyncandnet41" /></p>

<p>Now ReSharper will be using a non-broken version of nUnit.</p>

<h3>Fixing nCrunch</h3>

<p>nCrunch is a little harder, but this fix works fine.</p>

<p>First open up <code>C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Remco Software\NCrunch for Visual Studio 2013</code>, then overwrite <code>nunit.core.dll</code> and <code>nunit.core.interfaces.dll</code> with the ones from the 2.6.2 zip you downloaded earlier.</p>

<p>Now nCrunch will be using the non-broken version. Yay</p>

<h2>Summary</h2>

<p>If you are using .NET 4.0, async/await <em>or</em> TPL and nUnit, do not upgrade your runners to 2.6.3 and if any tools/build servers you are using upgrade, make sure you set them back to using 2.6.2 manually</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[On Async and Sync Contexts]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/01/10/on-async-and-sync-contexts/"/>
    <updated>2014-01-10T22:12:49+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/01/10/on-async-and-sync-contexts</id>
    <content type="html"><![CDATA[<p>This week has been a really heavy learning experience for me in terms of async/await, .ConfigureAwait() and how it interacts with Synchronisation Contexts. Quite a few of my assumptions were wrong, or the behaviour is different between the .NET 4.0 implementation (CTP3 and RTM) and what happens in .NET 4.5.</p>

<p>In this post I will cover:</p>

<ul>
<li>What .ConfigureAwait(false) does in .net 4.0 and in .net 4.5, and why they act differently</li>
<li>Some guidance around using await in a rich client app (i.e await for <em>offloading</em>, not scalability) .net 4.0 in particular, .net 4.5 behaves better and the guidance is not as relevant</li>
<li>How you can use custom awaiters to switch contexts</li>
</ul>


<!-- more -->


<h2>Quick SynchronizationContext Intro</h2>

<p>If you do not know what synchronization context&rsquo;s are, then I will quickly cover them here. If you know what they do, skip to the next section.</p>

<p>A SynchronizationContext allows you to queue a unit of work on another <em>context</em>, a context can be a specific thread or it may be shared between multiple threads. For example you can get the SynchronizationContext of the current thread by going <code>var uiSyncContext = SynchronizationContext.Current</code>, you can use it to run a delegate on the UI thread (or whatever context the SynchronizationContext represents) with <code>uiSyncContext.Send(state =&gt; { MyProperty = state; }, state: "bar")</code>. This will pass the string &ldquo;bar&rdquo; through as state (without implicitly capturing the outside closure) then assign to MyProperty on the UI thread.</p>

<p>SynchronizationContext&rsquo;s also get notified when asynchronous work is started, which is how frameworks like (<a href="http://www.nunit.org/">nUnit</a>, <a href="http://xunit.codeplex.com/">xUnit 2.0</a>, <a href="https://github.com/TestStack/TestStack.BDDfy">BDDfy</a> and others supports tests which have a method signature of <code>async void</code></p>

<h2>How await uses SynchronisationContext&rsquo;s</h2>

<p>Async/await is just compiler magic to make it easier to compose asynchronous stuff, it does not make your code run asynchronously all it does is when it sees an await, it splits your method up into a state machine then when the thing you are awaiting finishes executing, the state machine is resumed and your code continues running. Resuming execution is called the <em>continuation</em>.<br/>
A great feature of the <code>await</code> keyword is that it captures the current SynchronizationContext before it runs the asynchronous operation, then it will post the continuation to that SynchronizationContext, meaning if you are on the UI Thread when you <code>await Foo()</code> once <code>Foo()</code> finishes running your code will continue execution on the UI Thread.</p>

<p>This scenario here is called <em>offloading</em>, because the UI thread is an important thread you want to run as little code as possible on the UI thread.</p>

<h3>Controlling await with .ConfigureAwait()</h3>

<p>To change the default behaviour TPL gives us the <code>.ConfigureAwait(bool continueOnCapturedContext)</code>, this allows you to write code like this:</p>

<pre><code>public async Task&lt;ObservableCollection&lt;DataViewModel&gt;&gt; DoSomeStuff() {
    var results = await _service.GetSomeData().ConfigureAwait(false);
    var mappedData = MapDataToViewModels(results); // Just pretend this is CPU bound work
    return mappedData;
}
</code></pre>

<p>Because of the <code>.ConfigureAwait(false)</code> our continuation and the <code>MapDataToViewModels()</code> method call will be run on a background thread (unless the awaited task is already complete, then the continuation will be executed in-line). Lets take this one step further</p>

<pre><code>public async Task&lt;ObservableCollection&lt;DataViewModel&gt;&gt; DoSomeStuff() {
    var results = await _service.GetSomeData().ConfigureAwait(false);
    var mappedData = MapDataToViewModels(results);
    var moreData = await _service.GetMoreData();
    UpdateViewModelsWithAdditionalData(moreData);
    return mappedData;
}
</code></pre>

<p>In which context does <code>UpdateViewModelsWithAdditionalData(moreData);</code> run?</p>

<p>The answer is <em>it depends</em>, on .net 4.0 <code>UpdateViewModelsWithAdditionalData(moreData);</code> runs on the UI thread, on .net 4.5 it will run on the <em>threadpool</em>. Why is this? To answer that we need to dive into something called the execution context.</p>

<h3>Execution Context?</h3>

<p>When our .NET code is executing, these is a bunch of additional metadata which floats around with our thread, these are things like security information and the synchronisation context. For more in depth information on the .net execution context have a read of <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx">http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx</a>.</p>

<p>The important thing to know about the execution context is that the .NET framework flows it around so things work as we would expect, for instance if we start a new thread, out execution context will go with us. Task.Run, ThreadPool.QueueUserWorkItem() etc all will flow the execution context (but will supress the flow of the SynchronizationContext).</p>

<h2>Differences between .NET 4.0 and 4.5</h2>

<p>So we have explained some of the moving parts when we are dealing with async/await. (If you would like me to do a more in depth post on async/await in general and how it works starting from the basics, leave a comment below).</p>

<p>Above I showed this code</p>

<pre><code>public async Task&lt;ObservableCollection&lt;DataViewModel&gt;&gt; DoSomeStuff() {
    var results = await _service.GetSomeData().ConfigureAwait(false);
    var mappedData = MapDataToViewModels(results);
    var moreData = await _service.GetMoreData();
    UpdateViewModelsWithAdditionalData(moreData);
    return mappedData;
}
</code></pre>

<p>And said that in .NET 4.0 <code>UpdateViewModelsWithAdditionalData(moreData);</code> would run on the UI thread and in .NET 4.5 it would run on the ThreadPool. This is because of how the different implementations capture the <code>ExecutionContext</code>.</p>

<h3>Breakdown of .NET 4.0</h3>

<p>If we break this method down into what will be executed. This is a mixture of the generated state machine, library code and code to just demonstrate what is happening (because there are heaps of moving parts).</p>

<pre><code>int state;
Results results;

void IAsyncStateMachine.MoveNext()
{
    switch 1:
        var mappedData = MapDataToViewModels(results);
        // etc...
        break;
    // etc...
    default:
        var ex = ExecutionContext.Capture();
        var task = _service.GetSomeData();

        TaskAwaiter.OnCompletedInternal(task, ()=&gt; {
            ex.Run(()=&gt;
            {
                results = task.Result;
                state = 1;
                MoveNext();
            });
        }, continueOnCapturedContext: false);
}
</code></pre>

<p>Now there are a few things to look at in this small bit of code, first is <code>var ex = ExecutionContext.Capture();</code>, this captures the current execution context and the ExecutionContext contains the SynchronizationContext so when we execute <code>MoveNext()</code> our SynchronizationContext has been restored BUT because the TaskAwaiter.OnCompletedInternal has been told to not continue on the captured context it will be run on the default task scheduler.</p>

<p>The end result of all this is when <code>var mappedData = MapDataToViewModels(results);</code> runs we will:</p>

<ul>
<li>Be running on the ThreadPool</li>
<li>SynchronizationContext.Current will still be the <code>DispatcherSynchronizationContext</code></li>
</ul>


<p>So on the next line when we await and <em>do not use</em> .ConfigureAwait(false) the continuation will run on the captured SynchronizationContext</p>

<h3>.NET 4.5 Behaviour</h3>

<p>Lets have a look at what the code looks like in .NET 4.5 land.</p>

<pre><code>int state;
Results results;

void IAsyncStateMachine.MoveNext()
{
    switch 1:
        var mappedData = MapDataToViewModels(results);
        // etc...
        break;
    // etc...
    default:
        var ex = ExecutionContext.CaptureInternal(ExecutionContext.CaptureOptions.IgnoreSyncCtx); 
        var task = _service.GetSomeData();

        TaskAwaiter.OnCompletedInternal(task, ()=&gt; {
            ex.Run(()=&gt;
            {
                results = task.Result;
                state = 1;
                MoveNext();
            });
        }, continueOnCapturedContext: false);
}
</code></pre>

<p>Notice the line where the execution context is captured, in .NET 4.5 the AsyncMethodBuilderCore calls an <em>internal</em> method on the ExecutionContext which allows the caller to specify that they do not want the SynchronizationContext to be captured as part of the ExecutionContext.</p>

<p>The reason .NET 4.0 and .NET 4.5 are different is that this internal cannot be called from the Async Targeting Pack because it&rsquo;s a library, in .NET 4.5 the AsyncMethodBuilderCore is part of the framework so it can call this internal methods.</p>

<h3>How does TaskEx.Run not capture SynchronizationContext?</h3>

<p>Because TaskEx.Run delegates to <code>Task.Factory.StartNew()</code> which is part of the framework, it passes the option to not capture the SynchronizationContext</p>

<h2>Some guidance for .NET 4.0</h2>

<p>The general guidance is any library code should use <code>.ConfigureAwait(false)</code> so our continuations do not constantly post back to the UI thread, because .NET 4.0 always flows the SynchronizationContext it means that <em>all</em> of our await calls should have <code>.ConfigureAwait(false)</code> which is pretty ugly. Also because .ConfigureAwait(false) still checks if the task is complete, using <code>.ConfigureAwait(false)</code> does not guarantee that we will no longer be executing on the UI thread.</p>

<p>Rather than using .ConfigureAwait() we can explicitly get our code running on the ThreadPool as soon as possible. There are two options for this (that I can see currently):</p>

<p>In ViewModels when you invoke any sort of async service, wrap it in a <code>await TaskEx.Run(()=&gt;_myService.DoStuffAsync());</code>, this is quite good because if your service calls other services you do not get the problem where all your services have <code>TaskEx.Run</code> scattered everywhere and you are scheduling a heap more things into the ThreadPool.</p>

<p>Create a app services layer which your viewmodels interact with, in this layer you delegate to your domain or existing app services, but wrap it in a <code>TaskEx.Run(()=&gt;..);</code></p>

<pre><code>| UI/ViewModels |   ==&gt;   | Service Layer (TaskEx.Run) |   ==&gt;   | Rest of app (never has sync context) |
</code></pre>

<p>Both of these options basically try and make sure that only code executing in the ViewModels have a SynchronizationContext, and the rest of your application had no threading concerns.</p>

<h3>Additional Option for .NET 4.5</h3>

<p>If you are using .NET 4.5, then another option is to create a custom awaiter (<em>note</em> this feature was removed from the async CTP, possibly because it doesn&rsquo;t work properly in .NET 4.0 and also because it can confuse people)</p>

<pre><code>await TaskHelper.SwitchToThreadPool();
</code></pre>

<p>Just awaiting this will cause our async method to switch onto the ThreadPool, personally I think this is quite nice because you do not have to pay the Lambda Tax of <code>Task.Run(..)</code></p>

<p>The code is pretty simple</p>

<pre><code>public static class TaskHelper
{
    public static SwitchContextToThreadPoolAwaiter SwitchToThreadPool()
    {
        return new SwitchContextToThreadPoolAwaiter();
    }
}

public struct SwitchContextToThreadPoolAwaiter : INotifyCompletion
{
    public SwitchContextToThreadPoolAwaiter GetAwaiter() { return this; }

    public bool IsCompleted { get { return false; } }

    public void OnCompleted(Action continuation)
    {
        if (!Thread.CurrentThread.IsThreadPoolThread)
            ThreadPool.QueueUserWorkItem(state =&gt; ((Action)state)(), continuation);
        else
            continuation();
    }

    public void GetResult() { }
}
</code></pre>

<h2>Summary</h2>

<p>I dived into this because of randomly failing tests when I upgraded to nCrunch 2.2 beta, this was due to some false assumptions about how async/await worked in .net 4.0 and also because of some <em>helper</em> classes which scheduled work on the threadpool or on the main UI thread.
Because of the way the SyncContext flowed, the nUnit synchronisation context was present where we thought it should not be. Because of this our code and helpers were not working correctly as the WPF UI DispatcherSynchronizationContext can be captured as a TaskScheduler and has a few other differences.</p>

<p>In short</p>

<ul>
<li>.NET 4.0 flows the SynchronizationContext always, even when you use <code>.ConfigureAwait(false)</code></li>
<li>.NET 4.5 does not flow the SynchronizationContext when you use <code>.ConfigureAwait(false)</code></li>
<li>Don&rsquo;t try and use the nUnit SynchronizationContext as a task scheduler</li>
<li>If you are using .NET 4.0, use TaskEx.Run to get off the UI Thread as fast as possible, then use an <code>await</code> in your viewmodel to capture the UI thread and bring you back to it</li>
<li>Make sure your application code does not need to run on the UI thread, if you have services (like say an <code>IDialogService</code>) then it should post to the UI dispatcher in that service so it is effectively mocked in your unit tests. This was the main source of our issues with tests failing..</li>
<li>Don&rsquo;t mix threading concerns and application code</li>
</ul>


<p>I Hope that helps a few people understand SynchronizationContexts, ExecutionContexts and how async/await works with either of them.</p>

<h2>Resources</h2>

<p><a href="http://blogs.msdn.com/b/pfxteam/archive/2012/06/15/executioncontext-vs-synchronizationcontext.aspx">Stephen Toub on ExecutionContext vs SynchronizationContext (talks about .net 4.5 behaviour)</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Blog Migration]]></title>
    <link href="http://jake.ginnivan.net/blog/2014/01/06/blog-migration/"/>
    <updated>2014-01-06T00:51:56+08:00</updated>
    <id>http://jake.ginnivan.net/blog/2014/01/06/blog-migration</id>
    <content type="html"><![CDATA[<p>I have finally decided to move from FunnelWeb to Jekyll. My needs for a blog engine are changing, and at the moment I am liking the static site generators.</p>

<p>Those of you subscribed to my RSS feeds will likely get duplications, sorry about that.</p>

<h2>LinqPad Migration script</h2>

<p>Migrates posts, and images (putting them in the correct spot for Jekyll sites and rewriting links in your blog posts as it goes)</p>

<p>Available at <a href="http://share.linqpad.net/76oqrd.linq">http://share.linqpad.net/76oqrd.linq</a></p>

<h2>Other Links</h2>

<p><a href="https://github.com/tokkonopapa/octopress-tagcloud">https://github.com/tokkonopapa/octopress-tagcloud</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[GitReleaseNotes Initial Release!]]></title>
    <link href="http://jake.ginnivan.net/gitreleasenotes/"/>
    <updated>2013-12-17T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/gitreleasenotes</id>
    <content type="html"><![CDATA[<p>I have just used GitReleaseNotes to publish a release of GitReleaseNotes on GitHub <a href="https://github.com/JakeGinnivan/GitReleaseNotes/releases/tag/0.2.0">https://github.com/JakeGinnivan/GitReleaseNotes/releases/tag/0.2.0</a>!</p>

<p>I am excited about this project because it will save me a heap of time and effort with managing the open source projects I do releases for.</p>

<p>GitReleaseNotes was another project I kicked off about the same time that <a href="https://github.com/simoncropp">Simon Cropp</a> and <a href="https://github.com/andreasohlund">Andreas Öhlund</a> were kicking off similar projects, see <a href="https://github.com/Particular/ReleaseNotesCompiler">https://github.com/Particular/ReleaseNotesCompiler</a>. We decided to start the projects off down different roads to start with, then maybe merge later once we both could experiment with ideas.</p>

<!-- more -->


<h2>What does it do</h2>

<p>The concept is quite simple, you can optionally specify a Git tag (it will select the newest tag if you do not specify one). It will then scan all newer commits for references to issues.</p>

<p>Once it has all the referenced commits, it will connect the issue tracker you specify, currently GitHub or Jira (and soon YouTrack, TFS and BitBucket) and fetch all the closed issues which have been referenced.
It will then output your release notes in <a href="http://www.semanticreleasenotes.org/">Semantic Release Notes</a> format (which is also markdown) to a file you specify.</p>

<p>It can also publish a release on GitHub, including the generated release notes.</p>

<p>Here are some examples of the types of release notes it can generate:</p>

<p><a href="https://github.com/JakeGinnivan/GitReleaseNotes/blob/master/src/GitReleaseNotes.Tests/ReleaseNotesGeneratorTests.ApproveSimpleTests.approved.txt">Simple single issue release</a><br/>
<a href="https://github.com/JakeGinnivan/GitReleaseNotes/blob/master/src/GitReleaseNotes.Tests/ReleaseNotesGeneratorTests.MultipleReleases.approved.txt">Multiple releases</a></p>

<h2>How to use it</h2>

<p>GitReleaseNotes is a .NET exe, but can be used on ALL project types (JavaScript, Ruby, Java, whatever) because it simply works with Git and whatever issue tracker you use.</p>

<pre><code>GitReleaseNotes.exe /IssueTracker Github /Repo JakeGinnivan/GitReleaseNotes /Token ######################### /OutputFile ReleaseNotes.md
</code></pre>

<p>To Publish, just add the <code>/Publish</code> switch and specify the version you want to publish with the <code>/Version</code> switch. Like so</p>

<pre><code>GitReleaseNotes.exe /IssueTracker Github /Repo JakeGinnivan/GitReleaseNotes /Token ######################### /Publish /Version 0.2.0
</code></pre>

<h2>How to setup on TeamCity</h2>

<p>TeamCity is not required, but I like being able to press a button and my latest CI build gets published.</p>

<p>Well, I am using <a href="https://github.com/JakeGinnivan/GitHubFlowVersion">GitHubFlowVersion</a> which helps me do Semantic Versioning with ease, but if you have another versioning strategy most of the instructions are the same.</p>

<p>Assuming you have a CI build which creates the artifacts, or you have an existing build you will be adding to.</p>

<ol>
<li>Head to <a href="https://github.com/settings/applications">https://github.com/settings/applications</a> and create an access token</li>
<li>Create a new configuration parameter in teamcity called <code>GitHubToken</code>, set the value to the access token you have just created and edit the spec field and paste in <code>password display='hidden'</code>, which will mean your GitHub access token will not be published into any build logs and will just be ####ed out.</li>
<li>Your VCS root must be set to checkout <code>Automatically on Agent</code>, otherwise GitReleaseNotes will not run</li>
<li>Make sure you check GitReleaseNotes.exe into source control so you can access it</li>
<li>Create a new build step which is running a command line application, and make it look something like this<br/>
 <code>GitReleaseNotes\GitReleaseNotes.exe /IssueTracker GitHub /Publish /Token %GitHubToken% /Repo JakeGinnivan/GitReleaseNotes /Version %dep.OpenSourceProjects_GitReleaseNotes_CI.system.GitHubFlowVersion.SemVer%</code></li>
</ol>


<p>My version number is the SemVer of my CI build, if you are using GitHubFlowVersion you will have to create a dummy system.GitHubFlowVersion.SemVer variable, otherwise you cannot reference it across builds (doesn&rsquo;t exist at configure time, it is created when you run GitHubFlowVersion).</p>

<p>And thats it, you can have a build publishing your release notes to GitHub and this will also tag master with the version you have just published.</p>

<p>There are still plenty of issues with this project and heaps of work to do, but I like the way it is shaping up. Feedback/contributions are welcome.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Git Flow Versioning]]></title>
    <link href="http://jake.ginnivan.net/git-flow-versioning/"/>
    <updated>2013-10-02T00:00:00+08:00</updated>
    <id>http://jake.ginnivan.net/git-flow-versioning</id>
    <content type="html"><![CDATA[<p>As a follow up to my last post <a href="http://jake.ginnivan.net/release-nuget-semver-packages-from-teamcity">http://jake.ginnivan.net/release-nuget-semver-packages-from-teamcity</a> I have been investigating more into different ways to achieve semantic versioning and being able to release in an easy way.</p>

<p>Next stop on my trip was looking into Git-Flow and how it manages releases, initially it seemed very waterfally and too heavy to use on an open source project, but I thought it may fit at different clients. I was instantly drawn to the fact that releases have an explicit step to version at the start of the release process, this is great, I can manage my project, merge pull requests, add features then when I am ready, I can decide to release, put together release notes and figure out if this is a major, minor or patch release.</p>

<p>Much to my surpise, it is actually very light-weight and you can drop much of it if your process is simpler (say for open source).</p>

<p><a href="https://github.com/TestStack/ConventionTests">https://github.com/TestStack/ConventionTests</a> is my guinea pig!</p>

<p>To get started, I decided to try and implement git-flow manually to really understand what is going on. There are plenty of explainations out there, so I will just be running through what I did, and how it works from my point of view. I always have two remotes setup for my projects, &lsquo;upstream&rsquo; is the main repository, &lsquo;origin&rsquo; is my fork.</p>

<!-- more -->


<h2>1. Convert the repo over to git-flow</h2>

<p>From your git command line</p>

<pre><code>git checkout master
git fetch upstream
git merge upstream/master
git checkout develop
git push upstream develop
</code></pre>

<p>This pushes the <code>develop</code> branch into your repo, then head to the project settings in github and change the default branch to <code>develop</code>.</p>

<h2>2. Install GitFlowVersion</h2>

<p>I am a big fan on Simon Cropp&rsquo;s (<a href="https://twitter.com/SimonCropp">https://twitter.com/SimonCropp</a>) work. He has been working on <a href="https://github.com/Particular/GitFlowVersion">https://github.com/Particular/GitFlowVersion</a> with Andreas Öhlund.</p>

<p>Basically GitFlowVersion uses the conventions in place in git-flow to make it really easy to version your software.</p>

<p>Once up and running, tags off <code>master</code> get a normal version, say <code>v2.1.0</code> (assume this is the LAST tagged release), develop CI builds get the version <code>v2.2.0-unstable20</code> where the minor is LASTMINOR + 1 and there has been 20 commits since the last tag on master. Or <code>v&lt;major&gt;.&lt;minor+1&gt;.0-unstable&lt;#commitssincelastrelease&gt;</code>
Release branches have a version of <code>v2.2.0-beta</code> where 2.2.0 is the version you have put in the release branch name (in this case <code>release-2.2.0</code>)
You can also tag a release branch as <code>rc1</code> or <code>rc2</code> and the version will become <code>v2.2.0-&lt;tag&gt;</code>.</p>

<p>If this sounds confusing, its not, and it is all pretty automatic, read on to see what it actually means for you maintaining a project.</p>

<h2>3. Contributing/Pull Requests</h2>

<p>I always use feature branches, but not for an entire feature. I use very short lived branches, which I put up as a pull request as soon as I am done. I am known to submit 3+ pull requests all within the space of an hour when I work on a project because I just fix a bunch of small things.</p>

<p>Nothing much changes here, except you take you branch from <code>develop</code>. So</p>

<pre><code>git checkout develop
git fetch upstream
git merge upstream/develop
git checkout -b FixingSomething
</code></pre>

<p>Pull requests now target <code>develop</code>, so I do my commits, push to origin like normal and submit my pull request targeting <code>develop</code></p>

<p>Your CI build (assuming you are building pull requests) will trigger with build number <code>v2.2.0-PullRequest50</code>, where the version is the last release, with the minor bumped, just like develop version numbers, except the semver tag is PullRequest&lt;PR#>.
I think that is pretty neat.</p>

<h2>4. Releasing a new version</h2>

<p>When you decide you want to release, or start preparing a release you can either take a release branch, or merge develop straight into master and tag master with the release (afaik this doesn&rsquo;t cause any issues :P)</p>

<p>In my mind there are two styles to run a project,</p>

<ol>
<li>every checkin builds, then if tests pass autodeploys. These projects cannot adhere to semantic versioning, but the changes are often so tiny that upgrades pose little risk.</li>
<li>At some point in time, the decision to release is made, this could be as soon as a pull request is merged, or after a particular milestone is reached. All the projects I am currently contributing to work in this way.</li>
</ol>


<h3>4.1 Using a release branch</h3>

<p>Using a release branch allows you to make the decision I am going to release, there may be a few things I know I have to do before releasing (DbUp is a great example of this). But I don&rsquo;t want to stop being able to merge pull requests. To release using a branch (assume develop is up to date), and I am only fixing a bug in the current v2.1.0 release</p>

<pre><code>git checkout -b release-2.1.1
</code></pre>

<p>or</p>

<pre><code>git flow release start 2.1.1
</code></pre>

<p>I can now leave this branch open for a bit, do the work I need to do to release 2.1.1 or send it to someone else on the team to OK. I could even release the 2.1.1 build as a pre-release package on NuGet. It would have version 2.1.1-beta1 remember.</p>

<p>Once I am happy, either the pre-release package has got the feedback I wanted, or I have made the additional changes I need I simply merge the branch to master (with the &ndash;no-ff option), tag, then delete the remote branchs. Remember this is if you are doing it manually, you can also just go <code>git flow release finish</code> if you have the git-flow extensions installed, or use source tree and click a button :P The first two commands are not needed if you haven&rsquo;t committed anything to the release branch</p>

<pre><code>git checkout develop
git merge release-2.1.1 --no-ff
git checkout master
git merge release-2.1.1 --no-ff
git tag 2.1.1
</code></pre>

<p>or</p>

<pre><code>git flow release finish 2.1.1
</code></pre>

<p>Then publish</p>

<pre><code>git push upstream master
git push --tags
git branch -d release-2.1.1
git push upstream :release-2.1.1
</code></pre>

<p>or</p>

<pre><code>git flow release publish 2.1.1
</code></pre>

<h3>4.2 Skip release branch</h3>

<p>If you don&rsquo;t want to bother with the release branch, you could also just go</p>

<pre><code>git checkout master
git merge develop --no-ff
git tag 2.1.1
git push upstream master
git push --tags
</code></pre>

<h2>5. Publish the build</h2>

<p>Now you have the release build from your CI you can progress through your build pipeline and release to NuGet or publish to a test environment or whatever the first step is in your Continuous Delivery pipeline.</p>

<h2>That&rsquo;s it</h2>

<p>I think Git-Flow is actually not too bad for releasing projects using semantic versioning, most of the time in this is writing the release notes, seeing what has changed since the last release (which is really easy due to the conventions in place!) and checking to see if you have any breaking changes which would mean a major version bump.</p>

<p>As a summary. Here is me fixing and releasing a feature as a pre-release package. The current version on NuGet is currently v2.2.0</p>

<pre><code>git fetch upstream
git checkout develop
git merge upstream/develop
git checkout -b SomeFeature

# Work..
git commit -am "Some experimental feature"
git push origin SomeFeature

# Submit pull request, so NOTHING has changed yet, this PR is merged
git fetch upstream
git checkout develop
git merge upstream/develop # to get my changes into my local develop branch

# So now I am starting the release, nothing before here is new if you are using GitHub flow
git checkout -b release-2.3.0
git push upstream release-2.3.0
</code></pre>

<p>Now my CI builds, and I click the button to promote the last CI build as a pre-release NuGet package. Once I am happy, I have got my feedback</p>

<pre><code>git checkout master
git merge release-2.3.0 --no-ff
git tag 2.3.0
git push upstream master
git push upstream --tags
</code></pre>

<p>My CI will build, and I can click the publish button on teamcity to release to NuGet.</p>

<p>Thoughts? Do you know of an easier way. I am REALLY open to suggestions and willing to try stuff out at the moment :)</p>
]]></content>
  </entry>
  
</feed>
