<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Continuous Developer]]></title><description><![CDATA[Follow my journey into the world of  Continuous Integration / Continuous Deployment / Continuous *. I'll also cover random dev topics that I come across in my day to day work.]]></description><link>https://duanemckibbin.com/</link><generator>Ghost 0.11</generator><lastBuildDate>Thu, 19 Nov 2026 14:00:14 GMT</lastBuildDate><atom:link href="https://duanemckibbin.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Why do you have an implementation in your interface?]]></title><description><![CDATA[I was recently helping some developers who are new to C# to learn some basic concepts. Among those concepts were interfaces and classes.]]></description><link>https://duanemckibbin.com/2020/02/18/why-do-you-have-implementation-in-interface/</link><guid isPermaLink="false">8db4aa6b-0f24-44c7-922a-1a7924b3316c</guid><category><![CDATA[c#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[.net]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Tue, 18 Feb 2020 06:43:30 GMT</pubDate><media:content url="http://duanemckibbin.com/content/images/2020/02/cytonn-photography-GJao3ZTX9gU-unsplash-e1582005809692.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="interfacesinc">Interfaces in C#</h2>

<blockquote>
  <img src="http://duanemckibbin.com/content/images/2020/02/cytonn-photography-GJao3ZTX9gU-unsplash-e1582005809692.jpg" alt="Why do you have an implementation in your interface?"><p>An INTERFACE in C# is a type definition similar to a class, except that it <strong>purely represents a contract</strong> between an object and its user. It can neither be directly instantiated as an object, nor can data members be defined. So, an interface is nothing but a collection of method and property <strong>declarations</strong> (<a href="https://en.wikibooks.org/wiki/C_Sharp_Programming/Interfaces">C# Programming</a>, emphasis mine)</p>
</blockquote>

<p>Any vaguely experienced C# developer would understand and agree with the above definition. Interfaces are purely function signatures but do no contain any actual implementation. </p>

<pre><code class="language-csharp">public interface IFruit  
{
    void EatMe();
}

public class Apple : IFruit  
{
    public override void EatMe() 
    {
    }
} 
</code></pre>

<h2 id="myconfusion">My confusion</h2>

<p>I was recently helping some developers who are new to C# to learn some basic concepts. Among those concepts were interfaces and classes.</p>

<p>I came across the following interface that intuitively looks incorrect, but Visual Studio was not complaining and the code was building:</p>

<pre><code class="language-csharp">public interface IFruit  
{
    void EatMe();

    int Sweetness 
    {
        get 
        {
            return 5;
        }
    }
}
</code></pre>

<p>What is going on here, why is it possible to add an implementation to an interface? You'll notice that the property is not returning a local variable value, but that's because the compiler does complain when you try to add those.</p>

<h2 id="cdefaultinterfacemethods">C# Default Interface Methods</h2>

<p>The reason that this works is a new C# 8 feature called <strong>Default Interface Methods/Implementations</strong>. Developers can now add implementation details to an interface so that the implementing class doesn't need to. But why?</p>

<h3 id="picturethescenario">Picture the scenario:</h3>

<ol>
<li>I write and publish a new library for managing fruit. At the time of publishing, I only considered that fruit would be eaten and so I created an interface like the one right at the top of this post.  </li>
<li>The library is wildly popular and I have many millions of users all implementing my <code>IFruit</code> interface in their extremely important line of business apps.  </li>
<li>I've received a lot of feedback from my users that they need some way to check the sweetness of the fruit before deciding whether to eat it or not, so I decide to add a <code>Sweetness</code> property.  </li>
<li>Awesome, I'm such a responsive, caring library maintainer. I push out the change and wait for the thank you emails...  </li>
<li>I get them from a few people (those that asked for Sweetness), but the majority of my emails are from everyone else who doesn't care about sweetness, but who's super critical software no longer builds because they have not implemented this silly property. 😮</li>
</ol>

<p>Enter C# 8 and this new <strong>Default Interface Implementations feature</strong> which were added for this exact reason. They allow you to: <br>
1. Add private static member variables <br>
1. Add default implementations for properties defined on the interface <br>
1. Add default implementations for methods defined on the interface</p>

<p>Using these features, I would be able to add my <code>Sweetness</code> property without affecting users of my library who didn't care.</p>

<pre><code class="language-csharp">public interface IFruit  
{
    void EatMe();

    private static int _defaultSweetness;
    int Sweetness 
    {
        get 
        {
            return _defaultSweetness;
        }
        set
        {
          //do nothing
        }
    }

    void SweetEnoughToEat(int desiredSweetness) 
    {
       return Sweetness &gt;= desiredSweetness;
    }

}
</code></pre>

<h2 id="butbutthisjustfeelswrong">But, but this just feels wrong</h2>

<p>I feel you, it does feel wrong but it also feels like an elegant solution to a real problem. That being said, it's probably not a problem that we encounter in our regular projects. My advice: know it exists for the case when you'll need it, but don't abuse it by giving all interfaces default implementations, that's what abstract classes exist for.</p>

<p>You can read a bit more <a href="https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/default-interface-methods-versions">here</a>, <a href="https://www.infoq.com/articles/default-interface-methods-cs8/">here</a>, <a href="https://www.c-sharpcorner.com/article/working-with-default-interface-implementation-in-c-sharp-8-0/">here</a> and <a href="https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/">here</a> </p>]]></content:encoded></item><item><title><![CDATA[Using ASP.NET Core goodies in a console app]]></title><description><![CDATA[<h2 id="theproblem">The problem</h2>

<p>I've been working a lot on ASP.net Core web applications recently and have really come to enjoy the built in dependency injection and configuration libraries. </p>

<p>I was recently building a console app using .NET Core and really missed having these goodies available to me. There are .NET</p>]]></description><link>https://duanemckibbin.com/2019/06/26/using-asp-net-core-goodies-in-a-console-app/</link><guid isPermaLink="false">004dc866-3840-4c55-838f-c1ec7cbfab33</guid><category><![CDATA[core]]></category><category><![CDATA[.net]]></category><category><![CDATA[config]]></category><category><![CDATA[json]]></category><category><![CDATA[aspnet]]></category><category><![CDATA[console]]></category><category><![CDATA[dependency injection]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Wed, 26 Jun 2019 07:00:01 GMT</pubDate><content:encoded><![CDATA[<h2 id="theproblem">The problem</h2>

<p>I've been working a lot on ASP.net Core web applications recently and have really come to enjoy the built in dependency injection and configuration libraries. </p>

<p>I was recently building a console app using .NET Core and really missed having these goodies available to me. There are .NET standard libraries, so there was no reason I couldn't use them, but I hit a few snags on the way. For ASP.net, Visual Studio does a great job of adding everything for you as well as wiring everything up. The documentation is also pretty much all ASP.net focused. Hopefully this article will help someone else trying to add these goodies to their apps. If not, I have a record for myself :)</p>

<p>I'm not going to go into all the details of how these various libraries work, just some high-level tips and how to use them outside ASP.net core. You should be able to follow the Microsoft docs for the details.</p>

<h2 id="1configuration">1. Configuration</h2>

<p>.NET framework apps manage configuration in an XML file called <code>app.config</code> / <code>web.config</code> (in the <code>&lt;appsettings/&gt;</code> section). There are static helper classes available that one could use to then access the values. </p>

<p>This functionality is no longer available, instead ASP.net Core introduced a variety of options for managing configuration. The one I'm most familiar with is a JSON file, but there are many others, see <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2#providers">here</a></p>

<p>Other cool features include:</p>

<ul>
<li>Automatically binding your settings to C# objects, taking types into account. This is a huge improvement over the <code>&lt;appsettings&gt;</code> method where everything comes back as a string.</li>
<li>The concept of hierarchical / cascading settings. A developer can define a base settings file and then override specific properties based on some logic, e.g. the environment that the app is executing in.</li>
</ul>

<p>To get this configuration into your application:</p>

<ol>
<li>Install the required Nuget packages: <br>
<ol><li><code>Microsoft.Extensions.Configuration</code></li>
<li><code>Microsoft.Extensions.Configuration.FileExtensions</code></li>
<li><code>Microsoft.Extensions.Configuration.Binder</code></li>
<li><code>Microsoft.Extensions.Configuration.Json</code></li></ol></li>
<li><p>Add an <code>appsettings.json</code> file to your project root, and make sure its set to copy to the output folder on build.</p>

<pre><code>{
     "ConnectionStrings" : {
         "Connection": "localhost,..."
     }
     "configKey" : "someValue",
     "configSection" : {
         "key": 123
     }
}
</code></pre></li>
<li><p>Add the following in your <code>Program.cs</code> file, in <code>Main()</code></p>

<pre><code>var config = new ConfigurationBuilder()
             .AddJsonFile("appsettings.json", false, true)
             .Build();
</code></pre></li>
<li><p>You can then access your setting wherever you need them with</p>

<pre><code>config["configKey"]; //Dictionary syntax
//or
config.GetSection("configSection")["key"]; 
//or
config.GetConnectionString("Connection"); //Syntactical sugar over config.GetSection["ConnectionString"]
</code></pre></li>
<li><p>To bind the config to a matching object:</p>

<pre><code>class ConfigSection() 
{
    public int key { get; set; }
} 


/**********************************/
var myConfig = new ConfigSection();
var config = config.GetSection("configSection");
config.Bind(myConfig);
</code></pre></li>
<li>We can set it up to auto-bind but for that we'll need dependency injection, so lets look at that.</li>
</ol>

<h2 id="dependencyinjection">Dependency Injection</h2>

<p>There are many 3rd party dependency injection frameworks that you may have used before, but ASP.net core comes with a built in one that is pretty simple, but really effective for most use cases.</p>

<ol>
<li>Install the required Nuget packages: <br>
<ol><li><code>Microsoft.Extensions.DependencyInjection</code></li>
<li><code>Microsoft.Extension.Options.ConfigurationExtensions</code></li></ol></li>
<li><p>Add the following in your <code>Program.cs</code> file, in <code>Main()</code></p>

