<?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[jeroenhildering.com]]></title><description><![CDATA[The thoughts and brain fragments of a developer]]></description><link>https://jeroenhildering.azurewebsites.net/</link><generator>Ghost 0.11</generator><lastBuildDate>Thu, 25 Jun 2026 06:29:53 GMT</lastBuildDate><atom:link href="https://jeroenhildering.azurewebsites.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Identity Propagation with .NET Core 2]]></title><description><![CDATA[When moving to a microservice oriented architecture, one obstacle to overcome is identity authentication and authorization.]]></description><link>https://jeroenhildering.azurewebsites.net/2018/07/23/identity-propagation-with-net-core-2/</link><guid isPermaLink="false">48515849-c863-47d9-a5d3-b3362589cd92</guid><category><![CDATA[.net core]]></category><category><![CDATA[.net]]></category><category><![CDATA[identity]]></category><category><![CDATA[propagation]]></category><category><![CDATA[authorization]]></category><category><![CDATA[authentication]]></category><category><![CDATA[security]]></category><category><![CDATA[microservices]]></category><category><![CDATA[microservice]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Mon, 23 Jul 2018 20:35:54 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2018/07/auth-flow-1.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2018/07/auth-flow-1.jpg" alt="Identity Propagation with .NET Core 2"><p>Enterprises continue to move from big monoliths to a microservice oriented architecture. Of course, this has lots of advantages over having one or more big monoliths in terms of scalability, maintainability and so forth. When moving to a microservice oriented architecture, one obstacle to overcome is identity authentication and authorization. </p>

<p>Most of the time, the propagation of the end user security context tends to stop at the API gateway layer, and a more generic security mechanism such as a service account, with basic authentication for example, steps in to secure traffic between microservices. In that case there is no way of telling if an end user is allowed to access a specific resource. This also introduces the risk of resources getting exposed due to service accounts which might have super-user privileges. So, a better solution would be to propagate the end user security context to every microservice that is being called during the lifetime of the request.</p>

<h3 id="securingeachstep">Securing each step</h3>

<p>Typically, in such an architecture you would have one or multiple identity providers which can issue tokens to end users. Usually this is done using OpenID Connect, OAuth or JSON Web Tokens. Either way, these tokens are usually put in the <code>Authorization</code> header of the request. When the request is received by the first microservice, it would check if this token is a valid token at the identity provider and otherwise throw a HTTP 401/403 if not.</p>

<p>When that microservice has to make a request to another microservice to fetch additional data to construct the resource, the token has to be propagated to that other microservice as well. Most of the time the token is fetched from the authorization header at controller level and passed on to the method making the call to the next microservice. However, this makes the code completely dependent on passing tokens which you most likely don't want. To overcome this problem I've made a <code>DelegatingHandler</code> which can be used by any instance of <code>HttpClient</code>:</p>

<pre class="line-numbers language-csharp"><code>public class AuthorizationHeaderHandler : DelegatingHandler  
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public AuthorizationHeaderHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override Task<httpresponsemessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue(HeaderNames.Authorization, out var authHeader))
        {
            request.Headers.Authorization = AuthenticationHeaderValue.Parse(authHeader);
        }

        return base.SendAsync(request, cancellationToken);
    }
}
</httpresponsemessage></code></pre>  

<p>The <code>AuthorizationHeaderHandler</code> will propagate the incoming token to request that is made using the <code>HttpClient</code> that implements this handler. To get that token we have to access the current <code>HttpContext</code>. Because we can't access <code>HttpContext</code> in .NET Core outside a controller, there is a helper class called <code>HttpContextAccessor</code> which we can use to access the current <code>HttpContext</code>. The <code>AuthorizationHeaderHandler</code> uses this helper class to get the authorization token from the current request headers and put it on the outgoing request just before it is send.</p>

<p>Now to add this delegating handler to any <code>HttpClient</code>, using the new <code>HttpClientFactory</code> that is available as of .NET Core 2, can be done in like so:  </p>

<pre class="line-numbers language-csharp"><code>services.AddHttpContextAccessor();  
services.TryAddTransient&lt;AuthorizationHeaderHandler&gt;();  
services.AddHttpClient("AuthorizedClient")  
    .AddHttpMessageHandler&lt;AuthorizationHeaderHandler&gt;();
</code></pre>  

<p>For this example i've used a named <code>HttpClient</code>. The <code>AuthorizationHeaderHandler</code> has to be added as <code>Transient</code> dependency in order for it to be available to the <code>HttpClientFactory</code>. Note that there is an extension method available to add the <code>HttpContextAccessor</code> dependency.</p>

<p>When making a request to another microservice, for example:</p>

<pre class="line-numbers language-csharp"><code>public class Foo  
{
    private readonly IHttpClientFactory _httpClientFactory;

    public Foo(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task&lt;string&gt; Bar()
    {
        var client = _httpClientFactory.CreateClient("AuthorizedClient");

        return await client.GetStringAsync("http://somemicroserviceurl");
    }
}
</code></pre>  

<p>The authorization header is automatically set on every request that is made using the <code>HttpClient</code> from the <code>HttpClientFactory</code>. This way the end user security context can be propagated in a clean way instead of passing tokens everywhere and making your code dependent on it.</p>

<p>Check out the full source code at <a href="https://github.com/JeroenHildering/AuthTokenPropagate" target="_blank">GitHub</a>.</p>]]></content:encoded></item><item><title><![CDATA[Debugging decompiled .NET sources]]></title><description><![CDATA[How to debug decompiled .NET sources using dotPeek and Visual Studio.]]></description><link>https://jeroenhildering.azurewebsites.net/2017/10/11/debugging-decompiled-net-sources/</link><guid isPermaLink="false">53439b41-d0f1-476c-8525-047d7c9c085f</guid><category><![CDATA[.net core]]></category><category><![CDATA[debug]]></category><category><![CDATA[debugging]]></category><category><![CDATA[assembly]]></category><category><![CDATA[decompiled]]></category><category><![CDATA[sources]]></category><category><![CDATA[source]]></category><category><![CDATA[dotpeek]]></category><category><![CDATA[visual studio]]></category><category><![CDATA[symbol server]]></category><category><![CDATA[symbols]]></category><category><![CDATA[assemblies]]></category><category><![CDATA[.net]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Wed, 11 Oct 2017 19:47:22 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2017/10/debug.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2017/10/debug.jpg" alt="Debugging decompiled .NET sources"><p>Recently I decided to purchase the N2 Elite as I'm unable to get all the <a href="https://www.nintendo.com/amiibo/" target="blank">amiibo</a>'s out there to use with my <a href="https://www.nintendo.com/switch/" target="_blank">Nintendo Switch</a> to get extra's in some of the games I own. The N2 Elite comes with a tool called 'USB Manager Application'. As I hook up the RFID reader and fire up the application, all seems to be in working order. But when i try to load some dump files, the images seem to be broken or not found as I get a big questionmark where the image should be. Everything else works fine but the images don't. The more I load, the more questionmarks I get. It's starting to irritate me.</p>

<p>Maybe I can figure out the problem, so I take a closer look at the application and it's assemblies. As it turns out, they are .NET assemblies so I could possibly decompile and debug them.</p>

<h3 id="prerequisites">Prerequisites</h3>

<ul>
<li><a href="https://www.jetbrains.com/decompiler/" target="_blank">dotPeek</a></li>
<li><a href="https://www.visualstudio.com/downloads/" target="_blank">Visual Studio</a></li>
<li>A source that can be decompiled</li>
</ul>

<h4 id="step1decompilingtheassemblies">Step 1: Decompiling the assemblies</h4>

<p>Decompiling an assembly works best on assemblies that aren't obfuscated by any tool. As it turns out, they weren't when I tried to load them into dotPeek.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/assemblies.PNG" alt="Debugging decompiled .NET sources"></p>

<p>Now where to begin? I start looking around in the executable assembly, which seems to be a windows forms application, and I find a method called <code>ShowN2EliteBanks</code>. As I look at the decompiled source, this function most likely has something to do with showing the images that are missing. I would like to put a breakpoint at the beginning of the function and see what goes on there on runtime.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/function.PNG" alt="Debugging decompiled .NET sources"></p>

<h4 id="step2fireupthesymbolserver">Step 2: Fire up the symbol server</h4>

