<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <id>http://brendanforster.com/</id>
 <title>brendan forster</title>
 <link href="http://brendanforster.com/atom.xml" rel="self" />
 <link href="http://brendanforster.com/" />
 <updated>2013-05-20T12:27:05+00:00</updated>
 <author>
   <name>Brendan Forster</name>
   <email>me@brendanforster.com</email>
 </author>

 
 <entry>
   <title>Should I make this object a singleton?</title>
   <link href="http://brendanforster.com//blog/should-i-make-this-object-a-singleton.html" />
   <updated>2013-05-20T00:30:00+00:00</updated>
   <id>http://brendanforster.com/blog/should-i-make-this-object-a-singleton.html</id>
   <content type="html">
	<![CDATA[<p><strong>Note</strong>: This is just a first pass on the post, as I need to touch on various tools I've used in the past to identify these constraints. But let's start with the concepts.</p>

<p>Someone asked me a question yesterday along the lines of, well, this:</p>

<blockquote class="twitter-tweet" data-conversation="none"><p>@<a href="https://twitter.com/nickhodgemsft">nickhodgemsft</a> Roger, cheers @<a href="https://twitter.com/shiftkey">shiftkey</a> thoughts? Will it be better to create a life long Crypto obj rather than this <a href="http://t.co/bn3hRIiGdt" title="http://twitter.com/HDizzle84/status/336104817707589633/photo/1">twitter.com/HDizzle84/stat…</a></p>&mdash; HDizzle (@HDizzle84) <a href="https://twitter.com/HDizzle84/status/336104817707589633">May 19, 2013</a></blockquote>


<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>


<p>Singletons? My first instinct was to reach for the hose and dampen such discussion down immediately before someone got hurt.</p>

<p>But no, that's not right. I need to explain myself.</p>

<p>So I wanted to put together a simple guide on how to determine <em>when</em> the <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton pattern</a> is a suitable use case - yes, it gets a bad reputation due to misuse, but there are some scenarios where it does add value (and is often necessary).</p>

<h2>How expensive is it to create?</h2>

<p>Imagine you have a database connection - say <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx">SqlConnection</a> - and you create an instance of it to connect to a database?</p>

<p><strong>TODO:</strong> show windbg object dump of a SqlConnection object</p>

<p>Inside this SqlConnection object you should see a bunch of underlying resources - these are the components which make the magic happen when you perform a "SELECT * FROM Table" in your application.</p>

<p>Many of the objects you create in your application are probably simpler than this - classes to hold data, for example - but once you start interacting with the underlying platform and identify various bottlenecks in your applications understanding what resources are hiding where is invaluable knowledge.</p>

<p>The other thing to keep in mind with objects is what they encapsulate. If your classes interacts with the network, storage or attached devices, for example, you are likely to face specific rules with how you use access these resources.</p>

<p>An example: if you're ever making concurrent web requests to a specific domain, .NET will actually throttle you to two concurrent requests. You can change this if you <a href="http://msdn.microsoft.com/en-us/library/fb6y0fyc.aspx">know where to look</a> but the defaults are designed to be "good enough" for most scenarios.</p>

<p>Another example: <a href="http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx">database connection pools</a> - a finite number of connections which are managed and reused over the lifetime of an application - instead of arbitrarily creating, using, and then destroying connections each time we need them.</p>

<h2>What about my memory footprint?</h2>

<p>So assuming the above constraint isn't affecting your classes, you might be able to get away with creating objects whenever necessary.</p>

<p>But what if you're making a mobile app? Memory becomes a significant constraint on any mobile applications - and the more moving parts you have in a mobile application, the more you need to optimise to reduce the impact of those moving parts.</p>

<blockquote><p>I don't need to worry about that, my stack has generational garbage collection (GC).</p></blockquote>

<p>But that's not actually a solution - more like a crutch. GC isn't a free lunch - it's overhead that you're now invoking periodically (technically GC will run whenever it needs to, which is often at the worst possible time due to memory pressure) because you were lazy with how you structured your application.</p>

<p><strong>TODO:</strong> demonstrate .NET performance counters around GC, with a sample that does stupid things</p>

<h2>What about multi-threaded code?</h2>

<p>This is the hardest part to discuss, because multi-threaded code is hard. Really hard.</p>

<p>If your object is <a href="http://en.wikipedia.org/wiki/Immutable_object">immutable</a> (that is, you can call the same function on an object <strong>as many times as possible until the end of time</strong> and you'll always get the same result) then it might be possible for it to be used as a singleton object.</p>

<p><strong>TODO:</strong> discuss the simplest gotcha - two threads entering a function at the same time</p>

<p><strong>TODO:</strong> discuss where basic locking will cause you different sorts of headaches</p>

<p><strong>TODO:</strong> what would Ayende do?</p>

<h2>But I just want to use it as a global object</h2>

<p>Please don't. This introduces unnecessary coupling into your application, at the value of saving a few keystrokes.</p>

<p><strong>TODO:</strong> explain the god object pattern and why it is bad</p>

<p><strong>TODO:</strong> outline where this is utterly unavoidable and you need to suck it up and just God Object that sucker</p>

<h2>What's the damn answer, Brendan?</h2>

<p>Ok, so if you've read this far - I thank you.</p>

<p>So when should you consider wrapping an object in the singleton pattern?</p>

<ul>
<li>Firstly, beware of how multi-threading <em>actually</em> works - no, the TPL is cheating.</li>
<li>If it's expensive to create, consider it.</li>
<li>If it's touching underlying system resources, consider it.</li>
<li>If you need to optimise for memory usage, consider it.</li>
</ul>


<h2>Feedback is Welcome</h2>

<p>Did I miss something? Get something wrong?</p>

<p>Leave a comment and let me know.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Yet Another "Add LESS to your ASP.NET MVC Project" Post</title>
   <link href="http://brendanforster.com//blog/yet-another-implement-less-in-aspnetmvc-post.html" />
   <updated>2013-05-12T13:00:00+00:00</updated>
   <id>http://brendanforster.com/blog/yet-another-implement-less-in-aspnetmvc-post.html</id>
   <content type="html">
	<![CDATA[<h2>You've probably done this too</h2>

<p>If you kicked off a new ASP.NET webapp recently, somewhere after <code>File -&gt; New Project</code> you probably got excited about using a CSS preprocessor like LESS or SASS because:</p>

<ul>
<li>nobody writes CSS directly anymore</li>
<li>it's supposed to make your life easier</li>
<li>something with unicorns and rainbows</li>
</ul>


<p>This post isn't about that. This is about the little quirks I had to jump through to get a usable development environment for writing LESS code.</p>

<p>NOTE: This uses the bundling features in MVC4. If you're using a version of MVC which is older than that, go upgrade. Bundling is <strong>so nice</strong>.</p>

<h2>Step 1 - The Installer-ation</h2>

<p>To NuGet!</p>

<pre><code>PM&gt; Install-Package dotLess
</code></pre>

<p>Go run that in a new project. I'll wait.</p>

<p>Done? Great, so go write a little LESS code (I've just called this file <code>sample.less</code> for the purposes of this demo):</p>

<div class="highlight"><pre><code class="css"><span class="k">@color</span><span class="o">:</span> <span class="nf">#4D926F</span><span class="p">;</span>

<span class="nc">.site-title</span> <span class="nt">a</span> <span class="p">{</span>
  <span class="k">color</span><span class="o">:</span> <span class="o">@</span><span class="k">color</span><span class="p">;</span>
<span class="p">}</span>
<span class="nt">h3</span> <span class="p">{</span>
  <span class="k">color</span><span class="o">:</span> <span class="o">@</span><span class="k">color</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>


<p>And then include it in your Razor layout...</p>

<div class="highlight"><pre><code class="xml"><span class="cp">&lt;!DOCTYPE html&gt;</span>
<span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">&quot;en&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;head&gt;</span>
        <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">&quot;utf-8&quot;</span> <span class="nt">/&gt;</span>
        <span class="nt">&lt;title&gt;</span>@ViewBag.Title - My ASP.NET MVC Application<span class="nt">&lt;/title&gt;</span>
        <span class="nt">&lt;link</span> <span class="na">href=</span><span class="s">&quot;~/favicon.ico&quot;</span> <span class="na">rel=</span><span class="s">&quot;shortcut icon&quot;</span> <span class="na">type=</span><span class="s">&quot;image/x-icon&quot;</span> <span class="nt">/&gt;</span>
        <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width&quot;</span> <span class="nt">/&gt;</span>
        @Styles.Render(&quot;~/Content/less&quot;)
        @Scripts.Render(&quot;~/bundles/modernizr&quot;)
    <span class="nt">&lt;/head&gt;</span>
    <span class="c">&lt;!--  and more stuff here obvs --&gt;</span>
</code></pre></div>


<p>But you're application doesn't know about <em>how</em> it can transform LESS code into CSS. That's where bundles come in.</p>

<h2>Step 2 - Dude, where's my bundle?</h2>

<p>Bundles are an easy way to merge and minify resources in your application (such as JavaScript files and CSS stylesheets). In addition to being a lovely convenience, it's actually a great way to improve site performance (fewer HTTP requests, reducing size of response payload).</p>

<p>So go back to NuGet and use this:</p>

<pre><code>PM&gt; Install-Package System.Web.Optimization.Less
</code></pre>

<p>And add your bundle to the appropriate location within <code>BundleConfig.cs</code></p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">BundleConfig</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">RegisterBundles</span><span class="p">(</span><span class="n">BundleCollection</span> <span class="n">bundles</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// NOTE: existing bundles are here </span>

        <span class="c1">// add this line</span>
      <span class="n">bundles</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="k">new</span> <span class="n">LessBundle</span><span class="p">(</span><span class="s">&quot;~/Content/less&quot;</span><span class="p">).</span><span class="n">Include</span><span class="p">(</span><span class="s">&quot;~/Content/*.less&quot;</span><span class="p">));</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>


<p>Bundles support a limited subset of wildcard syntax, but you can include multiple folders within a bundle.</p>

<p>So this <code>LessBundle</code> gives you the ability to combine and minify files when running the application in <code>&lt;compilation debug="false" /&gt;</code> mode, and it takes care of transforming LESS code into CSS - without needing to update the layout everytime you add a new file to the project.</p>

<p>Editor's note: I wasn't aware of this package on the last runthrough - instead I found this <code>LessBundle</code> code in a <a href="https://gist.github.com/benfoster/3924025">gist</a> from <a href="http://ben.onfabrik.com/">@benfosterdev</a> which looks very similar to the source for that package, so I'll give him kudos for it.</p>

<h2>Step 3 - But wait, there's more!</h2>

<p>But what about when testing locally? Well, bundles are rather lazy in development mode:</p>

<ul>
<li>no minification</li>
<li>no bundling</li>
<li>in fact the files just appear as LESS resources to the browser</li>
</ul>


<p>So you <em>still</em> need to tell your application how it can serve LESS files to the browser, independent all this bundling work.</p>

<p>dotLess will apply transforms to your web.config when you install it through NuGet to provide handlers which can process a specific LESS file:</p>

<div class="highlight"><pre><code class="xml"><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span>
<span class="nt">&lt;configuration&gt;</span>
  <span class="nt">&lt;configSections&gt;</span>
    <span class="nt">&lt;section</span> <span class="na">name=</span><span class="s">&quot;dotless&quot;</span> <span class="na">type=</span><span class="s">&quot;dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core&quot;</span> <span class="nt">/&gt;</span>
  <span class="nt">&lt;/configSections&gt;</span>
  <span class="c">&lt;!-- these probably do something useful --&gt;</span>
  <span class="nt">&lt;dotless</span> <span class="na">minifyCss=</span><span class="s">&quot;false&quot;</span> <span class="na">cache=</span><span class="s">&quot;true&quot;</span> <span class="na">web=</span><span class="s">&quot;false&quot;</span> <span class="nt">/&gt;</span>
  <span class="nt">&lt;system.webServer&gt;</span>
    <span class="nt">&lt;handlers&gt;</span>
      <span class="c">&lt;!-- for IIS7+ --&gt;</span>
      <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">&quot;dotless&quot;</span> <span class="na">path=</span><span class="s">&quot;*.less&quot;</span> <span class="na">verb=</span><span class="s">&quot;GET&quot;</span> <span class="na">type=</span><span class="s">&quot;dotless.Core.LessCssHttpHandler,dotless.Core&quot;</span> <span class="na">resourceType=</span><span class="s">&quot;File&quot;</span> <span class="na">preCondition=</span><span class="s">&quot;&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/handlers&gt;</span>
  <span class="nt">&lt;/system.webServer&gt;</span>
  <span class="nt">&lt;system.web&gt;</span>
    <span class="nt">&lt;httpHandlers&gt;</span>
      <span class="c">&lt;!-- for IIS6 --&gt;</span>
      <span class="nt">&lt;add</span> <span class="na">path=</span><span class="s">&quot;*.less&quot;</span> <span class="na">verb=</span><span class="s">&quot;GET&quot;</span> <span class="na">type=</span><span class="s">&quot;dotless.Core.LessCssHttpHandler, dotless.Core&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/httpHandlers&gt;</span>
  <span class="nt">&lt;/system.web&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div>


<p>Editor's Note: when I last ran through these steps I didn't get these config transforms applied on install. I was really looking forward to a rant here because I'd gone through the hard yards to add these handlers by hand - but of course it worked this time.</p>

<p>So these handlers allow you to compile an individual LESS file and see the results in the browser.</p>

<p><img src="/img/posts/less/dev-experience.png" alt="" /></p>

<p>Oh, and don't forget to remove the handlers in your config transforms when you go to production (this is an example of the <code>Web.Release.config</code> transforms file).</p>

<div class="highlight"><pre><code class="xml"><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;configuration</span> <span class="na">xmlns:xdt=</span><span class="s">&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;</span><span class="nt">&gt;</span>
  <span class="nt">&lt;system.web&gt;</span>
    <span class="nt">&lt;compilation</span> <span class="na">xdt:Transform=</span><span class="s">&quot;RemoveAttributes(debug)&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;httpHandlers&gt;</span>
      <span class="nt">&lt;add</span> <span class="na">xdt:Transform=</span><span class="s">&quot;Remove&quot;</span> <span class="na">xdt:Locator=</span><span class="s">&quot;Match(type)&quot;</span> <span class="na">path=</span><span class="s">&quot;*.less&quot;</span> <span class="na">verb=</span><span class="s">&quot;GET&quot;</span> <span class="na">type=</span><span class="s">&quot;dotless.Core.LessCssHttpHandler, dotless.Core&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/httpHandlers&gt;</span>
  <span class="nt">&lt;/system.web&gt;</span>
  <span class="nt">&lt;system.webServer&gt;</span>
    <span class="nt">&lt;handlers&gt;</span>
      <span class="nt">&lt;add</span> <span class="na">xdt:Transform=</span><span class="s">&quot;Remove&quot;</span> <span class="na">xdt:Locator=</span><span class="s">&quot;Match(name)&quot;</span> <span class="na">name=</span><span class="s">&quot;dotless&quot;</span> <span class="na">path=</span><span class="s">&quot;*.less&quot;</span> <span class="na">verb=</span><span class="s">&quot;GET&quot;</span> <span class="na">type=</span><span class="s">&quot;dotless.Core.LessCssHttpHandler,dotless.Core&quot;</span> <span class="na">resourceType=</span><span class="s">&quot;File&quot;</span> <span class="na">preCondition=</span><span class="s">&quot;&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/handlers&gt;</span>
  <span class="nt">&lt;/system.webServer&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div>

]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Custom server headers - bad for your health?</title>
   <link href="http://brendanforster.com//blog/custom-server-headers-bad-for-your-health.html" />
   <updated>2013-05-04T06:00:00+00:00</updated>
   <id>http://brendanforster.com/blog/custom-server-headers-bad-for-your-health.html</id>
   <content type="html">
	<![CDATA[<p>I just finished another project with a customer which involved a pentest (penetration testing) review for their upcoming launch. And as usual, this involves hiding a bunch of headers that IIS and ASP.NET serve up on each response.</p>

<p>In particuar:</p>

<ul>
<li>Server (from IIS)</li>
<li>X-Powered-By (from IIS)</li>
<li>X-AspNet-Version (from ASP.NET)</li>
<li>X-AspNetMvc-Version (from ASP.NET MVC)</li>
</ul>


<p>Why? Because sending these headers in your response exposes information about your server to clients (including the bad guys). <a href="http://www.troyhunt.com/2012/02/shhh-dont-let-your-response-headers.html">Troy Hunt</a> explains it in more detail but our approaches differ slightly:</p>

<ul>
<li>I've just focused on the ASP.NET stack</li>
<li>this approach doesn't require any changes to IIS</li>
<li>I don't care about IIS 6 (it shipped with Windows Server 2003, so that'll be 10 years soon!)</li>
</ul>


<h2>NuGet all the pain away</h2>

<p>So I was going to write a NuGet package to solve this problem but I was then pointed to this package from David Duffett - <a href="https://github.com/davidduffett/Dinheiro/tree/master/Dinheiro.RemoveUnnecessaryHeaders">Dinheiro.RemoveUnnecessaryHeaders</a>. Thanks for saving me the time, David!</p>

<p>So go grab it from NuGet:</p>

<pre><code>PM&gt; Install-Package Dinheiro.RemoveUnnecessaryHeaders
</code></pre>

<p>You can do this by hand if you want - in fact, I'll explain the package behaviour here.</p>

<p>First, it applies a config transform to remove the <code>X-Powered-By</code> and <code>X-AspNet-Version</code> headers:</p>

<div class="highlight"><pre><code class="xml"><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;</span>
<span class="nt">&lt;configuration&gt;</span>
  <span class="nt">&lt;system.web&gt;</span>
    <span class="nt">&lt;httpRuntime</span> <span class="na">enableVersionHeader=</span><span class="s">&quot;false&quot;</span> <span class="nt">/&gt;</span>
  <span class="nt">&lt;/system.web&gt;</span>
  <span class="nt">&lt;system.webServer&gt;</span>
    <span class="nt">&lt;httpProtocol&gt;</span>
      <span class="nt">&lt;customHeaders&gt;</span>
        <span class="nt">&lt;remove</span> <span class="na">name=</span><span class="s">&quot;X-Powered-By&quot;</span> <span class="nt">/&gt;</span>
      <span class="nt">&lt;/customHeaders&gt;</span>
    <span class="nt">&lt;/httpProtocol&gt;</span>
  <span class="nt">&lt;/system.webServer&gt;</span>
<span class="nt">&lt;/configuration&gt;</span>
</code></pre></div>


<p>Next, we use <code>WebActivator</code> to hook into the <code>PreApplicationStart</code> event to run some custom behaviour:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[assembly: WebActivator.PreApplicationStartMethod(typeof(MyWebApplication.App_Start.RemoveUnnecessaryHeaders), &quot;Start&quot;)]</span>
</code></pre></div>


<p>This method takes care of two things. The first is disabling the <code>X-AspNetMvc-Version</code> header, and then registering a module to remove the <code>Server</code> header.</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">RemoveUnnecessaryHeaders</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">Start</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="n">DynamicModuleUtility</span><span class="p">.</span><span class="n">RegisterModule</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">RemoveUnnecessaryHeadersModule</span><span class="p">));</span>
        <span class="n">MvcHandler</span><span class="p">.</span><span class="n">DisableMvcResponseHeader</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>


<p>And there's an important note about this code - it's only supported for IIS7+. Just a heads up.</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">RemoveUnnecessaryHeadersModule</span> <span class="p">:</span> <span class="n">IHttpModule</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">void</span> <span class="nf">Init</span><span class="p">(</span><span class="n">HttpApplication</span> <span class="n">context</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// This only works if running in IIS7+ Integrated Pipeline mode</span>
        <span class="k">if</span> <span class="p">(!</span><span class="n">HttpRuntime</span><span class="p">.</span><span class="n">UsingIntegratedPipeline</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>

        <span class="n">context</span><span class="p">.</span><span class="n">PreSendRequestHeaders</span> <span class="p">+=</span> <span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">e</span><span class="p">)</span> <span class="p">=&gt;</span>
        <span class="p">{</span>
            <span class="kt">var</span> <span class="n">app</span> <span class="p">=</span> <span class="n">sender</span> <span class="k">as</span> <span class="n">HttpApplication</span><span class="p">;</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">app</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="n">app</span><span class="p">.</span><span class="n">Context</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Response</span><span class="p">.</span><span class="n">Headers</span><span class="p">.</span><span class="n">Remove</span><span class="p">(</span><span class="s">&quot;Server&quot;</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">};</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">void</span> <span class="nf">Dispose</span><span class="p">()</span> <span class="p">{</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>


<p>That <code>PreSendRequestHeaders</code> event is the last opportunity ASP.NET gets to intercept the response (including reading headers set by IIS) before it gets sent to the client.</p>

<h2>Defaults are good - except when they're not</h2>

<p>Just about all of the teams I've worked with have had this requirement as part of their go-live checklist (or raised by a security review) which made me think...</p>

<p><em>Why aren't these headers disabled by default?</em></p>

<p><em>And why does it require changes in so many different places in IIS and ASP.NET?</em></p>

<h2>A footnote on X- Headers</h2>

<p>If this is the first you are reading about this issue, HTTP headers which are prefixed by X- are custom headers which are not part of the HTTP spec. It allows servers, frameworks and applications to include custom metadata in HTTP requests and responses.</p>

<p>My favourite example of this is Twitter's Rate Limiting API, which sends custom headers with each API call that an application makes:</p>

<pre><code>X-RateLimit-Limit: 350
X-RateLimit-Remaining: 350
X-RateLimit-Reset: 1277485629
</code></pre>

<p>As a consumer of Twitter's API, my application would need to look for these headers and understand the values.</p>

<p>Recently <a href="http://cprieto.com">Cristian</a> pointed me at <a href="http://tools.ietf.org/html/rfc6648">RFC 6648</a> which, as it clearly states, is about:</p>

<blockquote><p>"Deprecating the "X-" Prefix and Similar Constructs in Application Protocols"</p></blockquote>

<p>It's very RFC-y in it's wording - and it's also only a year old which is really young in RFC time - but it's definitely something to keep in mind when designing custom headers for your application to serve or handle in the future.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Internet Sabbatical - An Experiment</title>
   <link href="http://brendanforster.com//blog/experiment-internet-sabbatical.html" />
   <updated>2012-11-26T12:00:00+00:00</updated>
   <id>http://brendanforster.com/blog/experiment-internet-sabbatical.html</id>
   <content type="html">
	<![CDATA[<p>As this year comes to a close (a few more things to do yet) I wanted to try something different over the holiday season - an internet sabbatical.</p>

<h3>A What?</h3>

<p>From 21 December (when I jump on a plane for the holidays) to 6 January (when I jump on a plane to come back for work) I plan to "go to ground" and avoid the internet.</p>

<h3>Why?</h3>

<p>I am burned out - plain and simple.</p>

<p>I would love to just "power on through" like it wasn't a problem but I've been doing that for the past few weeks already and its not changing much.</p>

<p><img src="/img/posts/internet/swanson.gif" /></p>

<p>Plus I intend to spend a bunch of time here:</p>

<p><img src="/img/posts/internet/beach.jpg" /></p>

<p>Doing stuff like this:</p>

<p><img src="/img/posts/internet/hammock.jpg" /></p>

<p>And it has terrible phone reception anyway (yay!)</p>

<h3>The Ground Rules</h3>

<p>Here's the low-down:</p>

<ul>
<li>No Internet Access</li>
<li>No Twitter/Facebook</li>
<li>No checking emails</li>
<li>No computers or things that will let me code</li>
</ul>


<p>But I won't go completely off the reservation:</p>

<ul>
<li>Phone - to keep in contact with friends and family, but that's it</li>
<li>Xbox - I'm keen to play some Assassin's Creed III (or other games) so that's included</li>
</ul>


<p>And given I won't have technology to report on my progress (pen and paper perhaps?), you'll just have to wait and see how I go.</p>

<h3>Happy Holidays</h3>

<p>If you need to get in touch with me over the holidays, there are "old-school" methods (see above) but otherwise I wish you all a happy and safe holiday season and we'll see you all in 2013!</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>What's my secret? An unoffical unconfirmed guide</title>
   <link href="http://brendanforster.com//blog/unofficial-unconfirmed-awesome-guide.html" />
   <updated>2012-09-23T12:30:00+00:00</updated>
   <id>http://brendanforster.com/blog/unofficial-unconfirmed-awesome-guide.html</id>
   <content type="html">
	<![CDATA[<h2>Introduction</h2>

<p>After surviving <a href="http://australia.msteched.com/">TechEd Australia</a> - as well as hitting some important deadlines for a client - I was looking forward to getting back into various side-projects again now that things are coming back to (realtively) normal.</p>

<p>I fired off an email looking for tips from my colleagues what they do to help get creative, and one of the replies I got back was this:</p>

<blockquote><p>I find the third question silly coming from you. You are one of the the most productive and creative people I know and I wish I knew your secret to it. <br/> <br/>Sorry mate; but you don't get to be an MVP, a main member on Code52, talk at conferences and so on and then ask others how they are productive and creative :p<br/> <br/>Share your secret already ;-)</p></blockquote>


<p>So I owe someone a blog post to explain myself.</p>

<h2>Brendan's Unofficial Unconfirmed Guide To Being Awesome</h2>

<p>First up, some warnings:</p>

<ul>
<li>This is me speaking from my experiences only.</li>
<li>I will often suggest things which I do not do. Yes, that makes me appear hypocritical. No, it is not intended.</li>
<li>Please consult with a medical professional before taking any of the below advice.</li>
<li>This is all subject to change.</li>
</ul>


<p>Without further ado, let's dive in...</p>

<h3>Make time for it</h3>

<p>While I appreciate that there are many developers who are happy <a href="http://www.hanselman.com/blog/DarkMatterDevelopersTheUnseen99.aspx">"dark matter" developers</a>, I've always seen a correlation between awesome developers and developers who will spend time improving themselves outside of work hours.</p>

<p>Don't feel bad if you're not someone who obsesses over code outside of work. But don't feel that it's out of reach.</p>

<p>Not sure where to start? Start small. Set aside a half hour once a week.</p>

<p>Can't find time in the evenings? Why not try and <a href="http://99u.com/tips/6954/The-1-Step-Plan-for-Super-Productivity">get up earlier</a> instead?</p>

<p><strong>Note:</strong> As many people who know me will testify, I am not a morning person.  I'll generally find a couple of evenings each week to hack on various things late into the night - it's an old habit I still haven't shaken from my university days - as that's when things are quieter and I can focus better on things. Your milage will vary.</p>

<h3>Set yourself goals (even small ones)</h3>

<p>To ensure you're making the best of youur spare time, set some goals up front to ensure you work towards something tangible and useful. Starting small with your goals will help.</p>

<p>To illustrate this, here's a few goals which I would like to work on over the coming weeks/months:</p>

<ul>
<li>learn about Neo4J and graph database concepts by building a proof-of-concept accounting webapp</li>
<li>learn about DirectX and de-rust on my C++ skills by building a Windows 8 app</li>
</ul>


<p>See how they can be considered daunting goals?</p>

<p>Let's break that first item down a bit:</p>

<ul>
<li>Read up on concepts behind graph databases</li>
<li>Getting Neo4J setup on my local machine</li>
<li>Experimenting with working with Neo4J and the REST API</li>
<li>Getting a simple webapp setup to interact with Neo4J (Ruby/Python?)</li>
<li>Sketching out the app idea</li>
<li>Build out a small piece to demonstrate the app</li>
</ul>


<p>You get the picture - take a big piece of work and break it down into manageable chunks.</p>

<p>By tackling something in chunks you also get a number of other benefits:</p>

<ul>
<li>be able to demonstrate learning earlier on (e.g. interacting with an API first before building the app)</li>
<li>get feedback without investing significant amounts of time (and put it aside if its not fun)</li>
<li>be able to work on multiple goals at the same thing (rather than procrastinating because you're stumped on something)</li>
</ul>


<p>Of course it looks like Dave Tchepak beat me to the punch on this with a <a href="http://davesquared.net/2012/02/goals-for-devs.html">more detailed post</a> earlier in the year, so I'll defer to him on this.</p>

<h3>Don't just read and watch</h3>

<p>It's easy to sit down and read some blogs on a topic and think to yourself "Well that was easy!" It's easy to watch some screencasts on a subject and think "I know X now, great!"</p>

<p>I want to challenge you to go beyond the passive learning and build something based on what you've learned. The size of it doesn't really matter, but I've always found it important to take the things I've learned and apply them to the real world.</p>

<p>This helps in several ways:</p>

<ul>
<li>demonstrating that I was paying attention</li>
<li>leaving the hand-holding of the blog posts/screencasts and work without that safety net</li>
<li>reinforcing the learning while it is fresh in my mind</li>
</ul>


<p>I love blog posts and screencasts, but these days I try and balancing consuming posts/screencasts and creating things.</p>

<h3>Don't be afraid to fail</h3>

<p>It can be daunting when faced with something completely new and unfamiliar. With the amazing pace that technology and software moves at these days, it's impossible to keep up with everything. And that's OK.</p>

<p>Focus on what you could use at work.</p>

<p>Focus on what you're interested in.</p>

<p>Focus on what might make you a better developer.</p>

<p>Dive in, try something, don't be afraid to make a mistake. Because you will. And that's OK.</p>

<p>Just make sure you learn from your mistakes, or that you make different mistakes.</p>

<p>Here's a couple of little experiments I've worked on in the past that haven't come to fruition (yet?):</p>

<ul>
<li>bringing WebRat syntax tests to <a href="/simpler-ui-testing-for-wpf-apps.html">automating testing of WPF apps</a></li>
<li>weaving async/await code to trace when <a href="https://github.com/shiftkey/Fody.AsyncErrorHandling">background tasks fail silently</a></li>
<li><a href="https://github.com/shiftkey/winrt-backport-hilarity">backporting WinRT APIs</a> to .NET so that libraries and apps can transition to the new APIs more easily</li>
</ul>


<p>I could weep for things that didn't eventuate, but life's too short.</p>

<h3>Share all the things!</h3>

<p>And how will we know how awesome you are if you don't tell us?</p>

<p>After parking my blog ages ago (mostly because I was never really "happy" with it and I'd compulsively tweak things), I've started to come around to Hanselman's words: <a href="http://www.hanselman.com/blog/YourWordsAreWasted.aspx">"Every developer should have a blog"</a>. I'm a habitual Twitter user and thoroughly enjoy the medium for what it is, and I know that I spend time which I should be spending on blogging.</p>

<p>To compensate for this, I publish a lot of my stuff on <a href="https://github.com/shiftkey">GitHub</a>. Yeah, its lazy. But its out there at least. Even this blog is <a href="https://github.com/shiftkey/blog">public</a> - and its just a static site generated using <a href="https://github.com/mojombo/jekyll">Jekyll</a> and hosted on <a href="http://www.heroku.com/">Heroku</a>.</p>

<p>Don't be afraid to write - for example, my last post on <a href="http://brendanforster.com/notes/git-alias.html">git aliases</a> got several "Hey you missed X" comments on it because I wrote it in a rush and missed a couple of details with the end script.</p>

<p>If people only blogged perfect posts I'd never end up blogging anything.</p>

<h2>Feedback</h2>

<p>I'm running out of words and I bet you guys are getting tired of me over-sharing, so I'll tie this one off here. What have I missed? What did I say wrong? Let me know in the comments.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Why You Should Care About Git Alias</title>
   <link href="http://brendanforster.com//notes/git-alias.html" />
   <updated>2012-09-16T12:30:00+00:00</updated>
   <id>http://brendanforster.com/notes/git-alias.html</id>
   <content type="html">
	<![CDATA[<h3>Why do I need alias?</h3>

<p>One of my favourite bits of "feedback" from Mercurial users is that "you don't need to type out the full command with hg - git is dumb" or something like that. While they're not totally incorrect here, they are comparing the out of the box experiences between git and hg.</p>

<p>Mercurial will recognise shorthand for commands when you type enough characters to distingush the right command, like:</p>

<pre><code>hg com -&gt; hg commit
hg sta -&gt; hg status
hg sum -&gt; hg summary
hg ci -&gt; hg commit 
</code></pre>

<p>That's right, hg does <a href="http://mercurial.selenic.com/wiki/AliasExtension">aliases</a> too...</p>

<p>Git however will scream at you when you mistype a command. And you will swear in return (either at yourself or at git).</p>

<p>So to save yourself from screaming in the future, you can customise git to recognise custom commands. It will save you so much time.</p>

<p>Aliases are stored per-user in the <code>.gitconfig</code> file - or in the <code>.git/config</code> file for a repository. All the below scripts will install in the global config file - but you can drop the <code>--global</code> parameter if you don't want that behaviour.</p>

<h3>Adding shorthand as aliases</h3>

<p>Here's some shorthand commands for the common git tasks:</p>

<pre><code># git st
git config --global alias.st "status"   
# git co 
git config --global alias.co "checkout" 
# git ci
git config --global alias.ci "commit"   
# git br
git config --global alias.br "branch"   
# git df
git config --global alias.df "diff"     
# git lp
git config --global alias.lp "log -p"   
</code></pre>

<p>These are some of the common examples from the <a href="http://gitready.com/intermediate/2009/02/06/helpful-command-aliases.html">here</a>.</p>

<h3>Customising existing commands</h3>

<p>My favourite example of this is a prettier output from <code>git log</code> - so you can see at a glance the activity on the branch you are currently working on:</p>

<pre><code># git lg
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative"
</code></pre>

<p>Of course, someone far smarter than me <a href="http://www.jukie.net/bart/blog/pimping-out-git-log">wrote this one</a>...</p>

<p>A few simpler ones:</p>

<pre><code># git com -&gt; checkout master
git config --global alias.com "checkout master"

# git fe -&gt; fetch latest changes
git config --global alias.fe "fetch origin"

# git hr -&gt; hard reset state of master
git config --global alias.hr "reset origin/master --hard"

# git me -&gt; get my user name
git config --global alias.me "config user.name"
</code></pre>

<p>And you can even embed scripts into an alias. Here's a couple of simple scripts to see what commits have been added for today (by me any by others):</p>

<pre><code># git today
git config --global alias.today "!git all --since='12am' --committer=\"`git me`\""

# git today-all
git config --global alias.today-all "!git all --since='12am'"

# git bn -&gt; get current branch name
git config --global alias.bn "!git for-each-ref --format='%(refname:short)' `git symbolic-ref HEAD`"
</code></pre>

<p>Do you see where we're going with this? :)</p>

<h3>Mashing commands together</h3>

<p>Remember how in my <a href="/notes/my-git-habits.html">last post</a> I mentioned a rather verbose workflow for merging in changes?</p>

<p>Well let's take it away with one simple command: <code>sync</code></p>

<pre><code># git sync
git config --global alias.sync "!git update &amp;&amp; git co master &amp;&amp; git pull &amp;&amp; git co @{-1}" 
</code></pre>

<p>But that's rather basic - it doesn't actually rebase my branch that I'm on.</p>

<p>Let's do a slightly different command: <code>resync</code></p>

<pre><code># git resync -&gt; sync repository and rebase current branch    
git config --global alias.resync "!sh -c 'BRANCH_NAME=$(git bn) &amp;&amp; git com &amp;&amp; git fe &amp;&amp; git hr &amp;&amp; git rebase master $BRANCH_NAME'"
</code></pre>

<p>Note how this one uses aliases defined earlier in the post for readability? Yeah, it's rad.</p>

<h3>I'm lazy, give me the gist of it (lol pun)</h3>

<p>I'm checking some other git repos I have lying around to ensure I have all my aliases in one spot, but in the meantime open your <code>~/.gitconfig</code> file (check <code>C:\Users\{username}\</code> if you're on Windows) and paste these values under the <code>[alias]</code> node. If the <code>[alias]</code> node doesn't exist, create it.</p>

<script src="https://gist.github.com/3732023.js?file=.gitconfig"></script>


<p>Got a cool alias you want to share? Fork the gist above!</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>My Git Habits</title>
   <link href="http://brendanforster.com//notes/my-git-habits.html" />
   <updated>2012-09-16T06:30:00+00:00</updated>
   <id>http://brendanforster.com/notes/my-git-habits.html</id>
   <content type="html">
	<![CDATA[<p>First up, a disclaimer: <strong>This is just one person's opinion and should be treated as such.</strong></p>

<p>If you workflow is similar, that's great. If you workflow is radically different, that's great too. With things like git its very easy to have different workflows, so I'll just be speaking from my experiences here.</p>

<h3>Introduction</h3>

<p>Generally speaking, my git flow is based off the <a href="https://github.com/NancyFx/Nancy/wiki/Git-Workflow">documentation</a> for contributors to the NancyFx project. When working on features, this is my high-level flow:</p>

<ol>
<li>Create a local branch for the feature</li>
<li>Work on your feature and get it reviewed -- you do code reviews, right?</li>
<li>Merge the changes into master</li>
<li>Push the changes up to the remote repository</li>
</ol>


<p>How does that look from the comamnd line?</p>

<ul>
<li>git checkout -b ReallyCoolFeature master</li>
<li>... stuff gets done ...</li>
<li>git add -u . -- add all removes and modifies to the staging area</li>
<li>git add .    -- add new files to the staging area</li>
<li>git commit -m "#1234 implemented" -- associating commits with work items is awesomely helpful</li>
<li>git checkout master</li>
<li>git pull origin/master</li>
<li>git merge ReallyCoolFeature</li>
<li>git push origin master</li>
</ul>


<p><strong>Note:</strong> Yeah, I like to be explicit with my remotes and branch names in these commands. Haters gonna hate.</p>

<p>But that's all fairly straight-forward and not really leveraging the <a href="http://think-like-a-git.net/sections/git-makes-more-sense-when-you-understand-x/example-4-lsd-and-chainsaws.html">new states of mind</a> that git makes possible.</p>

<h3>Rebase all the things</h3>

<p>Where git truly comes into its own is with rebasing. For those who aren't familiar with it, rebasing allows you to change the history of a branch. This is generally considered very bad&#0153; to do with public repositories but when you use it only locally it gives you so much control over everything.</p>

<p>For example, have you ever:</p>

<ul>
<li>used a branch for multiple, disparate tasks that you wish you could reorder for readability?</li>
<li>accidentally forgot to save a file and had to spread a task over multiple commits as a result?</li>
<li>wanted to update an old branch to the latest changes and avoid merge conflicts?</li>
<li>wanted to split out a branch into multiple branches and process them separately?</li>
</ul>


<p>If you consider a branch to be a chain of commits - with a parent commit representing the creation point of the branch - then rebasing is the operation to:</p>

<ul>
<li>change the creation point of a branch</li>
<li>change the order of the commits in a branch</li>
<li>change the commits in a branch - squash commits together</li>
<li>remove commits from a branch</li>
</ul>


<p>At this point you are probably thinking "Oh man, I'm going to nuke my branch and lose all my work" but if you look more closely at what the rebase does, you'll find that its a lot safer than you think.</p>

<p>A rebase operation will</p>

<ul>
<li>set the repository to the new creation point</li>
<li>create a temporary branch just for this rebase operation</li>
<li>apply the commits one by one to ensure they apply cleanly</li>
<li>update the pointers for the branch and remove the temporary branch</li>
<li>set the repository to the last commit of the new branch</li>
</ul>


<p>When I say "ensure the commits apply cleanly" here, I indicate that git will ensure that additions and subtractions to each file make sense. If they don't (for example, the file has changed significantly enough), it will pause and ask the user to manually confirm the commit.</p>

<p>At any point during a rebase that requires user input, you can abort and git will roll back to the state it was in before the rebase operation started.</p>

<h3>Speak English, Brendan!</h3>

<p>So I got side-tracked a bit just then. Apologies.</p>

<p>So what do I use rebasing for?</p>

<ul>
<li><em>reordering</em> - if I do a bit of code cleanup during my work, that remains separate from the current task and can be put before/after when reviewing code</li>
<li><em>squashing</em> - generally speaking, your commits should be granular enough to be easy to follow. But sometimes things go too far and you want to bring related commits together (e.g. missed deleting a file from the previous commit)</li>
<li><em>splitting</em> - if you've got a complex branch you could split it up into multiple branches and integrate them in gradually.</li>
</ul>


<p>All of this is possible by using interactive rebase - before it kicks off the operation, it displays the commits available and allows you to specify the operations to perform.</p>

<p><strong>Note:</strong> There's two minor differences when you squash commits together. One operation, <code>fixup</code>, is intended to merge a commit without including the commit message. The other, <code>squash</code>, will bring the commit message across and allow you to edit the commit message after the squash.</p>

<h3>Merging is overrated anyway</h3>

<p>Yes, that might be a controversial thing to say at this point. Merges are considered important to indicate when two branches have been brought together. But I submit to you, the jury of the internet - do we really need it? I'm not advocating abandoning merges at all - they have a purpose, which is to indicate changes additional to the branch being merged in.</p>

<p>If I can rebase a branch on top of the current master, I've just avoided the need for a merge commit completely (it becomes a fast-forward merge and the pointers are moved forward). I can then push and get on with the next task.</p>

<p>I guess this comes back to how you use branches. Git works excellently when you create a branch for a task, integrate the code into master, and delete the branch once its reached the end of its useful life.</p>

<p>Not everyone can work that way (that might be a rant for another day), but I see this a discipline issue rather than a pro/con of the tool itself.</p>

<h3>My Opinionated Git Flow</h3>

<p>So with a slight tweak to step 3, my flow becomes:</p>

<ol>
<li>Create a local branch for the feature</li>
<li>Work on your feature and get it reviewed -- you do code reviews, right?</li>
<li>Rebase the branch on master</li>
<li>Push the changes up to the remote repository</li>
</ol>


<p>How does that look from the comamnd line?</p>

<ul>
<li>git checkout -b ReallyCoolFeature master</li>
<li>... stuff gets done ...</li>
<li>git add -u . -- add all removes and modifies to the staging area</li>
<li>git add .    -- add new files to the staging area</li>
<li>git commit -m "#1234 implemented" -- associating commits with work items is awesomely helpful</li>
<li>git checkout master</li>
<li>git pull origin/master master</li>
<li>git rebase master ReallyCoolFeature</li>
<li>git checkout master</li>
<li>git merge ReallyCoolFeature --ff-only</li>
<li>git push origin master</li>
</ul>


<p>Combine that with some hot git alias action (this is getting fairly long as-is), you can strip away much of those commands into a simple "sync" step which you run against the branch you are working on.</p>

<h3>What's next?</h3>

<p>I could go on about using <code>reset</code> and <code>cherry-pick</code> commands and head further down the git rabbit hole, but I think the next posts should cover these things:</p>

<ul>
<li><code>git alias</code> - seriously, this is like crack for scripters</li>
<li>a general rant about discipline when managing commits - git has corrupted my brain, and I've found myself applying concepts to situations where I have used other VCSes (even TFS, not using git-tfs or tf-git)</li>
</ul>

]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Sharing my personal backlog with the world</title>
   <link href="http://brendanforster.com//visible-personal-backlog.html" />
   <updated>2012-07-16T10:30:00+00:00</updated>
   <id>http://brendanforster.com/visible-personal-backlog.html</id>
   <content type="html">
	<![CDATA[<p>Ever since I got back from holidays a few weeks ago I've been in a bit of a rut trying to tackle the backlog of stuff I've been meaning to do (projects half-done, contributions I've promised other people, things I've been meaning to blog about).</p>

<h3>The Experiment</h3>

<p>This experiment comes down to three simple things:</p>

<ul>
<li>maintain a list of tasks which need to be done (ordered by priority)</li>
<li>focus on one thing at a time</li>
<li>make it visible to the world to add some peer input to the situation</li>
</ul>


<p>For the tool to make this happen, I've decided to use <a href="https://trello.com/">Trello</a>. After using Trello for the Code52 projects in the past, I felt that it was the best fit between ease of administration and ease of viewing.</p>

<p>The board is hosted at <a href="https://trello.com/board/public-backlog/50039c94fe5e1f8037b9b583">https://trello.com/board/public-backlog/50039c94fe5e1f8037b9b583</a>.</p>

<h3>What can you do?</h3>

<p>You should be able to leave a comment on any of the items currently there. What sort of comments would help? Things like:</p>

<ul>
<li>"Can you explain this one?" (I've been too brief with a task which may be complex)</li>
<li>"Can you do this sooner?" (this is something you are interested in)</li>
<li>"Can I help out with this?" (this is something you might be able to help out with)</li>
</ul>


<h3>Caveats</h3>

<p>This is something that I'll flesh out over the next few days and there may be some details missing.</p>

<p>There are some items on the list which are deliberately vague - I'll indicate which tasks are "teasers" at this point in time, but I've got no issues with you seeing where they sit in my priority queue.</p>

<p>And there are some things which I just can't plain talk about (but really need to do anyway) so I'll need to figure out a way to represent them properly. Not everything on my plate at the moment is OSS work :)</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>So I accidentally a web guy MVP</title>
   <link href="http://brendanforster.com//so-i-accidentally-a-web-guy-mvp.html" />
   <updated>2012-07-08T10:30:00+00:00</updated>
   <id>http://brendanforster.com/so-i-accidentally-a-web-guy-mvp.html</id>
   <content type="html">
	<![CDATA[<p>So I just had this little email land in my inbox last week.</p>

<blockquote><p>Congratulations! We are pleased to present you with the 2012 Microsoft MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP.NET/IIS technical communities during the past year.</p></blockquote>

<p>After the chaos of first half of the year (which I still want to get back to, just trying to summon the energy again after a brief respite to head over to NDC this year) this caught me off-guard, but has been an honour to accept nonetheless.</p>

<p>I'll comment a bit further on the details once I've signed away my life and get an idea of what's involved, but given the ASP.NET dev stack (well, the <em>good</em> bits anyway ::smileyface::) is now on <a href="http://aspnetwebstack.codeplex.com/">Codeplex</a> I'm keen to spend some time digging into that and helping out wherever my powers might be of benefit.</p>

<p>There's also shiny things coming along in the upcoming release (I've hacked a bit on Web API, and Single Page Apps is on my radar but I haven't used in anger) which are on my never-ending TODO list.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Introducing code52</title>
   <link href="http://brendanforster.com//introducing-code52.html" />
   <updated>2012-01-03T10:30:00+00:00</updated>
   <id>http://brendanforster.com/introducing-code52.html</id>
   <content type="html">
	<![CDATA[<p>Back from a self-imposed internet break (taking a phone which doesn't do 3G coverage and going rural is a good way to do this) and <a href="http://twitter.com/aeoth">Paul</a> and <a href="http://twitter.com/tobin">Tobin</a> couldn't wait to kick off our new collaborative project.</p>

<center><a href="http://code52.org"><img class='right ' src='/img/posts/Code52/logo.png' width='' height='' alt='' title=''></a></center>


<br/>


<p>There's a bit more of a blurb on <a href="http://code52.org/about.html">the website</a> - its an idea we're still wrapping our heads around by using a bit of trial and error.</p>

<p>We're already hard at work on our <a href="http://code52.org/downmarker">first project</a> and we'd love to see people drop into the <a href="http://jabbr.net/#/rooms/code52">Jabbr room</a> and get involved. Amd pf course, there's a <a href="http://twitter.com/code_52">Twitter account</a> too to follow.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>2011 - Where did the time go?</title>
   <link href="http://brendanforster.com//2011-recap.html" />
   <updated>2011-12-20T12:00:00+00:00</updated>
   <id>http://brendanforster.com/2011-recap.html</id>
   <content type="html">
	<![CDATA[<p><article></p>

<p>Three more days til Christmas. I intend to unplug completely from the internet from then until the end of the year (place a bet with your nearest bookie on the odds I'll crack before then) so I'm writing this now over a cold beer, wondering where the hell the year went - as well as the hot weather.</p>

<p><img class='right ' src='/img/main/recap-lrg.jpg' width='600' height='400' alt='' title=''></p>

<p>So where did 2011 go? Let's recap:</p>

<h2>Perth</h2>

<p>Work sent me over to Perth to work with a client between February and April. It was an interesting project, but the real fun was catching up with the developer community over beers (and they love their beer over in Perth). Particular shout outs to <a href="http://twitter.com/jakeginnivan">Jake Ginnivan</a> (a "brother from another mother" according to someone who shall remain nameless) and <a href="http://twitter.com/jtango18">JT</a> for making the non-work hours as <a href="http://www.hulabulabar.com">entertaining</a> as humanly possible.</p>

<p>I also managed to catch up with relatives over there over there (my cousin, her husband and three young kids live in Perth) and see some bands:</p>

<ul>
<li><a href="http://streetlightmanifesto.com/">Streetlight Manifesto</a> - two hours in the mosh pit is enought for any man. An item crossed off the bucket list.</li>
<li><a href="http://westcoastbluesnroots.com.au/">West Coast Blues and Roots Festival</a> - finally got to see Cat Empire live, and a bunch of other artists. Toots and the Maytals was an unexpected pleasure.</li>
</ul>


<p>The only downside of my time in Perth was that my grandma passed away after having a stroke last year - it felt weird being away from the family when it all occurred, but I went back for the funeral to say my farewells.</p>

<h2>NDC and Europe</h2>

<p>While I was over in Perth, I was also madly planning my Europe trip. It coincided with <a href="http://www.ndcoslo.com/">NDC</a> which was an amazing conference in itself.</p>

<p>In no particular order:</p>

<ul>
<li>pre-drinks with Richard Campbell, Rob Conery, Shay Friedman and others (fairly certain I still owe Richard a Famous Grouse for something).</li>
<li>three days jam packed with content - I can't recall another event where I'd have three or more sessions in the same timeslot I wanted to see.</li>
<li>some great parties after the official one ;)</li>
<li>hammocks to recover in after! (while mocking certain Brits on Twitter)</li>
<li>an epic technical discussion over post-conference drinks with <a href="http://twitter.com/kkzomic">Krzysztof</a>, <a href="http://twitter.com/philiplaureano">Philip</a> and <a href="http://twitter.com/gfraituer">Gael</a> (I tried to keep up but my brain had been melted over the previous days) before we all went our separate ways.</li>
</ul>


<p> <center><img class='' src='/img/posts/recap/hammock.jpg' width='' height='' alt='' title=''></center></p>

<p>After the conference I headed up to Stavanger with Philip - it was a lot of fun to talk shop while hiking for a couple of hours to what is essentially <a href="http://i.telegraph.co.uk/multimedia/archive/01359/Stavanger_1359940c.jpg">a giant rock in the middle of nowhere</a>. I was also invited to stay a few days with <a href="http://twitter.com/thomasjo">Thomas Johanson's</a> family in rural Norway - which was capped off with a Norweigan BBQ and aquavit!</p>

<p>After Norway, I spent a weekend in Copenhagen seeing the sights and ran into <a href="http://umbraco.com/cg11">some Umbraco guys doing whatever those Umbraco guys do</a>.</p>

<p>Then it was onward to Germany (a week of beer and sight-seeing) and France (a week of wine and beer and sight-seeing).</p>

<p>Highlights:</p>

<ul>
<li>the quickest <a href="/inotifypropertychanged-stop-the-madness.html">blog post</a> I've written (about 20 minutes), which still gets mentions in odd places</li>
<li>having dinner and drinks with a group of Romanian retirees in Berlin. I didn't speak Romanian, they didn't speak English, but the staff were excellent mediators and fun was had by all.</li>
<li>our pub crawl group being scolded by a German/French waiter in Hofbrauhaus Munich for being too loud with our chanting - "Zis is not Oktoberfest!".</li>
<li>visiting the Dachau concentration camp outside Munich and standing inside a gas chamber - an experience I still can't put into words.</li>
<li>drinking the train's bar cart dry of beer with a gang of tourists when the train from Munich to Paris broke down at Metz for a few hours.</li>
<li>wandering around Paris and accidentally finding Voltaire's tomb (as well as other famous French figures like Marie Curie) at the Pantheon.</li>
</ul>


<center><img class='' src='/img/posts/recap/voltaire.jpg' width='' height='' alt='' title=''></center>




<br />


<h2>BUILD and Los Angeles</h2>

<p>Aside from unveiling the new version of Windows, and causing a collective conniption of the .NET community with their <a href="http://dougseven.com/2011/09/15/a-bad-picture-is-worth-a-thousand-long-discussions/">marketecture diagrams</a>, it was an entertaining conference to chat with the guys behind the products. They'd been very quiet for a while, and were keen to talk to anyone at the conference who'd lend them an ear.</p>

<p><strong>Ed:</strong> <em>I'll come back to this discussion. I do want to fuel <a href="http://twitter.com/MossyBlog">someone's</a> rage on the topic :)</em></p>

<p>On top of that there was Legoland - if I was ten years old, it would have been paradise. But I still enjoyed a bunch of things there - the Star Wars Lego was particularly good.</p>

<center><img class='' src='/img/posts/recap/cantina.jpg' width='' height='' alt='' title=''></center>




<center>The Cantina Bar from A Lost Hope (complete with animatronic band)</center>




<br />


<p>Ran into some Aussie friends who are now state-side, like <a href="http://twitter.com/jthake">Jeremy Thake</a>, <a href="http://twitter.com/damianedwards">Damian Edwards</a> (again) and <a href="http://twitter.com/will_robertson">Will Robertson</a>.</p>

<h2>Community Stuff</h2>

<p>I branched out into doing more presentations this year - not something deliberate, just opportunities crop up and I do enjoy jumping into the deep end:</p>

<ul>
<li><strong>dddMelbourne</strong> - Ruby and .NET for fun and profit</li>
<li><strong>Newcastle Coders Group</strong> - XAML - past, present and future.</li>
<li><strong>RDN Dev Day</strong> - Practical Applications of the Modern Web</li>
<li><strong>ALT.NET Sydney</strong> - Recap from BUILD</li>
<li><strong>Windows Phone 7 Workshops</strong> (Sydney and Perth)</li>
<li><strong>dddBrisbane</strong> - Windows 8 - Who Moved My Cheese?</li>
</ul>


<h2>What's next for 2012?</h2>

<p>Can I have a good nap and get back to you on that?</p>

<p></article></p>

<div style="margin-top: 50px">
<em>Image: http://www.flickr.com/photos/opethpainter/2866967426/</em>
</div>

]]>
   </content>
   
 </entry>
 
 <entry>
   <title>ALT.NET Open Spaces Recap</title>
   <link href="http://brendanforster.com//alt-net-open-spaces-2011.html" />
   <updated>2011-12-03T08:00:00+00:00</updated>
   <id>http://brendanforster.com/alt-net-open-spaces-2011.html</id>
   <content type="html">
	<![CDATA[<p>I flew down to Melbourne this weekend to catch up with the locals and talk about various topics around the .NET space. Here's the abridged recap - each session was scheduled for about 30 minutes and we (mostly) stuck to the schedule during the day.</p>

<p>Disclaimer: I was sleep deprived and recovering from a party the night before. I may be recalling things differently to how they actually happened. Hell, I'm fairly certain I have the sessions listed out of order.</p>

<p><em>There's supposed to be a photo here, but the only one I found (that's right, I didn't bother to take photos myself) was on lockerz.com, which seems to be a site that wants your Facebook details in exchange for something called "grab it". I'm not even going to link to it, that's how disappointed I am...</em></p>

<h3>User Groups</h3>

<p>We started off the day with a discussion on how everyone perceived the user groups they attend - what works, how to grow a user group, discussions and war stories and whatnot. A lot of good ideas came out of this, which will hopefully materialies in the new year.</p>

<p><em>We had tacked on a session for talking about open source, but that seemed to have fallen through the cracks when the discussion for user groups went on longer than expected. Sadface.</em></p>

<h3>Code Dojo</h3>

<p>As a follow up of the ALT.NET code dojo recently, the group discussed <a href="http://codekata.pragprog.com/2007/01/kata_fourteen_t.html">this kata</a> and how to solve the problem. Unfortunately things got sidetracked (I was most annoyed I hadn't heard about this 'trigram' concept before) and we didn't get to demonstrate a good TDD design before the session expired. But it was still an entertaining discussion on how to tackle a problem, even if we didn't agree on much.</p>

<h3>New Frontiers</h3>

<p>After a quick break, we discussed how languages outside the .NET ecosystem have impacted on .NET and what might be coming down the pipe. A few takeaways from the discussion - some people wanted more concepts to be brought into C#, while others were feeling that the "one language to rule them all" didn't feel right.</p>

<h3>Refactoring</h3>

<p>I teamed up with <a href="http://twitter.com/rbanks54">Richard</a> to talk about refactoring existing code, R# tips and tricks, and Richard shouting at me to "no no, go down, not up" when navigating some sample code from ages ago. Was fun.</p>

<h3>RAD Frameworks</h3>

<p>And here's where things got entertaining. What started out as a discussion of tools and libraries to simplify building apps.</p>

<p><strong>First things first:</strong> as soon as 'RAD' was mentioned, it was a red rag to much of the audience. It wasn't the intent, but all attempts to refocus the discussion failed miserably.</p>

<p><strong>Secondly:</strong> I was fascinated by the number of people who were anti-third party libraries for their UIs. They preferred to roll their own, but I didn't push the discussion into why. Perhaps this is my background in client apps clouding my perceptions...</p>

<p><strong>Lastly:</strong> data access. Oh man, I'm sick to death of this discussion. There's so many choices that whenever someone asks why I'm not using XYZ I have to physically force myself to listen. Can we move on as a society?</p>

<h3>"What if this is as good as it gets?"</h3>

<p>This was a neat discussion about how someone might go about staying in a technical career with software development and avoid the whole "management" position in the hierarchy. Of course, he was currently doing Sharepoint, so that was noted and made fun of.</p>

<p><em>A few dedicated souls continued on this thread of discussion at the pub after and came to a concensus that there was a correlation between architect-style roles and a conservative approach to new technologies. We had a number of ideas around how to bridge this gap, but its always been a tricky challenge in my experiences when working with clients.</em></p>

<h3>Code Coverage and Analysis</h3>

<p><a href="http://twitter.com/scubamunki">Shaun</a> discussed some of his work with code coverage tools and some gotchas with the code. This was the first time I'd heard of OpenCover (<em>audible gasp</em>), an OSS project he works on, and it was awesome to catch up with him after and have my brain melted by another IL junkie :)</p>

<h3>Agile Discussion</h3>

<p>This was the point where I ran out of steam - 4:30am starts will do that to a guy. We discussed how agile projects manage the relationships with stakeholders, <em>scene missing</em> and something about estimation?</p>

<p>Anyway, as we wrapped up at about 3ish a few of the group headed to the pub up the road for further discussion. I'd worked in Melbourne last year, so it was great to catch up with the locals again and talk shop.</p>

<h3>Wrapup</h3>

<p>Big thanks to <a href="http://twitter.com/pjimmy">@pjimmy</a> for organising the event and to <a href="http://twitter.com/rbanks54">Richard</a> for helping with herding cats in the morning. It was a great event, and hopefully it'll be back bigger and better next year - there's rumours abound about a Sydney event next year.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>jQuery and KnockoutJS in Win8? Sure, why not!</title>
   <link href="http://brendanforster.com//jquery-knockout-win8.html" />
   <updated>2011-10-25T13:00:00+00:00</updated>
   <id>http://brendanforster.com/jquery-knockout-win8.html</id>
   <content type="html">
	<![CDATA[<p>Apparently this is old news to some. Trendsetters...</p>

<p>With Windows 8 supporting HTML/JS (I refuse to call anything HTML5 these days - the words have lost all meaning to me, but that's another topic) applications, I was asked if <a href="http://jquery.com/">jQuery</a> is supported - with a goal to making JS applications more maintainable.</p>

<p>As I'd heard it mentioned at BUILD - and hadn't heard a major drama since people have been using the Developer Preview bits - I expected that it worked. However, to confirm this for myself, I found this <a href="http://social.msdn.microsoft.com/Forums/en-US/winappswithhtml5/thread/66273417-92cd-4a35-b9a1-281d962eff59">forum thread</a> on MSDN with a couple of caveats.</p>

<p>No fire and brimstone? Oh well, I'll just double-check...</p>

<p>After adding the jQuery file to the project, I modified the <strong>default.html</strong> file to include the jQuery file <strong>before</strong> the default.js file. The default.js file contains the bootstrapping code for the application:</p>

<pre><code>   &lt;link rel="stylesheet" href="/css/default.css" /&gt;
    <strong>&lt;script src="/js/jquery-1.6.4.js"&gt;&lt;/script&gt;</strong>
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;

</code></pre>


<p>And at the bottom of the default.js file, I use a simple selector to find a DOM element:</p>

<pre><code>            // other code

            WinJS.UI.process(<strong>$('#appbar')[0]</strong>)
                .then(function () { 
                    <strong>$('#home').click(navigateHome);</strong>
                });

            WinJS.Navigation.navigate(homePage);

            <strong>var host = $('#contentHost');</strong>
        }
    }

    WinJS.Navigation.addEventListener('navigated', navigated);
    WinJS.Application.start();

})();
</code></pre>


<p>and started making use of selectors elsewhere instead of document.getElementById to make the code more concise...</p>

<h2>And what of KnockoutJS?</h2>

<p>I've only had basic experience with <a href="http://knockoutjs.com/">Knockout</a>, but found an easier scenario to support. I dropped in the code and modified the detailPage template.</p>

<pre><code>   &lt;link rel="stylesheet" href="/css/default.css" /&gt;
    &lt;link rel="stylesheet" href="/css/detailPage.css" /&gt;
    &lt;script type="ms-deferred/javascript" src="/js/detailPage.js"&gt;&lt;/script&gt;
    <strong>&lt;script type="ms-deferred/javascript" src="/js/knockout-1.2.1.js"&gt;&lt;/script&gt;</strong>
&lt;/head&gt;

</code></pre>


<p>And then went to work making changes:</p>

<p><strong>In detailPage.js</strong></p>

<p><em>Before</em></p>

<pre><code>function fragmentLoad(elements, options) {
    var item = options &amp;&amp; options.item ? options.item : getItem();
    elements.querySelector('.pageTitle').textContent = item.group.title;

    WinJS.UI.processAll(elements)
        .then(function () {
            elements.querySelector('.title').textContent = item.title;
            elements.querySelector('.content').innerHTML = item.content;
        });
}
</code></pre>

<p><em>After</em></p>

<pre><code>function fragmentLoad(elements, options) {
    var item = options &amp;&amp; options.item ? options.item : getItem();
    WinJS.UI.processAll(elements).then(function () { <strong>ko.applyBindings(item);</strong> });
}
</code></pre>


<p><strong>In detailPage.html - declared some bindings using the data-bind attribute</strong></p>

<pre><code>&lt;div class="detailPage fragment"&gt;
    &lt;header role="banner" aria-label="Header content"&gt;
        &lt;button disabled class="win-backbutton" aria-label="Back"&gt;&lt;/button&gt;
        &lt;div class="titleArea"&gt;
            &lt;h1 class="pageTitle win-title" <strong>data-bind="text: group.title"</strong>&gt;&lt;/h1&gt;

        &lt;/div&gt;
    &lt;/header&gt;
    &lt;section role="main" aria-label="Main content"&gt;
        &lt;article&gt;
            &lt;div&gt;
                &lt;header&gt;

                    &lt;h1 class="title win-contentTitle" <strong>data-bind="text: title"</strong>&gt;&lt;/h1&gt;
                &lt;/header&gt;
                &lt;div class="image" <strong>data-bind="style: { color: backgroundColor }"</strong>&gt;&lt;/div&gt;
                &lt;div class="content" <strong>data-bind="html: content"</strong>&gt;&lt;/div&gt;
            &lt;/div&gt;

        &lt;/article&gt;
    &lt;/section&gt;
&lt;/div&gt;
</code></pre>


<p>So by moving the binding expressions to the UI (like the MVVM pattern that is popular with XAML application) we can lean on frameworks to make our Javascript code easier to maintain. Other components of the default templates have their own binding attributes - <em>data-win-bind</em> - which I'll explain later, but I find the KnockoutJS syntax more concise.</p>

<p>In particular the use of <em>textContent</em> instead of <em>text</em> to denote a text value? Why? Drop the 'Content' part unless there's a real good reason - it feels like ceremony.</p>

<p>I'll formulate some more opinions on the WinJS side as I delve deeper....</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>I'm speaking at DDD Brisbane</title>
   <link href="http://brendanforster.com//ddd-brisbane.html" />
   <updated>2011-10-22T13:00:00+00:00</updated>
   <id>http://brendanforster.com/ddd-brisbane.html</id>
   <content type="html">
	<![CDATA[<p><img src='/img/main/metro-preview.png' width='400' height='300' alt='' title='' style='float: right;margin-left: 1.5em;'></p>

<p>The <a href="http://dddbrisbane.com">dddBrisbane</a> organisers sent out a call over the weekend to finalise the schedule - some very cool talks that I'm looking forward to seeing (look for the schedule to appear early this week).</p>

<p>I'm especially honoured to see my session was picked - especially after seeing the depth of Windows 8 talks submitted.</p>

<p>So what am I talking about?</p>

<h2>Windows 8 - Who Moved My Cheese?</h2>

<p>The slides are available on <a href="http://ddd-windows8.heroku.com">Heroku</a>.</p>

<p>The source code for the slides are available on <a href="http://github.com/shiftkey/dddbrisbane">Github</a>.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Doing the build server dance with NuGet</title>
   <link href="http://brendanforster.com//doing-the-build-server-dance-with-nuget.html" />
   <updated>2011-07-08T04:00:00+00:00</updated>
   <id>http://brendanforster.com/doing-the-build-server-dance-with-nuget.html</id>
   <content type="html">
	<![CDATA[<p>I started exploring NuGet package building yesterday evening, as a strategy for managing dependencies between projects I'm involved with.</p>

<p>And with NuGet in the enterprise being the <a href="http://www.hanselman.com/blog/NuGetForTheEnterpriseNuGetInAContinuousIntegrationAutomatedBuildSystem.aspx">upcoming hotness</a>, I thought I'd see how I could get companies I work with to start doing similar things with their internal projects. It was much easier than I'd expected, with a couple of hurdles.</p>

<h2>The Goal</h2>

<p>I have two projects, A and B. A has no upstream dependencies (that have NuGet packages, anyway), but B requires A.</p>

<p>So, after A builds and passes its tests, I want to:</p>

<ul>
<li>Create a new package for A, using it's build number.</li>
<li>Publish the package for A somewhere</li>
<li>Trigger a new build for B, using the newest version of A.</li>
<li>Verify B builds and passes tests.</li>
<li>Create a new package for B, using it's build number.</li>
<li>Publish the package for B somewhere.</li>
</ul>


<p>After a couple of hours work, I'm 95% of the way there.</p>

<h2>Defining the package specification</h2>

<p>As I wasn't really familiar with the process of creating the .nuspec file (sorry <a href="http://twitter.com/damianedwards">Damo</a>, your NDC talk was a long time ago :)) I decided to go and craft it by hand. I used this <a href="http://lostechies.com/joshuaflanagan/2011/06/23/tips-for-building-nuget-packages/">blog post</a> by <a href="http://twitter.com/jflanagan">Joshua Flanagan</a> (including a good reference <a href="https://github.com/DarthFubuMVC/bottles/blob/6d82e063fd889ac1909c98adc369a97b4c1e377e/packaging/nuget/bottles.nuspec">nuspec file</a>) to get started.</p>

<p>And that's about it. Put that into my build folder along with the NuGet.exe - I grabbed the latest one from the 1.4 OOB build on <a href="http://ci.nuget.org:8080/">NuGet CI server</a> due to an issue with how it parses the &lt;files&gt; element. This should be part of the next release.</p>

<h2>Building the package on the server</h2>

<p>So, I'm using TeamCity to build the project. Thus, I can use the build number directly against the NuGet package.</p>

<p>NOTE: Using the default value TeamCity provides for a project, which is just an incrementing integer, will fail with a "Version string portion was too short or too long" error. To fix that, go to General Settings and make it something more descriptive:</p>

<p><img src="img/posts/NuGet/BuildNumber.png" alt="General Settings" /></p>

<p>With that in place, the next step is to add in a post-build step:</p>

<p><a href="/img/posts/NuGet/PackageStep.png"><img src="/img/posts/NuGet/PackageStep-Small.png" alt="Post Build Step" /></a></p>


<p>The script I've used (duplicated for two different packages):</p>

<pre><code>del *.nupkg

.\NuGet.exe pack Package.nuspec -Version %system.build.number%
</code></pre>

<p>That script is courtesy of Scott Kirkland, who also has a decent guide to using NuGet on TC <a href="http://weblogs.asp.net/srkirkland/archive/2011/03/29/deploy-nuget-packages-during-ci-build-with-teamcity.aspx">here</a></p>

<h2>Publishing the package</h2>

<p>I didn't want to publish these packages to the NuGet gallery immediately, so what other options do I have? I could set up my own NuGet gallery. Or I could use <a href="http://www.myget.org/">MyGet</a> and skip all the hassle.</p>

<p>For those who aren't familiar with MyGet, its a service to create custom NuGet feeds. All I've done so far is create a private feed (which anyone can consume) and obtained an API key.</p>

<p><a href="img/posts/NuGet/myget.png"><img src="img/posts/NuGet/myget-small.png" alt="Post Build Step" /></a></p>


<p>While MyGet supports the ability to upload or create packages within the admin UI, I was feeling lazy and wanted to push packages from the build server.</p>

<p>This required an additional line in the script:</p>

<pre><code>del *.nupkg

.\NuGet.exe pack Package.nuspec -Version %system.build.number%

forfiles /m *.nupkg /c "cmd /c NuGet.exe push @FILE &lt;your-key&gt; -Source https://www.myget.org/F/mahapps/"
</code></pre>

<p>which will find all .nupkg files and invoke <em>push</em> against the specific repository - in this case, my private feed.</p>

<h2>Trigger a new build</h2>

<p>This isn't directly related to NuGet, but I wanted to force a new build when upstream packages change in TeamCity.</p>

<p>Under Build Triggering in the Project Configuration, add a trigger for "Finish Build" and select the upstream project.</p>

<p><a href="img/posts/NuGet/buildtriggering.png"><img src="img/posts/NuGet/buildtriggering-small.png" alt="Add Build Trigger" /></a></p>


<h2>Update the package for A and test</h2>

<p>Right, this is where things get rough.</p>

<p>I added a step before building the project, and executed this command:</p>

<pre><code>.\Nuget.exe update ..\MahApps.Twitter.sln -Source http://www.myget.org/f/mahapps
</code></pre>

<p>which will look through all the projects in my solution and update to the newest packages it can find. I've added in my MyGet feed URL to grab the latest packages from the specific feed.</p>

<p>And this works. Kinda.</p>

<p><a href="img/posts/NuGet/updatescripts.png"><img src="img/posts/NuGet/updatescripts-small.png" alt="Success?" /></a></p>


<p>It updates my projects, but doesn't store updated packages locally.
Which causes my build to break.</p>

<p><a href="img/posts/NuGet/compileerrors.png"><img src="img/posts/NuGet/compileerrors-small.png" alt="Oops" /></a></p>


<p>Scouring the forums produced <a href="http://nuget.codeplex.com/discussions/264082">this discussion</a> on this issue, which recommended this workaround:</p>

<pre><code>nuget install MyProj\packages.config -o packages
</code></pre>

<p><strong>NOTE</strong>: a minor grievance with the <em>install</em> command. Unlike the <em>update</em> command, this works against a project's repository. This seems subpar, when I can call <em>update</em> against a solution file. Can we get some consistency with this? Or have I missed something with how install behaves?</p>

<p>Fine, not all workarounds are pretty.</p>

<p>Let's modify my script to suit:</p>

<pre><code>.\Nuget.exe update ..\MahApps.Twitter.sln -Source http://www.myget.org/f/mahapps -Source https://go.microsoft.com/fwlink/?LinkID=206669 -o ..\packages

.\Nuget.exe install ..\src\Identica\packages.config -Source http://www.myget.org/f/mahapps -Source https://go.microsoft.com/fwlink/?LinkID=206669 -o ..\packages

.\Nuget.exe install ..\src\NET4\packages.config -Source http://www.myget.org/f/mahapps -Source https://go.microsoft.com/fwlink/?LinkID=206669 -o ..\packages

.\Nuget.exe install ..\src\Tests\packages.config -Source http://www.myget.org/f/mahapps -Source https://go.microsoft.com/fwlink/?LinkID=206669 -o ..\packages

.\Nuget.exe install ..\src\WP7\packages.config -Source http://www.myget.org/f/mahapps -Source https://go.microsoft.com/fwlink/?LinkID=206669 -o ..\packages
</code></pre>

<p>Icky. Whatever, I've got awesome to do.</p>

<p><em>https://go.microsoft.com/fwlink/?LinkID=206669</em> is the path to the official NuGet feed (the build server couldn't find some packages), and it is explicitly after my local feed (I may have some custom packages which I prefer). And I've added the "-o" parameter to point to the default packages location, just in case.</p>

<p>Aaaaand...</p>

<p><a href="img/posts/NuGet/installedpackages.png"><img src="img/posts/NuGet/installedpackages-small.png" alt="Success!" /></a></p>


<p>Booyah!</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Soapbox: INotifyPropertyChanged - Stop the Madness</title>
   <link href="http://brendanforster.com//inotifypropertychanged-stop-the-madness.html" />
   <updated>2011-06-18T04:00:00+00:00</updated>
   <id>http://brendanforster.com/inotifypropertychanged-stop-the-madness.html</id>
   <content type="html">
	<![CDATA[<p>Its time to stop with this madness.</p>

<p>Apologies again to <a href="http://twitter.com/kiwipom">Ian</a> as I picked on him unnecessarily when I read yet another "Let's make OnPropertyChanged compile safe" <a href="http://xaml.geek.nz/binding/5">blog post</a> yesterday.</p>

<p>I don't have an issue with the approach, but I had an issue with the bigger picture - how little had changed for XAML developers in this regard. Keep in mind that lambdas were first made available in C# 3.0 - which itself was made available in 2007, with .NET 3.5.</p>

<p>I've been summoned into this debate <a href="http://www.mail-archive.com/ozdotnet@ozdotnet.com/msg03903.html">before</a> (and was assumed to be a "cool kid") so I thought I'd put down some thoughts on the issue, and what I think needs to change:</p>

<h2>Stop writing plumbing code</h2>

<p>Every time you write logic in the setter of a property, an angel disappoints her family by taking up stripping.</p>

<p>There have been compelling reasons to do so. After dealing with the resulting pain, I've explored other options to take all those needs away. So let's break it down:</p>

<p>To start off with the <em>worst</em> case scenario, we have:</p>

<pre><code>private string _someProperty;
public string SomeProperty
{
    get { return _someProperty; }
    set 
    { 
        _someProperty = value;
        OnPropertyChanged("SomeProperty");
    }
}
</code></pre>

<h3>Make it refactor-friendly - let's use a lambda instead!</h3>

<p>Yes, this is better than magic strings - that's about it. Don't you get that sinking feeling when adding a new property to the viewmodel, and the code inside the setter looks almost identical to all the others?</p>

<p>So let's change the property to look like:</p>

<pre><code>private string _someProperty;
public string SomeProperty
{
    get { return _someProperty; }
    set 
    { 
        _someProperty = value;
        OnPropertyChanged(() =&gt; SomeProperty);
    }
}
</code></pre>

<p>For an example implementation that accepts lambda statements, <a href="http://stackoverflow.com/questions/141370/inotifypropertychanged-property-name-hardcode-vs-reflection/1209104#1209104">this Stackoverflow answer</a> is a good starting point.</p>

<h3>I only want to raise the change when the backing value actually changes!</h3>

<p>"Wait," the audience exlaims in shock, "you're going to raise the event each time now." The author relents, and adds some code to end the pain for the audience:</p>

<pre><code>private string _someProperty;
public string SomeProperty
{
    get { return _someProperty; }
    set 
    { 
        if (_someProperty == value)
            return;

        _someProperty = value;
        OnPropertyChanged(() =&gt; SomeProperty);
    }
}
</code></pre>

<p>I'd better ensure this is defined in all the setters, and that the right backing field is used in each case. I'd look pretty silly if I'd used the wrong field, like this:</p>

<pre><code>// elsewhere in the codebase
private string _someOtherProperty;

// ...

private string _someProperty;
public string SomeProperty
{
    get { return _someProperty; }
    set 
    { 
        if (_someOtherProperty == value)
            return;

        _someProperty = value;
        OnPropertyChanged(() =&gt; SomeProperty);
    }
}
</code></pre>

<p>so I'd better do it real carefully...</p>

<h3>We need caching now!</h3>

<p>Really? That's what comes to mind next? You crazy developers.</p>

<p>Fine, let's add a dictionary to capture the event arguments, instead of recreating them each time (adapted from this <a href="http://www.paulstovell.com/strong-property-names">blog post</a>):</p>

<pre><code>public class ViewModelBase
{
    protected void OnPropertyChanged(Expression&lt;Func&lt;object&gt;&gt; lambda)
    {
        // magic happens here
    }

    private IDictionary&lt;string, PropertyChangedEventArgs&gt; _handlers = new Dictionary&lt;string, PropertyChangedEventArgs&gt;      

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventArgs args;

        if (!_handlers.ContainsKey(propertyName))
        {
            _handlers.Add(propertyName, new PropertyChangedEventArgs(propertyName));
        }

        args = _handlers[propertyName];

        PropertyChanged(this, args);
    }
}
</code></pre>

<p>Have we saved much? Perhaps. Perhaps not...</p>

<h3>Wait, what about cross-thread issues? I do a lot on the background thread!</h3>

<p>Ah yes. Have you ever been bitten by this one - a background thread updates a property, which triggers the PropertyChanged event, which asplodes because the UI can only be updated from the main thread?</p>

<h2>Stop. Put down the keyboard for a minute.</h2>

<p>See how quickly all these features around INotifyPropertyChanged can spiral out of control? You've worked out the code and classes necessary to solve a common problem, but some overhead remains for writing boilerplate code everywhere the solution is required. And while it is a manual process, it is prone to human error.</p>

<p>Go back and read that last sentence again. Did something click about what you've been doing all along with INotifyPropertyChanged?</p>

<p><img src="/img/posts/Achievement.jpg" alt="Huzzah!" /></p>

<h2>A what?</h2>

<p>INotifyPropertyChanged is a very specialised example of a cross-cutting concern.</p>

<p>We use INotifyPropertyChanged in many places when doing XAML-based applications - as it is critical when databinding POCO objects without requiring the use of DependencyProperty instances. Although we spent a lot of time optimising the behaviour of invoking INotifyPropertyChanged, we didn't improve <strong>how</strong> this code is used - we're still copying-and-pasting the same code around, and having to make manual changes to each instance to suit the property.</p>

<p>We need the ability to apply the INotifyPropertyChanged behaviour in an automatic way. Of course, there are various tradeoffs to consider - which I'll outline from my experiences.</p>

<h2>Further Reading</h2>

<p>I need to wrap this post up before it becomes even longer, but you can go and read on about these concepts:</p>

<p><strong>Sacha Barber - <a href="http://www.codeproject.com/KB/library/Aspects.aspx">Aspect Examples (INotifyPropertyChanged via Aspects)</a></strong></p>

<p><a href="http://twitter.com/philiplaureano">Philip Laureano</a> linked me this yesterday. A large read, but lots of demo code for people who want to see something more concrete.</p>

<p><strong><a href="http://code.google.com/p/notifypropertyweaver/">NotifyPropertyWeaver</a> - a .NET library for weaving INotifyPropertyChanged code into IL</strong></p>

<p>This is my library of choice for automating INotifyPropertyChanged usage. I definitely owe <a href="http://twitter.com/simoncropp">Simon</a> a beer (or drink of choice) next time we cross paths - its been a joy to use.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>On the Windows 8 Preview Video</title>
   <link href="http://brendanforster.com//on-the-windows-8-preview.html" />
   <updated>2011-06-08T04:00:00+00:00</updated>
   <id>http://brendanforster.com/on-the-windows-8-preview.html</id>
   <content type="html">
	<![CDATA[<p>For those who haven't seen it, this video was announced last week about how the Windows 8 UI is changing: <a href="http://www.youtube.com/watch?v=p92QfWOw88I">http://www.youtube.com/watch?v=p92QfWOw88I</a></p>

<p>It was the trigger for significant backlash - and not for what was said, but for what wasn't said around the other options available for building Windows applications.</p>

<h2>Yes, MSFT could have handled it better</h2>

<p>Since the video dropped, developers and possibly everyone with a blog has been raising concerns about the other options available to developers for building Windows apps. The underlying vibe has been "everything else has been abandoned, the only option is now HTML5, the sky is falling and I have nothing to wear". I haven't watched the Sinofsky video (if it was even recorded), but when you see reporting like:</p>

<blockquote><p>"The development platform is based on HTML5 and JavaScript." <a href="http://news.cnet.com/8301-31021_3-20068119-260/sinofsky-shows-off-windows-8-at-d9/">Source</a></p></blockquote>

<p>and constrast with a different source:</p>

<blockquote><p>"Windows 8 essentially supports two kinds of applications. One is the classic Windows application, which runs in a desktop very similar to the Windows 7 desktop." <a href="http://allthingsd.com/20110601/exclusive-making-sense-of-what-we-just-learned-about-windows-8/">Source</a></p></blockquote>

<p>then you know something got lost in the message.</p>

<h2>The sky is falling for <em>insert technology here</em></h2>

<p><a href="http://forums.silverlight.net/forums/t/230502.aspx">That thread</a>. Oh dear $deity, <a href="http://forums.silverlight.net/forums/p/230725/563975.aspx">that thread</a>.</p>

<p>I appreciate that the MSFT guys "in the field" are stuck between a rock and a hard place currently - they cannot provide details to answer people's concerns or questions, but are dealing with a large backlash due to the large amount that is not know currently.</p>

<p>As one of those in the audience who has to wait, in uncertainty, between now and <a href="http://www.buildwindows.com/">BUILD</a> to have these questions answered, I wish they would rethink this decision and respond to questions and help change the course of discussion.</p>

<p>While the video does mention:</p>

<blockquote><p>"Windows 8 also runs the existing Windows apps that you know and that you love"</p></blockquote>

<p>it then follows up with running Excel.</p>

<p>Yep. Excel.</p>

<p>While an Excel demo is a good indicator of the backwards compatibility that Windows is famous for, it was a jarring change from the rest of the video, and I'm not sure it was the best application to demonstrate.</p>

<p>Perhaps the developer story is not ready to show. Perhaps it was supposed to be about the shell, and HTML5 was only mentioned in passing. Perhaps, perhaps, perhaps. I suspect a demonstration of how a WPF/SL/Winforms/native application <strong>could</strong> look/feel/behave within the new shell would provide some information without giving much away.</p>

<p>The video was about creating interest in the new platform and discussing the opportunities it provides. Now is the time to talk more broadly, while everyone is talking about it.</p>

<p>So instead of <a href="http://forums.silverlight.net/forums/t/230744.aspx">drumming up more drama</a>, I thought I'd share some takeaways for both sides on this:</p>

<h2>Devs: pay attention to the user experience</h2>

<p>I hope developers took away from this story how the user experience of applications has changed, and how the classic WIMP (Windows, Icons, Menu, Pointer) applications will be impacted. Much like the transition from Windows Mobile 6.5 to Windows Phone 7, I anticipate some growing pains once developers get their hands on the development tools.</p>

<p>Touch input is also something that many Windows developers may not be familiar with. While it has been available to native developers since Windows 7 launched, and was added to WPF and Silverlight with subsequent product releases, it hasn't really been utilized to anywhere near its full potential.</p>

<p>Get familiar with how gestures work - as a starting point, the WP7 emulator turns mouse inputs into touch inputs. Touch will be mandatory if you want an application to be usable on different form factors (Windows 8 is taking an iOS-ish route with the same codebase running on desktops, tablets and devices).</p>

<h2>MSFT: don't let the echo chamber continue</h2>

<p>I'm still baffled by the decision to stonewall. Developers are customers, and they have questions. Why not be pro-active and help smooth the transition over the coming months?</p>

<p>With all the strong and passionate opinions flying around, wouldn't it be good to plant some seeds of confidence and turn the conversation from "Where is XYZ?" to "What can I do with Windows 8 using XYZ?"</p>

<p>Give the community a baseline of information so they can start planning and start providing feedback. It doesn't have to be revealing all the cards, but the developer story for Windows 8 is (mostly) unknown currently. That's why people are concerned.</p>

<h2>MSFT: don't forget the hardware</h2>

<p>I've been looking for a kick-arse tablet device to run Windows on for a while, but have been stuck in Goldilocks-mode - "too large, too heavy, the battery is too short, etc" - and continue to sit on the fence. Much like with WP7, I'm curious about the involvement of hardware vendors to support the new features coming in Windows 8.</p>

<p>Windows 7 was launched with support for touch input, but it never really gained traction due to lack of a compelling tablet device - the Touchsmarts were a nice device, but were primarily for kiosks, rather than daily usage.</p>

<p>Compare Windows 7 to the WP7 launches - which have been done with device announcements involving hardware vendors - and it gives me hope that the launch can be done in a more "complete" fashion.</p>

<p>And I want to see more presentations from MSFT about Windows 8 using touch - drive the presentations from a tablet, demonstrate how the new UI supports touch, and compel me to put it everywhere.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>slsvcutil - Workaround StackOverflowException</title>
   <link href="http://brendanforster.com//slsvcutil-stackoverflowexception-workaround.html" />
   <updated>2011-05-06T04:00:00+00:00</updated>
   <id>http://brendanforster.com/slsvcutil-stackoverflowexception-workaround.html</id>
   <content type="html">
	<![CDATA[<p>I've hit this issue before, but it took a bit of googling to remember the fix - especially since that little site called <a href="http://www.stackoverflow.com/">stackoverflow</a> came into the mix :)</p>

<pre><code>D:\Readify\Hg\ReadifySample\src&gt;"C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Tools\Slsvcutil.exe" http://localhost:47862/Services/ParentService.svc

Process is terminated due to StackOverflowException.
</code></pre>

<p>No configuration options set. No informative error message. Annoying.</p>

<p>The solution, which was initially posted <a href="http://blogs.msdn.com/b/silverlightws/archive/2010/04/30/workaround-for-stackoverflowexception-when-using-slsvcutil-exe.aspx">here</a> over a year ago, is to add in a configuration file alongside slsvcutil.exe, called <strong>slsvcutil.exe.config</strong>, which will point to the neutral-culture assembly.</p>

<pre><code>&lt;configuration&gt;
  &lt;satelliteassemblies&gt;
    &lt;assembly name="SlSvcUtil, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /&gt;
  &lt;/satelliteassemblies&gt;
&lt;/configuration&gt;
</code></pre>

<p>That's right. If you have set your system language to something <strong>other than US English</strong>, you will probably encounter this issue.</p>

<p>Enjoy.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Musing - Simpler UI Testing for WPF Apps</title>
   <link href="http://brendanforster.com//simpler-ui-testing-for-wpf-apps.html" />
   <updated>2011-03-26T03:00:00+00:00</updated>
   <id>http://brendanforster.com/simpler-ui-testing-for-wpf-apps.html</id>
   <content type="html">
	<![CDATA[<p>After spending some time this week getting to know Ruby and some of its testing frameworks (Shoulda, rspec, and TestCase), I thought I'd put pen
to paper and revisit why I started down this path.</p>

<h2>Some background</h2>

<p>The current project I am working on is a large data-driven WPF application, with a lot of complex scenarios to
identify, develop and test. There is a group of testers on the project, but I can see an opportunity to use
automated testing to verify functionality and allow testers to focus on areas of better value - exploratory testing, for example.</p>

<p>Yes, there are frameworks like <a href="http://white.codeplex.com/">White</a> or Coded UI Tests, but these tools were designed with developers in mind.
You have to write code like <a href="http://msdn.microsoft.com/en-us/magazine/dd483216.aspx">this</a> to drive the tests, and the tests are commonly written after the feature is implemented.</p>

<h2>Enter Automated Acceptance Testing</h2>

<p>In an ideal world, business users would define tests in an English-like language, which can then be translated into an executable
script and run against the application.</p>

<p>What I'm looking for in a framework for defining use cases:</p>

<ul>
<li>define the test first, so that the high-level scenario is set before development occurs</li>
<li>flexible with syntax for test cases - tailor scripts to suit people involved, while remaining declarative</li>
<li>integrate into deployment process to verify builds automated</li>
</ul>


<h2>Some inspiration from obscure corners</h2>

<p>When I first saw the syntax for <a href="http://msdn.microsoft.com/en-us/magazine/dd483216.aspx">webrat</a>, I was intrigued and jealous. To declare a test like this:</p>

<pre><code>class SignupTest &lt; ActionController::IntegrationTest

    def test_trial_account_sign_up
        visit home_path
        click_link "Sign up"
        fill_in "Email", :with =&gt; "good@example.com"
        select "Free account"
        click_button "Register"
    end
end
</code></pre>

<p>was not far off what I'd had in mind for something that was easy to follow and easy to write.</p>

<p>So I spent some time this week experimenting with various ways of achieving this against a sample WPF application.</p>

<p>I'm using rspec at the moment to run the test cases, and IronRuby and White to support the integration with the hosted WPF application.</p>

<h2>What does a test for the WPF application look like?</h2>

<pre><code>describe "new customers screen" do

    subject { Host.new(File.expand_path('./app/WpfTestApp.exe', File.dirname(__FILE__)))

    before(:each) do
        click "Add Customer"
    end

    it "cannot save empty form" do
        cannot_click "Save"
        can_click "Cancel"
    end

    it "can enter details for customer" do
        fill "FirstName", :with =&gt; "Brendan"
        fill "LastName", :with =&gt; "Forster"
        # and some other fields
        can_click "Save"
    end

    it "can save and return to main screen" do
        fill "FirstName", :with =&gt; "Brendan"
        fill "LastName", :with =&gt; "Forster"
        # and some other fields
        click "Save"
        assert_title "Dashboard"
    end

    after(:each) do
        cleanup
    end

    def method_missing(sym, *args, &amp;block)
        subject.send sym, *args, &amp;block
    end
end
</code></pre>

<p>The fields used here are based off the UI Automation features of the .NET Framework (some reading <a href="http://white.codeplex.com/">here</a> on recommendations)
which I'll dig into a bit later if people are interested.</p>

<p>The method_missing method is used to reduce the noise of writing "subject." to start each line - I'm not quite sold on the approach, but it was cleaner than the previous approaches I'd tried.
Also, rspec has a <a href="https://gist.github.com/663876">huge set of features</a> which I've barely scratched the surface on.</p>

<p>So with a set of files like the file above, the testrunner is a simple script to load specific files found in the current directory:</p>

<pre><code>require 'rubygems'
require 'rspec'
require 'host'

Dir[File.dirname(__FILE__) + '/*tests.rb'].each do |file| 
    load file
end
</code></pre>

<p>I'll share some more as I polish additional features (I'm most certainly doing Ruby wrong at the moment, so I keep refactoring code),
just needed to write this post.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Arguments about Project Structure</title>
   <link href="http://brendanforster.com//arguments-about-project-structure.html" />
   <updated>2011-02-23T03:00:00+00:00</updated>
   <id>http://brendanforster.com/arguments-about-project-structure.html</id>
   <content type="html">
	<![CDATA[<p>Whenever it comes time to kick off a new project, how do you structure it?</p>

<p>Given a greenfields situation - or even one of my side projects - I go for this layout:</p>

<ul>
<li>build</li>
<li>lib</li>
<li>src

<ul>
<li>samples</li>
<li>Project.ModuleA</li>
<li>Project.ModuleB</li>
<li>Project.Shell</li>
<li>Project.sln</li>
</ul>
</li>
<li>tools</li>
</ul>


<p>And what do those these folders represent?</p>

<p><strong>build</strong> - scripts for building and deploying the application. As soon as the application is required to be deployed to different environments, this should be scripted and added to source control.</p>

<p><strong>lib</strong> - dependencies required by the application. I generally group the dependent assemblies if required, but will generally drop the dll-xml combination into the root folder.</p>

<p><strong>samples</strong> - once the main solution gets beyond a specific size, it may be beneficial to separate the sample code out rather than compiling it within the main build.</p>

<p><strong>src</strong> - there be code.</p>

<p><strong>tools</strong> - dependencies required to build the application. This does not mean including every tool required to set up the developer baseline, but any special tools used during the build process</p>

<p>For example, these would not belong:</p>

<ul>
<li>Visual Studio</li>
<li>.NET Framework</li>
</ul>


<p>But I'd happily include these tools:</p>

<ul>
<li>FxCop</li>
<li>NCover</li>
<li>MSBuild Community Tasks</li>
</ul>


<p>as not all developers would have them installed on their machines.</p>

<h2>Why this structure?</h2>

<p><strong>Folder Names</strong></p>

<p>Remember the days of 8.3 filesystems? I do. But thankfully this isn't about that.</p>

<p>This structure also borrows from Unix conventions for arranging their codebases. I don't like how the necessary make files are hosted at the root.</p>

<p>As we're using Mercurial, we don't need to worry about using trunks or tags in the structure.</p>

<p><strong>Experience</strong></p>

<p>When I challenged <a href="http://twitter.com/aeoth">@aeoth's</a> project structure for the next version of MahTweets, he wanted to make it so that a developer with little experience in .NET (or programming) could download the source and try it out.</p>

<p>I'd argue the best introduction to a codebase is two things:</p>

<ul>
<li>a README file to provide some notes about the application</li>
<li>a batch file or script to run the application and execute tests</li>
<li>sample projects to complement the source</li>
</ul>


<p><strong>The build is important</strong></p>

<p>We had various pain points with the last version of MahTweets around managing loosely-coupled modules under development, and then building a signed ClickOnce installer with a custom script.</p>

<p>It ended up being a painful few nights bashing against MSBuild (have you ever tried to use SignFile manually?), but the effort burnt reminds me everytime I come across a new team or project to ask two simple questions:</p>

<ul>
<li>how can someone build and run the application with limited knowledge of the codebase?</li>
<li>how can someone test the application with limited knowledge of the codebase?</li>
</ul>


<p>If that process is known and documented, it highlights all the quirks with getting the application out. If it isn't documented, then typically you need to find the right person at the right time...</p>

<p>Putting the build components separate, but easily visible, makes everyone's life easier.</p>

<p><strong>Habit</strong></p>

<p>And lastly, this is my personal opinion. Having spent a lot of time playing around with Linux OSS in the past, I keep coming back to that style of structure when setting up my own projects. Seeing things like uppercase folder names at the root just feel odd.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Using Rx to Implement Filtering in MahTweets</title>
   <link href="http://brendanforster.com//using-rx-to-implement-filtering-in-mahtweets.html" />
   <updated>2011-02-19T03:00:00+00:00</updated>
   <id>http://brendanforster.com/using-rx-to-implement-filtering-in-mahtweets.html</id>
   <content type="html">
	<![CDATA[<p>As we're kicking development off for the next version of MahTweets in the coming weeks, the team has been looking at experimenting with new technology and bringing the most useful stuff into the application.</p>

<p>Filtering is one of the things that MahTweets is famous for, but we're always looking for ways to make it better and easier. We've been experimenting with using the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896">Reactive Extensions (Rx) for .NET</a> to simplify the entire pipeline and provide more freedom in the application.</p>

<h2>The Current Status</h2>

<p>MahTweets allow the user to filter streams by update type, contact or text. Filters can be applied to individual streams or globally.</p>

<p>Roughly speaking, this is how the filters are applied.</p>

<center><a href="img/posts/FiltersClassic.png"><img src="img/posts/FiltersClassic.png" width="700" /></a></center>


<p>Updates from external services are added to the queue, which then raises CollectionChangedEvent notifications to each views. The view is responsible for running an update through its configured filters.</p>

<p>Limitations about this approach:</p>

<ul>
<li>Global Ignores were implemented separately.</li>
<li>Custom filtering was implemented per update type.</li>
<li>UI was coupled to stream container and specific parameters.</li>
</ul>


<h2>First Cut using Rx</h2>

<p>FYI: If you're not familiar with the Observer Pattern, check out the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Wikipedia article</a> for starters. Rx uses the Observer pattern heavily.</p>

<p>We had a habit of using the phrase "filter" in many places of the application. To clarify our intent, we introduced two specific interfaces:</p>

<ul>
<li><strong>IStatusSubscriber</strong> - an extension which subscribes to a stream of incoming requests.</li>
<li><strong>IConditionalSubscriber</strong> : <strong>IStatusSubscriber</strong> - an extension which filters the updates before propogating to its consumers. Pass-thru or exclude filters can be specified.</li>
</ul>


<p>Replacing the Queue of messages with an IObservable/IObserver dual allows the application to leverage the Subject&lt;T&gt; class to manage the interactions between the services and the clients. This class resides in System.Reactive.dll and implements both IObservable&lt;T&gt; and IObserver&lt;T&gt;.</p>

<p>MahTweets also had some demo plugins for stream analytics, and abstracting away the queue support allows the application to plug in additional "global" services, using the same interfaces. Rx also allows observers to specify which thread to execute on, so the usage of the Dispatcher, TaskPool or ThreadPool (depending on scenario) can be configured without any plumbing code.</p>

<p>The interactions between these components now looks like:</p>

<center><a href="img/posts/RxFirstCut.png"><img src="img/posts/RxFirstCut.png" width="700" /></a></center>


<p>The biggest change is that subscribers interact with the IObservable, rather than being encompassed within the view. Each list still combines a set of filters, which display the combined set of results on-screen. However, when multiple filters are run in parallel, invalid items may appear.</p>

<p>Limitations about this approach:</p>

<ul>
<li>Excluded updates may be propogated through other subscribers in the same view.</li>
<li>Global Ignores still not supported.</li>
</ul>


<h2>Back to the Drawing Board</h2>

<p>So after some shut-eye and sun, I revisited the initial design for the IObservable implementation. What stood out to me was that:</p>

<ul>
<li>Include and exclude side-by-side has always been somewhat complex - both for users to understand, and determining which takes priority.</li>
<li>Include and exclude filters didn't need to exist in the same location.</li>
<li>Rx can support chaining observers, however...</li>
<li>Chaining isn't what the Observer pattern is about.</li>
</ul>


<p>After some more musing, I formed an opinion about subscriber rules (only mine so far):</p>

<p><strong>An exclude rule is applied globally. An include rule is applied locally.</strong></p>

<p>From my experiences with using Twitter, the typical use cases for exclude filters are:</p>

<ul>
<li>"Great, another Twitter spam concept..." <em>looks at paper.li</em></li>
<li>"Person XYZ is tweeting too much right now. I don't want to hear him for a while..."</li>
<li>"Oops, I said the i-word and the spammers are out and about..."</li>
</ul>


<p>On the other hand, the use cases for include filters can be like:</p>

<ul>
<li>"I want to see what <em>this</em> group of contacts is talking about..."</li>
<li>"I want to see tweets mentioning 'ABC' - (side note: more on search later)..."</li>
<li>"I want to see my mentions/messages..."</li>
</ul>


<p>Compare and contract (perhaps your experiences differ).</p>

<h2>Second Cut using Rx</h2>

<p>The second cut of the design allows for three subscriber hooks:</p>

<ul>
<li>Subscribers register against the source observable, without any filtering applied.</li>
<li>Subscribers register against the output observable, with the global filtering applied.</li>
<li>Exclude rules are applied closer to the source.</li>
</ul>


<center><a href="img/posts/RxSecondCut.png"><img src="img/posts/RxSecondCut.png" width="700" /></a></center>


<p>An internal subscriber verifies a status against a list of exclusions, and propogates the status further if it is valid. Each view only requires its inclusion rules (or a wildcard rule if no rules specified) to display results.</p>

<h2>The Next Step</h2>

<ul>
<li>Debate with <a href="http://twitter.com/aeoth">@aeoth</a> on this</li>
<li>Performance Testing against a large set of data.</li>
<li>Demonstrating how external plugins can include their own rules.</li>
<li>Demonstrate user interface changes for vNext.</li>
</ul>

]]>
   </content>
   
 </entry>
 
 <entry>
   <title>WP7 - Memory Profiling Adventures - Navigation (Updated)</title>
   <link href="http://brendanforster.com//wp7-memory-profiling-navigation.html" />
   <updated>2011-02-04T03:00:00+00:00</updated>
   <id>http://brendanforster.com/wp7-memory-profiling-navigation.html</id>
   <content type="html">
	<![CDATA[<p>In the course of wrapping up a SL-based WP7 application recently, I stumbled across a significant hurdle with memory consumption on the device...</p>

<h2>Updated</h2>

<p>After going back and forth with local Windows Phone guru <a href="http://nicksnettravels.builttoroam.com/">Nick Randolph</a> about the issue, and he <a href="http://nicksnettravels.builttoroam.com/blogengine/post/2011/02/10/Windows-Phone-7-Navigation-Memory-Usage.aspx">blogged</a> <a href="http://nicksnettravels.builttoroam.com/blogengine/post/2011/02/10/Windows-Phone-7-Navigation-Memory-Usage-Just-Got-Scary.aspx">about</a> the behaviour in more detail, we came to the conclusion that the garbage collection was not being triggered automatically. That's not necessarily a bad thing (see the <a href="http://nicksnettravels.builttoroam.com/blogengine/post/2011/02/10/Windows-Phone-7-Navigation-Memory-Usage-Just-Got-Scary.aspx">conditions for triggering a garbage collection</a> here) but is a concern for large WP7 applications.</p>

<p>The workaround I devised for this is to trigger a GC.Collect() after a number of page navigations. I would only add this to an application when absolutely necessary. The implementation of this I'll leave as an exercise to the reader.</p>

<p>Side note: I've seen various samples floating around which will use a timer to invoke a garbage collection call. Ignoring the use of timers on the device (which will drain the battery), a garbage collection call at an arbitrary time will likely impact on the user experience. Be smart about it, if you need to work this into an application.</p>

<p>Read on for the rest of the saga...</p>

<h2>Before We Begin...</h2>

<p>One of the requirements a WP7 application needs to satisfy is around memory consumption</p>

<h3>5.2.5 Memory Consumption</h3>

<p><em>An application must not exceed 90 MB of RAM usage, except on devices that have more than 256 MB of memory. You can use the <strong>DeviceExtendedProperties</strong> class to query the amount of memory that is available on the device and modify the application behavior at runtime to take advantage of additional memory. For more information, see the DeviceExtendedProperties class in MSDN.</em></p>

<p><em>Note:</em></p>

<p><em>The DeviceTotalMemory value returned by <strong>DeviceExtendedProperties</strong> indicates the physical RAM size in bytes. This value is less than the actual amount of device memory. For an application to pass certification, Microsoft recommends that the value returned by ApplicationPeakMemoryUsage is less than 90 MB when the DeviceTotalMemory is less than or equal to 256 MB</em></p>

<p>Source <a href="http://go.microsoft.com/?linkid=9730556">Microsoft</a></p>

<p>90 MB sounds like a lot of space - and yes, it is, when one remembers the era of 1.44MB diskettes (or earlier) you can't help but think that perhaps we are spoiled - but what can you do with that amount of memory?</p>

<p><strong>Note</strong> - Disregard the "devices with > 256MB" exception mentioned, as I want to see how we can optimise memory usage on SL without sacrificing features.</p>

<h2>How Do I Work Out My Memory Usage?</h2>

<p>As mentioned above, the <strong>DeviceExtendedProperties</strong> class contains a lot of runtime information about the application.</p>

<p>I drop this method into the App.xaml.cs class so that I can get statistics at any point of the application's lifecycle.</p>

<pre><code>public static void GetMemoryUsage(string task)
{
    var number = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
    Debug.WriteLine("{0} - ApplicationCurrentMemoryUsage: {1}", task, number);
    number = (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
    Debug.WriteLine("{0} - ApplicationPeakMemoryUsage: {1}", task, number);

    Debug.WriteLine("");
}
</code></pre>

<p>Oh, and don't forget the namespace</p>

<pre><code>using Microsoft.Phone.Info;
</code></pre>

<p>This allows parts of the application to log diagnostics, like:</p>

<pre><code>private void MainPageLoaded(object sender, RoutedEventArgs e)
{
    if (!App.ViewModel.IsDataLoaded)
        App.ViewModel.LoadData();

    App.GetMemoryUsage("Main - Loaded");

}
</code></pre>

<p>and see a message like in the Output Window:</p>

<pre><code>Main - Loaded - ApplicationCurrentMemoryUsage: 39870464
Main - Loaded - ApplicationPeakMemoryUsage: 39899136
</code></pre>

<h2>And now things get interesting...</h2>

<p>Testing out a simple application - two screens, both use the Panorama Control and independent ViewModels which display a "large" list of items (270-ish items, but text only).</p>

<p>Selecting an item in the main screen will navigate to the second screen. Pressing back will return the application to the main screen.</p>

<p>The code is <a href="http://brendanforster.com/get/panoramasample.zip">here</a> and the sample output can be seen on <a href="https://gist.github.com/812178">Gist</a></p>

<p>Graphing the memory at each step, the graph looks like this:</p>

<center><a href="img/posts/breakdown.png"><img src="img/posts/breakdown.png" width="800" /></a></center>


<p>But why is the memory footprint larger (by almost 10 MB) on returning to the main screen?</p>

<p><strong>Note:</strong> Removing the Panorama Control did not change this behaviour - it just made the numbers smaller (a 5MB difference rather than 10MB). Just a sign that making screens leaner will certainly assist with reducing the overall footprint, but not the answer I was looking for.</p>

<p>Repeating the scenario a few times, and the behaviour is the same.</p>

<center><a href="img/posts/pattern.png"><img src="img/posts/pattern.png" width="800" /></a></center>


<p>Puzzling...</p>

<h2>And the adventure begins</h2>

<p>The underlying <em>why</em> is what I want to understand more. Even with this simple application - which is displaying a large list of items - the size of the application is already close to the 90MB limit.</p>

<p>I've only been able to throw a couple of hours of spare time at this so far, but here's some notes from my investigation currently:</p>

<ul>
<li><p>Tested this with the <a href="http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/02/04/windows-phone-developer-tools-january-update.aspx">new emulator and SDK changes</a>. No change to the behaviour.</p></li>
<li><p>Haven't found any memory profiling tools for SL &amp; WP7 - if anyone has stuff in the works, I'd love to try them out. <a href="http://eqatec.com/Profiler/Overview.aspx">EQUATEC</a> make a profiler for CPU performance, which works wonderfully from my limited testing.</p></li>
<li><p>Aggressive garbage collection helped somewhat, but this approach makes me feel unclean. Using timers on the device to trigger a GC Collect is bad for battery performance, and the demo above shows that memory usage can spike between events for a PhoneApplicationPage.</p></li>
<li><p>Paging data from isolated storage could be worth attempting, but I don't think this is a temporary fix - as the application would load the full file, select a subset of the data, and then dispose the file. Chunking data in isolated storage would increase complexity.</p></li>
<li><p>Avoiding the use of navigation - and rolling some custom controls to support transitions instead - is the method that needs most work, but gives more control back to the application.</p></li>
</ul>

]]>
   </content>
   
 </entry>
 
 <entry>
   <title>MEF and Chaining Dependencies</title>
   <link href="http://brendanforster.com//mef-and-chaining-dependencies.html" />
   <updated>2010-12-20T03:00:00+00:00</updated>
   <id>http://brendanforster.com/mef-and-chaining-dependencies.html</id>
   <content type="html">
	<![CDATA[<p>A <a href="http://mef.codeplex.com/Thread/View">question</a> came up on the MEF discussion board recently (today?) about how to handle a complex graph of dependencies. Although it was "solved" - and I suspect it was a case of missing the required assembly, going by what info was at hand - it still prompted me to dig into how one can go beyond the basics.</p>

<h2>Scenario</h2>

<p>Imagine you have an application that calls off different services to execute tasks. Rather than hard-coding the services into the application, these can be defined as parts which are composed at runtime using MEF.</p>

<p>But the relationship between the application and the services is not straightforward, which gives a dependency graph similar to the below image:</p>

<center><img src="img/posts/DependencyGraph.png" height="500"  /></center>


<p>What should we do now?</p>

<p>As MEF uses the concept of a "contract" to resolve the <code>[Import]</code> and <code>[Export]</code> statements sprinkled within an application, this ultimately comes down to two similar approaches.</p>

<h2>Using Contract Names</h2>

<p>If the Proxy and Service implementations are equivalent - so we can avoid using distinct interfaces for behaviour which is identical - then we can use the same interface and specify a different contract for each extensibiity point defined in the application.</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">ConsumingApplication</span>
<span class="p">{</span>
<span class="na">    [ImportMany(&quot;Contoso.Application&quot;, typeof(IServiceProxy))]</span>
    <span class="k">public</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IServiceProxy</span><span class="p">&gt;</span> <span class="n">Services</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    
    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<p>And our simple client can use the corresponding [Export] statement.</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[Export(&quot;Contoso.Application&quot;, typeof(IServiceProxy))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">StandaloneProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
    <span class="c1">// implementation here </span>
<span class="p">}</span>
</code></pre></div>


<p>Our complex dependency has a bit more code, but it can be broken down into two main features:</p>

<ul>
<li>The contract which it satisfies - <strong>Contoso.Application</strong> and <strong>IServiceProxy</strong></li>
<li>The contract which it requires - <strong>Contoso.External</strong> and <strong>IServiceProxy</strong></li>
</ul>


<p>Which looks like this:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[Export(&quot;Contoso.Application&quot;, typeof(IServiceProxy))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">ActualProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
<span class="na">    [ImportMany(&quot;Contoso.External&quot;)]</span>
    <span class="k">public</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IServiceProxy</span><span class="p">&gt;</span> <span class="n">Services</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<p>So while reusing the same interface, we can specify <em>how</em> the parts relate.</p>

<h2>Using Contract Types</h2>

<p>If the behaviour of the proxy and the actual service are different, then we can just use the types to represent the contract.</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">ConsumingApplication</span>
<span class="p">{</span>
<span class="na">    [ImportMany(typeof(IServiceProxy))]</span>
    <span class="k">public</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IServiceProxy</span><span class="p">&gt;</span> <span class="n">Services</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<p>The exported contract becomes:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[Export(typeof(IServiceProxy))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">StandaloneProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<p>And our complex part still has two contracts:</p>

<ul>
<li><p>The contract which it satisfies - the <strong>IServiceProxy</strong> contract.</p></li>
<li><p>The contract which it requires - the <strong>IService</strong> contract (implicit due to the awesomeness of ImportMany)</p></li>
</ul>


<p>Which looks like this:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[Export(typeof(IServiceProxy))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">ActualProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
<span class="na">    [ImportMany]</span>
    <span class="k">public</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IService</span><span class="p">&gt;</span> <span class="n">Services</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<h2>And finally, InheritedExport</h2>

<p>To really simplify the contracts, you can decorate the interface with the <code>[InheritedExport]</code> attribute. This declares to MEF that all types which implement the interface should be used as exported parts, using the interface type as the contract.</p>

<p>So I annotate both interfaces:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[InheritedExport]</span>
<span class="k">public</span> <span class="k">interface</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
    <span class="c1">// code here</span>
<span class="p">}</span>

<span class="na">[InheritedExport]</span>
<span class="k">public</span> <span class="k">interface</span> <span class="n">IService</span>
<span class="p">{</span>
    <span class="c1">// code here</span>
<span class="p">}</span>
</code></pre></div>


<p>and can eliminate all other [Export] attributes from the codebase:</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">StandaloneProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
    <span class="c1">// implementation here</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">class</span> <span class="nc">ActualProxy</span> <span class="p">:</span> <span class="n">IServiceProxy</span>
<span class="p">{</span>
<span class="na">    [ImportMany]</span>
    <span class="k">public</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IService</span><span class="p">&gt;</span> <span class="n">Services</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="c1">// implementation here</span>
<span class="p">}</span>
</code></pre></div>


<p>Thoughts?</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>MEF - [Import] vs [ImportingConstructor]</title>
   <link href="http://brendanforster.com//mef-import-vs-importingconstructor.html" />
   <updated>2010-10-23T03:00:00+00:00</updated>
   <id>http://brendanforster.com/mef-import-vs-importingconstructor.html</id>
   <content type="html">
	<![CDATA[<p>A short discussion on Twitter recently started as a result of Jeremy Likness' article on MEF at <a href="http://www.informit.com/articles/article.aspx?p=1635818">InformIT</a>. I recommend reading it for anyone who is looking for an introduction to the MEF concepts.</p>

<p>The healthy debate was ultimately about [Import] being easier than [ImportingConstructor] to use. I disagreed, but at the time couldn't really put my finger on why I preferred it.</p>

<p>After a bit of pondering, this is what I've come up with.</p>

<h2>Compare and Contrast - [Import] versus [ImportingConstructor]</h2>

<p>Compare these two segments of code:</p>

<p>The [Import] version...</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">TwitterPlugin</span> <span class="p">:</span> <span class="n">IMicroblog</span>
<span class="p">{</span>
<span class="na">    [Import]</span>
    <span class="k">private</span> <span class="n">IApplicationSettingsService</span> <span class="n">_applicationSettings</span><span class="p">;</span>

<span class="na">    [Import]</span>
    <span class="k">private</span> <span class="n">IStatusUpdatesService</span> <span class="n">_statusUpdatesService</span><span class="p">;</span>

<span class="na">    [Import]</span>
    <span class="k">private</span> <span class="n">IContactsService</span> <span class="n">_contacts</span><span class="p">;</span>

    <span class="k">public</span> <span class="nf">TwitterPlugin</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="c1">// some constructor logic</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>


<p>Or the [ImportingConstructor] version...</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">TwitterPlugin</span> <span class="p">:</span> <span class="n">IMicroblog</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="k">readonly</span> <span class="n">IApplicationSettingsProvider</span> <span class="n">_applicationSettings</span><span class="p">;</span>
    <span class="k">private</span> <span class="k">readonly</span> <span class="n">IStatusUpdateService</span> <span class="n">_statusUpdatesService</span><span class="p">;</span>
    <span class="k">private</span> <span class="k">readonly</span> <span class="n">IContactsService</span> <span class="n">_contactsService</span><span class="p">;</span>

<span class="na">    [ImportingConstructor]</span>
    <span class="k">public</span> <span class="nf">Twitter</span><span class="p">(</span><span class="n">IApplicationSettingsProvider</span> <span class="n">applicationSettings</span><span class="p">,</span>
                   <span class="n">IStatusUpdateService</span> <span class="n">statusUpdateService</span>
                   <span class="n">IContactsService</span> <span class="n">contactsService</span><span class="p">)</span>
    <span class="p">{</span>
       <span class="n">_applicationSettings</span> <span class="p">=</span> <span class="n">applicationSettings</span><span class="p">;</span>
       <span class="n">_statusUpdatesService</span> <span class="p">=</span> <span class="n">statusUpdateService</span><span class="p">;</span>
       <span class="n">_contactsService</span> <span class="p">=</span> <span class="n">contactsService</span><span class="p">;</span>
    
       <span class="c1">// some constructor logic</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>


<p>So the second approach requires more code, but a good tool should have you saving many keystrokes - even Visual Studio 2010 will help out with that.</p>

<p>Other differences:</p>

<p><strong>Design - Constructor Injection versus Property Setters</strong></p>

<p>With the first approach, the properties are not populated until after the constructor is completed. If the class needs to perform tasks in the constructor which require its dependencies to be present, then you need to use the [ImportingConstructor] approach.</p>

<p>By using the [ImportingConstructor] attribute, the part declares to the container that it requires. Simple, easy to read, and can be used outside MEF by new'ing it up.</p>

<p><strong>Maintainability</strong></p>

<p>Jeremy raised a concern about the constructor signature growing over time, and that a set of properties on the class was a cleaner approach.</p>

<p>I see the "growing dependency count" as a design issue rather than a technical issue. Tacking on another [Import] attribute should be considered a code smell, just like adding an additional parameter to a constructor.</p>

<p>If your dependency count is more than a handful, then you should review the interfaces and see if they can be segregated/aggregated better. The dependency list is a representation of what the component requires to function. It should be the smallest possible set of interfaces, and no more. The interfaces should be lean and specialized, and classes can implement multiple interfaces if required.</p>

<p><strong>You can still use attributes</strong></p>

<p>Something these snippets don't demonstrate is that attributes can be combined with ImportingConstructor for specific scenarios:</p>

<p>For example, using [ImportMany]</p>

<div class="highlight"><pre><code class="csharp"><span class="k">private</span> <span class="k">readonly</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">ICreditService</span><span class="p">&gt;</span> <span class="n">_creditServices</span><span class="p">;</span>

<span class="na">[ImportingConstructor]</span>
<span class="k">public</span> <span class="nf">BankService</span><span class="p">([</span><span class="n">ImportMany</span><span class="p">]</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="n">IProductServices</span><span class="p">&gt;</span> <span class="n">productServices</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">_productServices</span> <span class="p">=</span> <span class="n">productServices</span><span class="p">;</span>
    
    <span class="c1">// some constructor logic</span>
<span class="p">}</span>
</code></pre></div>


<p>Or using AllowDefault to allow for scenarios where a component is not known:</p>

<div class="highlight"><pre><code class="csharp"><span class="k">private</span> <span class="k">readonly</span> <span class="n">ILogger</span> <span class="n">_logger</span><span class="p">;</span>

<span class="na">[ImportingConstructor]</span>
<span class="k">public</span> <span class="nf">BankService</span><span class="p">([</span><span class="n">Import</span><span class="p">(</span><span class="n">AllowDefault</span><span class="p">=</span><span class="k">true</span><span class="p">)]</span> <span class="n">ILogger</span> <span class="n">logger</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">logger</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
        <span class="n">_logger</span> <span class="p">=</span> <span class="k">new</span> <span class="n">DefaultLogger</span><span class="p">();</span>
    <span class="k">else</span>
        <span class="n">_logger</span> <span class="p">=</span> <span class="n">logger</span><span class="p">;</span>
    
    <span class="c1">// some constructor logic</span>
<span class="p">}</span>
</code></pre></div>


<p>And this still keeps all the composition "magic" in one location. MEF supports importing <a href="http://mef.codeplex.com/wikipage?title=Declaring%20Imports&amp;referringTitle=Guide">properties, fields and collections</a>, which could be scattered around the same class.</p>

<p><strong>Closing Statements</strong></p>

<p>Ultimately, I guess I'm advocating the [ImportingConstructor] approach because once a class grows to a significant complexity (requiring some parts and providing other parts) I feel that it is the saner approach.</p>

<p>For getting start with MEF, [Import] works fine - the barrier to entry is lowered greatly. But as the composition graph grows in an application - e.g. A &lt;-&gt; B &lt;-&gt; C &lt;-&gt; D - then I'd start simplifying the classes and pushing more "magic" into the constructor for readability's sake.</p>

<h2>While we're talking managing MEF parts</h2>

<p>When I first started using MEF, I avoided ImportingConstructor like the plague. Every time I saw ImportingConstructor being used, I thought "<em>Why add a constructor parameter to the constructor when I can just add an attribute?</em>"</p>

<p>After all, it just worked.</p>

<p>It was easy to get started with MEF - as the application grows, you can sprinkle some more magic around.</p>

<p>I've been using MEF since the early previews (Preview 6 i think was the first drop I tried out) for various apps. One of the bigger codebases running on MEF is <a href="http://www.mahtweets.com/">MahTweets</a>, a pluggable WPF client for various social media services.</p>

<p>For an upcoming release, I'm currently refactoring the MahTweets internals to replace StructureMap with Autofac. The <a href="http://code.google.com/p/autofac/wiki/MefIntegration">MEF integration extensions for Autofac</a> have been a great help to simplify the integration between Autofac's ContainerBuilder and MEF's ComposablePartCatalog, and I've found ways to reduce the required MEF syntax without changing existing functionality.</p>

<p>On the Autofac side, we can declare components in the container to be available for MEF composition.</p>

<div class="highlight"><pre><code class="csharp"><span class="n">container</span><span class="p">.</span><span class="n">RegisterType</span><span class="p">&lt;</span><span class="n">ApplicationSettingsProvider</span><span class="p">&gt;()</span>
         <span class="p">.</span><span class="n">As</span><span class="p">&lt;</span><span class="n">IApplicationSettingsProvider</span><span class="p">&amp;</span><span class="n">gt</span><span class="p">;()</span>
         <span class="p">.</span><span class="n">Exported</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span> <span class="n">x</span><span class="p">.</span><span class="n">As</span><span class="p">&lt;</span><span class="n">IApplicationSettingsProvider</span><span class="p">&gt;())</span> <span class="c1">// make this part visible to MEF components</span>
         <span class="p">.</span><span class="n">SingleInstance</span><span class="p">();</span>

<span class="n">container</span><span class="p">.</span><span class="n">RegisterType</span><span class="p">&lt;</span><span class="n">PluginSettingsProvider</span><span class="p">&gt;()</span>
         <span class="p">.</span><span class="n">As</span><span class="p">&lt;</span><span class="n">IPluginSettingsProvider</span><span class="p">&gt;()</span>
         <span class="p">.</span><span class="n">Exported</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span> <span class="n">x</span><span class="p">.</span><span class="n">As</span><span class="p">&lt;</span><span class="n">IPluginSettingsProvider</span><span class="p">&gt;())</span>
         <span class="p">.</span><span class="n">SingleInstance</span><span class="p">();</span>

<span class="p">...</span>

<span class="c1">// register external plugins for consumption</span>
<span class="n">container</span><span class="p">.</span><span class="n">RegisterComposablePartCatalog</span><span class="p">(</span><span class="n">catalog</span><span class="p">);</span>
</code></pre></div>


<p>This allows for better separation between the application and external parts, and reduces effort required to register a component with both the IoC container and the CompositionContainer.</p>

<p>I'll blog some more in the future on how you can use these parts to help manage MEF applications as they grow. I need to check out the MEF v2 drops first :)</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>IoC Tips - Autofac Factory Adapters</title>
   <link href="http://brendanforster.com//ioc-tips-autofac-factory-adapters.html" />
   <updated>2010-10-23T03:00:00+00:00</updated>
   <id>http://brendanforster.com/ioc-tips-autofac-factory-adapters.html</id>
   <content type="html">
	<![CDATA[<h2>Scenario</h2>

<p>A team has a change request come in from the business. For one of their screens, a timer should count up when a user pauses the current task.</p>

<p>As the application was already using an IoC container (Autofac), and a timer was already implemented to provide the behaviour for a similar task in this class, the constructor was quickly changed to:</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="nf">ScheduledBackupService</span><span class="p">(</span>
      <span class="p">...</span> <span class="p">,</span>
      <span class="n">ITimer</span> <span class="n">elapsedTimer</span><span class="p">,</span>
      <span class="n">ITimer</span> <span class="n">pausedTimer</span><span class="p">)</span>
<span class="p">{</span>
      <span class="p">...</span>
      <span class="k">this</span><span class="p">.</span><span class="n">elapsedTimer</span> <span class="p">=</span> <span class="n">elapsedTimer</span><span class="p">;</span>
      <span class="k">this</span><span class="p">.</span><span class="n">pausedTimer</span> <span class="p">=</span> <span class="n">pausedTimer</span><span class="p">;</span>
      <span class="p">...</span>
</code></pre></div>


<p>And from there they added in the additional code required, and the business was happy. And there was much rejoicing. But the team noticed that they were duplicating the same type in the constructor. Can the team do it better?</p>

<p>Rather than explicitly defining the two instances, the team can replace both instances with a factory adapter. In .NET, this can be represented as a <code>Func&lt;T&gt;</code> object - a method which requires no inputs and returns an instance of type T:</p>

<div class="highlight"><pre><code class="csharp"><span class="k">public</span> <span class="nf">ScheduledBackupService</span><span class="p">(</span>
      <span class="p">...</span> <span class="p">,</span> 
      <span class="n">Func</span><span class="p">&lt;</span><span class="n">ITimer</span><span class="p">&gt;</span> <span class="n">createTimer</span><span class="p">)</span>
<span class="p">{</span>
      <span class="p">...</span>                 
      <span class="n">elapsedTimer</span> <span class="p">=</span> <span class="n">createTimer</span><span class="p">();</span>
      <span class="n">pausedTimer</span> <span class="p">=</span> <span class="n">createTimer</span><span class="p">();</span>
      <span class="p">...</span>
</code></pre></div>


<p>To fix the compiler error from changing the constructor signature, the test code is updated to:</p>

<div class="highlight"><pre><code class="csharp"><span class="n">IScheduledBackupService</span> <span class="nf">GetScheduledBackupService</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">ScheduledBackupService</span><span class="p">(</span>
                <span class="p">...</span> <span class="p">,</span>
                <span class="p">()</span> <span class="p">=&gt;</span> <span class="n">MockRepository</span><span class="p">.</span><span class="n">GenerateStub</span><span class="p">&lt;</span><span class="n">ITimer</span><span class="p">&gt;());</span>
<span class="p">}</span>
</code></pre></div>


<h2>What about those unit tests?</h2>

<p>What if we need to use the mock object in a unit test - to raise events or stub methods? We can't track them if we use the function defined above...</p>

<p>As our existing tests relied on verifying the messages displayed using ITimer instances, I wrote a custom function to mimic the function behaviour and support the unit tests.</p>

<div class="highlight"><pre><code class="csharp"><span class="n">Func</span><span class="p">&lt;</span><span class="n">IDispatcherTimer</span><span class="p">&gt;</span> <span class="n">createTimers</span> <span class="p">=</span> <span class="p">()</span> <span class="p">=&gt;</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">elapsedTimer</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> 
    <span class="p">{</span>
        <span class="c1">// first call -&gt; mock &quot;elapsed&quot; timer</span>
        <span class="n">elapsedTimer</span> <span class="p">=</span> <span class="n">MockRepository</span><span class="p">.</span><span class="n">GenerateStub</span><span class="p">&lt;</span><span class="n">ITimer</span><span class="p">&gt;();</span>
        <span class="k">return</span> <span class="n">elapsedTimer</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">pausedTimer</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> 
    <span class="p">{</span>
        <span class="c1">// second call -&gt; mock &quot;paused&quot; timer</span>
        <span class="n">pausedTimer</span> <span class="p">=</span> <span class="n">MockRepository</span><span class="p">.</span><span class="n">GenerateStub</span><span class="p">&lt;</span><span class="n">ITimer</span><span class="p">&gt;();</span> 
        <span class="k">return</span> <span class="n">pausedTimer</span><span class="p">;</span>
    <span class="p">}</span>
      
    <span class="k">return</span> <span class="k">null</span><span class="p">;</span> <span class="c1">// subsequent calls not supported - will raise errors if used</span>
<span class="p">};</span>

<span class="n">IScheduledBackupService</span> <span class="nf">GetScheduledBackupService</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">ScheduledBackupService</span><span class="p">(</span>
                    <span class="p">...</span> <span class="p">,</span>
                    <span class="n">createTimers</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>


<p>And our tests remain clean and readable:</p>

<div class="highlight"><pre><code class="csharp"><span class="na">[TestMethod]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">ElapsedTimer_WhenServiceResumes_StartsAgain</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// arrange</span>
    <span class="kt">var</span> <span class="n">service</span> <span class="p">=</span> <span class="n">GetScheduledBackupService</span><span class="p">();</span>

    <span class="c1">// act</span>
    <span class="n">service</span><span class="p">.</span><span class="n">Start</span><span class="p">();</span>
    <span class="n">service</span><span class="p">.</span><span class="n">Pause</span><span class="p">();</span>
    <span class="n">service</span><span class="p">.</span><span class="n">Resume</span><span class="p">();</span>

    <span class="c1">// assert</span>
    <span class="n">elapsedTimer</span><span class="p">.</span><span class="n">AssertWasCalled</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">Start</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">Repeat</span><span class="p">.</span><span class="n">Twice</span><span class="p">());</span>
    <span class="n">elapsedTimer</span><span class="p">.</span><span class="n">AssertWasCalled</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">Stop</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">Repeat</span><span class="p">.</span><span class="n">Once</span><span class="p">());</span>
<span class="p">}</span>
</code></pre></div>


<h2>What else can I do from the container?</h2>

<p>Nicholas Blumhardt, maintainer of Autofac, has a <a href="http://nblumhardt.com/2010/01/the-relationship-zoo/">detailed entry</a> which discusses the different possible relationships between components, and how Autofac defines them. While the article is Autofac-centric, many of the other inversion of control containers for the .NET Framework support some of the features already.</p>

<p>It's a great read if you want to dive deeper into inversion of control concepts.</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Amped Web 2010 Recap</title>
   <link href="http://brendanforster.com//amped-web-2010-recap.html" />
   <updated>2010-10-16T03:00:00+00:00</updated>
   <id>http://brendanforster.com/amped-web-2010-recap.html</id>
   <content type="html">
	<![CDATA[<p><strong>Disclaimer:</strong> I'm currently running on a few hours of sleep so corrections may be required as the memories return. I'm also waiting for some of the photos to surface from the day - including <a href="http://twitter.com/Rog42">@Rog42</a>'s crazy photography experiments!</p>

<p>Yesterday was the <a href="http://www.ampedweb.org/">Amped Web</a> day, a hack day following the Web Directions South conference held in Sydney. The day is for teams to compete in specific categories - around design and development - and put together a solution in a few hours. It may have been an all-day event, but the time flew by. The solutions were reviewed by judges over the afternoon - providing feedback and suggestions as the teams polished their ideas.</p>

<p>I teamed up with <a href="http://tath.am/">Tatham Oddie</a> (<a href="http://twitter.com/tathamoddie">@tathamoddie</a>) and <a href="http://aaron-powell.com/">Aaron Powell</a> (<a href="http://twitter.com/slace">@slace</a>) to create a platform and prototype client for a specific problem.</p>

<p>What was that problem? Check out the video!</p>

<object width="480" height="385">
    <param name="movie" value="http://www.youtube.com/v/2ln9cTSkNtI?fs=1&amp;hl=en_US&amp;rel=0"></param>
    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/2ln9cTSkNtI?fs=1&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385">
    </embed>
</object>


<p>All the details are available on <a href="http://openconferenceprotocol.org/">http://openconferenceprotocol.org/</a>.</p>

<p>Our solution won the Best Overall Windows Phone application, and the "product launch" was a pitch to win the Grand Prize - a trip to Tokyo next month for <a href="http://east.webdirections.org/2010/">Web Directions East</a>.</p>

<p>When the dust settled and all the teams had their pitches, the judges decided to send us to Japan! I'm looking forward to seeing the Japanese development community in action, and it will be my first trip to Japan. Time to learn some more Ruby - and some Japanese won't hurt either!</p>

<p>Special thanks to John Allsopp (<a href="http://twitter.com/johnallsopp">@johnallsopp</a>) and the other organisers of Web Directions for putting together a great event. The sponsors of the event - Windows Phone, Adobe, Paypal, SBS, the Powerhouse Museum and others - also helped make the day awesome with food, swag and prizes.</p>

<p>I'll have to check out the full conference - and return to defend our title - in 2011.</p>

<p>But now, Tokyo awaits!</p>

<p><em>Footnote:</em></p>

<p>We'll continue to polish our idea over the coming weeks - adding features, enhancing the story, getting feedback from the community - so stay tuned for more. I'll put up a higher-res video of the WP7 application for those who are having troubles seeing it clearly in the pitch.</p>

<p>For those who have specific questions, you can leave a comment here or reach me on Twitter (<a href="http://twitter.com/shiftkey">@shiftkey</a>)</p>
]]>
   </content>
   
 </entry>
 
 <entry>
   <title>Hello World</title>
   <link href="http://brendanforster.com//hello-world.html" />
   <updated>2010-09-23T00:50:44+00:00</updated>
   <id>http://brendanforster.com/hello-world.html</id>
   <content type="html">
	<![CDATA[<p>Starting off this blog with a simple post. More styling to come during the coming days.</p>

<p><strong>Side note:</strong> here's the Factorial function in F#:</p>

<div class="highlight"><pre><code class="fsharp"><span class="k">let</span> <span class="k">rec</span> <span class="n">factorial</span> <span class="n">n</span> <span class="o">=</span>
<span class="k">match</span> <span class="n">n</span> <span class="k">with</span>
<span class="o">|</span> <span class="mi">0</span> <span class="o">-&gt;</span> <span class="mi">1</span>
<span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">n</span> <span class="o">*</span> <span class="n">factorial</span> <span class="o">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="o">)</span>
</code></pre></div>



]]>
   </content>
   
 </entry>
 
 
</feed>