<pre><code>            var serviceCollection = new ServiceCollection()
                // If you're using Entity Framework, configure the Context
                .AddDbContext&lt;MyDbContext&gt;(builder =&gt; builder                                   
                      .UseSqlServer(config.GetConnectionString("Connection"))
                )
                // If you need access to the raw config, do this here
                .AddSingleton&lt;IConfiguration&gt;(config)
                // Register any other dependencies
                .AddSingleton&lt;IService, Service&gt;()                        
                .AddSingleton&lt;IService2, Service2&gt;()
                .AddSingleton&lt;IService3, Service3&gt;()
                .AddSingleton&lt;IService4, Service4&gt;()
                // Register your config bindings
                .Configure&lt;ConfigSection&gt;(config.GetSection("configSection"));
                .BuildServiceProvider();
</code></pre></li>
<li><p>Now, because ASP.net is not the entry point, you will have to look up the first service, but the DI will ensure all of the following dependencies are resolved and injected.</p>

<pre><code>serviceCollection.GetService&lt;IService&gt;().DoSomething();
</code></pre></li>
<li><p>For more on the ASP.net DI tooling, check the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2">docs</a></p></li>
</ol>

<h2 id="butwaittheresmore">But wait, there's more</h2>

<p>ASP.net core has many more useful libraries that could probably be used in console apps, I haven't needed any yet, but I'll definitely have a look at them in the future and figure out what is required to get them working on their own.</p>

<p>Things like:</p>

<ul>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2">Logging</a></li>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2#environment-variables-configuration-provider">Configuration from Environment Variables</a></li>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-2.2&amp;tabs=windows">User Secrets Management</a></li>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.2">Support for multiple environments</a></li>
</ul>]]></content:encoded></item><item><title><![CDATA[Node Gyp with Visual Studio 2019]]></title><description><![CDATA[<p>I'm working on an Angular application and had to recently re-install my node_modules. This means installing node-sass which in turn uses node-gyp (python and c++) to build some native modules.</p>

<p>The node-gyp build kept failing as it couldn't find the MSBuild.exe in the location it expected. Turns out</p>]]></description><link>https://duanemckibbin.com/2019/04/09/node-gyp-with-visual-studio-2019/</link><guid isPermaLink="false">c6238a8a-305c-47c5-b634-55896f3aeb7a</guid><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Tue, 09 Apr 2019 11:55:52 GMT</pubDate><content:encoded><![CDATA[<p>I'm working on an Angular application and had to recently re-install my node_modules. This means installing node-sass which in turn uses node-gyp (python and c++) to build some native modules.</p>

<p>The node-gyp build kept failing as it couldn't find the MSBuild.exe in the location it expected. Turns out the in Visual Studio 2019, the location (and convention) has changed.</p>

<p>I see that it's an <a href="https://github.com/nodejs/node-gyp/issues/1411">open issue</a> on the node-gyp repo, with an open <a href="https://github.com/nodejs/node-gyp/pull/1715">PR</a>.</p>

<p>But in the meantime, I found a comment on the issue where someone wrote a nifty Powershell script that creates a shim EXE in the location node-gyp expects, but forwards the command to the actual msbuild.exe. Problem solved until it can be fixed properly.</p>

<p>You can find the script here: <a href="https://gist.github.com/noseratio/d81888eda77620e526c7eb2c3b75cba8">https://gist.github.com/noseratio/d81888eda77620e526c7eb2c3b75cba8</a></p>

<ol>
<li>Copy it into a text document and name something like <code>create-msbuild-shim.ps1</code>  </li>
<li>Open a PowerShell prompt as Administrator  </li>
<li><code>.\create-msbuild-shim.ps1</code>  </li>
<li>Re-run your <code>npm install</code> or <code>node-gyp rebuild</code></li>
</ol>]]></content:encoded></item><item><title><![CDATA[Selecting VarBinary data as Base64]]></title><description><![CDATA[<p><em><strong>Disclaimer:</strong> This post is more for me to remember how I did this for future me to find when I Google it :). But if it helps someone else, awesome.</em></p>

<p>I was recently working on a feature that required storing a small image (PNG) in a database. We're using SQL Server,</p>]]></description><link>https://duanemckibbin.com/2019/03/14/spot-checking-images-stored-in-a-sql-server-column/</link><guid isPermaLink="false">f5b954af-694e-4eb5-a887-fe846a58f702</guid><category><![CDATA[note to self]]></category><category><![CDATA[base64]]></category><category><![CDATA[varbinary]]></category><category><![CDATA[sql server]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Thu, 14 Mar 2019 08:54:59 GMT</pubDate><content:encoded><![CDATA[<p><em><strong>Disclaimer:</strong> This post is more for me to remember how I did this for future me to find when I Google it :). But if it helps someone else, awesome.</em></p>

<p>I was recently working on a feature that required storing a small image (PNG) in a database. We're using SQL Server, so I used the VarBinary type.</p>

<p>Once the image was stored, I want to just check that it was stored correctly as there was a bit of a process involved in generating and storing it.</p>

<p>I did a <code>SELECT</code> on the table and saw something like this: <code>0x89504E470D0A1A0A0000000D49...</code> which I assume is HEX of some sort, but when I tried to use an online tool to quickly convert the HEX back to PNG I got all sorts of errors.</p>

<p>After a bit of Googling, I <a href="https://stackoverflow.com/questions/45664937/retrieve-varbinary-value-as-base64-in-mssql">found a way</a> to select the data as Base64:</p>

<pre><code class="language-sql">select ImageData, base64  
from MyTableWithImagesInIt  
cross apply (select ImageData '*' for xml path('')) T (base64)  
</code></pre>

<p>I was then able to paste this Base64 string into <a href="https://onlinepngtools.com/convert-base64-to-png">this</a> helpful tool and get a quick preview of the PNG and to confirm that everything was generated and saved correctly.</p>]]></content:encoded></item><item><title><![CDATA[Home Automation 2 - Sonoff]]></title><description><![CDATA[<p><strong><em>This is part 2 of my series on <a href="https://duanemckibbin.com/tag/home-automation/">Home Automation</a></em></strong></p>

<ol>
<li><a href="https://duanemckibbin.com/2018/10/31/a-journey-into-the-world-of-home-automation/">Introduction</a>  </li>
<li>Sonoff  </li>
</ol>

<h1 id="sonoff">Sonoff</h1>

<p>In my last post I mentioned that after buying a Google Home, I wanted to try to automate some aspects of my house. After disappearing down many rabbit holes, a colleague suggested that I look at a</p>]]></description><link>https://duanemckibbin.com/2018/12/30/home-automation-2-sonoff/</link><guid isPermaLink="false">e18e22be-b9d7-47a9-bb21-f769a4daff06</guid><category><![CDATA[home automation]]></category><category><![CDATA[sonoff]]></category><category><![CDATA[smart switch]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Sun, 30 Dec 2018 20:26:15 GMT</pubDate><media:content url="https://sonoff.itead.cc/images/basicw.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://sonoff.itead.cc/images/basicw.jpg" alt="Home Automation 2 - Sonoff"><p><strong><em>This is part 2 of my series on <a href="https://duanemckibbin.com/tag/home-automation/">Home Automation</a></em></strong></p>

<ol>
<li><a href="https://duanemckibbin.com/2018/10/31/a-journey-into-the-world-of-home-automation/">Introduction</a>  </li>
<li>Sonoff  </li>
</ol>

<h1 id="sonoff">Sonoff</h1>

<p>In my last post I mentioned that after buying a Google Home, I wanted to try to automate some aspects of my house. After disappearing down many rabbit holes, a colleague suggested that I look at a device called a <a href="https://www.itead.cc/sonoff-wifi-wireless-switch.html">Sonoff</a> from a company called ITEAD. Most of the Sonoff devices are based off the ESP8266 chip, which is a simple micro-controller with built in WiFi.</p>

<h2 id="sonoffbasic">Sonoff Basic</h2>

<p><img src="http://continuousdeveloper.com/content/images/2018/12/sonoff_basic.jpg" alt="Home Automation 2 - Sonoff"></p>

<p>I started off with a Sonoff Basic, which is a WiFi enabled smart switch that enables you to control devices using the ITEAD app (or the Google Home/Amazon Echo). They're relatively cheap (+/- <a href="http://www.smartkit.co.za/product/sonoff-basic/">R125</a> or about $8) so I thought they would be a good way to get my toes wet in home automation. </p>

<h2 id="simpleusage">Simple usage</h2>

<p>The simplest usage of the Sonoff Basic would be as follows:</p>

<ol>
<li>Attach mains voltage to the input terminals  </li>
<li>Attach some sort of appliance to the output terminals  </li>
<li>Power it up and connect it to your WiFi (using the ITEAD eWeLink app)  </li>
<li>Use the app to switch your appliance on or off <br>
<ul><li>There is also a physical switch on the top to toggle the relay manually</li></ul></li>
<li>Your Google Home / Amazon Echo can be integrated with eWeLink to allow voice control  </li>
<li>Placing the Sonoff Basic inline on a short extension cord would allow you to control just about any appliance that can be plugged in (just remember that the device is only rated for a current of 10A)</li>
</ol>

<h2 id="letsgetcomplicated">Lets get complicated</h2>

<p>I however decided to complicate matters slightly. I noticed that the <a href="http://www.smartkit.co.za/product/sonoff-basic/">company</a> I was buying it from offered to flash a custom firmware onto the device. Being the curious developer that I am, I went for that option. The custom firmware is called <a href="https://github.com/arendst/Sonoff-Tasmota">TASMOTA</a>.</p>

<p>Flashing TASMOTA opens up a lot of possibilities and extra functionality not available on the standard Sonoff device. Features such as:</p>

<ol>
<li>You're not reliant on a 3rd party cloud infrastructure to control your house (this is the number one reason I was keen to try TASMOTA)  </li>
<li>Control/status via an MQTT broker, which in turn allows integration into just about any home automation system  </li>
<li>Built in rules  </li>
<li>Web interface  </li>
<li>Over the air updates  </li>
<li>Access to the other pins on the ESP8266 (some soldering required)</li>
</ol>

<p>As mentioned, my Sonoff came pre-flashed with TASMOTA. I have since bought the required equipment to flash them myself, perhaps that will be another post, but there is already plenty of content online about how to do that.</p>

<h2 id="howiusedit">How I used it</h2>