<p>As I do not possess the source code, I can't simply run the application using Visual Studio, set a breakpoint and start debugging. This is where the dotPeek <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms680693(v=vs.85).aspx" target="_blank">symbol server</a> comes in handy. What the symbol server in dotPeek actually does is provide symbol files for the assemblies we decompiled in the previous step. The symbol files can obviously be used for debugging purposes. The dotPeek symbol server runs on <code>http://localhost:33417</code> by default. I doublecheck the settings and fire up the symbol server.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/symbol-server.PNG" alt="Debugging decompiled .NET sources"></p>

<h4 id="step2configurevisualstudio">Step 2: Configure Visual Studio</h4>

<p>To use the symbols provided by the dotPeek symbol server in Visual Studio, we need to add it. Fire up Visual Studio, navigate to <code>Tools -&gt; Options -&gt; Debugging -&gt; Symbols</code> and add the dotPeek symbol server.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/add-symbol-server.PNG" alt="Debugging decompiled .NET sources"></p>

<p>Now, we want to debug code that is not ours. This is disabled by default within Visual Studio. To enable this feature, navigate to <code>Tools -&gt; Options -&gt; Debugging -&gt; General</code> and untick <code>Enable Just My Code</code>.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/just-my-code.PNG" alt="Debugging decompiled .NET sources"></p>

<h4 id="step3attachthedebugger">Step 3: Attach the debugger</h4>

<p>Because we can't run any source code, I start up the application and hook up the Visual Studio debugger to the running process. </p>

<h4 id="step4creatingabreakpoint">Step 4: Creating a breakpoint</h4>

<p>But now what? How am I supposed to set a breakpoint when I don't have any source code available?  You can add a <code>New Function Breakpoint</code> by pressing <code>crtl + b</code> or by navigating to <code>Debug -&gt; New Breakpoint -&gt; New Function Breakpoint</code>. I put in the name of the function I found in Step 1 and click OK.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/add-breakpoint.PNG" alt="Debugging decompiled .NET sources"></p>

<h4 id="step5livedebugging">Step 5: Live debugging</h4>

<p>I push some buttons in the application hoping it will trigger the function, and suddenly BOOM.</p>

<p><img src="https://jeroenhildering.azurewebsites.net/content/images/2017/10/hit-breakpoint.PNG" alt="Debugging decompiled .NET sources"></p>

<p>The breakpoint was hit! Now I'm able to do some debugging as I normally would. </p>

<h3 id="recap">Recap</h3>

<p>The problem turned out to be an instance of <code>ResourceManager</code> that was <code>null</code> in the libamiibo assembly supplied with the application. After some further investigation, I found libamiibo to be open source. So I cloned the repository from github, recompiled the source code, updated the assemblies and fixed the problem.</p>]]></content:encoded></item><item><title><![CDATA[Mapping exceptions to HTTP responses with .NET Core]]></title><description><![CDATA[Handling exceptions and returning the appropriate response is considered a best practice. Handling exceptions in .NET Core still has a few downsides.]]></description><link>https://jeroenhildering.azurewebsites.net/2016/11/24/mapping-exceptions-to-http-responses-with-net-core/</link><guid isPermaLink="false">2c98f0b2-70c9-4c49-a85d-56e247ea8da8</guid><category><![CDATA[asp.net]]></category><category><![CDATA[csharp]]></category><category><![CDATA[json]]></category><category><![CDATA[webapi]]></category><category><![CDATA[rest]]></category><category><![CDATA[api]]></category><category><![CDATA[.net core]]></category><category><![CDATA[core]]></category><category><![CDATA[exceptions]]></category><category><![CDATA[exception]]></category><category><![CDATA[http]]></category><category><![CDATA[response]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Thu, 24 Nov 2016 09:28:39 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/11/error.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/11/error.jpg" alt="Mapping exceptions to HTTP responses with .NET Core"><p>Handling exceptions and returning the appropriate response to the application consuming your API or the user browsing your web application, is considered a best practice when developing software. Handling exceptions with .NET Core is as easy as pie. You can read all about it <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling" target="_blank">here</a>. However, there are still a few downsides:</p>

<ul>
<li>All types of exceptions are redirected to the same controller action and thus result in the same response.</li>
<li>All types of exceptions result in a HTTP 500 Internal Server Error.</li>
<li>Cross referencing logged exceptions with reported ones is still a pain.</li>
</ul>

<p>What to do if you are building a JSON REST API? Always return the same kind of response with the same HTTP status code? Doesn't sound like a good idea, giving the consuming application a proper response with an error code and a message describing the error is probably a better solution. So what if we could map an exception to a HTTP response?</p>

<h3 id="goingdowntheroadofmiddleware">Going down the road of middleware</h3>

<p>To be able todo this, I figured I could create some middleware that I can hook up to my pipeline to handle it like so:  </p>

<pre class="line-numbers language-csharp"><code>app.UseResponseExceptionHandler(options =>  
{
    options.Map&lt;ArgumentNullException>(HttpStatusCode.BadRequest);
    options.Map&lt;KeyNotFoundException>(HttpStatusCode.NotFound, 
        "The requested resource was not found.");
    options.Map&lt;CustomException>(HttpStatusCode.NotAcceptable, 
        new CustomResponse { Error = "Custom error" });
});
</code></pre>  

<p>The middleware has three ways of mapping exceptions to HTTP responses:</p>

<h4 id="1httpstatuscodeonly">1. HTTP status code only</h4>

<p>When only mapping a HTTP status code to an exception, the exception message is used in the response:  </p>

<pre class="language-http"><code>HTTP/1.1 400 Bad Request  
Content-Type: application/json

{"message":"Value cannot be null. Parameter name: param"}
</code></pre>

<h4 id="2httpstatuscodewithanerrormessage">2. HTTP status code with an error message.</h4>

<p>When mapping a HTTP status code with an error message, the given error message will be used in the response:  </p>

<pre class="language-http"><code>HTTP/1.1 404 Not Found  
Content-Type: application/json

{"message":"The requested resource was not found."}
</code></pre>

<h4 id="3httpstatuscodewithanobject">3. HTTP status code with an object.</h4>

<p>When mapping a HTTP status code with an object, the specified object will be serialized and put in the response:  </p>

<pre class="language-http"><code>HTTP/1.1 406 Not Acceptable  
Content-Type: application/json

{"error":"Custom error"}
</code></pre>

<h3 id="unhandledexceptions">Unhandled exceptions</h3>

<p>But what about exceptions we don't map? Exceptions that are not mapped will be treated as what you can call 'unhandled'. Because they are not expected to occur, a random error code is generated, logged and put in the response for easy cross referencing:  </p>

<pre class="language-http"><code>HTTP/1.1 500 Internal Server Error  
Content-Type: application/json

{
    "errorCode":"ERR_40A7DD58",
    "message":"An unhandled exception has occurred, please check the log for details."
}
</code></pre>  

<p>The error code is default prefixed with <code>ERR_</code>, but is overridable through the options parameter as well as the default error message:  </p>

<pre class="line-numbers language-csharp"><code>app.UseResponseExceptionHandler(options =>  
{
    options.ErrorCodePrefix = "ERROR_";
    options.DefaultErrorMessage = "Unknown exception, please contact the System Administrator";
});
</code></pre>  

<p>The JSON serializer settings can also be modified by using the options parameter.</p>

<h3 id="puttingitalltogether">Putting it all together</h3>

<p>To prevent your code from turning into spaghetti code, you should consider moving away from exceptions and program in a more functional way by implementing <code>Result</code> and <code>Maybe</code> objects to avoid having to throw exceptions yourself. However, exceptions like an <code>ArgumentNullException</code> will most likely keep existing somewhere in your code. Logging error codes and outputting them makes tracking bugs and providing feedback to end users a lot faster, resulting in better code and making users more happy. In those cases, this middleware might come in handy.</p>