<ol>
<li>To keep things simple, I installed the Sonoff inline in a short extension cord. I then plugged our lounge lamp into the new cord.  </li>
<li>Without the eWeLink app, the WiFi connection option is a bit different, there a few options available (you enter the mode by <a href="https://github.com/arendst/Sonoff-Tasmota/wiki/Button-usage">pressing different button combinations</a>): <br>
<ol><li>When flashing the firmware, set the WiFi details (this wasn't a option for me as it was already flashed)</li>
<li>Start the device up as a WiFi access point and connect to it directly (this is a common technique used to configure Wifi IOT devices like the Google Chromecast)</li>
<li>Use an Android app called ESP8266 SmartConfig</li>
<li>Use Wifi Protected Setup (WPS) if your router supports it (mine does but it's a pain to use)</li></ol></li>
</ol>

<p>I ended up using the Access Point method and configuring my WiFi details. There after I was able to switch the lamp using the button or the web interface of the Sonoff. This was all well and good, but not super useful. I needed some way to control the device remotely without having to log into it all the time. But that's the topic of my next post, coming soon.</p>

<p><img src="http://continuousdeveloper.com/content/images/2018/12/sonoff_web_interface.png" alt="Home Automation 2 - Sonoff"></p>]]></content:encoded></item><item><title><![CDATA[A journey into the world of home automation]]></title><description><![CDATA[<p>I recently spent some birthday money importing a <a href="https://store.google.com/us/product/google_home_mini?hl=en-US">Google Home Mini</a> and I've really enjoyed using it to control my various ChromeCast (audio and video) devices around the house as well as asking the Google Assistant random things. I somehow even managed to get my normally skeptical wife to use</p>]]></description><link>https://duanemckibbin.com/2018/10/31/a-journey-into-the-world-of-home-automation/</link><guid isPermaLink="false">62be5d58-d153-43d8-b818-44b7154e763d</guid><category><![CDATA[home automation]]></category><category><![CDATA[google home]]></category><category><![CDATA[electronics]]></category><category><![CDATA[pet project]]></category><category><![CDATA[series]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Wed, 31 Oct 2018 04:34:22 GMT</pubDate><media:content url="http://duanemckibbin.com/content/images/2018/10/google_home_mini_personal_assistant_price.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://duanemckibbin.com/content/images/2018/10/google_home_mini_personal_assistant_price.jpg" alt="A journey into the world of home automation"><p>I recently spent some birthday money importing a <a href="https://store.google.com/us/product/google_home_mini?hl=en-US">Google Home Mini</a> and I've really enjoyed using it to control my various ChromeCast (audio and video) devices around the house as well as asking the Google Assistant random things. I somehow even managed to get my normally skeptical wife to use it to play music.</p>

<p><img src="http://continuousdeveloper.com/content/images/2018/10/google_home_mini_personal_assistant_price.jpg" alt="A journey into the world of home automation"></p>

<p>I couldn't help but notice all of the cool home automation stuff in the Google Home app and decided to do some exploring around home automation. I disappeared down many rabbit holes and watched many Youtube videos and have now decided to start the process of automating my home.</p>

<p>I always wished that I had studied electrical engineering, or at least done some sort of electronics courses at University. So this is my chance to teach myself and at the same time put my software skills to use for something at home. I haven't really had a pet project that I felt passionate about for a long time.</p>

<p>I thought I'd blog about my experiences and learnings, others may find it interesting or helpful. It may even inspire others to dig into the subject and try something in their homes.</p>

<p>Stay tuned for my next post on a cool little device I discovered, called a Sonoff, that's cheap yet powerful and flexible.</p>

<p>Also, checkout this guy's <a href="https://www.youtube.com/user/SuperHouseTV">YouTube channel</a>, he's really inspired me to get stuck in and given me many great ideas.</p>]]></content:encoded></item><item><title><![CDATA[Zero Downtime Deployments In An IIS World]]></title><description><![CDATA[<p>This article was originally published on <a href="https://www.offerzen.com/blog/zero-downtime-deployments-in-an-iis-world">OfferZen</a>.</p>

<p>Anne Gonschorek was a huge help in making this article come together. She’s looking for more contributers to the OfferZen blog. Take a look at <a href="http://source.offerzen.com/">Source</a> for more info.</p>

<hr>

<p>We live in a digital world where service downtime is not tolerated by</p>]]></description><link>https://duanemckibbin.com/2018/08/03/hot-deployments-to-iis-using-tfs-vsts/</link><guid isPermaLink="false">d63a8ba1-2573-4a15-a33e-eb2ba854f094</guid><category><![CDATA[blue/green]]></category><category><![CDATA[hot deployment]]></category><category><![CDATA[zero downtime]]></category><category><![CDATA[vsts]]></category><category><![CDATA[visual studio team services]]></category><category><![CDATA[tfs]]></category><category><![CDATA[powershell]]></category><category><![CDATA[iis]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Fri, 03 Aug 2018 04:57:45 GMT</pubDate><content:encoded><![CDATA[<p>This article was originally published on <a href="https://www.offerzen.com/blog/zero-downtime-deployments-in-an-iis-world">OfferZen</a>.</p>

<p>Anne Gonschorek was a huge help in making this article come together. She’s looking for more contributers to the OfferZen blog. Take a look at <a href="http://source.offerzen.com/">Source</a> for more info.</p>

<hr>

<p>We live in a digital world where service downtime is not tolerated by customers, but at the same time, not everyone has the luxury of cold standby environments or Kubernetes clusters to enable this. I recently had the task of finding a way to make zero downtime deployments work using good old Microsoft IIS, as well as automating the deployments behind a single click. I’m sure there are others out there with similar constraints. If you’re one of them, then this is for you.</p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Cover-image-5.png" alt=""></p>

<h4 id="projectcodenameavoidweekenddeployments">Project Codename: “Avoid weekend deployments”</h4>

<p>Until recently, our team has been doing deployments out of the regular business hours (i.e just before 9am or after 5pm). This has worked really well for us, but the honeymoon is coming to an end. We’re now building systems that need to be up all the time as we never know when a customer may need to access them. The traditional deployment time in other parts of the company is Sunday morning at 5am, but <a href="https://www.youtube.com/watch?v=r2fsdQEcLS4">ain't nobody got time for that</a>.</p>

<p>Now, I know what you’re thinking: just use Docker with Kubernetes and set up a cluster in “The Cloud” so you can do rolling hot deployments! Easy. I really wish that was an option for us, but unfortunately, it just isn’t. Here’s why:</p>

<ul>
<li>We may not host in the cloud because we work at a big financial institution with strict data requirements.</li>
<li>We may soon be able to use Docker for our deployments, but only Linux based and our stack is .net running in IIS. We’re moving slowly to .net core, but aren’t quite there yet.</li>
<li>Even if we used containers, we don’t yet have any high availability tools in place to do hot deployments.</li>
<li>We do run multiple instances of our production systems behind a load balancer, but unfortunately we don’t have any control over the load balancer as it is managed by the company’s IT infrastructure team.</li>
</ul>

<h4 id="oursaviourbluegreendeployments">Our saviour: Blue/Green Deployments</h4>

<p>My research led me to a concept called <a href="https://martinfowler.com/bliki/BlueGreenDeployment.html">Blue/Green deployments</a> as well as an <a href="https://kevinareed.com/2015/11/07/how-to-deploy-anything-in-iis-with-zero-downtime-on-a-single-server/">article on how to implement them</a> with IIS on a single server.</p>

<h6 id="thegeneralconceptofabluegreendeploymentisthefollowing">The general concept of a blue/green deployment is the following:</h6>

<ol>
<li>We set up two instances of the application (blue and green)  </li>
<li>We only expose one instance to customers at a time(live) <br>
The other instance is a staging instance that is running but inaccessible from the outside  </li>
<li>We deploy to the staging instance  </li>
<li>We warm up the staging instance so that all IIS boot up processes are complete  </li>
<li>We bring the staging instance online and for a brief period of time both instances are available to customers  </li>
<li>We drain the the old live instance by allowing all existing connections to finish while not allowing new connections  </li>
<li>We take the old instance offline and the other instance becomes the new default live</li>
</ol>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Gif-v2-1.gif" alt=""></p>

<p>Here’s how you do this for yourself:</p>

<h5 id="bluegreendeploymentwithiisonasingleserver">Blue/green deployment with IIS on a single server</h5>

<h6 id="iisprerequisites">IIS Prerequisites</h6>

<p>First of all, we will need to install 2 modules into IIS:</p>

<ul>
<li><a href="https://www.iis.net/downloads/microsoft/application-request-routing">ARR</a> and</li>
<li><a href="https://www.iis.net/downloads/microsoft/url-rewrite">Url Rewrite</a></li>
</ul>

<h6 id="applicationrequestroutingakaarr">Application Request Routing (aka ARR)</h6>

<p>ARR enables IIS to work as a reverse proxy in front of a farm of IIS instances. In normal cases the other instances would be on other servers like a true server farm. This is a valid option for blue/green deployments but in our case, we wanted to keep it in our existing infrastructure, so the instances will all be on the same machine.</p>

<h6 id="urlrewrite">Url Rewrite</h6>

<p>The server farm is not exposed on a port to the outside world by IIS. We need to use the Url Rewrite module to route traffic to the Server Farm instead of directly to the regular web applications. This is what gives us the power to take an instance offline without affecting users.</p>

<p>Once both modules are installed, we restart the IIS management console.</p>

<h5 id="configuringiis">Configuring IIS</h5>

<p>Before we get started with the new IIS configuration, we need to decide a few things:</p>

<ul>
<li><strong>What do we call our server farm?</strong> There isn’t really a science to choosing this name, it will be used in a few places though so keep it simple and descriptive. (in this example I used “my-website”)</li>
<li><strong>What ports will each of the instances run on?</strong> Make sure they’re available on your server. (e.g. 8888,9999)</li>
<li><strong>Where will each instance be deployed?</strong> IIS uses “C:\inetpub\wwwroot” by default but your company may have different standards. Use whatever works for your team. Just remember that you need to folders and I would recommend differentiating them with a blue/green suffix (e.g. c:\inetpub\wwwroot\my.website.blue)</li>
</ul>

<p>Now let’s set our blue and green instance up. ARR requires that the different instances each have their own host names but we want to run these on the same machine. That’s why we trick the machine by editing the hosts file:</p>

<p>Open “C:\Windows\System32\drivers\etc\hosts” in a text editor and add the following:</p>

<pre><code>127.0.0.1    my-website  
127.0.0.1   my-website-blue  
127.0.0.1   my-website-green  
</code></pre>

<p>Now, back to IIS. You’ll see a new entry on the left titled “Server Farms”. Right-clicking allows you to add a new farm:</p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Create-Server-Farm.png" alt="Create-Server-Farm"></p>

<p>Give the new farm a name as decided earlier. Then we need to define the servers in the farm. These names must match the hostnames added to the hosts file earlier:</p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Add-Server.png" alt="Add-Server"></p>

<p>Click the “Add” button, and then capture similar details for the green instance (with the green hostname and port). Then click “Finish”. Once done, expand the server farm name and click on “Servers”. You should see something like this:</p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Servers.png" alt="Servers"></p>

<h6 id="configuringwebsites">Configuring websites</h6>

<p>Next, we have to configure two websites, each pointing to their own file systems and listening on their own ports. In our case, we configured as follows (using the locations and ports decided on earlier):</p>

<p><strong>MyWebsite.Blue</strong></p>

<ul>
<li>C:\inetpub\wwwroot\mywebsite.blue</li>
<li>Port 8888</li>
</ul>

<p><strong>MyWebsite.Green</strong></p>

<ul>
<li>C:\inetpub\wwwroot\mywebsite.green</li>
<li>Port 9999</li>
</ul>

<p>Sites</p>

<p>You should now be able to open a browser on the server and navigate to:</p>

<ul>
<li><a href="http://my-website-blue:8888">http://my-website-blue:8888</a></li>
<li><a href="http://my-website-green:9999">http://my-website-green:9999</a></li>
</ul>

<p>You’ll notice that the ARR module is not yet routing to these servers if you hit IIS on port 80. To enable this, we’ll need to add a URL Rewrite Rule.</p>

<h6 id="addingaurlrewriterule">Adding a Url Rewrite Rule</h6>

<p>Click on the root node in IIS, locate the icon named “URL Rewrite” and open it. Click “Add Rule” in the top right and configure your rule as follows:</p>

<p><em>Edit the inbound rule:</em></p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Rules1.png" alt="Rules1"></p>

<p><em>Set the conditions:</em></p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Rules2.png" alt="Rules2"></p>

<p><em>Set the server variables:</em></p>

<p><img src="https://offerzen.ghost.io/content/images/2018/07/Rules3.png" alt="Rules3"></p>

<p>Any traffic directed at <a href="http://my-website">http://my-website</a> on port 80 will now be routed to the server farm called “my-website”. ARR will then take over and route to our instances. If you now navigate to <a href="http://my-website">http://my-website</a> you should see your site.</p>

<blockquote>
  <p>If you were to differentiate the two deployments, you’d notice that ARR round-robins between the two sites. This behaviour is nice for load balancing, but not for our use case, because we want to have one instance offline so we can deploy to it without affecting users.</p>
</blockquote>

<p><em>Right click on an instance (doesn’t really matter which one) and select “Take Server Offline.</em></p>

<p>Now we're all set. If you happen to read the article I mentioned, you’ll see they suggest taking the staging server out of the farm using the health monitoring. I found this didn’t work for us because:</p>

<ul>
<li>The health check runs every second and was causing our request logs to fill up really quickly on both the staging and live instances</li>
<li>More importantly, IIS would still occasionally route traffic to the unhealthy node. This would mean the client getting the old version of the app, or if the app pool is turned off to save resources the customer would get an error page.</li>
</ul>

<p><strong>To get around these issues, I made the following changes:</strong></p>

<ul>
<li>I kept the health check in place, but changed it to only run every 30 seconds</li>
<li>I take the staging server offline completely, it is still accessible internally, but ARR stops routing traffic to it
With that all set up, it's time to automate the deployment.</li>
</ul>

<h5 id="automatingallthethingsleveluponpowershell">Automating all the things - Level up on Powershell</h5>

<p>We’ve been on a drive to make sure all of our deployments are automated and triggered with a single click. This ensures deployments are reproducible, predictable and can be performed by someone without a detailed knowledge of the system. We’ve achieved that using our on-premise instance of Microsoft’s Team Foundation Server (also known as Visual Studio Team Services). TFS basically runs on PowerShell scripts, so I’ll focus on the <a href="https://github.com/duanemck/iis-bluegreen-powershell">scripts I wrote</a> instead of getting too much into TFS. Hopefully, you will be able to use the scripts on other build servers as well. I’ve picked out parts of the script to highlight how they work.</p>

<h6 id="powershellmodulesandutilities">Powershell Modules and Utilities</h6>

<p>There are a few functions that I ended up using all over the place. These have been pulled out into their own modules. There are also a couple of functions used to assist in running the scripts remotely on the target machine. I won’t cover those here but they are in the <a href="https://github.com/duanemck/iis-bluegreen-powershell">repo</a>.</p>

<h6 id="iismanagementmodule">IIS Management Module</h6>

<p>We need to make use of the PowerShell cmdlets that allow us to query and control IIS.</p>

<p>For this, we first need to load the assembly into our context:</p>

<pre><code class="language-powershell">[System.Reflection.Assembly]::LoadFrom("$env:systemroot\system32\inetsrv\Microsoft.Web.Administration.dll")
</code></pre>

<p>We can then get an instance of the ServerManager:  </p>

<pre><code class="language-powershell">$mgr = new-object Microsoft.Web.Administration.ServerManager
</code></pre>

<p>Using this, we can get a handle on a specific server farm using its name:</p>

<pre><code class="language-powershell">function Get-ServerFarm([string]$serverFarmName)) {  
    # Get the ServerManager
    $mgr = new-object Microsoft.Web.Administration.ServerManager
    # Get the server configuration and find the section managing the farms
    $conf = $mgr.GetApplicationHostConfiguration()
    $section = $conf.GetSection("webFarms")
    $webFarms = $section.GetCollection()
    $webFarm = $webFarms | Where-Object {
        $_.GetAttributeValue("name") -eq $serverFarmName
    }
    // Return the farm matching the name we’re looking for
    $webFarm
}
</code></pre>

<p>Once we’ve found the farm, we need to locate the individual servers within the farm:</p>

<pre><code class="language-powershell">function Get-Server($serverFarmName,$instanceName) {  
    $webFarm = Get-ServerFarm $serverFarmName
    $servers = $webFarm.GetCollection()

    $server = $servers | Where-Object {
        $_.GetAttributeValue("address") -eq $instanceName
    }
    return $server;
}
</code></pre>

<p>Using the above two functions, we can then query and control IIS to coordinate the deployment.</p>

<p>Have a look at the <a href="https://www.offerzen.com/blog/**http://**">full module</a> for the rest of the code.</p>

<h6 id="preparationscript">Preparation Script</h6>

<p>Before we deploy anything, we still need to determine which instance is which. For this, we use a <a href="https://github.com/duanemck/iis-bluegreen-powershell/blob/master/prepare/01_get-staging-and-live.ps1">preparation script</a> that queries IIS and returns the current state:</p>

<pre><code class="language-powershell"># Use a module function to check if the Blue instance is online
if (Get-ServerOnline $serverFarmName "$serverFarmName-blue") {  
    $result["LiveBlueGreen"] = "Blue"
    $result["LiveDeployPath"] = $bluePath
    $result["LiveServer"] = "$serverFarmName-blue"

    $result["StagingBlueGreen"] = "Green"
    $result["StagingDeployPath"] = $greenPath
    $result["StagingServer"] = "$serverFarmName-green"
}
</code></pre>

<p>If blue is not online, it means that green must be the live instance, so we have a similar block getting the state of the green instance.</p>

<h6 id="deploy">Deploy</h6>

<p>The preparation script helped us discover where we need to deploy our new code. We do this using the normal deployment steps of our deployment tool into <strong>$result.StagingDeployPath.</strong></p>

<h6 id="swap">Swap</h6>

<p>Now that staging contains the latest version, we can do the actual work of the zero-downtime deployment.</p>

<ol>  
<li>First we need to <a href="https://github.com/duanemck/iis-bluegreen-powershell/blob/master/swap/02_warm-up-staging.ps1">warm the staging instance up</a>. The application pool has likely been recycled and we don’t want users to experience the delay of starting up. Warming it up will also help us check if there are any configuration errors preventing the instance from starting. This has saved us before when we forgot to make some changes to the server.</li>


<pre><code class="language-powershell"># Loop until we have a satisfactory response time
Do {  
    $time = Measure-Command {
        # Query the site on it’s internal port and measure the response time
        $res = Invoke-WebRequest $stagingSite
    }
    $ms = $time.TotalMilliSeconds
    If ($ms -ge $minTime) {
        Write-Host "$($res.StatusCode) from $stagingSite in $($ms)ms"
    }
} While ($ms -ge $minTime)
</code></pre>



<li>Now that it’s warmed up, we can <a href="https://github.com/duanemck/iis-bluegreen-powershell/blob/master/swap/03_bring-staging-up.ps1">bring the staging instance into the server farm</a> to start processing requests. This is a pretty simple command that just tells IIS to bring it online.</li>


<pre><code class="language-powershell"># Make sure it is set to state=Available
Set-InstanceState $serverFarmName $stagingInstance 0  
# Bring it 
Set-ServerOnline $serverFarmName $stagingInstance  
</code></pre>



<li>Next, we <a href="https://github.com/duanemck/iis-bluegreen-powershell/blob/master/swap/04_drain-live-instance.ps1">drain the connections</a> to the old live instance and then take it offline by setting its state to “Drain” and then monitoring it’s counters until it is no longer serving requests.</li>


<pre><code class="language-powershell"># Keep checking until the live instance is no longer processing requests. 
$startDate = Get-Date
Write-Host "Checking requests per second"  
Do {  
    $currentConnections = Get-RequestsPerSecond $serverFarmName $liveInstance       
    If ($currentConnections -gt 0) {
        Write-Host "Still $currentConnections requests per second"
    }
    else {
        Write-Host "0 requests per second"
    }
} While ($currentConnections -gt 0 -and $startDate.AddSeconds(10) -gt (Get-Date))

# Now that it is finished servicing its requests, we can take it out of the farm
Set-ServerOffline $serverFarmName $liveInstance  
</code></pre>