<p>Check out the full source at <a href="https://github.com/JeroenHildering/ResponseExceptionHandler" target="_blank">GitHub</a>.</p>]]></content:encoded></item><item><title><![CDATA[Continuous Delivery (CD) for .NET applications using Jenkins]]></title><description><![CDATA[The key to delivering software more rapidly and more frequently is having a continuous delivery process which makes deploying your application as easy as pushing a button.]]></description><link>https://jeroenhildering.azurewebsites.net/2016/04/25/continuous-delivery-for-net-applications-using-jenkins/</link><guid isPermaLink="false">48b53a8c-a9a4-4b4c-bd0f-375963577dfa</guid><category><![CDATA[asp.net]]></category><category><![CDATA[jenkins]]></category><category><![CDATA[continuous]]></category><category><![CDATA[integration]]></category><category><![CDATA[delivery]]></category><category><![CDATA[CD]]></category><category><![CDATA[azure]]></category><category><![CDATA[cloud]]></category><category><![CDATA[itq]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Mon, 25 Apr 2016 09:13:00 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/04/continuous_delivery.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/04/continuous_delivery.jpg" alt="Continuous Delivery (CD) for .NET applications using Jenkins"><p>The key to delivering software more rapidly and more frequently is having a continuous delivery process which makes deploying your application as easy as pushing a button. When it's easy to deploy your application, bugfixes and new features end up in production way faster and in a more agile way than the old fashion way of manually creating a package and handing it over to someone from the ops team who would then deploy it to the requested environment. </p>

<p>Delivering software the old fashion way is often prone to human error and takes a lot more time forcing developers to create bigger releases with a larger number of features and bugfixes which in turn also takes more time. This is obviously bad for business because end-users will have to wait much longer to be able to enjoy new releases, and in the meantime they could be getting frustrated by potential bugs which aren't going to be resolved very quickly.</p>

<h3 id="oneclickdeploy">One-click deploy</h3>

<p>The main goal is to be able to deploy our application by the click of a button. To do that, we're going to be using <a href="https://jenkins.io/" target="_blank">Jenkins</a> and add a deployment process to our <a href="http://jeroenhildering.com/2016/04/07/continuous-integration-for-net-applications-using-jenkins/" target="_blank">previous</a> CI job to deploy our application to <a href="https://azure.microsoft.com" target="_blank">Microsoft Azure</a>.</p>

<h6 id="prerequisites">Prerequisites</h6>

<ul>
<li>Follow my <a href="http://jeroenhildering.com/2016/04/07/continuous-integration-for-net-applications-using-jenkins/" target="_blank">previous</a> blogpost to create a continuous integration job using Jenkins.</li>
<li>Create a <a href="https://account.windowsazure.com" target="_blank">Microsoft Azure Account</a>.</li>
<li>Create a new <a href="https://portal.azure.com" target="_blank">Azure App Service</a> in the Azure portal.</li>
<li>Create a shared network location or setup an <a href="https://en.wikipedia.org/wiki/Binary_repository_manager" target="_blank">Artifact Repository</a> to store the build artifact.</li>
<li>Install the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Promoted+Builds+Plugin" target="_blank">Promoted Builds</a> plugin for Jenkins.</li>
</ul>

<p>We're going to use the Promoted Builds plugin to create a build artifact of our application and deploy it to Azure via <a href="http://www.iis.net/downloads/microsoft/web-deploy" target="_blank">Web Deploy</a>. Because the Azure App Service we've created already supports Web Deploy, there is no need to install it. In this case Azure is our production environment. I recommend also having a development, test and acceptance environment to be able to test and preview your application before it gets deployed to production.</p>

<h6 id="artifactrepositories">Artifact repositories</h6>

<p>Because we're creating a build artifact, it is wise to store that artifact in a binary repository or on a shared location. This way you're not only able to keep track of all your releases, but also to rollback a previous version. There are a few good repositories out there such as <a href="https://archiva.apache.org/index.cgi" target="_blank">Archiva</a>, <a href="https://www.jfrog.com/open-source/" target="_blank">Artifactory</a>, <a href="http://www.sonatype.org/nexus/" target="_blank">Nexus</a> and <a href="https://packagedrone.org/" target="_blank">Package Drone</a>. <a href="https://binary-repositories-comparison.github.io/" target="_blank">Here</a> is a good comparison chart for you to decide which repository suits you best.</p>

<h6 id="step1createapromotionprocess">Step 1: Create a promotion process</h6>

<p>Navigate using your favorite browser to the Jenkins job you've created and tick the <code>Promote builds when...</code> checkbox. The following section appears: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Promotion_process.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
In this case we're going to create the process of deploying our application to a production environment so the name of this process is going to be <code>Production</code>. Tick the <code>Only when manually approved</code> checkbox because we don't want to trigger the process automatically. </p>

<p>Typically you can tick the <code>Promote immediately once the build is complete</code> checkbox for a development promotion process. This means that when a build is succeeded and all unit tests pass, a build artifact is created immediately and is then deployed to the development environment.</p>

<p>If you have multiple promotion processes, i recommend ticking the <code>When the following upstream promotions are promoted</code> checkbox and fill in the previous promotion process name (e.g. <code>Acceptance</code>) that has to be successfully executed before being able to approve the next promotion process. This way you will force your application being deployed to other environments first such as development, test and acceptance before reaching production. An example would be <code>Development &gt; Test &gt; Acceptance &gt; Production</code>.</p>

<h6 id="step2createabuildartifact">Step 2: Create a build artifact</h6>

<p>To create a build artifact click the <code>Add action</code> button in the <code>Actions</code> region of your promotion process and select <code>Build a Visual Studio project or solution using MSBuild</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Create_Build_Artifact.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
This step is almost equal to our build step which we created in our CI process, but now we're going to create a web deploy package in stead of compiling the solution. To create that package, we have to add a few command line arguments:</p>

<ul>
<li><code>/T:Clean;Build;Package</code> to create a Web Deploy package.</li>
<li><code>/p:Configuration=Release</code> to use the release configuration. </li>
<li><code>/p:OutputPath="obj\Release"</code> to put the artifact in the obj\Release folder of the current project. </li>
<li><code>/p:PrecompileBeforePublish=true</code> to precompile our application.</li>
</ul>

<h6 id="step3storethebuildartifact">Step 3: Store the build artifact</h6>

<p>Next we have to store our build artifact we've just created. In this case we will keep it simple and just copy it to a shared network location. Click the <code>Add action</code> button again and select <code>Execute Windows batch command</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Copy_Build_Artifact.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
Because we're just copying the artifact to another location, i've created a <code>xcopy</code> command that copies the build artifact to a specified network location and create a folder with the Jenkins build number.</p>

<h6 id="step4deploythebuildartifact">Step 4: Deploy the build artifact</h6>

<p>To be able to deploy to Azure via Web Deploy you first have to download the <code>Publish Profile</code> of your Azure App Service. Go to the Azure Portal, navigate to your App Service and click the <code>Get Publish Profile</code> button. You should get something like this:  </p>

<pre class="line-numbers language-xml"><code>&lt;publishData>  
    &lt;publishProfile profileName="YourProject - Web Deploy" 
            publishMethod="MSDeploy" 
            publishUrl="yourproject.scm.azurewebsites.net:443" 
            msdeploySite="YourProject" 
            userName="$YourProject" 
            userPWD="someRandomPassword" 
            destinationAppUrl="http://yourproject.azurewebsites.net" 
            SQLServerDBConnectionString="" 
            mySQLDBConnectionString="" 
            hostingProviderForumLink="" 
            controlPanelLink="http://windows.azure.com" 
            webSystem="WebSites">
        &lt;databases />
    &lt;/publishProfile>
    &lt;publishProfile 
            profileName="YourProject - FTP" 
            publishMethod="FTP" 
            publishUrl="ftp://waws-prod-sn1-027.ftp.azurewebsites.windows.net/site/wwwroot" 
            ftpPassiveMode="True" 
            userName="YourProject\$YourProject" 
            userPWD="someRandomPassword" 
            destinationAppUrl="http://yourproject.azurewebsites.net" 
            SQLServerDBConnectionString="" 
            mySQLDBConnectionString="" 
            hostingProviderForumLink="" 
            controlPanelLink="http://windows.azure.com" 
            webSystem="WebSites">
        &lt;databases />
    &lt;/publishProfile>
&lt;/publishData>
</code></pre>  

<p>We are going to use the <code>Web Deploy</code> profile in our next action. Because there is no MSDeploy plugin for Jenkins click <code>Add action</code> and select <code>Execute Windows batch command</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Deploy_Build_Artifact.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
This is a pretty large command using the MSDeploy executable, so let's go over the command line arguments:</p>

<ul>
<li><code>-verb:sync</code> to update our web application.</li>
<li><code>-source:package="YourProject\obj\Release\_PublishedWebsites\YourProject_Package\YourProject.zip"</code> to use the build artifact for deployment.</li>
<li><code>-dest:auto,computerName='https://yourproject.scm.azurewebsites.net:443/msdeploy.axd?site=yourproject',UserName='$YourProject',Password='someRandomPassword',AuthType='Basic',includeAcls='false'</code> to set the destination for our deployment using the data from the downloaded Publish Profile. <code>includeAcls</code> is set to false because we don't want to deploy file ownership information.</li>
<li><code>-setParam:name='IIS Web Application Name',value='yourproject'</code> to override the web application name with the one specified in the Azure App Service.</li>
<li><code>-disableLink:AppPoolExtension</code> to disable setting the AppPool because it is already set by Azure.</li>
<li><code>-disableLink:ContentExtension</code> to disable deploying the contents of optionally configured virtual directories.</li>
<li><code>-disableLink:CertificateExtension</code> to disable deploying optionally included certificates.</li>
</ul>

<p>That's it for the production process. Once a build is completed and successfully passed the configured unit tests, the only thing you have to do to deploy your application is go to your build in Jenkins, click the <code>Promotion Status</code> button in the left option pane and click the <code>Approve</code> button of the promotion process you want to execute.</p>

<h3 id="rollback">Rollback</h3>

<p>But what about rollback? A similar promotion process can be created. Instead of creating and copying a build artifact, we are only going to deploy an archived artifact. </p>

<p>Click the button <code>Add another promotion process</code> and call it <code>Rollback production</code>. Again tick the <code>Only when manually approved</code> checkbox. But now we are going to add a parameter to our process by clicking the button <code>Add Parameter</code> and selecting <code>String Parameter</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Rollback_Production.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
Because we want to rollback a specific release, we're going to use the Jenkins build number to select an artifact from the shared network location. Again click <code>Add action</code> and select <code>Execute Windows batch command</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/Rollback_Build_Artifact.PNG" alt="Continuous Delivery (CD) for .NET applications using Jenkins">
Copy the MSDeploy command from Step 4 and change the <code>-source</code> parameter to point to the artifact from the shared network location in stead of the one created in the obj folder: <code>-source:package="\\neworklocation\Production\#%BuildVersion%\YourProject.zip"</code>. As you can see, the <code>BuildVersion</code> parameter is used in the path to point to the artifact created from that specific build. You can pass the parameter when approving your promotion process at the Promotion Status screen.</p>

<h3 id="thoughts">Thoughts</h3>

<p>Instead of deploying to Azure, you could also deploy to a local server or even to a docker or windows container using an orchestration tool such as <a href="https://azure.microsoft.com/en-us/services/service-fabric/" target="_blank">Microsoft Azure Service Fabric</a> or <a href="http://pivotal.io/platform" target="_blank">Pivotal Cloud Foundry</a>. </p>

<p>As i mentioned earlier, create several promotion processes for your environments. Be sure to archive artifacts if needed, as archiving development releases is not really necessary. Make promotion processes dependent on each other to ensure your application is always being deployed though your entire DTAP street before reaching production. </p>]]></content:encoded></item><item><title><![CDATA[Continuous Integration (CI) for .NET applications using Jenkins]]></title><description><![CDATA[Having a Continuous Integration (CI) and Continuous Delivery (CD) process during the various stages of development helps to reduce risks, catch bugs more quickly and rapidly deploy software.]]></description><link>https://jeroenhildering.azurewebsites.net/2016/04/07/continuous-integration-for-net-applications-using-jenkins/</link><guid isPermaLink="false">93bf2d63-ba51-43b7-a6c9-c932b52930cc</guid><category><![CDATA[asp.net]]></category><category><![CDATA[jenkins]]></category><category><![CDATA[CI]]></category><category><![CDATA[continuous]]></category><category><![CDATA[integration]]></category><category><![CDATA[delivery]]></category><category><![CDATA[itq]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Thu, 07 Apr 2016 12:07:40 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/04/continuous.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/04/continuous.jpg" alt="Continuous Integration (CI) for .NET applications using Jenkins"><p>Having a Continuous Integration (CI) and Continuous Delivery (CD) process during the various stages of development helps to reduce risks, catch bugs more quickly and rapidly deploy software to various environments. These benefits result in developers being able to implement business requirements and user needs more quickly and turning the process of releasing software into a business advantage.</p>

<h3 id="tools">Tools</h3>

<p>There are many tools out there to accommodate CI and CD for your application such as TeamCity, Jenkins, GitLab CI, Bamboo, Team Foundation Server, etc. In this case we're going to setup CI (and later on CD) using <a href="https://jenkins.io/" target="_blank">Jenkins</a> and <a href="https://bitbucket.org/" target="_blank">Atlassian Bitbucket</a>.</p>

<p>Jenkins is an upcoming populair open source Continuous Integration and Continuous Delivery tool that provides you to automate builds and deployments for various programming languages. There is an extensive <a href="https://wiki.jenkins-ci.org/display/JENKINS/Plugins" target="_blank">plugin library</a> available that allows you to use and configure tools like MSBuild and MSTest in your job with ease.</p>

<h3 id="automateit">Automate IT</h3>

<p>To actually create and setup a job, a few prerequisites are required:</p>

<h6 id="prerequisites">Prerequisites</h6>

<ul>
<li>Setup a VM or physical server running Windows.</li>
<li>Install <a href="https://jenkins.io/content/thank-you-downloading-windows-installer#stable" target="_blank">Jenkins</a>.</li>
<li>Install <a href="https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx" target="_blank">Visual Studio</a> or <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48159" target="_blank">Microsoft Build Tools</a>.</li>
<li>Install <a href="https://git-scm.com/download/win" target="_blank">Git for Windows</a> (or any other code repository client tools).</li>
<li>Create a <a href="https://bitbucket.org/account/signup/" title=" target=&quot;_blank">Bitbucket</a> (or any other code repository) account and create a repository for your code.</li>
<li>Install the <a href="https://wiki.jenkins-ci.org/display/JENKINS/MSBuild+Plugin" target="_blank">MSBuild plugin</a> for Jenkins.</li>
<li>Install the <a href="https://wiki.jenkins-ci.org/display/JENKINS/MSTest+Plugin" target="_blank">MSTest plugin</a> for Jenkins.</li>
<li>Install the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin" target="_blank">Git plugin</a> for Jenkins.</li>
</ul>

<p>To compile and test your .NET application using Jenkins, <code>MSBuild</code> and <code>MSTest</code> are obviously required. I recommend installing Visual Studio which contains all the necessary tools to compile, test and measure your application rather then installing the trimmed down Microsoft Build Tools, especially if you are using the Microsoft Fakes framework in your unit tests. Installing Visual Studio Ultimate or higher next to Jenkins would be the best approach to cover that scenario so you are able to run those unit tests using Jenkins.</p>

<h6 id="configuringplugins">Configuring plugins</h6>

<p>The installed plugins must be configured in order to use them. Go to the <code>Configure System</code> section in Jenkins and fill in the paths to the executables for the Git, MSBuild and MSTest plugins.</p>

<h6 id="step1createanewjob">Step 1: Create a new job</h6>

<p>To create a new job in Jenkins, navigate to the Jenkins web interface using your favorite browser and click on the <code>New item</code> button. This navigates to the screen below: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/project-type.PNG" alt="Continuous Integration (CI) for .NET applications using Jenkins">
Fill in your project name, select <code>Freestyle project</code> and click <code>OK</code>. The Freestyle project job type consists of all the necessary elements such as SCM integration, build scripts and optional steps required for our project.</p>

<h6 id="step2connectyourrepository">Step 2: Connect your repository</h6>

<p>The next step is to connect your repository so Jenkins knows where to find and pull your code. Scroll down to the section <code>Source Code Management</code> and select <code>Git</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/connect_git.PNG" alt="Continuous Integration (CI) for .NET applications using Jenkins">
Fill in your repository URL and create a user within Jenkins that has at least read access to the configured repository. In this case we will be pulling and monitoring the <code>master</code> branch for changes. </p>