<li>Now we just <a href="https://github.com/duanemck/iis-bluegreen-powershell/blob/master/swap/05_post-deploy-health-check.ps1">double check</a> that everything is ok by querying the IIS status in a similar way to the beginning. We also do some additional checks to make sure each instance is in the state we expect (i.e. Live is online and Staging is not).</li>  
</ol>

<h5 id="architectureconsiderations">Architecture Considerations</h5>

<p>Deploying in this way does mean that we needed to make some slight changes to the way that we build our applications. There may be cases where an older frontend tries to access a newer API. Or a newer API accessing a newer version of the database.</p>

<p>For this reason, we will need to ensure that the public API service of each component is always backwards compatible:</p>

<ul>
<li>We never rename or delete a database column until all consumers are updated. We then remove the old columns in subsequent releases.</li>
<li>We never remove or break an existing API endpoint, we rather add new ones and deprecate the old ones until they can be safely removed.</li>
</ul>

<h5 id="futureenhancements">Future Enhancements</h5>

<p>We have this automated process running for a few of our deployments and are slowly rolling it out to the rest. I’ve also had some time to think about some enhancements I’d like to explore:</p>

<ul>
<li>We’d like to find some way to pause the deployment while the staging instance has been updated but not yet live. We could then access it internally and verify that everything is ok before doing the final switch.</li>
<li>I’d like to share this with other people using TFS by publishing the scripts as a TFS extension.
I’d love to hear your feedback and suggestions, would this be useful to you or your company? How would you improve it?</li>
</ul>

<h5 id="resources">Resources</h5>

<ul>
<li><strong>Blue Green Deployments:</strong> <a href="https://martinfowler.com/bliki/BlueGreenDeployment.html">Martin Fowler</a> is a giant in the industry, if he recommends a technique, it’s definitely worth looking into it.</li>
<li><strong><a href="https://kevinareed.com/2015/11/07/how-to-deploy-anything-in-iis-with-zero-downtime-on-a-single-server/">Also, here's the original article that inspired me</a></strong></li>
</ul>

<p><strong>Required IIS Modules</strong></p>

<ul>
<li><a href="https://www.iis.net/downloads/microsoft/application-request-routing">Application Request Routing</a></li>
<li><a href="https://www.iis.net/downloads/microsoft/url-rewrite">URL Rewrite</a></li>
</ul>

<p><strong>PowerShell Resources</strong></p>

<ul>
<li><a href="https://github.com/duanemck/iis-bluegreen-powershell">My Powershell Scripts</a></li>
</ul>

<p>My Powershell skills were pretty basic when starting this project. It took a lot of Googling and experimenting to get things working how I needed. These resources were particularly helpful:</p>

<ul>
<li><a href="https://docs.microsoft.com/en-us/powershell/">Main documentation</a></li>
<li><a href="https://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/">Executing Remotely</a></li>
<li><a href="https://stackoverflow.com/questions/14441800/how-to-import-custom-powershell-module-into-the-remote-session">Installing a module on a remote machine</a></li>
</ul>

<p><strong>Bonus TFS Integration Resources</strong></p>

<p>When running Powershell scripts on TFS/VSTS, <a href="https://blogs.msdn.microsoft.com/premier_developer/2016/04/13/tips-for-writing-powershell-scripts-to-use-in-build-and-release-tasks/">specifically formatted log output</a> can be used to communicate with the build agent.</p>

<p>There is also a <a href="https://www.powershellgallery.com/packages/VstsTaskSdk/0.9.0">PowerShell API</a> that is quite useful and can be used instead of the log formats</p>]]></content:encoded></item><item><title><![CDATA[Code coverage for .net Core with OpenCover]]></title><description><![CDATA[<h6 id="context">Context</h6>

<p>We've recently been on a big drive to improve <a href="https://en.wikipedia.org/wiki/Code_coverage">code coverage</a> on all of our code bases. Our tech stack include Angular 1.6, Angular 6, ASP.net 4 and asp.net Core. Test coverage in the JavaScript world is pretty amazing with tools like <a href="https://github.com/gotwarlost/istanbul">Istanbul</a>, but we've battled</p>]]></description><link>https://duanemckibbin.com/2018/07/13/opencover-with-net-core/</link><guid isPermaLink="false">2d0cf373-ff59-4556-8758-25a4cc48b5c1</guid><category><![CDATA[.net]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[core]]></category><category><![CDATA[coverage]]></category><category><![CDATA[vstest]]></category><category><![CDATA[opencover]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Fri, 13 Jul 2018 20:48:13 GMT</pubDate><content:encoded><![CDATA[<h6 id="context">Context</h6>

<p>We've recently been on a big drive to improve <a href="https://en.wikipedia.org/wiki/Code_coverage">code coverage</a> on all of our code bases. Our tech stack include Angular 1.6, Angular 6, ASP.net 4 and asp.net Core. Test coverage in the JavaScript world is pretty amazing with tools like <a href="https://github.com/gotwarlost/istanbul">Istanbul</a>, but we've battled to find the same for C# without paying a fortune. That is until we came across <a href="https://github.com/OpenCover/opencover">OpenCover</a>.</p>

<p>Code coverage tools work by profiling the binaries while the tests are run and then recording various metrics such as lines/branches covered. See <a href="https://en.wikipedia.org/wiki/Code_coverage">this wiki article</a> for more details.</p>

<p>OpenCover is an open source .net code coverage tool built specifically for the traditional .net framework. This post is the result of my research into getting it working with .net Core as well as the resultant dotnet tool I built to assist us.</p>

<h6 id="runningtestsinnetcore">Running tests in .net Core</h6>

<p>.net Core tests are executed using the dotnet command line tool:</p>

<p><code>dotnet test [project]</code></p>

<p>The dotnet tool ensures the relevant binaries are built and then tests are run using the vstest tool. The tool only allows one to run tests on a single project at a time, more on this later. </p>

<h6 id="runningopencover">Running OpenCover</h6>

<p>I'm not going to go into the details of running OpenCover (check their page, linked above, for their docs), but in general, one provides an executable to profile as well as the arguments for that executable.</p>

<p>So, for .net Core, we need to pass in the dotnet command line to be profiled and then build up the console arguments for our tests</p>

<p><code>OpenCover.Console.Exe -target:"c:\program files\dotnet\dotnet.exe" -targetargs:"test [Project File]"</code></p>

<p>The tests run successfully, but we get the following output indicating that no coverage was recorded: <br>
<img src="https://duanemckibbin.com/content/images/2018/07/debugtype.jpg" alt=""></p>

<p>This is because dotnet core binaries do not expose the required debug information by default. We'll need to add the following to each project file we want to profile:  </p>

<pre><code class="language-xml">&lt;PropertyGroup&gt;  
  &lt;DebugType&gt;Full&lt;/DebugType&gt;
&lt;/PropertyGroup&gt;  
</code></pre>

<p>Now when we run it, we get a different error: <br>
<img src="https://duanemckibbin.com/content/images/2018/07/oldstyle-1.jpg" alt=""></p>

<p>It turns out that some of the APIs OpenCover uses to profile the app are missing in .net Core. Luckily, there is a work around, we can pass <code>-oldstyle</code> to OpenCover to use different APIs.</p>

<p><code>OpenCover.Console.Exe -target:"c:\program files\dotnet\dotnet.exe" -targetargs:"test [Project File]" -oldstyle</code></p>

<p><strong>Success!</strong></p>

<p><img src="https://duanemckibbin.com/content/images/2018/07/success.jpg" alt=""></p>

<p>The results are written to a file called <code>results.xml</code> by default which is a bit tricky to analyze. There are some tools available on nuget that will convert the file to HTML or to a format called Cobertura which is useful for code coverage reporting in VSTS/TFS.:</p>

<ul>
<li><a href="https://www.nuget.org/packages/ReportGenerator/">ReportGenerator</a></li>
<li><a href="https://www.nuget.org/packages/OpenCoverToCoberturaConverter/">OpenCoverToCoberturaConverter</a></li>
</ul>

<h6 id="introducingdotnettestx">Introducing dotnet-testx</h6>

<p>The above commands can get out of hand quickly, especially when one starts passing in more arguments to <code>dotnet test</code> or to OpenCover directly. Also, when trying to improve coverage, one may want to keep generating the report after every test written.</p>

<p>The dotnet cli has an extension mechanism that allows one to write custom commands. In .net core 2.1, these can be installed globally (similar to <code>npm install -g</code>). Details <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools">here</a>.</p>

<p>dotnet-testx is a dotnet tool that handles the following for you:</p>

<ul>
<li>Detect the project file in the current folder, or discover all project files in sub folders</li>
<li>Resolve the location of OpenCover and the reporting tools in nuget's cache</li>
<li>Execute OpenCover with some sensible defaults:
<ul><li>Merge results from multiple runs (1 per project) into 1</li>
<li>Output to folder named <code>coverage</code> so it doesn't pollute the source code</li>
<li>Pass in some filters for DLLs to be ignored in the coverage report</li></ul></li>
<li>Generate an HTML report using ReportGenerator</li>
<li>Open the report in the browser</li>
<li>Convert the report to Cobertura for your TFS/VSTS build</li>
<li>Generate trx test results report for TFS/VSTS</li>
<li>Used together with <code>dotnet watch</code> enables re-running when code changes</li>
</ul>

<p>The tool can be installed with: <code>dotnet tool install --global dotnet-testx</code></p>

<p>Usage:  </p>

<pre><code>dotnet testx

dotnet testx --html --browser

dotnet testx --cobertura

dotnet testx --discover-projects "*Tests.csproj"

dotnet watch --project [project-file] testx -- [dotnet testx arguments]  
</code></pre>

<p>Note: The tool is not bundled with OpenCover or any of the reporting tools. You will need to install them from nuget into your project.</p>

<p>The code lives <a href="https://github.com/duanemck/dotnet-testx">here</a> <br>
The nuget package is <a href="https://www.nuget.org/packages/dotnet-testx/">here</a></p>

<p>I really hope someone else finds this useful. The tool currently works for my needs, but I'll be happy to expand it or accept PRs to extend the usage for other unique use cases.</p>]]></content:encoded></item><item><title><![CDATA[Keeping your C# and TypeScript models in sync]]></title><description><![CDATA[<p><img src="http://continuousdeveloper.com/content/images/2017/10/csharp_loves_ts.png" alt="jsinsa logo"></p>