<p>Now, Jenkins is not pulling code automagical, first a build trigger must be created. Bitbucket offers integration with Jenkins via <a href="https://confluence.atlassian.com/bitbucket/manage-webhooks-735643732.html" target="_blank">webhooks</a> or <a href="https://confluence.atlassian.com/bitbucketserver/using-repository-hooks-776639836.html" target="_blank">repository hooks</a>. A <code>hook</code> can be made to trigger a job when SCM changes occur. I would recommend configuring a hook over polling manually to reduce the number of jobs running on Jenkins. If you want to manually poll your repository, just check the <code>Poll SCM</code> or <code>Build periodically</code> checkbox in the <code>Build Triggers</code> section. <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/build-triggers.PNG" alt="Continuous Integration (CI) for .NET applications using Jenkins"></p>

<h6 id="step3addabuildstep">Step 3: Add a build step</h6>

<p>To actually compile your project or solution that Jenkins pulled from your repository, a build step must be created. Scroll down to the <code>Build</code> section, select <code>Add build step</code> and choose <code>Build a Visual Studio project or solution using MSBuild</code>. The following step is created: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/build_step-1.PNG" alt="Continuous Integration (CI) for .NET applications using Jenkins">
Select the version of MSBuild you want to use, in this case we will use the <code>Default</code> one. And enter the path to the solution or project file that has to be compiled using MSBuild. In our case we are compiling <code>YourProject.sln</code>. The solution file is in the root of the working directory, so no additional path prefixing is required.</p>

<h6 id="step4rununittests">Step 4: Run unit tests</h6>

<p>The last thing to do is to create a build step to run your unit tests after your code has been successfully compiled. To do this, select <code>Add build step</code> again and choose <code>Run unit tests with MSTest</code>: <br>
<img src="https://jeroenhildering.azurewebsites.net/content/images/2016/04/build_step_mstest.PNG" alt="Continuous Integration (CI) for .NET applications using Jenkins">
Select the version of MSTest you want to use, again in our case we will use the <code>Default</code> one. And enter the paths to the dlls containing your unit tests.</p>

<h3 id="nextstep">Next step</h3>

<p>And there you have it, a fully automated Jenkins job that pulls code from the repository when a SCM change occures, compiles it and runs unit tests. Ofcourse these are the minimal steps required to create a Continuous Integration job for your project, many other options can be configured such as pushing notifications to Slack, parameterizing builds, creating reports, etc.</p>

<p>The next step is to configure Continuous Delivery (CD) using Jenkins, check out my <a href="http://jeroenhildering.com/2016/04/25/continuous-delivery-for-net-applications-using-jenkins/">next</a> blog post to do so.</p>]]></content:encoded></item><item><title><![CDATA[Web API versioning]]></title><description><![CDATA[Let's start of by saying all API's exposed to the public or to third parties should implement some kind of versioning. Why? Read this blogpost.]]></description><link>https://jeroenhildering.azurewebsites.net/2016/02/26/web-api-versioning/</link><guid isPermaLink="false">aa0ea485-ebbd-46d7-a880-b151c62ab85e</guid><category><![CDATA[asp.net]]></category><category><![CDATA[csharp]]></category><category><![CDATA[json]]></category><category><![CDATA[webapi]]></category><category><![CDATA[xml]]></category><category><![CDATA[versioning]]></category><category><![CDATA[rest]]></category><category><![CDATA[api]]></category><category><![CDATA[itq]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Fri, 26 Feb 2016 10:21:54 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/02/version-2.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/02/version-2.jpg" alt="Web API versioning"><p>Let's start by saying all API's exposed to the public or to third parties should implement some kind of versioning. Why? API's tend to evolve as the world moves on, so when making changes we don't want to break stuff using our api every time we do so. </p>

<p>Well then, if we need versioning, what is <em>"the right way"</em> of implementing it? Short answer: there is none. Long answer: there are various ways of doing so, but every single one has downsides.</p>

<h3 id="mostcommonwaysofapiversioning">Most common ways of API versioning</h3>

<p>There are lots of ways to implement versioning, below are the most common ones.</p>

<h6 id="hostnameversioning">Host name versioning</h6>

<p>In this case the version number is put in the host name:  </p>

<pre><code>GET https://v1.awesomeapi.com/foo/bar</code> HTTP/1.1
Host: v1.awesomeapi.com
Accept: application/json</pre>

<p>This can be tricky in debug mode if you are accessing raw IP addresses such as <code>127.0.0.1</code> or using IIS express to debug your application. But, this method of versioning can be usefull if you want to route incomming requests to different servers as you can create DNS records for different versions of your API.  </p>

<h6 id="urlversioning">URL versioning</h6>

<p>This is basically putting the version number somewhere in the url:  </p>

<pre><code>GET https://awesomeapi.com/v1/foo/bar</code> HTTP/1.1
Host: awesomeapi.com
Accept: application/json</pre>

<p>If we concur that the URL should represent the resource, then that would mean every time the data is changed the api version should be changed as well. Changing the data of your resource should not affect the API version. </p>

<h6 id="querystringparameterversioning">Query string parameter versioning</h6>

<p>The version is put in the querystring like so:  </p>

<pre><code>GET https://awesomeapi.com/foo/bar?version=1</code> HTTP/1.1
Host: awesomeapi.com
Accept: application/json</pre>

<p>Query string parameter versioning has pretty much the same issues as URL versioning, but also the risk of someone not specifying it. What happens if someone doesn't? The API might throw an exception or use some kind of default version you wouldn't expect.</p>

<h6 id="acceptheaderversioning">Accept header versioning</h6>

<p>Accept header versioning is usually done by either adding a parameter:  </p>

<pre><code>GET https://awesomeapi.com/foo/bar</code> HTTP/1.1
Host: awesomeapi.com
Accept: application/json; version=1</pre>

<p>Or by specifying a custom vendor media type:  </p>

<pre><code>GET /foo/bar</code> HTTP/1.1
Host: awesomeapi.com
Accept: application/vnd.producer.product-v1+json</pre>

<p>Accept header versioning with a parameter is generally considered as best practice, although some clients may not understand this format. </p>

<p>Using custom media types seems logical because you describe how you'd like the data. But, if you have a lot of entities this approach might cause a lot of kludge which can result in a lot of maintenance overtime. If you consider using custom media types, be sure to include detailed documentation about them so everyone knows how they work and what they represent.</p>

<h6 id="customheaderversioning">Custom header versioning</h6>

<p>And then there is versioning using a custom header:  </p>

<pre><code>GET https://awesomeapi.com/foo/bar</code> HTTP/1.1
Host: awesomeapi.com
Accept: application/json
X-Api-Version: 1</pre>

<p>Using a custom header is not really a semantic way of describing the resource. The <code>HTTP</code> spec tells us to use the accept header to describe how to present the resource the way we want it to, why reproduce this with a custom header?</p>

<p>Then again on using headers, it could be difficult for certain clients to set them. Imagine a <code>JavaScript</code> client making a <code>JsonP</code> call, in this case it is likely to be a real pain to set a custom header value.</p>

<h3 id="onerouteconstrainttorulethemall">One route constraint to rule them all!</h3>

<p>Because we can't really agree on one specific type of versioning to be the best way for all clients out there, i've created a <code>HttpRouteConstraint</code> that supports all of the above with the exception of host name versioning. The full code is available on GitHub, the link is found at the end of this article.</p>

<p>By using route contraints, we can be in control of where requests are being routed to. To be able to do that, we have to create a class that implements <code>IHttpRouteConstraint</code>.</p>

<pre class="line-numbers language-csharp"><code>public class VersionConstraint : IHttpRouteConstraint  
{
    private readonly string[] _allowedVersions;

    public VersionConstraint( string allowedVersions )
    {
        _allowedVersions = !string.IsNullOrWhiteSpace( allowedVersions ) ? 
            allowedVersions.Split( new[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).Select( x => x.Trim() ).ToArray();
    }

    public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object=""> values, HttpRouteDirection routeDirection )
    {
        if( routeDirection != HttpRouteDirection.UriResolution ) return true;

        // Do some matching versions overhere
    }
}</string,></code></pre>

<p>The version constraint takes an <code>allowedVersions</code> parameter to specify which api versions should be allowed to use. Now for URL versioning, the default route should be something like this:</p>

<pre class="line-numbers language-csharp"><code>// Allow version to be part of the url  
config.Routes.MapHttpRoute(  
    name: "VersionedApi",
    routeTemplate: "api/{version}/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
    constraints: new { version = new VersionConstraint("1,2") }
);</code></pre>

<p>Where the <code>version</code> parameter is used in the route constraint we just made. Matching the version from the URL is fairly easy by adding this to the match method:</p>

<pre class="line-numbers language-csharp" data-start="11"><code>public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection )  
{
    if( routeDirection != HttpRouteDirection.UriResolution ) return true;

    if( !values.ContainsKey( parameterName ) ) return false;

    return allowedVersions.Contains( values[parameterName].ToLower().TrimStart( 'v' ), StringComparer.InvariantCultureIgnoreCase );
}</code></pre>

<p>To get the version from a query string parameter, a little more code is required. So i've created the following function:</p>

<pre class="line-numbers language-csharp"><code>private static string GetVersionFromQueryString( HttpRequestMessage request, string key )  
{
    // Get version parameter value from querystring
    return request.GetQueryNameValuePairs().Any( x => x.Key.Equals( key ) ) ? 
        request.GetQueryNameValuePairs().First( x => x.Key.Equals( key, StringComparison.InvariantCultureIgnoreCase ) ).Value : 
        null;
}
</code></pre>

<p>And added it to the match function:</p>

<pre class="line-numbers language-csharp" data-start="11"><code>public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection )  
{
    if( routeDirection != HttpRouteDirection.UriResolution ) return true;

    var version = values.ContainsKey( parameterName ) ? 
        (string) values[parameterName].ToLower().TrimStart( 'v' ) :
        GetVersionFromQueryString( request, "version" );

    return allowedVersions.Contains( version, StringComparer.InvariantCultureIgnoreCase );
}</code></pre>

<p>The method checks if a query string parameter <code>version</code> exists, and returns the value if so. You,ve probably noticed i've made the match function prefer URL versioning over query string versioning. I will be doing the same with the other implementations as well. </p>

<p>Now for parsing the accept header for accept header versioning, the following function is used:</p>

<pre class="line-numbers language-csharp"><code>private static string GetVersionFromAcceptHeader( HttpRequestMessage request, string paramName )  
{
    if ( !request.Headers.Accept.Any() ) return null;

    foreach ( var acceptHeader in request.Headers.Accept )
    {
        // Support for application/json; [paramName]=[VERSION]
        if ( acceptHeader.Parameters.Any( x => x.Name.Equals( paramName, StringComparison.InvariantCultureIgnoreCase ) ) )
            return acceptHeader.Parameters.First( x => x.Name.Equals( paramName, StringComparison.InvariantCultureIgnoreCase ) ).Value;
        // Support for application/vnd.yourvendorname-v[VERSION]+json
        if ( !string.IsNullOrEmpty( acceptHeader.MediaType ) && 
              Regex.IsMatch( acceptHeader.MediaType, @"application\/vnd\..*-v([\d]+(\.\d+)*)\+(json|xml)" ) )
            return Regex.Match( acceptHeader.MediaType, @"(?<=-v)[\d]+(\.\d+)*" ).value;="" }="" return="" null;="" <="" code=""></=-v)[\d]+(\.\d+)*"></code></pre>

<p>The function will match <code>application/json; version=1</code> as well as <code>application/vnd.awesomeapi-v1+json</code>. Again added it to the match method:</p>

<pre class="line-numbers language-csharp" data-start="11"><code>public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection )  
{
    if( routeDirection != HttpRouteDirection.UriResolution ) return true;

    var version = values.ContainsKey( parameterName ) ? 
        (string) values[parameterName].ToLower().TrimStart( 'v' ) :
        GetVersionFromQueryString( request, "version" ) ??
        GetVersionFromAcceptHeader( request, "version" );

    return allowedVersions.Contains( version, StringComparer.InvariantCultureIgnoreCase );
}</code></pre>

<p>Last but not least, the custom header versioning uses the following function:</p>

<pre class="line-numbers language-csharp"><code>private static string GetVersionFromCustomHeader( HttpRequestMessage request, string name )  
{
    // Get version from custom header
    IEnumerable<string> keys;
    return !request.Headers.TryGetValues( name, out keys ) ? null : keys.First();
}
</string></code></pre>

<p>Added to the match method:</p>

<pre class="line-numbers language-csharp" data-start="11"><code>public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection )  
{
    if( routeDirection != HttpRouteDirection.UriResolution ) return true;

    var version = values.ContainsKey( parameterName ) ? 
        (string) values[parameterName].ToLower().TrimStart( 'v' ) :
        GetVersionFromQueryString( request, "version" ) ??
        GetVersionFromAcceptHeader( request, "version" ) ??
        GetVersionFromCustomHeader( request, "X-Api-Version" );

    return allowedVersions.Contains( version, StringComparer.InvariantCultureIgnoreCase );
}</code></pre>

<p>There you have it, one route contstraint that supports the four most common implementations of versioning. But wait! What about a default version? If no version is supplied you probably would want to force a default version upon your client. One way of doing this is, is by creating an <code>AppSetting</code> with de default version in your <code>web.config</code> and using that value in our <code>VersionedRouteConstraint</code>:</p>

<pre class="line-numbers language-xml"><code>&lt;appSettings>  
  &lt;add key="DefaultApiVersion" value="1" />
&lt;/appSettings></code></pre>

<p>I would recommend using the lowest version of your API available as the default version. This version is the only version guaranteed not to break when changes are pushed. </p>

<p>Now to use the <code>AppSetting</code> in our <code>RouteConstraint</code>, i've created a private property that gets the value from the config and defaults to <code>1</code> if no setting is found:</p>

<pre class="line-numbers language-csharp"><code>private static string DefaultVersion  
{
    get
    {
        var defaultVersion = ConfigurationManager.AppSettings["DefaultApiVersion"];
        return !string.IsNullOrWhiteSpace( defaultVersion ) ? defaultVersion : "1";
    }
}
</code></pre>

<p>Added to the match method:</p>

<pre class="line-numbers language-csharp" data-start="11"><code>public bool Match( HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection )  
{
    if( routeDirection != HttpRouteDirection.UriResolution ) return true;

    var version = values.ContainsKey( parameterName ) ? 
        (string) values[parameterName].ToLower().TrimStart( 'v' ) :
        GetVersionFromQueryString( request, "version" ) ??
        GetVersionFromAcceptHeader( request, "version" ) ??
        GetVersionFromCustomHeader( request, "X-Api-Version" ) ??
        DefaultVersion;

    return allowedVersions.Contains( version, StringComparer.InvariantCultureIgnoreCase );
}</code></pre>

<p>Now that all that is done, what if we want to route a specific version to a specific controller action. We can't, because we don't have a <code>RouteFactoryAttribute</code> that uses our newly made route constraint. So we have to make one:</p>

<pre class="line-numbers language-csharp"><code>public class VersionedRoute : RouteFactoryAttribute  
{
    private readonly string _allowedVersions;

    public VersionedRoute( string template, string allowedVersions ) : base( template )
    {
        _allowedVersions = allowedVersions;
    }

    public override IDictionary<string, object=""> Constraints
    {
        get
        {
            var constraints = new HttpRouteValueDictionary {{"version", new VersionConstraint( _allowedVersions )}};
            return constraints;
        }
    }
}</string,></code></pre>

<p>Now we can do awesome stuff like this to route the request using the version constraint:</p>

<pre class="line-numbers language-csharp"><code>[VersionedRoute( "api/product/{id}", "v1" )]  
public Product Get( int id ) {  
    // Return some product for API v1
}</code></pre>

<p>There is one <em>but</em>, when using custom media types with accept header versioning. When your API supports multiple formatters, we must make them aware of our custom media types so the appropriate formatter is used to serialize the response. </p>

<p>To make sure <code>JSON</code> is outputted when using the accept header <code>application/vnd.webapiversioning-v1+json</code> and <code>XML</code> is outputted when using <code>application/vnd.webapiversioning-v1+xml</code> using the default formatters, the media types must be added to the corresponding formatters in the <code>Global.asax</code>:</p>