<p>I've been working on a new Angular (v4) application that talks to a C# (asp.net core) backend. One of the things I love about Angular is TypeScript, and one of the things I love about TypeScript is the ability to define the models you'll send and receive. I love</p>]]></description><link>https://duanemckibbin.com/2017/10/16/keeping-your-c-and-typescript-models-in-sync/</link><guid isPermaLink="false">b4264a09-3f12-437b-99d2-754135cc62a1</guid><category><![CDATA[typescript]]></category><category><![CDATA[c#]]></category><category><![CDATA[csharp]]></category><category><![CDATA[typewriter]]></category><category><![CDATA[models]]></category><category><![CDATA[autogenerate]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Mon, 16 Oct 2017 05:28:23 GMT</pubDate><media:content url="http://duanemckibbin.com/content/images/2017/10/csharp_loves_ts.png" medium="image"/><content:encoded><![CDATA[<img src="http://duanemckibbin.com/content/images/2017/10/csharp_loves_ts.png" alt="Keeping your C# and TypeScript models in sync"><p><img src="http://continuousdeveloper.com/content/images/2017/10/csharp_loves_ts.png" alt="Keeping your C# and TypeScript models in sync"></p>

<p>I've been working on a new Angular (v4) application that talks to a C# (asp.net core) backend. One of the things I love about Angular is TypeScript, and one of the things I love about TypeScript is the ability to define the models you'll send and receive. I love me some Intellisense when writing my code.</p>

<p>Now, C# and TypeScript are very similar, but also sufficiently different that I couldn't just copy my C# viewmodels across to TypeScript land. So I went searching for some solutions.</p>

<p>I came across a few websites that would do the conversion, but they were all pretty opinionated about the way the TypeScript classes were generated and those opinions didn't seem to match the way my Angular project was setup.</p>

<p>Then I came across a Visual Studio extension called <a href="https://frhagn.github.io/Typewriter/">TypeWriter</a> that autogenerates TypeScript models based on C# files.</p>

<p>The defaults didn't match what I needed and it didn't import linked types, but the great thing is that it's heavily customizable and after a bit of trial and error I managed to get exactly what I wanted.</p>

<p>This simple example of C#:  </p>

<pre><code class="language-csharp">// MyEnum.cs
public enum MyEnum {  
  Value1 = 1,
  Value2 = 2
}

// MyClass1.cs
public class MyClass1 {  
  public int Id {get;set;}
  public string Name {get;set;}
  public MyEnum Type {get;set;}
}

//MyClass2.cs
public class MyClass2 {  
  public bool IsActive {get;set;}
  public MyClass1 OtherClass {get;set;}
}
</code></pre>

<p>Becomes this in TypeScript:  </p>

<pre><code class="language-javascript">// my-enum.ts
export enum MyEnum {  
   value1 = 1,
   value2 = 2
}

//my-class1.ts
import { MyEnum } from './my-enum';

export class MyClass1 {  
  public id: number;
  public name: string;
  public type: MyEnum;
}

//my-class2.ts
import { MyClass1 } from './my-class1';

export class MyClass2 {  
  public isActive: boolean;
  public otherClass: MyClass1;
}
</code></pre>

<p>My TypeWriter template file does the following:</p>

<ol>
<li>Only generates classes that end in "Model"  </li>
<li>Generates Enums  </li>
<li>Removes the word "Model" from the class name for TypeScript  </li>
<li>Converts the filenames to kebab-case (i.e. MyClass to my-class)  </li>
<li>Generates imports for referenced non-primitive types  </li>
<li>Places the files into a folder called "GeneratedFronted" so they don't polute my C# files.</li>
</ol>

<p>The template only seems to find files in the same folder as itself, so depending on your project setup, you'll need to add it to multiple folders. It seems that "Add As Link" doesn't work though.</p>

<p>Here is my TypeScriptTemplate.tst file:</p>

<pre><code class="language-csharp">${
    using Typewriter.Extensions.Types;
    using System.Text.RegularExpressions;
    using System.Diagnostics;

    string ToKebabCase(string typeName){
        return  Regex.Replace(typeName, "(?&lt;!^)([A-Z][a-z]|(?&lt;=[a-z])[A-Z])","-$1", RegexOptions.Compiled)
                     .Trim().ToLower();
    }

    string CleanupName(string propertyName, bool? removeArray = true){
        if (removeArray.HasValue &amp;&amp; removeArray.Value) {
            propertyName = propertyName.Replace("[]","");
        }
        return propertyName.Replace("Model","");
    }

    Template(Settings settings)
    {
        settings.OutputFilenameFactory = (file) =&gt; {
            if (file.Classes.Any()){
                var className = file.Classes.First().Name;
                className = CleanupName(className);
                className = ToKebabCase(className);
                return $"GeneratedFrontend\\{className}.ts";
            }
            if (file.Enums.Any()){
                var className = file.Enums.First().Name;
                className = ToKebabCase(className);
                return $"GeneratedFrontend\\{className}.ts";
            }
            return file.Name; 
        };
    }

    string Imports(Class c) =&gt; c.Properties
                                .Where(p=&gt;!p.Type.IsPrimitive || p.Type.IsEnum)
                                .Select(p=&gt; $"import {{ {CleanupName(p.Type.Name)} }} from './{ToKebabCase(CleanupName(p.Type.Name))}';")
                                .Aggregate("", (all,import) =&gt; $"{all}{import}\r\n")
                                .TrimStart();

    string CustomProperties(Class c) =&gt; c.Properties
                                        .Select(p=&gt; $"\tpublic {p.name}: {CleanupName(p.Type.Name, false)};")
                                        .Aggregate("", (all,prop) =&gt; $"{all}{prop}\r\n")
                                        .TrimEnd();

    string ClassName(Class c) =&gt; c.Name.Replace("Model","");    

}$Classes(*Model)[$Imports
export class $ClassName   {  
$CustomProperties
}]$Enums(*)[export enum $Name { $Values[
    $name = $Value][,]
}]
</code></pre>]]></content:encoded></item><item><title><![CDATA[Chasing an elusive System.Net.IPAddress bug]]></title><description><![CDATA[<p>I don't think I've ever encountered a bug in the .NET framework and as such, its the last thing I would ever suspect when something is not working. That is, until now.</p>

<h6 id="context">Context</h6>

<p>A system I am working on contains a section that may only be accessed from within a</p>]]></description><link>https://duanemckibbin.com/2017/08/30/chasing-a-net-framework-bug/</link><guid isPermaLink="false">1b9407ee-2802-4c78-a250-dec5970b6cb3</guid><category><![CDATA[.net]]></category><category><![CDATA[IPAddress]]></category><category><![CDATA[ArgumentOutOfRangeException]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Wed, 30 Aug 2017 07:19:40 GMT</pubDate><content:encoded><![CDATA[<p>I don't think I've ever encountered a bug in the .NET framework and as such, its the last thing I would ever suspect when something is not working. That is, until now.</p>

<h6 id="context">Context</h6>

<p>A system I am working on contains a section that may only be accessed from within a corporate network. We achieve this by filtering by the user's IP address. We're also using Node as a reverse proxy which adds the user's IP as a header (otherwise our API thinks all requests are coming from the proxy as the source IP gets lost on the way).</p>

<p>Node interprets the IP using <a href="https://en.wikipedia.org/wiki/IPv6">IPv6</a>, even though our internal network and restricted ranges are IPv4. This means we need to convert from IPv6 to v4 before checking if the IP is in range. We use <a href="https://github.com/jsakamoto/ipaddressrange">this library</a> to do the range checking.</p>

<pre><code class="language-csharp">using System.Net;

var ipHeader = request.Headers[ForwardingIPHeader];  
var userIP = IPAddress.Parse(ipHeader);  
var ipv4 = userIP.MapToIPv4();

//Check that IP is in range
</code></pre>

<h6 id="theproblem">The problem</h6>

<p>So we rolled out the feature, it was working well on developers machines. It passed QA and worked for most production users, except when it didn't. We confirmed the users were in the correct IP range and that they had the correct rights. What made it even stranger, was that it worked sometimes for those same users.</p>

<p>Inspecting the log files showed that we were getting an <code>ArgumentOutOfRangeExcpetion</code> when mapping the IP.</p>

<p>Being the good clean coder that I am :) I wrote some extra unit tests using the actual IPs that were failing. To my dismay, they all passed.</p>

<p>After adding some more logging, and managing to reproduce on our QA environment, I Googled my heart out and found 1 lone <a href="https://stackoverflow.com/questions/23608829/why-does-ipaddress-maptoipv4-throw-argumentoutofrangeexception">StackOverflow</a> question with the same problem.</p>

<p>Turns our, there is a bug in the parse method that causes an overflow for 1 part of the address. The conversion is done using bit shifting, and the last part of the IP is cast to a byte, which only supports 0-255. So IPs with anything over 127 in the last section (i.e. 192.168.2.132) would cause the exception.</p>

<p>This explains the seemingly random occurrence of the failure. </p>

<p>My PC also has .NET 4.7 installed, whereas the other environments were on 4.5.2. It seems the bug was fixed in 4.6 onwards.</p>

<h6 id="solution">Solution</h6>

<p>The StackOverflow post contains the correct code, but that doesn't help much when its contained in the framework. I toyed with the idea of getting the IPAdress source from GitHub and adding my own custom implementation, but that wasn't as trivial as it sounds.</p>

<p>But the obvious solution would be to upgrade the .NET version which we ended up doing in the end.</p>

<h6 id="conclusion">Conclusion</h6>

<p>Don't trust the .NET framework ... kidding :) But also, don't rule it out completely that there may be bugs in it.</p>]]></content:encoded></item><item><title><![CDATA[JSinSA 2016]]></title><description><![CDATA[<p><img src="https://continuousdeveloper.com/content/images/2016/06/jsinsa.jpg" alt="jsinsa logo"></p>

<p>I just finished speaking at the 2016 edition of <a href="http://www.jsinsa.com">JSinSA</a> on the topic of <a href="http://tjanczuk.github.io/edge/">edge.js</a>. I thoroughly enjoyed it and I think the talk was well received. </p>

<p>The talk was recorded and will be released publicly soon, I'll share the link when that happens. In the meantime, here are</p>]]></description><link>https://duanemckibbin.com/2016/07/16/jsinsa-2016/</link><guid isPermaLink="false">2ffc2322-708a-4383-8cd7-b3b89529be30</guid><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Sat, 16 Jul 2016 14:55:06 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://continuousdeveloper.com/content/images/2016/06/jsinsa.jpg" alt="jsinsa logo"></p>

<p>I just finished speaking at the 2016 edition of <a href="http://www.jsinsa.com">JSinSA</a> on the topic of <a href="http://tjanczuk.github.io/edge/">edge.js</a>. I thoroughly enjoyed it and I think the talk was well received. </p>

<p>The talk was recorded and will be released publicly soon, I'll share the link when that happens. In the meantime, here are my <a href="https://continuousdeveloper.com/content/images/2016/06/jsinsa2016_edgejs.zip">slides</a></p>

<p>If you were there, let me know in the comments what you thought of the talk and of edge.js</p>]]></content:encoded></item><item><title><![CDATA[Protecting routes in Angular 2 (new new router)]]></title><description><![CDATA[<p>Angular 2's router has been through some serious changes lately, I think the current version is the 2nd rewrite of the original beta router. I've been using it in a medium sized project at work and I'm really liking it so far.</p>

<p>One thing I needed was to be able</p>]]></description><link>https://duanemckibbin.com/2016/07/06/protecting-routes-in-angular-2/</link><guid isPermaLink="false">65f75073-1e57-42c1-a7ed-dc396f21fdaa</guid><category><![CDATA[angular]]></category><category><![CDATA[angular2]]></category><category><![CDATA[routes]]></category><category><![CDATA[routeguard]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Wed, 06 Jul 2016 05:37:28 GMT</pubDate><content:encoded><![CDATA[<p>Angular 2's router has been through some serious changes lately, I think the current version is the 2nd rewrite of the original beta router. I've been using it in a medium sized project at work and I'm really liking it so far.</p>

<p>One thing I needed was to be able to lock people out of a route based on permissions. In previous versions of the router, components could implement the OnActivate interface and provide some hints to the router. But in v3 of the router, that is no longer an option. Instead they have a concept called Route/Auth Guards.</p>

<p>Now, you implement the CanActivate interface in it's own class and use that when configuring routes.</p>

<pre><code class="language-typescript">import { Injectable } from '@angular/core';  
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  
import { AuthService } from './auth.service';  
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthGuard implements CanActivate {  
    constructor(private authService: AuthService) { }

    canActivate() {
        if (this.authService.isLoggedIn()) {
            return Observable.of(true);
        }
        return this.authService.logIn();
    }
}
</code></pre>

<p>The canActivate method can return either a <code>boolean</code>, or an <code>Observable&lt;boolean&gt;</code>. In the above example, my <code>AuthService.logIn()</code> method will return an <code>Observable&lt;boolean&gt;</code> once the login process has completed, so I can pass that onto the router. If the user is already logged in, I just wrap <code>true</code> in an <code>Observable</code> and send that back.</p>

<p>UPDATE: If you're following along in your own code, make sure that the AuthService and AuthGuard are registered as providers somewhere in you DI tree. In my case, I configure all my services in main.ts when bootstrapping, for example:</p>

<pre><code class="language-typescript">import {AuthGuard} from './authguard';  
import {AuthService} from './auth.service';

let APP_SERVICES = [  
    AuthService
    ...
]

boostrap(AppComponent, [APP_ROUTER_PROVIDERS, APP_SERVICES, AuthGuard]);  
</code></pre>

<p>In my case, I'm using Active Directory authentication on the backend, so logging in is just a matter of hitting an endpoint and getting back the user's infomation. In most other cases, you would want to redirect the user to a login page if they are not yet authenticated. You can do that as well.</p>

<pre><code class="language-typescript">import { Router } from '@angular/router'

...

canActivate() {  
    if (this.authService.isLoggedIn()) {
        return true;
    }
    //Redirect the user before denying them access to this route
    this.router.navigate(['/login']);
    return false;
}
</code></pre>

<p>Now in my route configuration, I tell the router to use this <code>AuthGuard</code> class to decide if a route can be activated.</p>

<pre><code class="language-typescript">import { provideRouter, RouterConfig } from '@angular/router';  
import { AuthGuard } from './authguard';  
import { HomeComponent } from './home';

export const routes: RouterConfig = [  
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'login', component: LoginComponent /* Make sure to not guard this route */ },
];

export const APP_ROUTER_PROVIDERS = [  
    provideRouter(routes), AuthGuard
];
</code></pre>

<p>I haven't found a way to tell the router to just use the guard for all routes, so not sure if thats an option.</p>

<p>The <a href="https://angular.io/docs/ts/latest/guide/router.html">official documentation</a> explains this concept quite well</p>

<h6 id="bonusextratip">Bonus Extra Tip</h6>

<p>In my case, while waiting for the login to happen in the background, I wanted to give the user some feedback.</p>

<p>In my root component class:  </p>

<pre><code class="language-typescript">import { Component, OnInit } from '@angular/core';  
import { AuthService } from './auth.service';  
import { Observable } from 'rxjs/Observable';

export clas AppComponent implements OnInit {  
    constructor(private authService : AuthService){
    }

    loggedIn : Observable&lt;boolean&gt;;

    ngOnInit() {
        this.loggedIn = this.userService.logIn();
    }
}
</code></pre>

<p>You'll notice that I call <code>logIn()</code> here, even though it will be called in the <code>AuthGuard</code>. My <code>AuthService</code> actually stores the pending <code>Observable</code> and returns that one instead of starting a new request everytime. See <a href="https://continuousdeveloper.com/2016/07/06/re-using-rxjs-observables/">this post</a> for more on how I did that as there are some gotcha's when re-using <code>Observables</code>.</p>

<p>Then in the template:  </p>

<pre><code class="language-html">&lt;router-outlet&gt;&lt;/router-outlet&gt;  
&lt;div class="overlay" *ngIf="!(loggedIn | async)"&gt;  
    &lt;div class="loading"&gt;
        &lt;img class="loading" src="imgs/splashScreen.png"&gt;
    &lt;/div&gt;
    &lt;div class="text"&gt;Please wait...logging you in&lt;/div&gt;
    &lt;i class="fa fa-circle-o-notch fa-spin"&gt;&lt;/i&gt;
&lt;/div&gt;  
</code></pre>

<p>I used thes following styles to make the loading dialog cover the empty router. The spinner is from a FontAwesome font and stylesheet.  </p>

<pre><code class="language-css">.overlay {
    position:fixed;
    z-index: 1000;
    top : 0;
    right: 0;
    width:100%;
    height:100%;
    background-color: black;
    opacity: 0.8;
}

.overlay div.text {
    width:100%;
    text-align: center;
    color:white;
    font-size: 20px;
    top: 40%;
    position: absolute;
}

.overlay div.loading {
    width:100%;
    text-align: center;    
    margin-top:5%;    
}

.overlay i {
    font-size:48px;
    color:white;
    top: 48%;
    position: absolute;
    left: 49%;
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Re-using RxJS Observables]]></title><description><![CDATA[<p>I've been using Angular 2 recently to build a simple but not small application. Angular 2 makes heavy use of <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> <a href="http://reactivex.io/">Observables</a>, a library that I'm not yet very familiar with.</p>

<p>When making HTTP calls, the return type is <code>Observable</code> (Angular 1.x returns a promise). You can easily convert</p>]]></description><link>https://duanemckibbin.com/2016/07/06/re-using-rxjs-observables/</link><guid isPermaLink="false">39a4f7e0-27bd-4720-99a4-e8f73d6f7469</guid><category><![CDATA[angular2]]></category><category><![CDATA[observable]]></category><category><![CDATA[rxjs]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Wed, 06 Jul 2016 05:36:36 GMT</pubDate><content:encoded><![CDATA[<p>I've been using Angular 2 recently to build a simple but not small application. Angular 2 makes heavy use of <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> <a href="http://reactivex.io/">Observables</a>, a library that I'm not yet very familiar with.</p>

<p>When making HTTP calls, the return type is <code>Observable</code> (Angular 1.x returns a promise). You can easily convert the <code>Observable</code> to a promise (<code>http.get(url).toPromise()</code>), but I want to learn this new tool, so I have tried not to.</p>

<p>My application also requires that a user be authenticated before accessing any routes (authentication is done using Active Directory on the backend). See <a href="https://continuousdeveloper.com/2016/07/06/protecting-routes-in-angular-2/">this post</a> for how I achieved this in the router. You will see in that post, that I call the <code>logIn()</code> method from more than one place, but I obviously don't want more than one request created.</p>

<p>Initially, I thought this would be easy to solve:  </p>

<pre><code class="language-typescript">private loginRequest : Observable&lt;boolean&gt;;

logIn() : Observable&lt;boolean&gt; {  
    if (this.loginRequest){
      return this.loginRequest;
    }

    //To enable CORS with auth
    let options = new RequestOptions({withCredentials:true});

    this.loginRequest = this.http.get((this.serverUrl + '/user/login'), options)
        .map(response =&gt; this.loggedInUser = response.json())
        .map(user =&gt; true)
        .catch(this.handleError);

    return this.loginRequest;
  }
</code></pre>

<p>Easy enough, I just store the pending <code>Observable</code> and if <code>logIn()</code> is called again, I just return the stored version. Except, I was still seeing multiple HTTP requests to my login route.</p>

<p>Around this time, I came across a <a href="http://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html">post</a> from the excellent people at Thoughtram who do amazing work explaining Angular2 concepts.</p>

<p>Turns out, the Http client returns what is called a <strong>Cold Observable</strong>. Nothing is executed until it is subscribed to. And if it is subscribed to more than once, each subscription triggers a new HTTP request. It's not obvious in my other post where the subscription is taking place (there is no explicit <code>.subscribe()</code> called). </p>

<ol>
<li>The router automatically subscribes to the <code>Observable</code> returned from the <code>AuthGuard</code>  </li>
<li>The Aync pipe ( <code>isLoggedIn | async</code> ) also auto-subscribes</li>
</ol>

<p>I'll let the Thoughtram guys explain the details around Hot vs Cold <code>Observables</code>, read their post and then come back.</p>

<p>OK, so to fix it, I changed my code to this:  </p>