<pre class="line-numbers language-csharp"><code>GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(  
    new MediaTypeHeaderValue( "application/vnd.webapiversioning-v1+json" ) );
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Add(  
    new MediaTypeHeaderValue( "application/vnd.webapiversioning-v1+xml" ) );

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(  
    new MediaTypeHeaderValue( "application/vnd.webapiversioning-v2+json" ) );
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Add(  
    new MediaTypeHeaderValue( "application/vnd.webapiversioning-v2+xml" ) );</code></pre>

<p>Remember that you have to do this for every version your API supports. However, these media types are not typed and do not really describe the represented resource. To be able to create typed formatters, i've extended <code>JsonMediaTypeFormatter</code> and <code>XmlMediaTypeFormatter</code>:</p>

<pre class="line-numbers language-csharp"><code>public class TypedXmlMediaTypeFormatter : XmlMediaTypeFormatter  
{
    private readonly Type _resourceType;

    public TypedXmlMediaTypeFormatter( Type resourceType, MediaTypeHeaderValue mediaType )
    {
        _resourceType = resourceType;
        SupportedMediaTypes.Clear();
        SupportedMediaTypes.Add( mediaType );
    }

    public override bool CanReadType( Type type )
    {
        return _resourceType == type || _resourceType == type.GetEnumerableType();
    }

    public override bool CanWriteType( Type type )
    {
        return _resourceType == type || _resourceType == type.GetEnumerableType();
    }
}

public class TypedJsonMediaTypeFormatter : JsonMediaTypeFormatter  
{
    private readonly Type _resourceType;

    public TypedJsonMediaTypeFormatter( Type resourceType, MediaTypeHeaderValue mediaType )
    {
        _resourceType = resourceType;
        SupportedMediaTypes.Clear();
        SupportedMediaTypes.Add( mediaType );
    }

    public override bool CanReadType( Type type )
    {
        return _resourceType == type || _resourceType == type.GetEnumerableType();
    }

    public override bool CanWriteType( Type type )
    {
        return _resourceType == type || _resourceType == type.GetEnumerableType();
    }
}</code></pre>

<p>And then you are able to created typed formatters like this in the <code>Global.asax</code>: </p>

<pre class="line-numbers language-csharp"><code>// Add typed formatters  
GlobalConfiguration.Configuration.Formatters.Add(  
    new TypedJsonMediaTypeFormatter( typeof( Product ),
        new MediaTypeHeaderValue( "application/vnd.vendor.product-v1.0+json" ) ) );
GlobalConfiguration.Configuration.Formatters.Add(  
    new TypedJsonMediaTypeFormatter( typeof( ProductV2 ),
        new MediaTypeHeaderValue( "application/vnd.vendor.product-v2.0+json" ) ) );

GlobalConfiguration.Configuration.Formatters.Add(  
    new TypedXmlMediaTypeFormatter( typeof( Product ),
        new MediaTypeHeaderValue( "application/vnd.vendor.product-v1.0+xml" ) ) );
GlobalConfiguration.Configuration.Formatters.Add(  
    new TypedXmlMediaTypeFormatter( typeof( ProductV2 ),
        new MediaTypeHeaderValue( "application/vnd.vendor.product-v2.0+xml" ) ) );</code></pre>

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

<p>If you have the luxury of being in control over the API and the client consuming it, you can choose one type of versioning that suits best for both ends. If you are not, you probably want to pick two or three variants to widely support all clients out there.</p>

<p>Check out the full source at <a href="https://github.com/JeroenHildering/WebApiVersioning">GitHub</a>.</p>]]></content:encoded></item><item><title><![CDATA[ASP.Net MVC Flag Enumeration Model Binder]]></title><description><![CDATA[A while ago I ran into a problem trying to model bind a flag enumeration property where of course multiple values can be selected, so what you would like to have is a checkbox list to choose from.]]></description><link>https://jeroenhildering.azurewebsites.net/2014/03/28/asp-net-mvc-flag-enumeration-model-binder/</link><guid isPermaLink="false">76e912ca-6a87-4fe1-89a1-087150705d7b</guid><category><![CDATA[asp.net]]></category><category><![CDATA[csharp]]></category><category><![CDATA[mvc]]></category><category><![CDATA[itq]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Fri, 28 Mar 2014 17:10:00 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/02/checklist.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/02/checklist.jpg" alt="ASP.Net MVC Flag Enumeration Model Binder"><p>A while ago I ran into a problem trying to model bind a flag enumeration property where of course multiple values can be selected, so what you would like to have is a checkbox list to choose from. Apparently there is no such thing in ASP.Net MVC like a html helper method CheckBoxListFor available to use. But there is a nuget package you can download called <a href="https://www.nuget.org/packages/MvcCheckBoxList/1.4.4.5" target="_blank">MvcCheckBoxList</a>, this plugin is based on an <code>IEnumerable</code> from which it creates a checkbox list to let the user choose from. Unfortunatly no good for binding a flag enumeration property, so I’ve created my own custom html helper and flag enumeration model binder.</p>

<p>To create a checkbox list from an enumeration with a html helper we have to create a new static class with a static method that returns a <code>MvcHtmlString</code>. In my case I’ve created a method <code>CheckBoxListForEnum</code> that can also be sorted alphabetically for user friendlyness:</p>

<pre class="line-numbers"><code class="language-csharp">public static class HtmlHelpers  
{
    public static MvcHtmlString CheckBoxListForEnum&lt;TModel, TValue>( this HtmlHelper html, 
        Expression&lt;Func&lt;TModel, TValue>> expression, object htmlAttributes = null, bool sortAlphabetically = true )
    {
        var fieldName = ExpressionHelper.GetExpressionText( expression );
        var fullBindingName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( fieldName );
        var fieldId = TagBuilder.CreateSanitizedId( fullBindingName );

        var metadata = ModelMetadata.FromLambdaExpression( expression, html.ViewData );
        var value = metadata.Model;

        // Get all enum values
        IEnumerable values = Enum.GetValues( typeof( TValue ) ).Cast<tvalue>();

        // Sort them alphabetically by enum name
        if ( sortAlphabetically )
            values = values.OrderBy( i => i.ToString() );

        // Create checkbox list
        var sb = new StringBuilder();
        foreach ( var item in values )
        {
            TagBuilder builder = new TagBuilder( "input" );
            long targetValue = Convert.ToInt64( item );
            long flagValue = Convert.ToInt64( value );

            if ( ( targetValue & flagValue ) == targetValue )
                builder.MergeAttribute( "checked", "checked" );

            builder.MergeAttribute( "type", "checkbox" );
            builder.MergeAttribute( "value", item.ToString() );
            builder.MergeAttribute( "name", fieldId );

            // Add optional html attributes
            if ( htmlAttributes != null )
                builder.MergeAttributes( new RouteValueDictionary( htmlAttributes ) );

            builder.InnerHtml = item.ToString();

            sb.Append( builder.ToString( TagRenderMode.Normal ) );

            // Seperate checkboxes by new line
            sb.Append( "&lt;br />" );
        }

        return new MvcHtmlString( sb.ToString() );
    }
}</tvalue></code></pre>

<p>This method enables you to do awesome stuff like this:</p>

<pre class="line-numbers"><code class="language-csharp">@Html.CheckBoxListForEnum( m => m.EnumProperty )  
@Html.CheckBoxListForEnum( m => m.EnumProperty, new { @disabled = true } )
@Html.CheckBoxListForEnum( m => m.EnumProperty, new { @class = "checkbox" }, sortAlphabetically = false )
</code></pre>

<p>which neatly creates a checkbox list based on the enum of the property from your viewmodel.</p>

<p>Now that our checkbox list is created we also have correctly bind the selected values to our viewmodel when posting the data to the server. To do that we have to create a custom model binder that extends the mvc DefaultModelBinder class and override the GetPropertyValue method:</p>

<pre class="line-numbers"><code class="language-csharp">public class CustomModelBinder : DefaultModelBinder  
{
    protected override object GetPropertyValue( ControllerContext controllerContext, 
        ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder )
    {
        var propertyType = propertyDescriptor.PropertyType;

        // Check if the property type is an enum with the flag attribute
        if ( propertyType.IsEnum && propertyType.GetCustomAttributes&lt;FlagsAttribute>().Any() )
        {
            var providerValue = bindingContext.ValueProvider.GetValue( bindingContext.ModelName );
            if ( providerValue != null )
            {
                var value = providerValue.RawValue;
                if ( value != null )
                {
                    // In case it is a checkbox list/dropdownlist/radio button list
                    if ( value is string[] )
                    {
                        // Create flag value from posted values
                        var flagValue = ( ( string[] )value ).Aggregate( 0, ( current, v ) => current | ( int )Enum.Parse( propertyType, v ) );

                        return Enum.ToObject( propertyType, flagValue );
                    }
                    // In case it is a single value
                    if ( value.GetType().IsEnum )
                    {
                        return Enum.ToObject( propertyType, value );
                    }
                }
            }
        }
        return base.GetPropertyValue( controllerContext, bindingContext, propertyDescriptor, propertyBinder );
    }
}</code></pre>

<p>Our method filters all flag enumeration typed properties and returns a flag value created from the selected checkbox values. The only thing left to do is tell our application to use our modelbinder instead of the default modelbinder, this is done in <code>Global.asax</code>:</p>

<pre class="line-numbers"><code class="language-csharp">protected void Application_Start()  
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register( GlobalConfiguration.Configuration );
    FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters );
    RouteConfig.RegisterRoutes( RouteTable.Routes );
    BundleConfig.RegisterBundles( BundleTable.Bundles );

    // Register custom flag enum model binder
    ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}</code></pre>

<p>Now I hear you thinking that those enumaration string values aren’t really user friendly. A way to solve this is to create a strongly typed resource file, put all your enumeration in there and replace <code>builder.InnerHtml = item.ToString();</code> by this line: <code>builder.InnerHtml = !string.IsNullOrEmpty( StrongResource.ResourceManager.GetString( item.ToString() ) ) ? StrongResource.ResourceManager.GetString( item.ToString() ) : item.ToString();</code></p>

<p>This renders the checkbox list with strings from the strongly typed resource instead of those ToString values.</p>

<p>Check out the full source code at <a href="https://github.com/JeroenHildering/FlagEnumModelBinder">GitHub</a>.</p>]]></content:encoded></item><item><title><![CDATA[Replacing WCF DataContractJsonSerializer with Newtonsoft JsonSerializer]]></title><description><![CDATA[Have you ever had the need to customize json serialization and deserialization of your WCF rest endpoint?]]></description><link>https://jeroenhildering.azurewebsites.net/2014/03/21/replacing-wcf-datacontractjsonserializer-with-newtonsoft-jsonserializer/</link><guid isPermaLink="false">5d8fb46e-dba2-46f0-b00f-d5199969b18b</guid><category><![CDATA[wcf]]></category><category><![CDATA[asp.net]]></category><category><![CDATA[csharp]]></category><category><![CDATA[json]]></category><category><![CDATA[newtonsoft]]></category><category><![CDATA[itq]]></category><dc:creator><![CDATA[Jeroen]]></dc:creator><pubDate>Fri, 21 Mar 2014 16:50:00 GMT</pubDate><media:content url="https://jeroenhildering.com/content/images/2016/02/contract.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://jeroenhildering.com/content/images/2016/02/contract.jpg" alt="Replacing WCF DataContractJsonSerializer with Newtonsoft JsonSerializer"><p>Have you ever had the need to customize json serialization and deserialization of your WCF rest endpoint? I have, in particular to replace the WCF datetime format by generalized time format. By default, most json serializers serialize datetime objects to a generalized time format, this could lead to problems if you are creating a WCF rest endpoint which only supports input of microsofts datetime implementation like this <code>\/Date(1293034567877)\/</code>. A way to solve this problem is to replace the behavior of your rest endpoint by a custom one that uses newtonsofts json serializer instead.</p>

<p>To do this we have to create a message formatter class by implementing <code>IDispatchMessageFormatter</code>:  </p>

<pre class="line-numbers"><code class="language-csharp">public class NewtonsoftJsonDispatchFormatter : IDispatchMessageFormatter  
{
    public void DeserializeRequest( Message message, object[] parameters ) { ... }
    public Message SerializeReply( MessageVersion messageVersion, object[] parameters, object result ) { ... }
}</code></pre>

<p>This class will be using newtonsofts json serializer to serialize and deserialize messages. Next we have to create a behavior class that extends <code>WebHttpBehavior</code>:</p>

<pre class="line-numbers"><code class="language-csharp">public class NewtonsoftJsonBehavior : WebHttpBehavior  
{
    protected override IDispatchMessageFormatter GetRequestDispatchFormatter( OperationDescription operationDescription, ServiceEndpoint endpoint )
    {
        return new NewtonsoftJsonDispatchFormatter( operationDescription, true );
    }

    protected override IDispatchMessageFormatter GetReplyDispatchFormatter( OperationDescription operationDescription, ServiceEndpoint endpoint )
    {
        return new NewtonsoftJsonDispatchFormatter( operationDescription, false );
    }
}</code></pre>

<p>The only thing left to do is tell the WCF endpoint to use this new behavior. One way to do that is using your web.config to connect the new behavior to your endpoint. In order to do that we have to create a behavior extension class by extending the <code>BehaviorExtensionElement</code> class:</p>

<pre class="line-numbers"><code class="language-csharp">public class NewtonsoftJsonBehaviorExtension : BehaviorExtensionElement  
{
    public override Type BehaviorType
    {
        get { return typeof( NewtonsoftJsonBehavior ); }
    }

    protected override object CreateBehavior()
    {
        return new NewtonsoftJsonBehavior();
    }
}</code></pre>

<p>And create a content type mapper:</p>

<pre class="line-numbers"><code class="language-csharp">public class NewtonsoftJsonContentTypeMapper : WebContentTypeMapper  
{
    public override WebContentFormat GetMessageFormatForContentType( string contentType )
    {
        return WebContentFormat.Raw;
    }
}</code></pre>

<p>Now when configuring your binding you can simply setup an extension like this:</p>

<pre class="line-numbers"><code class="language-xml">&lt;extensions>  
  &lt;behaviorExtensions>
    &lt;add name="newtonsoftJsonBehavior" type="MyApp.NameSpace.NewtonsoftJsonBehaviorExtension, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  &lt;/behaviorExtensions>
&lt;/extensions></code></pre>

<p>Setup your enpoint behavior like this:</p>

<pre class="line-numbers"><code class="language-xml">&lt;endpointBehaviors>  
  &lt;behavior name="restEndPointBehavior">
    &lt;webHttp helpEnabled="false" defaultBodyStyle="Bare" defaultOutgoingResponseFormat="Json" faultExceptionEnabled="false" />
    &lt;newtonsoftJsonBehavior/>
  &lt;/behavior>
&lt;/endpointBehaviors></code></pre>

<p>Configure a webHttpBinding to use our custom contentTypeMapper:</p>

<pre class="line-numbers"><code class="language-xml">&lt;bindings>  
  &lt;webHttpBinding>
    &lt;binding name="restWebHttpBinding" contentTypeMapper="MyApp.NameSpace.NewtonsoftJsonContentTypeMapper, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  &lt;/webHttpBinding>
&lt;/bindings></code></pre>

<p>And finally setting up our endpoint like this:</p>

<pre class="line-numbers"><code class="language-xml">&lt;services>  
  &lt;service name="MyApp.NameSpace.Service" behaviorConfiguration="restServiceBehavior">
    &lt;endpoint address="" behaviorConfiguration="restEndPointBehavior" binding="webHttpBinding" bindingConfiguration="restWebHttpBinding" contract="MyApp.NameSpace.IService" />
  &lt;/service>
&lt;/services></code></pre>

<p>Your WCF rest endpoint is now using your own message formatter to serialize and deserialize messages! There are some other cool features when using newtonsofts json serializer. For example if your service method has a <code>byte[]</code> parameter, you can just post a <code>Base64</code> encoded string and it will be automatically deserialized to a <code>byte[]</code> on the server.</p>

<p>Check out the full source at <a href="https://github.com/JeroenHildering/WcfNewtonsoftJsonSerializer" target="new">GitHub</a>.</p>]]></content:encoded></item></channel></rss>