<pre><code class="language-typescript">this.loginRequest = this.http.get((this.serverUrl + '/user/login'), options)  
        .map(response =&gt; this.loggedInUser = response.json())
        .map(user =&gt; true)
        // This is the new part
        .publishLast()
        .refCount()
        // ... up to here
        .catch(this.handleError);
</code></pre>

<p>This now ensures that only the most recent result is returned whenever a new subscription occurs. And because HTTP only ever returns one result, we can be guarenteed that it will always be the same one.</p>]]></content:encoded></item><item><title><![CDATA[Using Ninject with WebAPI 2.0]]></title><description><![CDATA[How to wire Ninject into your WebAPI 2 context]]></description><link>https://duanemckibbin.com/2016/06/30/using-ninject-with-webapi-2-0/</link><guid isPermaLink="false">a2c7224f-4b85-4193-9a1e-e1db9237a175</guid><category><![CDATA[.net]]></category><category><![CDATA[ninject]]></category><category><![CDATA[mvc]]></category><category><![CDATA[webapi]]></category><category><![CDATA[nuget]]></category><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Thu, 30 Jun 2016 08:50:32 GMT</pubDate><media:content url="http://www.spiria.com/sites/default/files/blog/ninject-shuriken.png" medium="image"/><content:encoded><![CDATA[<img src="http://www.spiria.com/sites/default/files/blog/ninject-shuriken.png" alt="Using Ninject with WebAPI 2.0"><p>I struggled most of yesterday trying to get <a href="http://www.ninject.org/">Ninject</a> setup in an ASP.NET WebAPI 2.0 environment. </p>

<p>There are multiple Stack Overflow answers and blog posts that all say the same thing:</p>

<ul>
<li>Install <a href="https://www.nuget.org/packages/Ninject/">Ninject</a> in your project from Nuget</li>
<li>Install <a href="https://www.nuget.org/packages/Ninject.Web.WebApi/">Ninject.WebApi</a></li>
<li>Install <a href="https://www.nuget.org/packages/Ninject.Web.WebApi.WebHost/">Ninject.WebApi.WebHost</a></li>
</ul>

<p>Then everything should just magically work because the WebHost package adds a class (NinjectWebCommon.cs) to your App_Start folder that wires everything up.</p>

<p>Except it didn't. I tried various things, even the alternative method where you change the Global.asax.cs file instead, still nothing.</p>

<p>The code was definitely being called, and if I registered the same Ninject module in my tests, I could pull out a fully configured service. But when running the WebAPI, I would get an exception such as:</p>

<pre><code>An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.  
</code></pre>

<p>After much hair-pulling, a <a href="http://twitter.com/jamiebarrow">colleague</a> stumbled upon another Nuget package called <a href="https://www.nuget.org/packages/WebApiContrib.IoC.Ninject/">WebApiContrib.IoC.Ninject</a> that I installed and then added 1 line to my NinjectWebCommon.cs class</p>

<pre><code class="language-csharp">private static IKernel CreateKernel()  
{
    Kernel = new StandardKernel();
    try
    {
        Kernel.Bind&lt;Func&lt;IKernel&gt;&gt;().ToMethod(ctx =&gt; () =&gt; new Bootstrapper().Kernel);
        Kernel.Bind&lt;IHttpModule&gt;().To&lt;HttpApplicationInitializationHttpModule&gt;();

        RegisterServices(Kernel);

        //===Add this line===
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(Kernel);
        //===================
        return Kernel;
    }
    catch
    {
        Kernel.Dispose();
        throw;
    }
}
</code></pre>

<p>And now it works! So much for "Install the Nuget package and everything will work". <br>
Hope this post save someone else the trouble I had.</p>]]></content:encoded></item><item><title><![CDATA[Applying for a new South African ID Card]]></title><description><![CDATA[<figure class="inline-image">  
    <img style="width:1000px" src="https://duanemckibbin.com/content/images/2016/04/header.jpg" class="inline-image" alt="header">
</figure>

<p><strong>Note: This post will probably not interest you if you're not from South Africa :p</strong></p>

<p>The Department of Home Affairs <a href="http://www.techcentral.co.za/you-can-now-order-a-smart-id-online/64382/">recently launched</a> their <a href="https://ehome.dha.gov.za/eChannel/Home/UserFiltering">online portal</a> that enables applying for the new ID cards (replacing the old green books). In conjunction with support from the 4 major SA banks, the process</p>]]></description><link>https://duanemckibbin.com/2016/04/11/applying-for-a-new-rsa-id-card/</link><guid isPermaLink="false">5f37982f-89fe-42d9-87e8-e867c06cb121</guid><dc:creator><![CDATA[Duane]]></dc:creator><pubDate>Mon, 11 Apr 2016 07:25:34 GMT</pubDate><content:encoded><![CDATA[<figure class="inline-image">  
    <img style="width:1000px" src="https://duanemckibbin.com/content/images/2016/04/header.jpg" class="inline-image" alt="header">
</figure>

<p><strong>Note: This post will probably not interest you if you're not from South Africa :p</strong></p>

<p>The Department of Home Affairs <a href="http://www.techcentral.co.za/you-can-now-order-a-smart-id-online/64382/">recently launched</a> their <a href="https://ehome.dha.gov.za/eChannel/Home/UserFiltering">online portal</a> that enables applying for the new ID cards (replacing the old green books). In conjunction with support from the 4 major SA banks, the process is supposed to be quite streamlined. Its currently limited to people within the age range of 30-35, which I happen to be. I've always been a bit of an early adopter, so I thought I'd give the process a try.</p>

<p>Surprisingly it worked pretty well. You'll know why this is a surprise if you're South African and have ever had to deal with Home Affairs.</p>

<p>The website worked perfectly (though I hear there were some load issues shortly after launch) and I was able to complete the form within a few minutes. </p>

<p>One small gripe is that the logon process is quite laborious:</p>

<ul>
<li>Enter ID number and submit page</li>
<li>Enter your password and CAPTCHA and submit</li>
<li>Wait for an OTP via SMS and submit</li>
</ul>

<p>I get that security is important, and I wouldn't mind the process if the session length wasn't so short. Not sure what it is, but I found it timing out a few times while I looked something up elsewhere during the application process.</p>

<p>I hit a bit of a snag when it came to paying (R140) though. After entering my account details, I was told to authorize the payment on FNB's internet banking. The problem was, I couldn't find anywhere to authorize it. This is an FNB issue though, not Home Affairs.</p>

<p>FNB's Twitter guy (<a href="http://twitter.com/rbjacobs">@rbjacobs</a>) couldn't even help. I did eventually find it under "Pay => eFiling", duh why didn't I think to look there originally :)</p>

<figure class="inline-image">  
    <img style="width:500px" src="https://duanemckibbin.com/content/images/2016/04/homeaffairs_tweet.jpg" class="inline-image" alt="header">
</figure>

<p>Once the payment was authorized, I was able to make an appointment at an FNB branch (the one in the building that I work happened to support the new process). The appointment was for capturing a photo, finger prints and my signature. I captured the application on the weekend and was able to get an appointment for the following Monday. There also appeared to be many slots open, not sure if it will be so easy to get an immediate appointment once they roll-out to the whole country.</p>

<p>I've just come back from the appointment now, took 5 minutes to capture what they needed. The process was painless, I did have to wait about 10 minutes due to not all the Home Affairs staff being there (something about the IEC and registration weekend).</p>

<p>Now I wait 10 working days for the card, will update once I get it.</p>

<p>Overall, I'm very impressed with the process. It would be great if all government processes were this efficient, here's hoping.</p>

<hr>

<p><strong>Update 1 (2016/04/11):</strong> Since I posted this a few colleagues have also tried to apply, their experiences were not quite a smooth:</p>

<ul>
<li>If you accidentally select "New ID", instead of "Re-Issue", you can't change it later, you will need to restart the application.</li>
<li>The appointment confirmation emails seem to take a while to come through sometimes</li>
<li>Something I experienced as well, the confirmation PDF can't be read in Chrome, you will need to download it and open it in Adobe Reader. This is a similar issue with the PDFs issued by SARS.</li>
</ul>

<p><strong>Update 2 (2016/04/14):</strong> Looks like I'm one of 140 successful applicants to go through the whole process according to this <a href="http://www.htxt.co.za/2016/04/13/over-140-smart-id-and-passports-applications-completed-via-ehome-affairs-since-launch">article</a>. They also claim that appointments are booked up until the end of April, so seems like there may be a bit of a wait for new people applying, glad I got in there early.</p>

<p><strong>Update 3 (2016/04/04):</strong> Initially, I couldn't find a list of bank branches where you could make appointments, now <a href="http://www.htxt.co.za/2016/04/14/these-are-the-bank-branches-where-you-can-get-your-smart-id-or-passport">htxt.co.za</a> has published a list. If I understand correctly, you can also make appointments at Home Affairs branches, but who wants to do that :p</p>

<ul>
<li>FNB
<ul><li>Bank City / FNB Towers</li>
<li>Merchant Place (RMB head office in Sandton)</li>
<li>Centurion Lifestyle Centre</li>
<li>Menlyn Square</li></ul></li>
<li>Absa
<ul><li>Absa Towers (in JHB Town)</li>
<li>Centurion Lifestyle Centre</li>
<li>Ghandi Square</li></ul></li>
<li>Standard Bank
<ul><li>Killarney</li>
<li>Centurion</li>
<li>Standard Bank HQ in Town</li>
<li>Canal Walk (only branch among all he bank in Cape Town)</li></ul></li>
<li>Nedbank
<ul><li>Constantia Kloof</li>
<li>Rivonia</li></ul></li>
</ul>

<p>(See the <a href="http://www.htxt.co.za/2016/04/14/these-are-the-bank-branches-where-you-can-get-your-smart-id-or-passport">original story</a> for address details)</p>

<p><strong>Update 4 (2016/04/18):</strong> I received an SMS on Friday to collect, that's about 5 business days after applying. I went in this morning and collected, took me 10 minutes with 2 people in the collection queue in front of me.</p>

<p>Overall, this has been an excellent experience, definitely not expected from a SA Government department.</p>

<p><strong>Update 5 (2016/05/20):</strong> <a href="http://www.htxt.co.za/2016/05/18/ehome-affairs-opens-smart-id-applications-to-more-ages/">Home affairs has now opened the process up to 25-40 year olds</a>, looks like the pilot is going well</p>]]></content:encoded></item></channel></rss>