<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Code Outside of the Box</title>
<subtitle>Source to:</subtitle>
<link href="http://josephdaigle.me" />
<link rel="self" type="application/atom+xml" href="http://josephdaigle.me/feed.xml" />
<id>http://josephdaigle.me/feed.xml</id>
<updated>2018-05-02T19:17:03+00:00</updated>
<rights>Copyright 2015 © Joseph Daigle.</rights>

  <entry>
    <id>http://josephdaigle.me/2017/03/20/Hydrogen.Extensions.Mvc5-alpha-release</id>
    <published>2017-03-20T00:00:00+00:00</published>
    <updated>
       2017-03-20T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2017/03/20/Hydrogen.Extensions.Mvc5-alpha-release.html" />
		<title>Hydrogen Extensions for ASP.NET MVC 5 Alpha Release</title>
		<content type="html">&lt;p&gt;I’m happy to share the first alpha release of my extensions library for ASP.NET MVC 5 which &lt;strong&gt;adds support for async filters&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;You can download the library from &lt;a href=&quot;https://www.nuget.org/packages/Hydrogen.Extensions.Mvc5.Async&quot;&gt;NuGet&lt;/a&gt; and the source is available on &lt;a href=&quot;https://github.com/jdaigle/Hydrogen.Extensions.Mvc5&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can read about my journey to get here:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/12/improved-async-aspnet-mvc-part-1.html&quot;&gt;Part 1 - The Current Landscape&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/13/improved-async-aspnet-mvc-part-2.html&quot;&gt;Part 2 - Refactoring AsyncControllerActionInvoker&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/18/improved-async-aspnet-mvc-part-3.html&quot;&gt;Part 3 - Async Filter API&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;getting-started&quot;&gt;Getting started&lt;/h3&gt;

&lt;p&gt;First we need to swap out the default implementation &lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncActionInvoker&lt;/code&gt; with &lt;code class=&quot;highlighter-rouge&quot;&gt;Hydrogen.Extensions.Mvc5.Async.ControllerActionInvokerEx&lt;/code&gt;. There are two ways to do this:&lt;/p&gt;

&lt;p&gt;1) Set the &lt;code class=&quot;highlighter-rouge&quot;&gt;ActionInvoker&lt;/code&gt; property of a controller when it’s constructed:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class HomeController : Controller
{
    public HomeController()
    {
        ActionInvoker = ControllerActionInvokerEx.Instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;2) Using your DI container of choice, register &lt;code class=&quot;highlighter-rouge&quot;&gt;Hydrogen.Extensions.Mvc5.Async.ControllerActionInvokerEx&lt;/code&gt; as an implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncActionInvoker&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For example (using Autofac):&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;builder.RegisterInstance(ControllerActionInvokerEx.Instance)
        .As&amp;lt;IAsyncActionInvoker&amp;gt;()
        .SingleInstance();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Note that &lt;code class=&quot;highlighter-rouge&quot;&gt;ControllerActionInvokerEx&lt;/code&gt; can be used as a singleton. It doesn’t maintain any state.&lt;/p&gt;

&lt;h3 id=&quot;creating-an-async-filter&quot;&gt;Creating an async filter&lt;/h3&gt;

&lt;p&gt;You may create a subclass of &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncActionFilterAttribute&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncExceptionFilterAttribute&lt;/code&gt; and override the async methods.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class MyAsyncActionFilterAttribute : AsyncActionFilterAttribute
{
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // Execute code before the action is invoked.
        // You can &quot;short-circuit&quot; the action by setting 'context.Result'
        // and returning before calling 'next()'.
        
        // The implementation is responsible for calling 'next()'.
        var actionExecutedContext = await next().ConfigureAwait(false);

        // Execute code after the action is invoked
    }

    public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        // Execute code before the result is invoked.
        // You can &quot;short-circuit&quot; the action by setting 'context.Canceled = true'
        // and returning before calling 'next()'.
        
        // The implementation is responsible for calling 'next()'.
        var resultExecutedContext = await next().ConfigureAwait(false);

        // Execute code after the result is invoked
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Alternately you may implement any of the async filters:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncActionFilter&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncResultFilter&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncExceptionFilter&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncAuthorizationFilter&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Unfortunately, for compatibility reasons, you must also implement the non-async version of these filters (e.g. &lt;code class=&quot;highlighter-rouge&quot;&gt;void OnActionExecuting(ActionExecutingContext filterContext)&lt;/code&gt;). However, these methods can be a NOOP since the code is never executed by &lt;code class=&quot;highlighter-rouge&quot;&gt;ControllerActionInvokerEx&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This library, currently, does not implement as async version of &lt;code class=&quot;highlighter-rouge&quot;&gt;IAuthenticationFilter&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;this-is-an-alpha-release&quot;&gt;This is an alpha release&lt;/h3&gt;

&lt;p&gt;I fully expect there to be bugs, however I hope to use it in real production code soon.&lt;/p&gt;

&lt;p&gt;Maybe one day this code, or some derivation there of, can make it into an official release.&lt;/p&gt;

&lt;p&gt;I hope someone else might find this library useful. And I’d appreciate feedback, comments, or contributions (including bug reports)!&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2017/03/18/improved-async-aspnet-mvc-part-3</id>
    <published>2017-03-18T00:00:00+00:00</published>
    <updated>
       2017-03-18T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2017/03/18/improved-async-aspnet-mvc-part-3.html" />
		<title>Improving Async Support in ASP.NET MVC - Part 3 - Async Filter API</title>
		<content type="html">&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/12/improved-async-aspnet-mvc-part-1.html&quot;&gt;Part 1 - The Current Landscape&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/13/improved-async-aspnet-mvc-part-2.html&quot;&gt;Part 2 - Refactoring AsyncControllerActionInvoker&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/18/improved-async-aspnet-mvc-part-3.html&quot;&gt;Part 3 - Async Filter API&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The obvious solution is to just copy the API from &lt;a href=&quot;https://github.com/aspnet/Mvc/&quot;&gt;ASP.NET MVC Core&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public interface IAsyncAuthorizationFilter : IAuthorizationFilter
{
    Task OnAuthorizationAsync(AuthorizationContext context);
}

public interface IAsyncExceptionFilter : IExceptionFilter
{
    Task OnExceptionAsync(ExceptionContext context);
}

public interface IAsyncActionFilter : IActionFilter
{
    Task OnActionExecutionAsync(ActionExecutingContext context
        , ActionExecutionDelegate next);
}

public delegate Task&amp;lt;ActionExecutedContext&amp;gt; ActionExecutionDelegate();

public interface IAsyncResultFilter : IResultFilter
{
    Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next);
}

public delegate Task&amp;lt;ResultExecutedContext&amp;gt; ResultExecutionDelegate();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And that’s basically it.&lt;/p&gt;

&lt;p&gt;But you’ll notice that these async interfaces must also implement their non-async counterparts. Unfortunately MVC5 doesn’t have a shared marker interface as exists in MVC Core. And so the framework (and many 3rd party extensions) directly reference the filter types for various reasons. This means that implementations of the async interfaces will just need to implement the non-async methods as a &lt;a href=&quot;https://en.wikipedia.org/wiki/NOP&quot;&gt;NOOP&lt;/a&gt; - annoying but not the end of the world.&lt;/p&gt;

&lt;p&gt;Here’s an example implementation based on &lt;code class=&quot;highlighter-rouge&quot;&gt;FilterAttribute&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class AsyncActionFilterAttribute : FilterAttribute
    , IAsyncActionFilter
    , IAsyncResultFilter {

    public virtual void OnActionExecuting(ActionExecutingContext filterContext) {
    }

    public virtual void OnActionExecuted(ActionExecutedContext filterContext) {
    }

    public virtual async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        OnActionExecuting(context);
        if (context.Result == null) {
            OnActionExecuted(await next().ConfigureAwait(false));
        }
    }

    public virtual void OnResultExecuting(ResultExecutingContext filterContext) {
    }

    public virtual void OnResultExecuted(ResultExecutedContext filterContext) {
    }

    public virtual async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) {
        OnResultExecuting(context);
        if (!context.Cancel) {
            OnResultExecuted(await next().ConfigureAwait(false));
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Next time, putting everything together.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2017/03/13/improved-async-aspnet-mvc-part-2</id>
    <published>2017-03-13T00:00:00+00:00</published>
    <updated>
       2017-03-13T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2017/03/13/improved-async-aspnet-mvc-part-2.html" />
		<title>Improving Async Support in ASP.NET MVC - Part 2 - Refactoring AsyncControllerActionInvoker</title>
		<content type="html">&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/12/improved-async-aspnet-mvc-part-1.html&quot;&gt;Part 1 - The Current Landscape&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/13/improved-async-aspnet-mvc-part-2.html&quot;&gt;Part 2 - Refactoring AsyncControllerActionInvoker&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/18/improved-async-aspnet-mvc-part-3.html&quot;&gt;Part 3 - Async Filter API&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href=&quot;/2017/03/12/improved-async-aspnet-mvc-part-1.html&quot;&gt;Last time&lt;/a&gt; I began by discussing several of the shortcomings of the current ASP.NET MVC async implementation. Specifically the lack of async filters (action filters, etc.).&lt;/p&gt;

&lt;p&gt;I’ve decided that the most straight-forward approach is implement a refactored &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncControllerActionInvoker&lt;/code&gt;. This is the component within the MVC pipeline responsible for invoking filters.&lt;/p&gt;

&lt;p&gt;I’ve started a new project, &lt;a href=&quot;https://github.com/jdaigle/MvcAsync&quot;&gt;MvcAsync&lt;/a&gt;, for the refactored code.&lt;/p&gt;

&lt;h2 id=&quot;refactoring-apm-to-tap&quot;&gt;Refactoring APM to TAP&lt;/h2&gt;

&lt;p&gt;As I mentioned, most of the MVC pipeline is written using the classic Asynchronous Programming Model (APM) which requires Begin/End method pairs. This results in very convoluted code that is difficult to reason about.&lt;/p&gt;

&lt;p&gt;Fortunately it is possible to wrap APM using the Task-based Asynchronous Pattern (TAP). &lt;a href=&quot;https://twitter.com/aSteveCleary&quot;&gt;Stephen Cleary&lt;/a&gt; has &lt;a href=&quot;http://blog.stephencleary.com/2012/07/async-interop-with-iasyncresult.html&quot;&gt;written&lt;/a&gt; and great deal about the topic and has some wonderful &lt;a href=&quot;https://github.com/StephenCleary/AsyncEx&quot;&gt;resources&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can compare &lt;a href=&quot;https://github.com/jdaigle/MvcAsync/blob/9d1c50f3e3/MvcAsync/AsyncControllerActionInvokerEx.cs&quot;&gt;my implementation&lt;/a&gt; to the &lt;a href=&quot;https://github.com/jdaigle/aspnetwebstack/blob/v3.2.3/src/System.Web.Mvc/Async/AsyncControllerActionInvoker.cs&quot;&gt;original&lt;/a&gt; to see just how stark the difference is.&lt;/p&gt;

&lt;p&gt;And because I wrapped the incoming and outgoing APM, I was largely able to re-used the existing unit tests to assert that my implementation is correct (for now).&lt;/p&gt;

&lt;h2 id=&quot;performance&quot;&gt;Performance&lt;/h2&gt;

&lt;p&gt;By wrapping both in the incoming and outgoing APM methods in Tasks, I was originally worried about performance. So of course I decided to create a benchmark (using the fantastic &lt;a href=&quot;https://github.com/dotnet/BenchmarkDotNet&quot;&gt;BenchmarkDotNet&lt;/a&gt; library).&lt;/p&gt;

&lt;p&gt;I was pleasantly surprised by the results. Performance is nearly the same, and sometimes &lt;em&gt;better&lt;/em&gt; in my Task-based implementation.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;                                                        Method |       Mean |    StdDev |
-------------------------------------------------------------- |----------- |---------- |
 AsyncControllerActionInvokerEx_BeginInvokeAction_NormalAction | 17.5357 us | 0.5481 us |
      AsyncControllerActionInvokerEx_InvokeAction_NormalAction | 16.9045 us | 0.2451 us |
   AsyncControllerActionInvoker_BeginInvokeAction_NormalAction | 17.1643 us | 0.1946 us |
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Of course I’m assuming there would be an even greater improvement in performance if the entire pipeline could be refactored to use TAP. Unfortunately that would require a lot of changes, many of them breaking changes.&lt;/p&gt;

&lt;h2 id=&quot;using-asynccontrolleractioninvokerex-at-runtime&quot;&gt;Using &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncControllerActionInvokerEx&lt;/code&gt; at Runtime&lt;/h2&gt;

&lt;p&gt;Fortunately it’s pretty easy to swap in a custom ActionInvoker at runtime. As a developer you have a few options:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;You can create an implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncActionInvokerFactory&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;IActionInvokerFactory&lt;/code&gt; and register with your DI container.&lt;/li&gt;
  &lt;li&gt;You can directly register an &lt;code class=&quot;highlighter-rouge&quot;&gt;IAsyncActionInvoker&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;IActionInvoker&lt;/code&gt; with your DI container.&lt;/li&gt;
  &lt;li&gt;You can simply assign the &lt;code class=&quot;highlighter-rouge&quot;&gt;ActionInvoker&lt;/code&gt; property on &lt;code class=&quot;highlighter-rouge&quot;&gt;Controller&lt;/code&gt; in a constructor.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;next-time&quot;&gt;Next Time&lt;/h2&gt;

&lt;p&gt;Next time I hope to start planning out the API for new async filters.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2017/03/12/improved-async-aspnet-mvc-part-1</id>
    <published>2017-03-12T00:00:00+00:00</published>
    <updated>
       2017-03-12T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2017/03/12/improved-async-aspnet-mvc-part-1.html" />
		<title>Improving Async Support in ASP.NET MVC - Part 1</title>
		<content type="html">&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/12/improved-async-aspnet-mvc-part-1.html&quot;&gt;Part 1 - The Current Landscape&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/13/improved-async-aspnet-mvc-part-2.html&quot;&gt;Part 2 - Refactoring AsyncControllerActionInvoker&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2017/03/18/improved-async-aspnet-mvc-part-3.html&quot;&gt;Part 3 - Async Filter API&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;the-current-landscape&quot;&gt;The Current Landscape&lt;/h2&gt;

&lt;p&gt;ASP.NET MVC (&lt;a href=&quot;https://www.nuget.org/packages/microsoft.aspnet.mvc/&quot;&gt;the non-core version&lt;/a&gt;) has enjoyed decent support for asynchronous actions. The older Asynchronous Programming Model (APM) approach required inheriting from &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncController&lt;/code&gt; and involved creating &lt;code class=&quot;highlighter-rouge&quot;&gt;ActionAsync()&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;ActionCompleted()&lt;/code&gt; method pairs. The newer Task-based Asynchronous Pattern (TAP), or async/await, approach simplified development significantly by allowing action methods on normal controllers to return &lt;code class=&quot;highlighter-rouge&quot;&gt;Task&amp;lt;ActionResult&amp;gt;&lt;/code&gt;. On the one hand, the implementation of async inside ASP.NET MVC has been kludgey at best. On the other hand, Microsoft did a good job of tying in async support without any major breaking changes.&lt;/p&gt;

&lt;p&gt;Despite this, there are a number of use cases that are simply not supported making it &lt;em&gt;really challenging&lt;/em&gt; to create async-only business libraries.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Asynchronous filters (action filters, authentication filters, etc.)&lt;/li&gt;
  &lt;li&gt;Asynchronous action results (such as rendering Razor views)&lt;/li&gt;
  &lt;li&gt;Asynchronous child actions (resulting from lack of async action results)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Granted these problems and more are solved in &lt;a href=&quot;https://docs.microsoft.com/en-us/aspnet/core/&quot;&gt;ASP.NET Core&lt;/a&gt;. But a lot of world runs on a mix of legacy code, including web forms and old ASP.NET web services. It would have been nice to have some of these features back ported to the ASP.NET MVC 5.x trunk.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And so I am attempting to just that.&lt;/strong&gt; I’m also planning to document the process. Whether or not these changes ever make it into an “official” release, I think this is a worth-while exercise that hopefully someone finds useful.&lt;/p&gt;

&lt;h2 id=&quot;the-aspnet-mvc-async-pipeline&quot;&gt;The ASP.NET MVC Async Pipeline&lt;/h2&gt;

&lt;p&gt;Supporting asynchronous action filters is right at the top of my list. All of the code today used to invoke action filters lives in &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncControllerActionInvoker&lt;/code&gt;, so I figured it wouldn’t be &lt;em&gt;too hard&lt;/em&gt;. Unfortunately that’s where discovered that the MVC pipeline isn’t built around async/await, but rather classic APM.&lt;/p&gt;

&lt;p&gt;Let’s look at how the pipeline is layered today:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// This is the main entry point after a request is matched to a route
// (also called when rendering a child action)
class MvcHandler : IHttpAsyncHandler {
    IAsyncResult BeginProcessRequest(...)
    void EndProcessRequest(IAsyncResult)
}

// Called from MvcHandler
class Controller : IAsyncController {
    IAsyncResult BeginExecute(...)
    void EndExecute(IAsyncResult)
}

// Called from Controller
// Invokes MVC filters and executes ActionDescriptor
class AsyncControllerActionInvoker : IAsyncActionInvoker {
    IAsyncResult BeginInvokeAction(...)
    bool EndInvokeAction(IAsyncResult)
}

// Called from AsyncControllerActionInvoker
// Different concrete implementation based on whether it's a TPL or APM action
abstract class AsyncActionDescriptor {
    IAsyncResult BeginExecute(...)
    object EndExecute(IAsyncResult)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I want to rewrite &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncControllerActionInvoker&lt;/code&gt; so that its internal logic is based on async/await, which will hopefully clean up the code quite a bit. But I suspect that wrapping Task/APM at both the entry point and when calling to &lt;code class=&quot;highlighter-rouge&quot;&gt;AsyncActionDescriptor&lt;/code&gt; will result in some performance loss. Which means I might as well rewrite the &lt;em&gt;whole stack&lt;/em&gt;. But then this is a breaking change (like ASP.NET Core).&lt;/p&gt;

&lt;h2 id=&quot;getting-started&quot;&gt;Getting Started&lt;/h2&gt;

&lt;p&gt;The source code today is still hosted on &lt;a href=&quot;CodePlex&quot;&gt;https://aspnetwebstack.codeplex.com/&lt;/a&gt;. I decided to fork the repository and push my work to a branch on GitHub: &lt;a href=&quot;https://github.com/jdaigle/aspnetwebstack/tree/async-pipeline-cleanup&quot;&gt;https://github.com/jdaigle/aspnetwebstack/tree/async-pipeline-cleanup&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I’m not sure yet if I should modifying the code in &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Mvc&lt;/code&gt; and recompile, or if I should try implementing the stack in an separate assembly and replace at runtime (introducing breaking changes will obviously have an effect on that).&lt;/p&gt;

&lt;p&gt;Next time I hope to have a working build of the revised async pipeline (with all existing unit tests passing). And then I’ll take on designing an API for the async filters.&lt;/p&gt;

&lt;p&gt;But in the meantime if anyone has any comments or feedback please feel free to leave them below or contact me.&lt;/p&gt;

&lt;h3 id=&quot;update-2017-03-13&quot;&gt;Update: 2017-03-13&lt;/h3&gt;

&lt;p&gt;It seems that Microsoft is, in fact, &lt;a href=&quot;https://twitter.com/DamianEdwards/status/839506865830535169&quot;&gt;working on a 5.2.4 release&lt;/a&gt;. And there will be a new home for AspNetWebStack on &lt;a href=&quot;https://github.com/aspnet/aspnetwebstack&quot;&gt;GitHub&lt;/a&gt; eventually. In fact, you can find the nightlys of 5.2.4 on &lt;a href=&quot;https://www.myget.org/gallery/aspnetwebstacknightly/&quot;&gt;MyGet&lt;/a&gt;. So &lt;em&gt;maybe&lt;/em&gt; I could get some of my changes and ideas accepted once development is open again.&lt;/p&gt;

&lt;p&gt;Honestly I’m not sure why Microsoft isn’t doing 5.2.4 in the open already - it’s a bit disheartening.&lt;/p&gt;

&lt;h3 id=&quot;update-2017-05-07&quot;&gt;Update 2017-05-07&lt;/h3&gt;

&lt;p&gt;The &lt;a href=&quot;https://github.com/aspnet/aspnetwebstack&quot;&gt;AspNetWebStack&lt;/a&gt; repository is finally open.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/09/12/code-first-migrations-with-horton</id>
    <published>2016-09-12T00:00:00+00:00</published>
    <updated>
       2016-09-12T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/09/12/code-first-migrations-with-horton.html" />
		<title>&quot;Code-First&quot; Migrations with Horton</title>
		<content type="html">&lt;p&gt;Ask any MS SQL Server database expert about Entity Framework, particularly “code-first” migrations, and you’ll get responses like this:&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet&quot; data-conversation=&quot;none&quot; data-lang=&quot;en&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;&lt;a href=&quot;https://twitter.com/JosephDaigle&quot;&gt;@JosephDaigle&lt;/a&gt; &amp;quot;Code First&amp;quot; = Database Last.&lt;/p&gt;&amp;mdash; Geoff Hiten (@SQLCraftsman) &lt;a href=&quot;https://twitter.com/SQLCraftsman/status/763448503741931520&quot;&gt;August 10, 2016&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;It’s true. The entire concept of “code-first” can be distilled into one simple description; your application code generates your database schema. If you’re using EF migrations, then the typical workflow is to run &lt;em&gt;add-migration&lt;/em&gt; which compares your DbContext’s current model with what it thinks is the previous model (based on the last migration applied to the database) and generates a new migration from the difference.&lt;/p&gt;

&lt;p&gt;There are two fundamental problems with this “code-first” approach. First, EF generates awful defaults. For example, it’ll create an index for each foreign key of a table (whether you need it or not!). It also generates FK constraints with &lt;code class=&quot;highlighter-rouge&quot;&gt;ON DELETE CASCADE&lt;/code&gt;, something I rarely want in my schema. Developers will almost never change these defaults which can result in sub-optimal schemas.&lt;/p&gt;

&lt;p&gt;This directly leads to the other fundamental problem; auto-generated migrations allow developers to further distance themselves from the database. It’s easy to blindly trust the schema that EF generates. And ultimately I think this does actual harm by abstracting something (the database schema) which shouldn’t be abstracted in the first place!&lt;/p&gt;

&lt;p&gt;There a lot of other problems with EF migrations in general (such as poor tooling, lack of idempotency, and the requirement to implement “Down” migrations), but that’s content for another article.&lt;/p&gt;

&lt;h3 id=&quot;scaffolding-migrations-with-horton&quot;&gt;Scaffolding Migrations with Horton&lt;/h3&gt;

&lt;p&gt;Historically I’ve frowned upon scaffolding migrations. Despite this, I still often find myself copying/pasting existing migrations and changing names and identifiers - it’s so much easier to start from something rather than nothing. Also, teams that use EF “code-first” migrations are accustomed to &lt;em&gt;always&lt;/em&gt; scaffolding (in fact, there is no other way to add a migration).&lt;/p&gt;

&lt;p&gt;And so I think there might be a gap in a lot of SQL-migration-based tooling: a way to scaffold a new migration to reduce time and errors. But the keyword is “scaffold”: the migration should always be reviewed and cleaned up before committing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To this end, I’ve added an experimental feature to Horton to scaffold new database migrations.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The code &lt;a href=&quot;https://github.com/jdaigle/Horton/tree/migration_gen_plugin&quot;&gt;lives in a branch&lt;/a&gt;, with the most important class being the EF &lt;a href=&quot;https://github.com/jdaigle/Horton/blob/migration_gen_plugin/src/Horton.MigrationGenerator/EF6/DiffTool.cs&quot;&gt;DiffTool&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This feature uses EF’s “Metadata Workspace” to analyze the mapping entity model and compare it to a physical database schema. Specifically, the tool looks for new tables and schemas, new or altered columns, and new possible FK constraints.&lt;/p&gt;

&lt;p&gt;Why not dropped objects? Well, just because something was removed from the code doesn’t mean it should be removed from the database. This I think is another fundamental problem with EF’s “code-first” migrations.&lt;/p&gt;

&lt;p&gt;How does it work? Horton has learned a new command named &lt;code class=&quot;highlighter-rouge&quot;&gt;ADD-MIGRATION&lt;/code&gt;. You simply execute this command, and if any changes are detected then it will prompt for the “name” of the new migration to write. The migration is written to your migration directory and given the next sequence number.&lt;/p&gt;

&lt;p&gt;There are a couple of other minor points:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The command works from a strict set of conventions:&lt;/li&gt;
  &lt;li&gt;Your concrete DbContext implementation must have a constructor which accepts a connection string or connection string name.&lt;/li&gt;
  &lt;li&gt;The path to the assembly containing the DbContext is defined in a &lt;code class=&quot;highlighter-rouge&quot;&gt;dbcontext.path&lt;/code&gt; file in the root of your migrations directory. Relative paths are allowed, and encouraged.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since there is a dependency on EF, I didn’t want to add this feature to the core Horton.exe engine. And so I quickly invented a command plugin system. Commands are dynamically added at runtime via reflection. Right now it’s really simple: Horton simply scans its app domain directory for .NET assemblies and registers any new command it finds.&lt;/p&gt;

&lt;p&gt;A final word: this is an experiment and has not been used for production purposes &lt;em&gt;yet&lt;/em&gt;. There are still some issues to work out, particularly regarding “legacy” schema and models.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/06/27/organizating-cqrs-code</id>
    <published>2016-06-27T00:00:00+00:00</published>
    <updated>
       2016-06-27T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/06/27/organizating-cqrs-code.html" />
		<title>Code Organization, CQRS Style</title>
		<content type="html">&lt;p&gt;I am a &lt;a href=&quot;/2016/05/17/command-pattern-therapy.html&quot;&gt;huge believer&lt;/a&gt; in the Command/Query pattern for my applications’ internal services and APIs, particularly for those services that touch a database.&lt;/p&gt;

&lt;p&gt;But I’ve been constantly challenged with code organization. What is the right approach for a particular project and team?&lt;/p&gt;

&lt;p&gt;I think you might find a lot of .NET developers, especially those that use ASP.NET MVC, lean towards code organization &lt;em&gt;by function&lt;/em&gt;. What does this mean?&lt;/p&gt;

&lt;p&gt;So in ASP.NET MVC, we have separate folders (and therefore namespaces) for &lt;em&gt;Controllers&lt;/em&gt;, &lt;em&gt;Views&lt;/em&gt;, and pretty much anything else like our &lt;em&gt;Model&lt;/em&gt;, &lt;em&gt;ActionFilters&lt;/em&gt;, &lt;em&gt;Helpers&lt;/em&gt;, etc. This kind of insanity often manifests itself in other parts of the code base. Therefore we may end up with something like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyServiceProject/
├── Commands/
│   ├── SomeFeature/
│   │   ├── FeatureUseCaseCommand.cs
├── CommandHandlers/
│   ├── SomeFeature/
│   │   ├── FeatureUseCaseCommandHandler.cs
├── Queries/
│   ├── SomeFeature/
│   │   ├── FeatureUseCaseQuery.cs
├── QueryHandlers/
│   ├── SomeFeature/
│   │   ├── FeatureUseCaseQueryHandler.cs
│ ... etc...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Obviously I would prefer to invert the hierarchy and organize the code by feature. For example:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyServiceProject/
├── SomeFeature/
│   ├── Commands/
│   │   ├── FeatureUseCaseCommand.cs
│   ├── CommandHandlers/
│   │   ├── FeatureUseCaseCommandHandler.cs
│   ├── Queries/
│   │   ├── FeatureUseCaseQuery.cs
│   ├── QueryHandlers/
│   │   ├── FeatureUseCaseQueryHandler.cs
│ ... etc...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That’s a bit better. I’ve also tried flattening the hierarchy:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyServiceProject/
├── SomeFeature/
│   ├── FeatureUseCaseCommand.cs
│   ├── FeatureUseCaseCommandHandler.cs
│   ├── FeatureUseCaseQuery.cs
│   ├── FeatureUseCaseQueryHandler.cs
│ ... etc...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;While this has less ceremony, the code itself can really start to feel cluttered.&lt;/p&gt;

&lt;p&gt;But one day I had a thought: why does the &lt;em&gt;Command&lt;/em&gt; and &lt;em&gt;CommandHandler&lt;/em&gt; need to be in separate files? They’re likely to change together, so it’s not a violation of the Single Responsibility Principle. and you can easily define two classes in the same file. So now we have this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyServiceProject/
├── SomeFeature/
│   ├── FeatureUseCaseCommand.cs
│   ├── FeatureUseCaseQuery.cs
│ ... etc...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;That’s pretty clean. I’m also experimenting with nested types:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static class FeatureUseCase {

    public sealed class Command : ICommand {
        public string Data { get; set; }
    }

    public sealed class Handler : ICommandHandler&amp;lt;Command&amp;gt; {
        public void Handle(Command command) {
            // handle command
        }
    } 
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This, I think, is very cool. Instead of having &lt;em&gt;FooCommand&lt;/em&gt; and &lt;em&gt;FooCommandHandler&lt;/em&gt;, I simply have a class named &lt;em&gt;Foo&lt;/em&gt; with &lt;em&gt;Command&lt;/em&gt; and &lt;em&gt;Handler&lt;/em&gt; as nested types. Functionally it’s no different from the former design. But maybe this reads better. Additionally, if I later decide to add something like validation, I can simply add whatever classes/code I need as a new nested types. The related code lives together in a single code file, and my project is clean.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/05/17/command-pattern-therapy</id>
    <published>2016-05-17T00:00:00+00:00</published>
    <updated>
       2016-05-17T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/05/17/command-pattern-therapy.html" />
		<title>Command Pattern Therapy</title>
		<content type="html">&lt;p&gt;I was planning to write a lengthy article arguing about the merits of the command pattern and how it relates to “clean” web application design. But while researching for this article I rediscovered a series by Jimmy Bogard entitled &lt;em&gt;Put your controllers on a diet&lt;/em&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://lostechies.com/jimmybogard/2013/10/10/put-your-controllers-on-a-diet-redux/&quot;&gt;https://lostechies.com/jimmybogard/2013/10/10/put-your-controllers-on-a-diet-redux/&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://lostechies.com/jimmybogard/2013/10/22/put-your-controllers-on-a-diet-defactoring/&quot;&gt;https://lostechies.com/jimmybogard/2013/10/22/put-your-controllers-on-a-diet-defactoring/&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://lostechies.com/jimmybogard/2013/10/23/put-your-controllers-on-a-diet-a-survey/&quot;&gt;https://lostechies.com/jimmybogard/2013/10/23/put-your-controllers-on-a-diet-a-survey/&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://lostechies.com/jimmybogard/2013/10/29/put-your-controllers-on-a-diet-gets-and-queries/&quot;&gt;https://lostechies.com/jimmybogard/2013/10/29/put-your-controllers-on-a-diet-gets-and-queries/&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://lostechies.com/jimmybogard/2013/12/19/put-your-controllers-on-a-diet-posts-and-commands/&quot;&gt;https://lostechies.com/jimmybogard/2013/12/19/put-your-controllers-on-a-diet-posts-and-commands/&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Take 15 minutes and read them. Seriously, I’ll wait. By and large these articles cover pretty much every argument I would make for restructuring your web application and business logic API into sets of commands and queries.&lt;/p&gt;

&lt;p&gt;Here’s a quick recap of the the most important take-aways from his series:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The controller is a “lousy” place for business logic. And terrible for unit testing. We want them to be slim and basically only responsible for converting data to and from requests and responses.&lt;/li&gt;
  &lt;li&gt;Don’t further abstract existing abstractions. I.e., don’t bother creating wrappers around your ORM. And &lt;em&gt;please don’t&lt;/em&gt; create an &lt;code class=&quot;highlighter-rouge&quot;&gt;IRepository&amp;lt;T&amp;gt;&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;IUnitOfWork&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;GET/POST should conform to semantics. A POST is a “command” and a GET is a “query”. Queries should have no side effects (other than logging, etc.) and return data. A command may mutate state, and returns a status code and sometimes a resource identifier.&lt;/li&gt;
  &lt;li&gt;Design your business logic API using objects representing “command” and “query” operations. These operations are handled by a mediator with a &lt;em&gt;single interface&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;I want to focus on that last point: building a single service interface.&lt;/strong&gt; Far too many applications I’ve seen suffer from a new type of “dependency hell”. It’s not uncommon to see a Controller with a constructor that has literally &lt;em&gt;dozens&lt;/em&gt; of “service” and “repository” interface parameters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interfaces are terrible for designing a constantly evolving businesss API.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interfaces have a number of problems. When I’m adding a new operation, should I create a new interface or should I add it to an existing interface? If so, which one?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adding a member to an interface is a breaking change.&lt;/strong&gt; Granted, in most applications there is only a single implementation (which begs the question, &lt;em&gt;why do we even need the interface&lt;/em&gt;?). But often we create mock/stub implementations for unit tests. And all of those tests need to be updated even if we’re not touching those features!&lt;/p&gt;

&lt;p&gt;It’s usually quite difficult to implement cross cutting concerns with interface-based services. Such as database transactions (you &lt;em&gt;are&lt;/em&gt; using explicit database transactions right?) and auditing/logging. There are some neat proxy frameworks out there that generate runtime code which proxy the interface calls and allow you to implement these cross cutting concerns. But it doesn’t &lt;em&gt;feel&lt;/em&gt; right to me.&lt;/p&gt;

&lt;p&gt;In my view, the command pattern is ideal as it clearly represents a pipeline:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;HTTP POST → Controller Action → Create Command → Execute → [stuff] → Handler → Return
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The POST is handled by a controller action. The controller action is responsible for a) creating a command and b) passing it to the command processing engine. The command processing engine executes a pre-configured pipeline of “behaviors”. You can think of these as not unlike ActionFilters in ASP.NET MVC. These can be anything from starting a database transaction/unit of work, to security checks, to logging and auditing. Ultimately the associated command handler method is called, passing the command object as a parameter.&lt;/p&gt;

&lt;p&gt;In fact, you could go so far as to allow ASP.NET MVC to create the command object and bind the properties:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[HttpPost]
public ActionResult CreateCustomer(CreateCustomerCommand command) {
    command.Validate(); // ensure the command properties are all valid from the POST
    CommandProcessor.Execute(command);
    return OK;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;How awesome is that? And the best part is that adding new features typically doesn’t require modifying existing code. Instead we’re just adding new classes.&lt;/p&gt;

&lt;p&gt;In fact, we can take it further and get rid of our dependency on a dependency injection framework. But that’s an argument best left for another article.&lt;/p&gt;

&lt;p&gt;I wouldn’t necessarily always design my application this way. It can be overkill for small apps that rarely change. However, &lt;strong&gt;for larger applications that are constantly changing, the command pattern is invaluable.&lt;/strong&gt; Software architecture is all about managing dependencies and churn. How easily can you add new features without touching existing code or introducing new dependencies?&lt;/p&gt;

&lt;p&gt;I strongly recommend that you consider using a single command/query framework for your business logic services, such as &lt;a href=&quot;https://github.com/jbogard/MediatR&quot;&gt;MediatR&lt;/a&gt;. Or &lt;a href=&quot;/2016/05/12/evolving-command-handler-design.html&quot;&gt;write your own&lt;/a&gt;, it’s not that hard and can be fun.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/05/12/evolving-command-handler-design</id>
    <published>2016-05-12T00:00:00+00:00</published>
    <updated>
       2016-05-12T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/05/12/evolving-command-handler-design.html" />
		<title>Evolving Command Handler Design</title>
		<content type="html">&lt;p&gt;It’s no surprise that I’m a big fan of the command and mediator patterns when building business logic and service APIs. Particularly when compared to the traditional approach to abstracting services: C# interfaces with methods.&lt;/p&gt;

&lt;p&gt;It’s awesome to be able to reduce &lt;em&gt;all&lt;/em&gt; of your service interfaces down to just one:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public interface IServiceAPI
{
    TResult Execute&amp;lt;TCommand&amp;gt;(TCommand command);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But this article is not about the merits of the pattern, or how to design your API layer. This article is going focus on my evolving ideas around implementing the actual command “handler” logic.&lt;/p&gt;

&lt;h3 id=&quot;in-the-beginning&quot;&gt;In the beginning&lt;/h3&gt;

&lt;p&gt;My very first technique is borrowed directly from NServiceBus when I first introduced to it seven years ago.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public interface ICommandHandler&amp;lt;TCommand, TResult&amp;gt;
{
    TResult Execute(TCommand command);
}

public class MyCommandHandler : ICommandHander&amp;lt;MyCommand, MyCommandResult&amp;gt;
{
    public MyCommandHandler(DbContext ... etc)
    {
        // ... set instance variables
    }
    
    public MyCommandResult Execute(MyCommand command)
    {
        // ... do stuff, access instance variables/etc.
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;It’s very simple&lt;/strong&gt;: each command is handled by a class that implements &lt;code class=&quot;highlighter-rouge&quot;&gt;ICommandHandler&amp;lt;TCommand&amp;gt;&lt;/code&gt;. A particular class &lt;em&gt;can&lt;/em&gt; implement multiple command handlers, however in practice Single Responsibility Principal (SRP) kicks in and you would typically create a separate class per command.&lt;/p&gt;

&lt;p&gt;Dependency injection in very straightforward too. Dependencies are supplied to the class’ constructor at runtime; often the command handler itself is constructed and managed by some IoC framework.&lt;/p&gt;

&lt;p&gt;During application startup the bootstrapping system will scan for non-abstract types that implement the command handler interface and register them against the command types. At runtime, the class is dynamically created and the method invoked. It’s no surprise that this approach is quite similar to how ASP.NET MVC controllers and actions work. In fact I’ve borrowed &lt;a href=&quot;https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/ActionMethodDispatcher.cs&quot;&gt;techniques from its code&lt;/a&gt; in my own frameworks.&lt;/p&gt;

&lt;p&gt;So while the code is simple to understand, &lt;strong&gt;it is a lot of ceremony and boilerplate&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;enter-functions&quot;&gt;Enter functions&lt;/h3&gt;

&lt;p&gt;Consider this: &lt;em&gt;an interface that defines only a single method is not an interface; it is a delegate&lt;/em&gt;. Why do we need to instantiate a class just to call our command handler function? What if we designed it just as a static method?&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static MyCommandResult Execute(MyCommand command)
{
    // do stuff
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We can simply declare, somewhere, a static method that matches our “interface”, or delegate: &lt;code class=&quot;highlighter-rouge&quot;&gt;public delegate TResult Execute&amp;lt;TCommand&amp;gt;(command);&lt;/code&gt;. Now it’s trivial to wire up code that executes appropriate delegate when a command of type &lt;code class=&quot;highlighter-rouge&quot;&gt;TCommand&lt;/code&gt; is supplied.&lt;/p&gt;

&lt;p&gt;That’s great, but what about my dependencies? Functional programming has solved this with &lt;a href=&quot;https://en.wikipedia.org/wiki/Currying&quot;&gt;currying&lt;/a&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static MyCommandResult Execute(MyCommand command, IDependency foo, IOtherDependency bar)
{
    // do stuff
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The idea is that our framework will, at runtime, compile a new expression that calls our command handler method with resolved dependencies. That compiled expression will match the common delegate. Again, this is nothing new - ASP.NET MVC does this with model binding of action parameters. And we have one fewer allocation since we’re not creating an instance of a class just to call a method.&lt;/p&gt;

&lt;p&gt;As far as automatically registering command handlers, there are a few techniques I’ve used the past. But the simplest has been to decorate each command handler method with an attribute, such as &lt;code class=&quot;highlighter-rouge&quot;&gt;[CommandHandlerAttribute]&lt;/code&gt;. This makes it super easy, at runtime, to scan and find the matching methods.&lt;/p&gt;

&lt;p&gt;I’ve experimented with static registration techniques, but they’re not pretty. I think this is mostly due to limitations in the expressiveness of C#. You can find an &lt;a href=&quot;https://gist.github.com/jdaigle/aa10e138e2802b3c42c09e3c906c0fdc&quot;&gt;example here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now we have lightweight static methods that are dynamically invoked.&lt;/strong&gt; But where do we put them? Unfortunately for .NET, all methods including static methods must be declared on a class. Do we create one static class per handler? Do we put them all in one giant class? How do we group them? How should we name the static class? I suppose this is a really minor concern, but it annoys me because naming and organization can be difficult.&lt;/p&gt;

&lt;h3 id=&quot;the-next-generation&quot;&gt;The next generation&lt;/h3&gt;

&lt;p&gt;While thinking about the “problem” of organizing my command handlers, I was recently made a connection to how frameworks like &lt;a href=&quot;http://nancyfx.org/&quot;&gt;NancyFx&lt;/a&gt; define modules. If you look at a typical &lt;a href=&quot;https://github.com/NancyFx/Nancy/wiki/Exploring-the-nancy-module&quot;&gt;Nancy module&lt;/a&gt; you might notice that, in a way, it’s just defining and mapping command handlers (pedantically speaking they’re “HTTP request” handlers, but conceptually the same).&lt;/p&gt;

&lt;p&gt;What if instead of a “NancyModule” we could build a “CommandModule”?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Caveat: this is all experimental. I’ve not tried this technique in production code.&lt;/em&gt;&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class ProductModule : CommandModule
{
    public ProductModule(IFoo foo, IBar bar)
    {
        Handle&amp;lt;AddProductModel&amp;gt;(command =&amp;gt;
        {
            foo.Something();
            return 1;
        });

        Handle&amp;lt;AddProductReview&amp;gt;(command =&amp;gt;
        {
            foo.Something();
            bar.SomethingElse();
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The way this, like NancyFx, works: on startup “modules” are discovered and initially constructed. This first pass results in a registry that maps the “request” (command type in my case) to a particular module and lambda. At runtime, when a “request” (i.e. command) is executed, the appropriate module is constructed and the corresponding lambda is executed.&lt;/p&gt;

&lt;p&gt;There are some interesting properties about this design:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The command handler lambda can compile with a closure around any referenced dependencies, which are passed via the module constructor.&lt;/li&gt;
  &lt;li&gt;When the command is executed, we do instantiate an instance of the module (one per “request”).&lt;/li&gt;
  &lt;li&gt;If the lambda was compiled with a closure, then another class is instantiated (one per “request”) with the captured references.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That is extra overhead, but maybe it’s a good tradeoff in order to have more expressive code? This seems like the perfect way to organize this code. Each module can be built with a clear and single purpose. I can use existing IoC frameworks to handle module construction and dependency injection. The framework itself becomes a lot simpler.&lt;/p&gt;

&lt;p&gt;Some brainstorming: Maybe there is a way to compile an expression which skips the module construction at runtime. We know about the about the &lt;code class=&quot;highlighter-rouge&quot;&gt;MethodInfo&lt;/code&gt; of the lambda. So we know about the anonymous &lt;code class=&quot;highlighter-rouge&quot;&gt;DeclaringType&lt;/code&gt;. If the &lt;code class=&quot;highlighter-rouge&quot;&gt;DeclaringType&lt;/code&gt; is for a closure, we can inspect it’s fields. At runtime, we can construct that object and populate the fields from an IoC container. Then use that call the method. So that’s one fewer allocation.&lt;/p&gt;

&lt;h3 id=&quot;wrapping-up&quot;&gt;Wrapping up&lt;/h3&gt;

&lt;p&gt;Over the years my ideas and design for command handlers has evolved.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;First were full-blown classes implementing a interface.&lt;/li&gt;
  &lt;li&gt;Then I reduced those down to simple static methods that live &lt;em&gt;somewhere&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Finally, I’ve experimented with “modules” that declare command handlers as lambdas.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each technique has pros and cons. Different applications, or contexts within a single application, may be suited to one technique over another. Some teams might be comfortable with one technique over another. But I’m curious about you, dear reader, and what technique you like and why?&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/04/13/modern-joel-test</id>
    <published>2016-04-13T00:00:00+00:00</published>
    <updated>
       2016-04-13T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/04/13/modern-joel-test.html" />
		<title>The Modern Joel Test</title>
		<content type="html">&lt;p&gt;&lt;a href=&quot;http://www.joelonsoftware.com/articles/fog0000000043.html&quot;&gt;The Joel Test&lt;/a&gt; is a classic article written &lt;a href=&quot;http://www.joelonsoftware.com/&quot;&gt;Joel Spolsky&lt;/a&gt; that describes 12 criteria often cited as useful to prospective employees when looking for a new software job.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;The Joel Test&lt;/strong&gt;&lt;/p&gt;

  &lt;ol&gt;
    &lt;li&gt;Do you use source control?&lt;/li&gt;
    &lt;li&gt;Can you make a build in one step?&lt;/li&gt;
    &lt;li&gt;Do you make daily builds?&lt;/li&gt;
    &lt;li&gt;Do you have a bug database?&lt;/li&gt;
    &lt;li&gt;Do you fix bugs before writing new code?&lt;/li&gt;
    &lt;li&gt;Do you have an up-to-date schedule?&lt;/li&gt;
    &lt;li&gt;Do you have a spec?&lt;/li&gt;
    &lt;li&gt;Do programmers have quiet working conditions?&lt;/li&gt;
    &lt;li&gt;Do you use the best tools money can buy?&lt;/li&gt;
    &lt;li&gt;Do you have testers?&lt;/li&gt;
    &lt;li&gt;Do new candidates write code during their interview?&lt;/li&gt;
    &lt;li&gt;Do you do hallway usability testing?&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;It was written &lt;em&gt;nearly 16 years ago&lt;/em&gt; and is still applicable today. For instance, you’d be surprised how many software shops still don’t use source control.&lt;/p&gt;

&lt;p&gt;But for contemporary software development, I think the test could use a few updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Do you use &lt;em&gt;modern&lt;/em&gt; source control?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;These days it’s not always enough to use source control. Developers often expect or demand to work with the best tools available. Such as Git or Mercurial (if anyone still uses that). You’ll find a lot of shops still using SVN or TFSVC. And that’s fine, but I think there are huge productivity gains to be had by adopting Git or Hg.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Can you make a build in one step?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nothing new here. Except that it’s common for builds to be scripted using something like make/rake/psake or some other task runner. Those scripts should be committed and versioned alongside the source code. XML build configurations are out, builds scripts are in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Do you use &lt;em&gt;Continuous Integration with automated builds&lt;/em&gt;?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Daily builds are a thing of the past. Automated CI builds are basically &lt;em&gt;want you need&lt;/em&gt; to develop quality software.&lt;/p&gt;

&lt;p&gt;And in the case of SaaS, I would take it a step further: &lt;strong&gt;do you automate deployment into your qa/staging/prod environments?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Do you have a bug database?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As most shops are practicing some form of “agile” development whereby requirements are represented as user stories or tasks in a backlog, bug tracking is usually integrated into that workflow. There are &lt;em&gt;countless&lt;/em&gt; tools available: TFS, Jira, Pivotal Tracker, etc.&lt;/p&gt;

&lt;p&gt;However I think it’s important that the development teams control these tools - there’s nothing worse than having a workflow dictated by management. Developers &lt;em&gt;hate&lt;/em&gt; paperwork and documentation, and neither directly result in higher quality software.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Do you fix bugs before writing new code?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nothing to do add here.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Do you have an up-to-date schedule?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What are you iterations like? Is it more SCRUM with strict time-boxed sprints, or is it a looser kanban approach? When and how are planning/retrospective meetings held? Standups?&lt;/p&gt;

&lt;p&gt;How do you plan/schedule work on technical debt and other non-user-story tasks?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Do you have a spec?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How is the backlog managed? Who are the product owners and business analysts? Are user stories well written and include screenshots and acceptance criteria?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Do programmers have quiet working conditions?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Said differently, &lt;strong&gt;do you have an open office plan?&lt;/strong&gt; This is probably quite subjective, but I personally hate open or shared offices.&lt;/p&gt;

&lt;p&gt;How are meetings scheduled? As a developer, can I block off my morning and/or afternoon such that &lt;em&gt;no meetings are allowed&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;Can I work remotely? Are there communication and collaboration tools in place to facilitate remote workers?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Do you use the best tools money can buy?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Do I get to control what’s installed on my machine? Do you use a proxy server or otherwise limit my Internet access? In the “enterprise” world it’s very common to find restrictions which actively prevent a software developer from doing his or her job.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. Do you have testers?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Do you do automated testing?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;11. Do new candidates write code during their interview?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I’m not going to open this can of worms today…&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;12. Do you do hallway usability testing?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I think some take this rule too literally - especially regarding remote teams. Everybody can do screen sharing these days with ease.&lt;/p&gt;

&lt;p&gt;It’s definitely important, but there’s a balance to find and it’s hard. You don’t want to just interrupt other people and drag them into your space to look at something, but you also don’t want to burden folks with meetings and scheduling.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/04/12/all-about-the-pentiums</id>
    <published>2016-04-12T00:00:00+00:00</published>
    <updated>
       2016-04-12T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/04/12/all-about-the-pentiums.html" />
		<title>It's All About the Pentiums</title>
		<content type="html">&lt;p&gt;A couple of months ago I wrote about &lt;a href=&quot;/2015/12/03/search-for-ultimate-dev-laptop.html&quot;&gt;searching for the ultimate dev laptop&lt;/a&gt;. Today there are some updates, but I’m going to focus on the processors. In this case, I’m looking at the top-of-the-line model each:&lt;/p&gt;

&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Model&lt;/th&gt;
            &lt;th&gt;Family&lt;/th&gt;
            &lt;th&gt;Number&lt;/th&gt;
            &lt;th&gt;Speed/Cores&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
        &lt;tr&gt;
            &lt;td&gt;Apple MacBook Pro 13&quot; (early-2015)&lt;/td&gt;
            &lt;td&gt;&quot;Broadwell-U&quot; (5th gen)&lt;/td&gt;&lt;td&gt;5557U&lt;/td&gt;&lt;td&gt;2 x 3.1GHz&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;Apple MacBook Pro 15&quot; (mid-2015)&lt;/td&gt;
            &lt;td&gt;&quot;Haswell-H&quot; (4th gen)&lt;/td&gt;&lt;td&gt;4980HQ&lt;/td&gt;&lt;td&gt;4 x 2.8GHz&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;Dell Latitude E5470&lt;/td&gt;
            &lt;td&gt;&quot;Skylake-H&quot; (6th gen)&lt;/td&gt;&lt;td&gt;6820HQ&lt;/td&gt;&lt;td&gt;4 x 2.7GHz&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;Dell XPS 13&lt;/td&gt;
            &lt;td&gt;&quot;Skylake-U&quot; (6th gen)&lt;/td&gt;&lt;td&gt;6560U&lt;/td&gt;&lt;td&gt;2 x 2.7GHz&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;Lenovo T460s&lt;/td&gt;
            &lt;td&gt;&quot;Skylake-U&quot; (6th gen)&lt;/td&gt;&lt;td&gt;6600U&lt;/td&gt;&lt;td&gt;2 x 2.6GHz&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Some notes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Apple has &lt;em&gt;still not released or announced&lt;/em&gt; updated MacBook Pros. Hence, they are a generation behind.&lt;/li&gt;
  &lt;li&gt;Dell has updated their Latitudes to latest processors. But the 6820HQ is technically the &lt;em&gt;older&lt;/em&gt; Skylake-H.&lt;/li&gt;
  &lt;li&gt;I’m now also comparing the Dell XPS 13. It’s even smaller than the Latitude. It has Thunderbolt instead of HDMI. It’s also touch, and perhaps a bit under-powered. But not severely. The biggest difference is that you can upgrade the HD and some other components.&lt;/li&gt;
  &lt;li&gt;Lenovo has also updated their T series. The Skylake-U is the “low power” processor.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So I’m still torn. I’m definitely going to wait and see what Apple does this summer.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/04/07/speaking-at-sqlsaturday-atlanta</id>
    <published>2016-04-07T00:00:00+00:00</published>
    <updated>
       2016-04-07T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/04/07/speaking-at-sqlsaturday-atlanta.html" />
		<title>Speaking at SQLSaturday Atlanta in May</title>
		<content type="html">&lt;p&gt;I’ll be speaking at &lt;a href=&quot;http://www.sqlsaturday.com/521/EventHome.aspx&quot;&gt;SQLSaturday&lt;/a&gt; in Atlanta on May 21, 2016. This is really exciting since it’s my first professional public speaking engagement.&lt;/p&gt;

&lt;p&gt;My session is called &lt;a href=&quot;http://www.sqlsaturday.com/521/Sessions/Details.aspx?sid=48794&quot;&gt;Data Access for Performance Junkies&lt;/a&gt;. Subtitled “or: How I Learned to Stop Worrying and Love the ORM.”&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;ORM frameworks get a bad rap for their performance characteristics and complexity. But like any tool, it’s all about learning to use correctly and intelligently. In this session we’ll look at how application developers often use (and misuse!) these tools, and identify and correct problematic usage patterns. We’ll also discover when it’s appropriate to use an ORM, when it’s not, and how incorporate “raw” SQL where it makes sense.&lt;/p&gt;
&lt;/blockquote&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/04/03/introducing-horton</id>
    <published>2016-04-03T00:00:00+00:00</published>
    <updated>
       2016-04-03T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/04/03/introducing-horton.html" />
		<title>Introducing Horton</title>
		<content type="html">&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/File:Horton_the_Elephant.jpg&quot;&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/en/d/d5/Horton_the_Elephant.jpg&quot; alt=&quot;Horton&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3 id=&quot;what-is-horton&quot;&gt;What is Horton?&lt;/h3&gt;

&lt;p&gt;Horton is the simple database migration utility. It’s a little program that does one thing: enables versioning of database schema through SQL based migration scripts.&lt;/p&gt;

&lt;p&gt;You’ll find a “&lt;strong&gt;getting started guide&lt;/strong&gt;” in the project’s &lt;a href=&quot;https://github.com/jdaigle/Horton&quot;&gt;GitHub repository&lt;/a&gt;. Horton is also released through GitHub. You can find and download the latest release from the &lt;a href=&quot;https://github.com/jdaigle/Horton/releases&quot;&gt;releases tab&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;what-does-it-do&quot;&gt;What does it do?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;It may help to read this first&lt;/strong&gt;: I recently &lt;a href=&quot;/2016/04/02/database-versioning-showdown.html&quot;&gt;wrote about database versioning with migrations&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Horton handles migrations for schema  objects &lt;em&gt;and desired state&lt;/em&gt; for “code” like objects (stored procedures, views, etc.). It was written to help apply database change scripts to production servers in a fully predictable and automated fashion (i.e. continuous deployment). It’s grown a number of features in recent years, but has never strayed from its very focused purpose.&lt;/p&gt;

&lt;h3 id=&quot;why-am-i-introducing-it-now-at-version-40&quot;&gt;Why am I “Introducing” it now at version 4.0?&lt;/h3&gt;

&lt;p&gt;Horton is actually the latest incarnation of a SQL migration tool I wrote almost seven years ago. The first commit was in September 2009! And even though it was &lt;em&gt;published&lt;/em&gt; on GitHub, it was always just an internal tool and I never treated it as a real open source project. But I’m trying to change that.&lt;/p&gt;

&lt;p&gt;Versions 1-3 did not strictly follow &lt;a href=&quot;http://semver.org/&quot;&gt;semantic versioning&lt;/a&gt; either. There were few, if any, breaking changes over its lifetime.&lt;/p&gt;

&lt;p&gt;For version 4, I decided to rewrite it.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I rewrote the command line parser. Actually, it uses &lt;a href=&quot;http://www.ndesk.org/Options&quot;&gt;NDesk.Options&lt;/a&gt; which is the best .NET command line parser I know of. The command line arguments are similar, but different. Notably you can execute different COMMANDs from the same tool.&lt;/li&gt;
  &lt;li&gt;I redesigned the &lt;code class=&quot;highlighter-rouge&quot;&gt;schema_info&lt;/code&gt; table. This is biggest breaking change as it renders the tool entirely incompatible with previous version. There’s an open GitHub issue suggesting how solve this if it becomes a problem (though highly unlikely because not many projects used the old tool!).&lt;/li&gt;
  &lt;li&gt;There’s cleaner separation between database specific code and the general horton program code. Data access is all based on ADO.NET, so in theory I should be able to support any provider.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’d love for folks to give it a try and provide feedback. Enjoy!&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/04/02/database-versioning-showdown</id>
    <published>2016-04-02T00:00:00+00:00</published>
    <updated>
       2016-04-02T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/04/02/database-versioning-showdown.html" />
		<title>The Database Versioning Showdown</title>
		<content type="html">&lt;p&gt;Versioning of your database schema is an important component of mature software development. Depending on your database system there are number of tools available to version your schema. While most are adequate for of version control, many are not necessarily well designed for the &lt;em&gt;deployment&lt;/em&gt; of schema changes.&lt;/p&gt;

&lt;p&gt;A lot of dev shops these days are practicing some form of continuous deployment (CD). This is particular useful to those who are building software-as-a-service (SaaS). The ability to go from source to a working application, including the database, is critical.&lt;/p&gt;

&lt;p&gt;While focusing on relational databases, most tools fall into one of two camps: 1) model based or 2) migration based.&lt;/p&gt;

&lt;h3 id=&quot;model-based-version-control&quot;&gt;Model Based Version Control&lt;/h3&gt;

&lt;p&gt;What I’m calling &lt;strong&gt;model based&lt;/strong&gt; version control refers to maintaining each object in the database (table, view, stored procedure, etc.) as a separate file in your version control system. Most often it takes the form of a SQL script containing the necessary &lt;code class=&quot;highlighter-rouge&quot;&gt;CREATE&lt;/code&gt; commands for the corresponding database object.&lt;/p&gt;

&lt;p&gt;Perhaps the two most popular tools, particularly in the .NET community are &lt;a href=&quot;http:/www.red-gate.com/products/sql-development/sql-source-control/&quot;&gt;Redgate’s SQL Source Control&lt;/a&gt; and &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/hh272702(v=vs.103).aspx&quot;&gt;SQL Server Data Tools (SSDT) database projects&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It’s easy to see how this approach provides excellent visibility into changes that are made to the schema. E.g. you can easily see the history of an individual object and also see line-by-line annotations.&lt;/p&gt;

&lt;p&gt;When it comes time to deploy, either upgrading an existing database instance or setting up a brand new one, the model represents a &lt;strong&gt;desired state&lt;/strong&gt;. Generally some tool is responsible for &lt;em&gt;comparing&lt;/em&gt; the model versus the existing state of a target database and generating an upgrade script. Some tools do a better job than others when it comes to determining the most efficient and &lt;em&gt;correct&lt;/em&gt; script to get to the desired state. But regardless, you’re relying on some algorithm to figure it out.&lt;/p&gt;

&lt;p&gt;The biggest danger of desired state upgrades is the &lt;strong&gt;potential for data loss&lt;/strong&gt;. A schema comparison tool will do it’s best to determine how to alter the schema correctly without data loss, for example renaming a column rather than dropping/adding, but it’s bound to make a mistake.&lt;/p&gt;

&lt;h3 id=&quot;migration-based-version-control&quot;&gt;Migration Based Version Control&lt;/h3&gt;

&lt;p&gt;Rather that representing the database as a model in your version control system, &lt;strong&gt;migrations&lt;/strong&gt; are a set of sequentially executable scripts that iteratively alter a database’s schema. Often just SQL scripts, and using a naming convention that may include a numeric prefix for ordering, migration scripts are usually very simple to reason about.&lt;/p&gt;

&lt;p&gt;They’re often written “by hand” to execute specific changes in a precise order. As a result there’s &lt;strong&gt;far less risk of data loss&lt;/strong&gt; as it’s easier to predict the script’s affects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Migrations are also efficient.&lt;/strong&gt; Instead of comparing and generating a change script, we simply execute the migrations that haven’t been run yet in the correct order. Often a special database table is used to maintain information about the migration scripts that have been executed.&lt;/p&gt;

&lt;p&gt;I &lt;em&gt;think&lt;/em&gt; database migrations first became really popular as part of the ActiveRecord ORM in Rails (i.e. Ruby on Rails) as far back as 2005-2006. You wrote “up” and “down” migrations in Ruby, and a tool that shipped with Rails would upgrade/downgrade the database accordingly. When building later versions of Entity Framework, Microsoft adopted a similar pattern for database migrations as part of their “code-first” database strategy. In a future article I’ll discuss why you don’t need another domain specific language (DSL) on top of SQL, and why it might actually be harmful.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But migrations aren’t perfect.&lt;/strong&gt; They require discipline. They usually require that &lt;em&gt;all database changes&lt;/em&gt; execute as a migration so that the schema is never “out of sync”. But I argue that this discipline is &lt;em&gt;a good thing&lt;/em&gt; as all changes are consistently version controlled and tracked. However, if it’s possible or it’s likely that the schema will be modified outside of migrations then the “desired state” model may in fact work better.&lt;/p&gt;

&lt;h3 id=&quot;why-not-both&quot;&gt;Why not both?&lt;/h3&gt;

&lt;blockquote class=&quot;twitter-tweet&quot; data-lang=&quot;en&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;wanted: DB migrations for schema, DB projects for sprocs/functions&lt;/p&gt;&amp;mdash; Jimmy Bogard (@jbogard) &lt;a href=&quot;https://twitter.com/jbogard/status/710188482279288832&quot;&gt;March 16, 2016&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;Clearly migrations are better suited for schema changes in which data preservation is critical. They naturally map to the how a DBA or developer may make changes: as a set of iterative commands performed step-by-step.&lt;/p&gt;

&lt;p&gt;However some database objects, such as stored procedures, views, and functions, &lt;em&gt;can&lt;/em&gt; exist independently of the underlying schema. They’re also not really tied to data &lt;em&gt;per se&lt;/em&gt;. Instead they’re more of an abstraction over the relational model. Stored procedures and functions, in particular, are almost “code” by their nature. So it does make sense to treat these like “classes” or code modules that are modified over time.&lt;/p&gt;

&lt;p&gt;Ideally we would have a tool that mixes both migrations and model/desired state. Fortunately these tools exist! In fact I wrote such a tool almost seven years ago (!!) which I now call &lt;a href=&quot;https://github.com/jdaigle/Horton&quot;&gt;Horton (https://github.com/jdaigle/Horton)&lt;/a&gt;. While researching for this article I stumbled across some other .NET based tools. One in particular that stoop out is &lt;a href=&quot;https://github.com/chucknorris/roundhouse&quot;&gt;RoundHousE (https://github.com/chucknorris/roundhouse)&lt;/a&gt;. It’s &lt;em&gt;not quite as old as Horton&lt;/em&gt;, but it’s been around long enough and seems has a well defined community, so it warrants attention.&lt;/p&gt;

&lt;p&gt;I suggest checking these out and figuring out how they might work in your continuous deployment strategy.&lt;/p&gt;

&lt;h3 id=&quot;further-reading&quot;&gt;Further Reading&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://enterprisecraftsmanship.com/2015/08/10/database-versioning-best-practices/&quot;&gt;Database versioning best practices&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://enterprisecraftsmanship.com/2015/08/18/state-vs-migration-driven-database-delivery/&quot;&gt;State vs migration-based database delivery&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/02/25/integrating-aspnet-mvc-and-webapi</id>
    <published>2016-02-25T00:00:00+00:00</published>
    <updated>
       2016-02-25T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/02/25/integrating-aspnet-mvc-and-webapi.html" />
		<title>Integrating ASP.NET MVC and WebAPI</title>
		<content type="html">&lt;p&gt;The &lt;em&gt;current&lt;/em&gt; versions of ASP.NET MVC and WebAPI (5.x) exists as two separate frameworks. Each has it’s own routing conventions, model binding, action filters, dependency resolver, controller factory, configuration patterns, etc. And if you dig into the &lt;a href=&quot;https://aspnetwebstack.codeplex.com/SourceControl/latest&quot;&gt;source code&lt;/a&gt; you’ll find A LOT over overlapping code; it’s practically copy/paste between the namespaces.&lt;/p&gt;

&lt;p&gt;But this does not mean you cannot mix the two together.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://odetocode.com/about/scott-allen&quot;&gt;Scott Allen&lt;/a&gt; has an &lt;a href=&quot;http://odetocode.com/blogs/scott/archive/2013/07/01/on-the-coexistence-of-asp-net-mvc-and-webapi.aspx&quot;&gt;excellent article&lt;/a&gt; in which he describes when to use each framework and when it might be appropriate to use both in the same project.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;I’ve gotten more than a few questions over the last year on how to use the ASP.NET MVC framework and the Web API framework together. Do they work together? Should they work together? When should you use one or the other?&lt;/p&gt;

  &lt;p&gt;Here’s some general rules of thumb I use.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Because each framework has it’s own separate processing pipeline, you need to consider carefully whether you &lt;em&gt;really need&lt;/em&gt; both frameworks in the same project. Especially if you do important things with routing and action filters, such as authentication or authorization - it’ll take extra work to share code and algorithms between the two.&lt;/p&gt;

&lt;p&gt;Fortunately the future is bright. ASP.NET Core promises to finally unify the frameworks.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders</id>
    <published>2016-02-19T00:00:00+00:00</published>
    <updated>
       2016-02-19T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html" />
		<title>Aftermarket ASP.NET MVC - Part 5 - Feature Folders</title>
		<content type="html">&lt;p&gt;This is &lt;strong&gt;part 5&lt;/strong&gt; of a multi-part series on “fixing” some of the inherit design problems with ASP.NET MVC.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-1.html&quot;&gt;Part 1 - Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;Part 2 - The View Engine&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html&quot;&gt;Part 3 - View Model Conventions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;Part 4 - Routing and URL Generation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html&quot;&gt;Part 5 - Feature Folders&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Part 6 - ActionResults and Content Negotiation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’ve also setup a &lt;a href=&quot;https://github.com/jdaigle/aspnetmvc5demo&quot;&gt;repository on GitHub&lt;/a&gt; that includes many of these experiments and implementations.&lt;/p&gt;

&lt;p&gt;Expanding on the theme from last time:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Don’t let your routing solution dictate how to organize your code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;ASP.NET MVC establishes the convention of putting all of your &lt;em&gt;controllers&lt;/em&gt; inside of a &lt;code class=&quot;highlighter-rouge&quot;&gt;Controllers\&lt;/code&gt; directory and all of your &lt;em&gt;views&lt;/em&gt; instead of a &lt;code class=&quot;highlighter-rouge&quot;&gt;Views\&lt;/code&gt; directory. This is, no surprise, extremely similar to the convention established by &lt;a href=&quot;http://rubyonrails.org/&quot;&gt;Rails&lt;/a&gt;. Remember that Rails was the new-hotness when ASP.NET MVC was first developed around 2007-2008.&lt;/p&gt;

&lt;p&gt;A prototypical ASP.NET MVC source code layout:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyApp/
├── assets/
│   ├── site.css
├── Controllers/
│   ├── HomeController.cs
│   ├── ProductsController.cs
├── Views/
│   ├── Home/
│   │   ├── HomePage.cshtml
│   │   ├── AboutPage.cshtml
│   ├── Products/
│   │   ├── Index.cshtml
│   │   ├── Detail.cshtml
│   ├── Shared/
│   │   ├── _Layout.cshtml
│   ├── _ViewStart.cshtml
│   ├── Web.config
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Yuck!&lt;/p&gt;

&lt;p&gt;A lot of people have written about how this is just a terrible way to organize your code. At the top level, you don’t see &lt;em&gt;your application&lt;/em&gt;. You see an MVC framework details leaking through.&lt;/p&gt;

&lt;p&gt;I &lt;em&gt;should&lt;/em&gt; be able to organization my code based on &lt;em&gt;feature&lt;/em&gt; instead of what type of class it is.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyApp/
├── assets/
│   ├── site.css
├── Home/
│   ├── HomeController.cs
│   ├── HomePage.cshtml
│   ├── HomePageViewModel.cs
│   ├── About.cshtml
│   ├── AboutViewModel.cs
├── Products/
│   ├── ProductsController.cs
│   ├── Index.cshtml
│   ├── IndexViewModel.cs
│   ├── Detail.cshtml
│   ├── DetailViewModel.cs
├── SharedViews/
│   ├── _Layout.cshtml
├── _ViewStart.cshtml
├── Web.config
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now you can look at the project structure and get a sense of what the app is! Additionally, all of the code related to a feature is in close proximity. In my opinion this makes development easier, possibly even faster.&lt;/p&gt;

&lt;h3 id=&quot;a-quick-word-about-areas&quot;&gt;A Quick Word About &lt;em&gt;Areas&lt;/em&gt;&lt;/h3&gt;

&lt;p&gt;In theory, the &lt;em&gt;Areas&lt;/em&gt; feature can get you pretty close to this model out of the box. However I’m not a fan of &lt;em&gt;Areas&lt;/em&gt;. They were originally designed to work sort of like “sub-projects”. In theory they can physically live in their own assemblies, but this causes problems. But at the end of the day &lt;em&gt;Areas&lt;/em&gt; still suffer, though internally, from the same organizational problems.&lt;/p&gt;

&lt;p&gt;I prefer to avoid areas.&lt;/p&gt;

&lt;h3 id=&quot;making-feature-folders-work&quot;&gt;Making Feature Folders Work&lt;/h3&gt;

&lt;p&gt;Unfortunately &lt;em&gt;Feature Folders&lt;/em&gt; won’t necessarily work out-of-the-box. There are a few things we need to tweak.&lt;/p&gt;

&lt;p&gt;First, as a mentioned in &lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;a previous article&lt;/a&gt;, assigning routes to individual actions is important.&lt;/p&gt;

&lt;p&gt;Second, the default view engine only knows to look for &lt;em&gt;views&lt;/em&gt; inside of &lt;code class=&quot;highlighter-rouge&quot;&gt;Views\&lt;/code&gt;. But we can subclass the default engine using &lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;the technique I wrote about here&lt;/a&gt; to make it work.&lt;/p&gt;

&lt;p&gt;Inside the traditional &lt;code class=&quot;highlighter-rouge&quot;&gt;Views\&lt;/code&gt; directory lives a special &lt;code class=&quot;highlighter-rouge&quot;&gt;Web.config&lt;/code&gt;. This does two things: 1) it makes the Razor tooling work and 2) it prevents access to the cshtml files in the directory tree as “web pages” (as the views are commonly deployed, and then compiled at runtime). We may move &lt;em&gt;some&lt;/em&gt; of the config to root the &lt;code class=&quot;highlighter-rouge&quot;&gt;Web.config&lt;/code&gt; of our project.&lt;/p&gt;

&lt;p&gt;First, we need to register and include the &lt;code class=&quot;highlighter-rouge&quot;&gt;RazorWebSectionGroup&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;configSections&amp;gt;
    &amp;lt;sectionGroup name=&quot;system.web.webPages.razor&quot;
                  type=&quot;System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, 
                        System.Web.WebPages.Razor, Version=3.0.0.0,
                        Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot;&amp;gt;
        &amp;lt;section name=&quot;host&quot; 
                 type=&quot;System.Web.WebPages.Razor.Configuration.HostSection,
                       System.Web.WebPages.Razor, Version=3.0.0.0,
                       Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot;
                 requirePermission=&quot;false&quot; /&amp;gt;
        &amp;lt;section name=&quot;pages&quot;
                 type=&quot;System.Web.WebPages.Razor.Configuration.RazorPagesSection,
                       System.Web.WebPages.Razor, Version=3.0.0.0,
                       Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot;
                 requirePermission=&quot;false&quot; /&amp;gt;
    &amp;lt;/sectionGroup&amp;gt;
&amp;lt;/configSections&amp;gt;

&amp;lt;system.web.webPages.razor&amp;gt;
    &amp;lt;host factoryType=&quot;System.Web.Mvc.MvcWebRazorHostFactory,
                       System.Web.Mvc, Version=5.2.3.0,
                       Culture=neutral, PublicKeyToken=31BF3856AD364E35&quot; /&amp;gt;
    &amp;lt;pages pageBaseType=&quot;System.Web.Mvc.WebViewPage&quot;&amp;gt;
    &amp;lt;namespaces&amp;gt;
        &amp;lt;add namespace=&quot;System.Web.Mvc&quot; /&amp;gt;
        &amp;lt;add namespace=&quot;System.Web.Mvc.Ajax&quot; /&amp;gt;
        &amp;lt;add namespace=&quot;System.Web.Mvc.Html&quot; /&amp;gt;
        &amp;lt;add namespace=&quot;System.Web.Routing&quot; /&amp;gt;
    &amp;lt;/namespaces&amp;gt;
    &amp;lt;/pages&amp;gt;
&amp;lt;/system.web.webPages.razor&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This essentially makes the Razor tooling and compilation work.&lt;/p&gt;

&lt;p&gt;Next, under &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;handlers&amp;gt;&lt;/code&gt; in &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;system.webServer&amp;gt;&lt;/code&gt; we need to add:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;add name=&quot;BlockViewHandler&quot; 
     path=&quot;*.cshtml&quot; 
     verb=&quot;*&quot; 
     preCondition=&quot;integratedMode&quot; 
     type=&quot;System.Web.HttpNotFoundHandler&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In the default &lt;code class=&quot;highlighter-rouge&quot;&gt;Views\Web.config&lt;/code&gt;, this handler is registered with the &lt;code class=&quot;highlighter-rouge&quot;&gt;path=&quot;*&quot;&lt;/code&gt;. But we don’t want to block access to &lt;em&gt;all files&lt;/em&gt;, just our cshtml files. Finally we can add an &lt;code class=&quot;highlighter-rouge&quot;&gt;appSetting&lt;/code&gt; to turn off “webpages”:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;add key=&quot;webpages:Enabled&quot; value=&quot;false&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Unless you want normal web pages to work… and why would you at this point? In which case you’ll need to leave them enabled and perhaps tweak the handler to not exclude the pages you want.&lt;/p&gt;

&lt;p&gt;Alternatively you can copy the default &lt;code class=&quot;highlighter-rouge&quot;&gt;Views\Web.config&lt;/code&gt; into each of your feature folders. But that’s ugly and possibly un-maintainable.&lt;/p&gt;

&lt;p&gt;Another interesting problem man run into: if you have a folder named &lt;code class=&quot;highlighter-rouge&quot;&gt;Foo\&lt;/code&gt;, and a URL such as &lt;code class=&quot;highlighter-rouge&quot;&gt;~\Foo\&lt;/code&gt; that matches that directory name, by default &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Routing&lt;/code&gt; won’t match that URL because it’s a physical folder on disk. In order to force &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Routing&lt;/code&gt; to match that URL, we need to set &lt;code class=&quot;highlighter-rouge&quot;&gt;RouteTable.Routes.RouteExistingFiles = true;&lt;/code&gt;. This setting changes the behavior so that it &lt;em&gt;does not&lt;/em&gt; first check that a file exists before attempting to find a route.&lt;/p&gt;

&lt;p&gt;I also encourage setting up routes that explicitly ignore your static assets (CSS/JS, images, HTML files, etc.) to help with performance.&lt;/p&gt;

&lt;h3 id=&quot;things-might-get-better-with-aspnet-core&quot;&gt;Things Might Get Better with ASP.NET Core&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Feature Folders almost just work.&lt;/em&gt; I think some of the decisions made in ASP.NET MVC are partially due to adopting the conventions of Rails-like frameworks, but also partly to workaround the inherit properties of ASP.NET.&lt;/p&gt;

&lt;p&gt;In ASP.NET, traditionally, you deploy everything as a file. You’re static content and your dynamic content (ASPX pages) are mixed. There’s no routing, and URLs are reflective of the physical layout of files on disk.&lt;/p&gt;

&lt;p&gt;But in almost any modern web application, except for static content, &lt;em&gt;URLs are an abstraction&lt;/em&gt; over dynamic content.&lt;/p&gt;

&lt;p&gt;Luckily ASP.NET Core throws away &lt;em&gt;everything&lt;/em&gt; and starts from &lt;em&gt;scratch&lt;/em&gt;. We may, for instance, have a project structure which looks like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;MyApp/
├── wwwroot/
│   ├── assets/
│   │   ├── site.css
├── Home/
│   ├── HomeController.cs
│   ├── HomePage.cshtml
│   ├── HomePageViewModel.cs
│   ├── About.cshtml
│   ├── AboutViewModel.cs
├── Products/
│   ├── ProductsController.cs
│   ├── Index.cshtml
│   ├── IndexViewModel.cs
│   ├── Detail.cshtml
│   ├── DetailViewModel.cs
├── SharedViews/
│   ├── _Layout.cshtml
├── _ViewStart.cshtml
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As you can see, they’ve introduced a &lt;code class=&quot;highlighter-rouge&quot;&gt;wwwroot&lt;/code&gt; directory. This is a special folder which contains all of the static content that will be deployed too the root of the web application on the server. Everything else in the project &lt;em&gt;is just code&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Fun fact: while you may compile this before deployment, it should be noted that ASP.NET Core has a new build model where it will compile your code at runtime &lt;em&gt;and&lt;/em&gt; detect changes recompile and relaunch.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/02/01/message-broker-architecture</id>
    <published>2016-02-01T00:00:00+00:00</published>
    <updated>
       2016-02-01T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/02/01/message-broker-architecture.html" />
		<title>High Performance Message Broker Design</title>
		<content type="html">&lt;p&gt;In my &lt;a href=&quot;/2016/01/25/introducing-lightrail.html&quot;&gt;previous post&lt;/a&gt; I talked of beginning research into designing and implementing an AMQP-based message broker.&lt;/p&gt;

&lt;p&gt;Implementing the network layer and AMQP protocol is relatively easy. But the actual message broker implementation (queuing, dispatch, and persistence) is an interesting problem.&lt;/p&gt;

&lt;p&gt;Here are some of the requirements:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I should be able to concurrently enqueue messages.&lt;/li&gt;
  &lt;li&gt;Enqueued messages may have a TTL.&lt;/li&gt;
  &lt;li&gt;Instead of de-queuing from the &lt;em&gt;head&lt;/em&gt; of the queue, I need to be able to &lt;em&gt;ACQUIRE&lt;/em&gt; a message.&lt;/li&gt;
  &lt;li&gt;An &lt;em&gt;ACQUIRED&lt;/em&gt; message will be delivered. If accepted, the message will be &lt;em&gt;ARCHIVED&lt;/em&gt;. If released the message becomes &lt;em&gt;AVAILABLE&lt;/em&gt; for delivery again from the same position (i.e. the head).&lt;/li&gt;
  &lt;li&gt;I should be able to spontaneously release &lt;em&gt;ACQUIRED&lt;/em&gt; messages after an expiry.&lt;/li&gt;
  &lt;li&gt;Consumers should be notified of new messages for delivery.&lt;/li&gt;
  &lt;li&gt;Consumers may filter messages.&lt;/li&gt;
  &lt;li&gt;Consumers should implement flow control to restrict the number of delivered messages.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I took a lot of inspiration from other open source projects such as &lt;a href=&quot;http://qpid.apache.org/&quot;&gt;Apache QPID&lt;/a&gt;, &lt;a href=&quot;http://activemq.apache.org/&quot;&gt;Apache ActiveMQ&lt;/a&gt; (specifically &lt;a href=&quot;https://activemq.apache.org/apollo/&quot;&gt;ActiveMQ Apollo&lt;/a&gt;), &lt;a href=&quot;https://en.wikipedia.org/wiki/RabbitMQ&quot;&gt;RabbitMQ&lt;/a&gt;, and &lt;a href=&quot;https://azure.microsoft.com/en-us/services/service-bus/&quot;&gt;Azure Service Bus&lt;/a&gt;. And the &lt;a href=&quot;http://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf&quot;&gt;AMQP Spec&lt;/a&gt; itself lends some guidance from the protocol level of how a broker might behave.&lt;/p&gt;

&lt;h3 id=&quot;concurrent-linked-list-queue&quot;&gt;Concurrent Linked List Queue&lt;/h3&gt;

&lt;p&gt;What I’ve discovered is that a traditional queue, such as .NET’s *ConcurrentQueue&lt;T&gt;* is insufficient. Particularly due to acquiring and releasing messages. But I can use a concurrent linked list, with some modifications.&lt;/T&gt;&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[HEAD] -&amp;gt; [ ] -&amp;gt; [ ] -&amp;gt; [ ] -&amp;gt; [ ] -&amp;gt; [ ] -&amp;gt; ... -&amp;gt; [ ] -&amp;gt; [TAIL] -&amp;gt; NULL
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Using a linked list as a queue requires maintaining &lt;code class=&quot;highlighter-rouge&quot;&gt;HEAD&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;TAIL&lt;/code&gt; pointers. Entries are enqueued by a) creating a new entry b) setting the &lt;code class=&quot;highlighter-rouge&quot;&gt;next-&amp;gt;&lt;/code&gt; pointer of the current &lt;code class=&quot;highlighter-rouge&quot;&gt;TAIL&lt;/code&gt; to the new node and c) and setting &lt;code class=&quot;highlighter-rouge&quot;&gt;TAIL&lt;/code&gt; to point to the new node. To dequeue a) take the &lt;code class=&quot;highlighter-rouge&quot;&gt;HEAD&lt;/code&gt; and if &lt;code class=&quot;highlighter-rouge&quot;&gt;next-&amp;gt;&lt;/code&gt; is not NULL b) set &lt;code class=&quot;highlighter-rouge&quot;&gt;HEAD&lt;/code&gt; to point to the next node.&lt;/p&gt;

&lt;p&gt;To achieve concurrency &lt;em&gt;without blocking or locking&lt;/em&gt;, we can use &lt;a href=&quot;https://en.wikipedia.org/wiki/Compare-and-swap&quot;&gt;compare-and-swap instructions&lt;/a&gt;. Essentially we loop until the system can atomically swap pointers from a known state. Here’s the implementation for Enqueue():&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/jdaigle/cc1449a99d4e6448672d.js?file=enqueue.cs&quot;&gt;&lt;/script&gt;

&lt;p&gt;We don’t actually want to “dequeue” in the sense of &lt;em&gt;removing&lt;/em&gt; the node. Instead we want to &lt;em&gt;acquire&lt;/em&gt;. We can accomplish this by maintaining some additional state in the queue entry itself. Consider a &lt;code class=&quot;highlighter-rouge&quot;&gt;state&lt;/code&gt; field with three values: &lt;code class=&quot;highlighter-rouge&quot;&gt;AVAILALBE&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;ACQUIRED&lt;/code&gt;, and &lt;code class=&quot;highlighter-rouge&quot;&gt;ARCHIVED&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;At any point we can get the next &lt;em&gt;available&lt;/em&gt; node by starting at the &lt;code class=&quot;highlighter-rouge&quot;&gt;HEAD&lt;/code&gt; and walking the list until we reach an &lt;code class=&quot;highlighter-rouge&quot;&gt;AVAILABLE&lt;/code&gt; entry, or NULL. Then &lt;em&gt;acquire&lt;/em&gt; the entry by changing the state. The entry can be &lt;code class=&quot;highlighter-rouge&quot;&gt;released&lt;/code&gt;, causing re-delivery, or &lt;code class=&quot;highlighter-rouge&quot;&gt;ARCHIVED&lt;/code&gt;. Again, we can use an algorithm that makes use of compare-and-swap to do this concurrently without blocking or locking.&lt;/p&gt;

&lt;p&gt;When an entry is &lt;code class=&quot;highlighter-rouge&quot;&gt;ARCHIVED&lt;/code&gt;, it’s not immediately removed the linked list. Instead we occasionally run a tweak-able scavenging algorithm. This algorithm walks the linked list and removes &lt;code class=&quot;highlighter-rouge&quot;&gt;ARCHIVED&lt;/code&gt; entries.&lt;/p&gt;

&lt;h3 id=&quot;queue-consumers&quot;&gt;Queue Consumers&lt;/h3&gt;

&lt;p&gt;In a message broker consumers of a queue usually come and go over. There may be multiple consumers. And we need a way to efficiently deliver messages to attached consumers.&lt;/p&gt;

&lt;p&gt;In this case a consumer will ultimately be some remote link (that’s AMQP terminology) that wishes to receive messages from a queue. So when a remote client connects, we may create and associate consumer for a queue. The consumer is disposed with the connection/session/link (actually AMQP supports re-attaching broken links by exchanging unsettled state maps, but it’s not a requirement).&lt;/p&gt;

&lt;p&gt;If I were building a simple blocking queue for a single consumer, I would utilize &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Threading.AutoResetEvent&lt;/code&gt;. The consumer has an event loop which attempts to dequeue the next message, and if unsuccessful calls &lt;code class=&quot;highlighter-rouge&quot;&gt;WaitOne()&lt;/code&gt; on the WaitHandle. Each time a message is enqueued, I call &lt;code class=&quot;highlighter-rouge&quot;&gt;Set()&lt;/code&gt; on the WaitHandle which signals the &lt;em&gt;blocked&lt;/em&gt; thread to continue.&lt;/p&gt;

&lt;p&gt;In theory I could create a blocking thread for each consumer. But there are several problems with this approach. 1) Each blocked thread consumes memory, and occupies a ThreadPool thread that could otherwise be doing work. 2) The WaitHandle will only a signal a single thread. So only a single consumer will be signaled, and only that consumer will attempt delivery.&lt;/p&gt;

&lt;p&gt;I need to be able to signal &lt;em&gt;all consumers&lt;/em&gt;. And do so fairly.&lt;/p&gt;

&lt;p&gt;My research lead me to implement a 
&lt;em&gt;single message delivery event loop thread&lt;/em&gt;. When signaled, it will loop over each consumer and attempt delivery of a single message. And continue until all messages are delivered.&lt;/p&gt;

&lt;p&gt;While this does in fact work, there are still concerns. a) What if there are messages to deliver but no consumers or b) what if there are consumers but no messages to deliver. One could visualize a situation where the loop is running constantly but not actually doing anything. Thus starving the system of resources.&lt;/p&gt;

&lt;p&gt;Instead, we can have the loop &lt;em&gt;end&lt;/em&gt; at the point of either a) no subscribers or b) no messages. We need a way to restart the loop. That’s when I learned about &lt;code class=&quot;highlighter-rouge&quot;&gt;ThreadPool.RegisterWaitForSingleObject&lt;/code&gt;. This allows us to register a WaitHandle which calls a callback delegate when the WaitHandle is set. Instead of having one of our own threads blocked, the OS efficiently handles it for us.&lt;/p&gt;

&lt;p&gt;Each time &lt;code class=&quot;highlighter-rouge&quot;&gt;Set()&lt;/code&gt; is called, it will call our callback delegate. I needed to implement a small flag to track whether the loop is already running to prevent it from running concurrently. We return from the callback when we’re out of work to do.&lt;/p&gt;

&lt;p&gt;Here’s the implementation:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/jdaigle/cc1449a99d4e6448672d.js?file=queuePump.cs&quot;&gt;&lt;/script&gt;

&lt;h3 id=&quot;flow-control&quot;&gt;Flow Control&lt;/h3&gt;

&lt;p&gt;Another aspect of the message broker is the idea of flow control. Each consumer implements credit-based flow control. Or, in AMQP terms, a link-credit. The “credit” is decremented on each delivery until it reaches 0. At 0, no more messages may be delivered until the credit increases.&lt;/p&gt;

&lt;p&gt;This ensures we never deliver more messages than the link can handle.&lt;/p&gt;

&lt;p&gt;This is actually quite straightforward to implement in our broker. The consumer object maintains the credit, and is decremented on each delivery. Before each delivery, the credit is inspected to ensure we can deliver. If not, that consumer is skipped. The consumer’s credit can be reset after messages are processed, etc. In the case of AMQP, we’ll receive &lt;code class=&quot;highlighter-rouge&quot;&gt;FLOW&lt;/code&gt; frames with updated credit.&lt;/p&gt;

&lt;p&gt;However the above message event loop will need to be modified to account for credit. Specifically, when no consumers have available credit we can stop the event loop. Upon setting new available credit, we can again &lt;code class=&quot;highlighter-rouge&quot;&gt;Set()&lt;/code&gt; the WaitHandle to restart the event loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next time&lt;/strong&gt; I’ll talk about making queues durable with append-only-file (AOF) style transaction logs, and idea I borrowed from Redis;.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/25/introducing-lightrail</id>
    <published>2016-01-25T00:00:00+00:00</published>
    <updated>
       2016-01-25T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/25/introducing-lightrail.html" />
		<title>Introducing LightRail</title>
		<content type="html">&lt;p&gt;&lt;a href=&quot;https://github.com/jdaigle/LightRail&quot;&gt;LightRail&lt;/a&gt; is actually three different things:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;An AMQP-based Message Broker for Windows (based on .NET)&lt;/li&gt;
  &lt;li&gt;An AMQP Client Library for .NET&lt;/li&gt;
  &lt;li&gt;A Service Bus Application Framework&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The name “LightRail” is based on the transportation metaphor adopted by &lt;a href=&quot;https://github.com/MassTransit/MassTransit&quot;&gt;MassTransit&lt;/a&gt;, another open source Service Bus framework. I also wanted the name to imply that it’s a much smaller library and framework.&lt;/p&gt;

&lt;h2 id=&quot;a-quick-history&quot;&gt;A Quick History&lt;/h2&gt;

&lt;p&gt;Many years ago while working at &lt;a href=&quot;http://www.clearwaveinc.com&quot;&gt;Clearwave&lt;/a&gt; we decided to use &lt;a href=&quot;https://github.com/Particular/NServiceBus&quot;&gt;NServiceBus&lt;/a&gt; to build out our asynchronous processing components. NServiceBus is a great framework. At the time it really only targeted MSMQ, however we decided to build our service bus on top of &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/bb522893.aspx&quot;&gt;SQL Server Service Broker&lt;/a&gt; to take advantage of the scaling and high availability that you get with SQL Server. It was relatively easy to implement &lt;em&gt;ITransport&lt;/em&gt; back then, &lt;a href=&quot;https://github.com/jdaigle/servicebroker.net&quot;&gt;and the code&lt;/a&gt; is still kind of around.&lt;/p&gt;

&lt;p&gt;Since then several things happened:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;NServiceBus went commercial. While still open source, it’s not free to use in commercial applications. The &lt;a href=&quot;https://github.com/Particular/NServiceBus/tree/2.0&quot;&gt;2.0 version&lt;/a&gt; remained &lt;a href=&quot;https://groups.yahoo.com/neo/groups/nservicebus/conversations/topics/9629&quot;&gt;open source with Apache V2&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;We quickly realized that NServiceBus’ abstractions were too limiting for what we wanted to do with Service Broker.&lt;/li&gt;
  &lt;li&gt;The 2.0 branch had a few performance issues.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So we actually “rewrote” NServiceBus as our own &lt;a href=&quot;https://github.com/clearwavebuild/CWServiceBus&quot;&gt;CWService&lt;/a&gt;. It’s kind of the same architecture, but very tightly coupled to Service Broker instead of MSMQ. And we made it open source.&lt;/p&gt;

&lt;p&gt;Since I’ve been a consultant with &lt;a href=&quot;http://www.intellinet.com&quot;&gt;Intellinet&lt;/a&gt; have had the opportunity to work on a project that had a need for something extremely similar to what we built with CWServiceBus. &lt;strong&gt;So I decided to start a project to rebuild CWServiceBus as a proper open source service bus application framework.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;But as I got started, I quickly realized that I was just rewriting NServiceBus… and I didn’t want to do that.&lt;/p&gt;

&lt;h2 id=&quot;the-amqp-paradigm-shift&quot;&gt;The AMQP Paradigm Shift&lt;/h2&gt;

&lt;p&gt;A few weeks ago I was listening to &lt;a href=&quot;https://www.dotnetrocks.com/?show=1242&quot;&gt;this podcast&lt;/a&gt; where they interviewed Clemens Vasters. They talked at length on his work with messaging standards and AMQP. Now I’ve known about AMQP from a very high level after having used &lt;a href=&quot;https://www.rabbitmq.com&quot;&gt;RabbitMQ&lt;/a&gt;. But I didn’t &lt;em&gt;really know AMQP&lt;/em&gt; until I decided to dig into the &lt;a href=&quot;http://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf&quot;&gt;actual 1.0 specification&lt;/a&gt;. And I starting &lt;a href=&quot;/2016/01/21/amqp.html&quot;&gt;learning even more&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A few things struck me:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;RabbitMQ doesn’t really support AMQP 1.0. It supports an older and incompatible version of the protocol.&lt;/li&gt;
  &lt;li&gt;Azure Service Bus (mostly) supports AMQP 1.0. The “cloud” product is awesome, but the “on premise” version is… bad.&lt;/li&gt;
  &lt;li&gt;There’s &lt;em&gt;not really&lt;/em&gt; any AMQP 1.0 based messaging broker for Windows today.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I was also been reading about &lt;a href=&quot;https://github.com/antirez/disque/blob/master/README.md&quot;&gt;Disque&lt;/a&gt; from Salvatore Sanfilippo (aka &lt;a href=&quot;http://antirez.com/news/100&quot;&gt;Antirez&lt;/a&gt;). It’s a super-light-weight message broker based on his work with Redis. And then I got the bug. &lt;strong&gt;I decided that I wanted to build a message broker for Windows using .NET and AMQP 1.0.&lt;/strong&gt; Crazy, I know.&lt;/p&gt;

&lt;p&gt;As I mentioned at the top, LightRail is actually three different things:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;An AMQP-based Message Broker for Windows (based on .NET)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I’m not doing a technical deep-dive with this article. But I’m planning to build something in .NET that runs on Windows. It’ll be fast. The persistence model is sort of based on what Antirez has done with Disque/Redis. But the networking protocol will be AMQP. There may be a secondary management channel over HTTP for monitoring and managing the service.&lt;/p&gt;

&lt;p&gt;I don’t yet know what features it’ll support. As a message broker it’ll be similar to RabbitMQ, Azure Service Bus, and Disque. I.E. the client receives a message and must acknowledge after processing. There will be at-least-once semantics and possibly at-most-once. Topic/subscription queues. Dead-letter queues. TTL, retries, filtering, etc. AMQP supports transactions and so will LightRail.&lt;/p&gt;

&lt;p&gt;The first version probably won’t be distributed. But I may experiment with different topologies such as a master/slave replication or even multi-master for some scenarios.&lt;/p&gt;

&lt;p&gt;And maybe one day it’ll be cross-platform targeting .NET Core. I could take advantage of &lt;a href=&quot;http://libuv.org/&quot;&gt;libuv&lt;/a&gt;, similar to how Microsoft is building &lt;a href=&quot;https://github.com/aspnet/KestrelHttpServer&quot;&gt;Kestrel&lt;/a&gt;, their cross-platform HTTP server.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;An AMQP Client Library for .NET&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;https://www.nuget.org/packages/WindowsAzure.ServiceBus/&quot;&gt;Azure Service Bus&lt;/a&gt; library has an AMQP support built in. But it’s built for Azure Service Bus first-and-foremost. It’s also not open source.&lt;/p&gt;

&lt;p&gt;Microsoft also maintains a &lt;a href=&quot;https://github.com/Azure/amqpnetlite&quot;&gt;AMQP 1.0 .NET Client Library&lt;/a&gt; (aka “amqpnetlite”). Comparing the two, it’s clear that they’re &lt;em&gt;very similar&lt;/em&gt;. Interestingly this library supports building both a “client” (which actively connects to a remote host) and a “server” (which listens for connections) or both.&lt;/p&gt;

&lt;p&gt;While it is a fairly complete library and seems to be well testing and relatively mature, I’m not a huge fan. The API is rough. The various components (network, protocol, encoding) are all very tightly coupled. And it’s not optimized for either client or server applications. And there may be performance related issues especially for server applications regarding allocations and value type boxing, among other concerns.&lt;/p&gt;

&lt;p&gt;So I decided to build my own. I am borrowing quite a bit from amqpnetlite, especially around type encoding. But the “core” library is really just centered around encoding and framing. There will be separate client and server implementations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A Service Bus Application Framework&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An AMQP library is not enough for a Service Bus. For that you need to handle routing, message serialization, dispatch, topics/subscriptions, timeouts, etc. That’s where the application framework comes in.&lt;/p&gt;

&lt;p&gt;Now, instead of rewriting NServiceBus, I decided to take a different approach. Rather than being a service bus framework for building applications, &lt;em&gt;I’m building a framework for building a service bus&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;But what’s the difference?&lt;/p&gt;

&lt;p&gt;I believe that one of the drawbacks of NServiceBus (and MassTransit, et al.) is the idea of completely abstracting away the underlying message queue or broker. In the days of MSMQ, maybe that made more sense. MSMQ didn’t really do anything other than queue and transport messages - the framework had to do a lot.&lt;/p&gt;

&lt;p&gt;But the result of all this abstraction is that some platform specific features may get lost, unless they decide to add an abstraction for that feature. I think this is same sort of problem we find today with massive ORM frameworks and libraries. Everything is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Leaky_abstraction&quot;&gt;leaky abstraction&lt;/a&gt;. And this is the problem we ran into with SQL Server Service Broker.&lt;/p&gt;

&lt;p&gt;So instead I want the framework to exist as a set of building blocks for building a service bus using some platform. Whether it’s Azure, RabbitMQ, MSMQ, Server Broker, LightRail, whatever. So when you use it in your application, you’re not using some generic service bus. You’re using an ‘X’ service bus including whatever platform specific features it has. Any abstractions will be based conceptually on AMQP. Given that AMQP is a capital “S” Standard, I think it’s a good move to try and view the world through that lens.&lt;/p&gt;

&lt;h3 id=&quot;going-forward&quot;&gt;Going Forward&lt;/h3&gt;

&lt;p&gt;Right now the project is very pre-alpha (or RC1 if I were the ASP.NET team ;). It barely does &lt;em&gt;anything&lt;/em&gt; I described above.&lt;/p&gt;

&lt;p&gt;In fact right now it’s nothing more than a research project. Maybe one day it’ll be mature enough to use in a real project. And then become a real open source project. Until then I’m kind of playing the the role of an &lt;a href=&quot;http://www.joelonsoftware.com/articles/fog0000000018.html&quot;&gt;architecture astronaut&lt;/a&gt;. In the future I’ll likely publish articles centered around specific technical components of the project.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/21/amqp</id>
    <published>2016-01-21T00:00:00+00:00</published>
    <updated>
       2016-01-21T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/21/amqp.html" />
		<title>AMQP&amp;#58; A Developer's Digest</title>
		<content type="html">&lt;h2 id=&quot;what-is-amqp&quot;&gt;What is AMQP?&lt;/h2&gt;

&lt;p&gt;An acronym for the “Advanced Message Queuing Protocol”. It is a &lt;a href=&quot;http://www.amqp.org/&quot;&gt;Standard (with a capital “S”)&lt;/a&gt; application layer protocol defining a messaging protocol for message-oriented software. It’s a &lt;strong&gt;binary protocol wire-level protocol&lt;/strong&gt;. It describes the format and structure of data sent across the network. It’s effectively peer-to-peer protocol, simply defining how two peers may exchange messages, &lt;em&gt;and not does define what roles the peers may or may not have&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;You can, for example, build a message broker. Or message queue. Or a gateway. Or an event bus. Or an “exchange”.  You get the idea. It supports virtually any type of messaging topology.&lt;/p&gt;

&lt;p&gt;This article aims to be update-able reference for those getting started with AMQP.&lt;/p&gt;

&lt;h2 id=&quot;the-protocol&quot;&gt;The Protocol&lt;/h2&gt;

&lt;p&gt;Here is the &lt;a href=&quot;http://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf&quot;&gt;actual 1.0 specification&lt;/a&gt;. It over 100 pages long, but it’s a relatively quick read. The protocol specification itself is relatively simple and broken into several layers.&lt;/p&gt;

&lt;h3 id=&quot;type-system&quot;&gt;Type System&lt;/h3&gt;

&lt;p&gt;AMQP implements it’s own binary encoding for types. It define primitive types that map to many popular programming languages and platforms. This enables a high-degree of interoperability. It also supports composite types.&lt;/p&gt;

&lt;h3 id=&quot;transport-layer--link-protocol&quot;&gt;Transport Layer / Link Protocol&lt;/h3&gt;

&lt;p&gt;Data is always transmitted across the wire in a &lt;em&gt;frame&lt;/em&gt;. AMQP defines frames for various types of control messages (opening connections, starting sessions, attaching links, transferring messages, etc.).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Connections&lt;/strong&gt; are usually &lt;em&gt;opened&lt;/em&gt; over a reliable protocol such as TCP.&lt;/li&gt;
  &lt;li&gt;A &lt;strong&gt;session&lt;/strong&gt; is &lt;em&gt;started&lt;/em&gt; on a connection. A single connection may multiplex several independent sessions.&lt;/li&gt;
  &lt;li&gt;On a session, one or more uni-directional &lt;strong&gt;links&lt;/strong&gt; are attached. Either peer may attach a link for sending or receiving. The link is attached, logically, to some terminus such as a queue.&lt;/li&gt;
  &lt;li&gt;Messages are &lt;em&gt;transferred&lt;/em&gt; over links.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since a single connection can multiplex multiple sessions and/or links, this means that network traffic can be streamlined. You don’t need multiple connections.&lt;/p&gt;

&lt;h3 id=&quot;messaging&quot;&gt;Messaging&lt;/h3&gt;

&lt;p&gt;The messaging layer covers:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Message format. Including structure, properties, and headers.&lt;/li&gt;
  &lt;li&gt;Delivery state for messages traveling between nodes. Messages need to be &lt;em&gt;settled&lt;/em&gt; which ensures the sender and receiver agree on the state of the transfer.&lt;/li&gt;
  &lt;li&gt;Sources and targets, and the states for messages stored at a distribution node. It also covers resumption of broken sessions and links.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;transactions&quot;&gt;Transactions&lt;/h3&gt;

&lt;p&gt;The protocol supports transactions across transfers and distinct links in either direction. A transactions is first &lt;em&gt;declared&lt;/em&gt; which establishes a transaction-id. Subsequent work is includes that transaction-id. At the end, the transaction is &lt;em&gt;discharged&lt;/em&gt;, which will either commit or rollback the transaction.&lt;/p&gt;

&lt;h3 id=&quot;security&quot;&gt;Security&lt;/h3&gt;

&lt;p&gt;You can encrypt the connection with TLS. Additionally, the protocol supports &lt;a href=&quot;https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer&quot;&gt;SASL&lt;/a&gt; to authenticate peers. Both protocols are be negotiated.&lt;/p&gt;

&lt;h2 id=&quot;whowhat-uses-amqp&quot;&gt;Who/what uses AMQP?&lt;/h2&gt;

&lt;p&gt;Microsoft’s Azure Service Bus supports AMQP. But not all Azure Service Bus features are supported over AMQP. The &lt;a href=&quot;https://www.nuget.org/packages/WindowsAzure.ServiceBus/&quot;&gt;client library&lt;/a&gt; implements AMQP (it’s not currently open source).&lt;/p&gt;

&lt;p&gt;Microsoft does have an open source AMQP client library: &lt;a href=&quot;https://github.com/Azure/amqpnetlite&quot;&gt;https://github.com/Azure/amqpnetlite&lt;/a&gt;. I believe that it’s very similar to the implementation in WindowsAzure.ServiceBus.&lt;/p&gt;

&lt;p&gt;The Apache Foundation has a number of open source projects: &lt;a href=&quot;https://qpid.apache.org/&quot;&gt;Apache Qpid&lt;/a&gt; and &lt;a href=&quot;http://activemq.apache.org/&quot;&gt;Apache ActiveMq&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are a number of other commercial and open source brokers, for example IBM MQ Light. But I don’t know a lot about them.&lt;/p&gt;

&lt;p&gt;And then there’s &lt;a href=&quot;https://www.rabbitmq.com/&quot;&gt;RabbitMQ&lt;/a&gt;. RabbitMQ is interesting because it is actually built on AMQP 0.9.1. That version was a pre-release and is a &lt;em&gt;very different&lt;/em&gt; and basically incompatible protocol. There is a plugin to support AMQP 1, but it’s marked as “experimental”!&lt;/p&gt;

&lt;h2 id=&quot;annotated-further-reading&quot;&gt;Annotated Further Reading&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf&quot;&gt;AMQP Version 1.0&lt;/a&gt;. The actual specification.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://kellabyte.com/2012/10/20/clarifying-amqp/&quot;&gt;Clarifying AMQP&lt;/a&gt;. Kelly explains the differences between AMQP 1.0 and the prelease 0.9 specification.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://paolopatierno.wordpress.com/2015/08/30/amqp-isnt-so-scary-if-you-know-how-to-start/&quot;&gt;AMQP Isn’t So Scary… If You Know How To Start!&lt;/a&gt;. Another digest style article with links and references.&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls</id>
    <published>2016-01-13T00:00:00+00:00</published>
    <updated>
       2016-01-13T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html" />
		<title>Aftermarket ASP.NET MVC - Part 4 - Routing and URL Generation</title>
		<content type="html">&lt;p&gt;This is &lt;strong&gt;part 4&lt;/strong&gt; of a multi-part series on “fixing” some of the inherit design problems with ASP.NET MVC.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-1.html&quot;&gt;Part 1 - Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;Part 2 - The View Engine&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html&quot;&gt;Part 3 - View Model Conventions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;Part 4 - Routing and URL Generation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html&quot;&gt;Part 5 - Feature Folders&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Part 6 - ActionResults and Content Negotiation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Update 2016-02-18: I’ve also setup a &lt;a href=&quot;https://github.com/jdaigle/aspnetmvc5demo&quot;&gt;repository on GitHub&lt;/a&gt; that includes many of these experiments and implementations.&lt;/p&gt;

&lt;p&gt;A common theme of this series is derived from the following quote I once read (but can no longer attribute):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Don’t let your routing solution dictate how to organize your code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In essence, &lt;strong&gt;don’t name your controllers and actions based on what your URLs to look like&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;ASP.NET MVC is built upon &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Routing&lt;/code&gt;, a powerful HttpModule and abstraction that maps a request (by matching URL, HTTP method, and other headers) to instances of an &lt;code class=&quot;highlighter-rouge&quot;&gt;IRouteHandler&lt;/code&gt;. Effectively &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Mvc&lt;/code&gt; is just that.&lt;/p&gt;

&lt;p&gt;Among the many poor defaults and other conventions established in ASP.NET MVC is the “default route” code that you usually find in the baked-in project template that almost everyone uses:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;routes.MapRoute(
    &quot;Default&quot;,
    &quot;{controller}/{action}/{id}&quot;,
    new { controller = &quot;Home&quot;,
          action = &quot;Index&quot;,
          id = &quot;&quot; }
);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;As we know this establishes the convention of a controller and action name defining the mapped URL. And, like many of these conventions, it is directly “borrowed” from Rails. We even have the silly notion of a “Home” and “Index” which I sort of consider “legacy” HTTP terms.&lt;/p&gt;

&lt;p&gt;In the early days of ASP.NET MVC &lt;em&gt;you sort of had to follow this convention&lt;/em&gt; because it was a pain to otherwise map URLs. But eventually we saw several open source projects attempt to fix that. &lt;strong&gt;My favorite was &lt;a href=&quot;https://github.com/mccalltd/AttributeRouting&quot;&gt;AttributeRouting&lt;/a&gt;&lt;/strong&gt;: you use simple attributes on your classes and methods to define the URL, or define your own conventions, and the framework wires it all up. You get a really good programming model and good decoupling of code and URL paths.&lt;/p&gt;

&lt;p&gt;In fact this library was so good, and popular, that Microsoft effectively re-implemented parts of &lt;em&gt;AttributeRouting&lt;/em&gt;; baking it right into the framework!&lt;/p&gt;

&lt;p&gt;But there’s a sad post-script: they only implemented a fraction of &lt;em&gt;AttributeRouting&lt;/em&gt;’s extensive list of features. And they did so in a way that you can’t really use &lt;em&gt;AttributeRouting&lt;/em&gt; as-is in ASP.NET MVC 5. And the project is now pretty much abandoned.&lt;/p&gt;

&lt;h3 id=&quot;tip-use-attribute-based-routing-exclusively&quot;&gt;Tip: Use Attribute-Based Routing, Exclusively.&lt;/h3&gt;

&lt;p&gt;While I definitely &lt;strong&gt;recommend using attribute-based routing exclusively&lt;/strong&gt;, there are some things to watch out for especially as you start adding a lot of mapped routes. I recommend reading about some of the performance issues that can pop up. Here is a good in-depth article that talks about it: &lt;a href=&quot;https://samsaffron.com/archive/2011/10/13/optimising-asp-net-mvc3-routing&quot;&gt;https://samsaffron.com/archive/2011/10/13/optimising-asp-net-mvc3-routing&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And don’t name your routes.&lt;/strong&gt; Yes, it will greatly speed up URL generation. But unless you have a relatively simple application that doesn’t change frequently, you’re going to have to &lt;em&gt;maintain&lt;/em&gt; both those names and their usage.&lt;/p&gt;

&lt;h3 id=&quot;tip-avoid-string-constants-for-url-generation&quot;&gt;Tip: Avoid String Constants for URL Generation&lt;/h3&gt;

&lt;p&gt;I really dislike that most of the &lt;code class=&quot;highlighter-rouge&quot;&gt;UrlHelper&lt;/code&gt; methods require strings for controller and action names. I encourage the use of &lt;code class=&quot;highlighter-rouge&quot;&gt;Microsoft.Web.Mvc&lt;/code&gt;, which includes a special class called &lt;code class=&quot;highlighter-rouge&quot;&gt;ExpressionHelper&lt;/code&gt; that can generate a URL string from a lambda expression referencing a controller class and action method. And so that I don’t need to pollute my project with namespace references, I created a small set of extension methods to abstract away that mess:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/jdaigle/453bcee73d8ee0ab7a7d.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Code that needs to generate a URL is now quite clean. It’s easier to refactor and to find references via static analysis.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var link
    = this.GetURL&amp;lt;SomeController&amp;gt;(c =&amp;gt; c.SomeAction(params...));
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Be warned that you do pay a small performance penalty with &lt;code class=&quot;highlighter-rouge&quot;&gt;ExpressionHelper&lt;/code&gt;.&lt;/em&gt; Your mileage may vary. So do your own testing and performance profiling!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You can also take a look at &lt;a href=&quot;https://github.com/T4MVC/T4MVC&quot;&gt;T4MVC&lt;/a&gt;&lt;/strong&gt;. This takes a different approach that utilizes &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/bb126445.aspx&quot;&gt;T4 text templates&lt;/a&gt; to generate constants and static helper methods based on your project and source code. I have used this extensively in the past which great success. It’s fast because you’re using constants. But it’s a bit intrusive since it requires changing your controller methods to be virtual and creates messy overloads (not to mention the whole code-gen part that some people dislike).&lt;/p&gt;

&lt;h4 id=&quot;experimental-idea-ahead&quot;&gt;Experimental Idea Ahead&lt;/h4&gt;

&lt;p&gt;An approach that I’m beginning to experiment with falls somewhere in between full-on expressions and static helpers. This article on &lt;a href=&quot;http://maxtoroq.github.io/2013/04/delegate-based-strongly-typed-url.html&quot;&gt;Delegate-based strongly-typed URL generation in ASP.NET MVC&lt;/a&gt; shows how we can use an action method delegate to generate route values (action name, parameters, etc.).&lt;/p&gt;

&lt;p&gt;But since action methods are instance methods, this approach requires a controller instance. Which, as the article explains, can get tricky if we want an action delegate for a controller &lt;em&gt;other than the one currently executing&lt;/em&gt;. It’s not too hard to get a “dummy”, or “uninitialized”, instance like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    public static T InstanceOf&amp;lt;T&amp;gt;() where T : ControllerBase
    {
        return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;One could even borrow from the concepts of T4MVC and automatically generate a static helper class with these “uninitialized” controller instances cached for URL generation. But so far any API I’ve created feels too messy compared to a lambda expression or T4MVC’s overrides.&lt;/p&gt;

&lt;p&gt;More experimentation is needed.&lt;/p&gt;

&lt;h3 id=&quot;tip-avoid-areas&quot;&gt;Tip: Avoid Areas&lt;/h3&gt;

&lt;p&gt;You can almost think of an area as a little MVC application embedded into another. It adds a new route value for matching named “area”. Often by convention the area name is simply another part of the URL path that precedes everything else. The built-in view engines and controller factory are also aware of areas, so you end up with self-contained “Controllers/” and “Views/” namespaces/folders under the area.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But it’s the completely wrong approach to modularity.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In a future article I plan on discussing some alternatives that actually make sense.&lt;/p&gt;

&lt;h3 id=&quot;further-reading-and-references&quot;&gt;Further Reading and References&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://samsaffron.com/archive/2011/10/13/optimising-asp-net-mvc3-routing&quot;&gt;Optimizing ASP.NET MVC3 Routing&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://maxtoroq.github.io/2014/02/why-aspnet-mvc-routing-sucks.html&quot;&gt;Why ASP.NET MVC Routing Sucks&lt;/a&gt; - (Note that I don’t agree with all of Max’s conclusions)&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://maxtoroq.github.io/2013/04/delegate-based-strongly-typed-url.html&quot;&gt;Delegate-based strongly-typed URL generation in ASP.NET MVC&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions</id>
    <published>2016-01-07T00:00:00+00:00</published>
    <updated>
       2016-01-07T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html" />
		<title>Aftermarket ASP.NET MVC - Part 3 - View Model Conventions</title>
		<content type="html">&lt;p&gt;This is &lt;strong&gt;part 3&lt;/strong&gt; of a multi-part series on “fixing” some of the inherit design problems with ASP.NET MVC.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-1.html&quot;&gt;Part 1 - Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;Part 2 - The View Engine&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html&quot;&gt;Part 3 - View Model Conventions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;Part 4 - Routing and URL Generation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html&quot;&gt;Part 5 - Feature Folders&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Part 6 - ActionResults and Content Negotiation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Update 2016-02-18: I’ve also setup a &lt;a href=&quot;https://github.com/jdaigle/aspnetmvc5demo&quot;&gt;repository on GitHub&lt;/a&gt; that includes many of these experiments and implementations.&lt;/p&gt;

&lt;h3 id=&quot;1-each-view-should-have-a-strongly-typed-view-model&quot;&gt;1) Each View Should Have a Strongly Typed View Model&lt;/h3&gt;

&lt;p&gt;By default, views in ASP.NET MVC have a &lt;code class=&quot;highlighter-rouge&quot;&gt;dynamic&lt;/code&gt; view model. The underlying object is simply a dynamic key/value bag. While this aids with “rapid development”, in my opinion it hurts long term maintenance. You lose static code analysis, compilation time error checking, refactoring support, and some debugging support.&lt;/p&gt;

&lt;p&gt;Instead, I think &lt;strong&gt;it’s far better to always have a strongly typed view model&lt;/strong&gt; for each and every view.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/strongly-typed-views.PNG&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;I also like the convention of &lt;strong&gt;putting view models alongside the view itself&lt;/strong&gt;. By convention the class name is the name of the view followed by “ViewModel”. Thus your view model’s name follows a pattern of &lt;code class=&quot;highlighter-rouge&quot;&gt;[Project].Views.[Feature].[ViewName]ViewModel&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;2-a-view-should-only-reference-properties-and-methods-from-the-view-model&quot;&gt;2) A View Should Only Reference Properties and Methods From the View Model&lt;/h3&gt;

&lt;p&gt;View engines in ASP.NET MVC, such as Razor, typically compile to classes that inherit from &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Mvc.WebViewPage&lt;/code&gt;. Unfortunately this includes a lot of cruft that carries over from classic ASP and ASP.NET web forms that inherit from &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.UI.Page&lt;/code&gt;. Essentially, the view has references to so much more
that it probably needs to just simply render a template!&lt;/p&gt;

&lt;p&gt;Accessing anything outside of the view model is an anti-pattern. Global or static state is also not a good idea. &lt;strong&gt;Remember that the only job of the view engine is to create a string from a template.&lt;/strong&gt; It can be reduced to just a named function that accepts a model a returns a string.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Don’t access HttpContext/Request/Response.&lt;/li&gt;
  &lt;li&gt;Don’t access the referenced controller.&lt;/li&gt;
  &lt;li&gt;Don’t access route data.&lt;/li&gt;
  &lt;li&gt;Don’t query a database or call external services.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;“But I need to know if a user is authenticated to show/hide things.”&lt;/em&gt;&lt;/strong&gt; Wrong. The view is responsible for rendering content and controls. If content or a control should be conditionally rendered, then the view model should include state that explicitly declares that condition.&lt;/p&gt;

&lt;h3 id=&quot;3-urls-for-links-and-buttons-should-be-part-of-the-view-model&quot;&gt;3) URLs for Links and Buttons Should Be Part of the View Model&lt;/h3&gt;

&lt;p&gt;ASP.NET MVC has the ability the generate URLs for routes based on a controller/action pair. This is great since since you don’t need to hardcode URLs all over the place (except you still deal with string constants). &lt;strong&gt;But you should not use &lt;code class=&quot;highlighter-rouge&quot;&gt;HtmlHelper&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;UrlHelper&lt;/code&gt; to create a link/button or generate an action URL from within the view template.&lt;/strong&gt; Instead, any generated URLs should be properties in the view model. This helps to further keep the view’s template clean and without references to constants, or worse, controllers and actions.&lt;/p&gt;

&lt;h3 id=&quot;additional-tip-pass-a-razor-template-as-a-parameter-to-a-view-model-helper-function&quot;&gt;Additional Tip: Pass a Razor Template as a Parameter to a View Model Helper Function&lt;/h3&gt;

&lt;p&gt;In your view model you can create methods that accept Razor templates as &lt;code class=&quot;highlighter-rouge&quot;&gt;Func&amp;lt;object, HelperResult&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public MvcHtmlString RenderIfCanEdit(
    Func&amp;lt;object, HelperResult&amp;gt; template)
{
    if (this.CanEdit) {
        return MvcHtmlString
            .Create(template.Invoke(null)
            .ToHtmlString());
    } else {
        return MvcHtmlString.Empty;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now in the view, you can do awesomeness like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    @Model.RenderIfCanEdit(
    @&amp;lt;p&amp;gt;
        ...
    &amp;lt;/p&amp;gt;
    )
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Depending on the scenario this can be a lot cleaner than having nasty looking if-statements. Here’s an &lt;a href=&quot;http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx/&quot;&gt;article by Phil Haack&lt;/a&gt; that explains it more detail.&lt;/p&gt;

&lt;h3 id=&quot;further-reading&quot;&gt;Further Reading&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/&quot;&gt;C# Razor Syntax Quick Reference&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://odetocode.com/blogs/scott/archive/2013/01/09/ten-tricks-for-razor-views.aspx&quot;&gt;Ten Tricks for Razor Views&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine</id>
    <published>2016-01-05T09:00:00+00:00</published>
    <updated>
       2016-01-05T09:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html" />
		<title>Aftermarket ASP.NET MVC - Part 2 - The View Engine</title>
		<content type="html">&lt;p&gt;This is &lt;strong&gt;part 2&lt;/strong&gt; of a multi-part series on “fixing” some of the inherit design problems with ASP.NET MVC.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-1.html&quot;&gt;Part 1 - Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;Part 2 - The View Engine&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html&quot;&gt;Part 3 - View Model Conventions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;Part 4 - Routing and URL Generation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html&quot;&gt;Part 5 - Feature Folders&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Part 6 - ActionResults and Content Negotiation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Update 2016-02-18: I’ve also setup a &lt;a href=&quot;https://github.com/jdaigle/aspnetmvc5demo&quot;&gt;repository on GitHub&lt;/a&gt; that includes many of these experiments and implementations.&lt;/p&gt;

&lt;p&gt;The problem with the default view engine in ASP.NET MVC stems not from how it renders a view, but how it &lt;em&gt;selects and finds&lt;/em&gt; a view to render. If you dig through the source code you’ll discover that &lt;em&gt;selecting and finding&lt;/em&gt; a view to render is tightly coupled with the actual view engine itself. That can be troublesome if we want to implement our own conventions.&lt;/p&gt;

&lt;p&gt;Further, &lt;strong&gt;the built-in view engine uses a convention of selecting and finding a view based on the controller and action’s name.&lt;/strong&gt; I consider this an anti-pattern. It couples a view to controllers and action methods by name. It is possible to override this behavior by constructing a ViewResult with the name or path of the specific view you want selected. But again we’re coupled, since the convention is to look in a directory based on the name of controller. We also have to use string constants throughout which means we lose the ability to refactor and perform static code analysis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;I think a better design is to select and find the view based on the type of view model returned.&lt;/strong&gt; I’ll talk about this more in a future article, but a really good convention to adopt is having a strongly typed view model per view. I also recommend that the view model class’ namespace match the “path” of the view. In fact, just put it in the same directory as the view! A benefit of this convention is that we can select the view simply by inspecting the type of the view model.&lt;/p&gt;

&lt;p&gt;Fortunately the code to implement this is just a single class:&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/jdaigle/a7d8ec3a6867f5250f55.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Not only does it select the view based on the view model’s class and namespace, but it degrades gracefully in the event that a view model is not supplied, or if the view model does not match any view. It’ll fallback to the default logic.&lt;/p&gt;

&lt;p&gt;And then on startup, insert the new view engine:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ViewEngines.Engines.Insert(0,
    new ViewModelSpecifiedViewEngine());
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In your controller actions, simply construct the view model and return the view result.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public ActionResult ListSomeResource() {
     var viewModel
         = new SomeResourceListViewModel();
     ...
     return View(viewModel);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This works well for partial view results too. However there is a hiccup: the use of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Partial()&lt;/code&gt; HTML helper is sort of broken by since it does not have an override that only accepts a view model object. It &lt;em&gt;requires a partial view name&lt;/em&gt;… how annoying. But easy enough to work around with this new view engine; the view name can be any string with length &amp;gt; 0. So I simply create an extension method to make it easier:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static MvcHtmlString PartialView(
    this HtmlHelper htmlHelper,
    object model)
{
    // minor hack, since all the internals of
    // finding a partial view require a partialViewName
    return htmlHelper.Partial(&quot;null&quot;, model);
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This is a great technique to adopt with composite or nested views. For example, I have a view model for a page (parent) that contains one or more partial (children) views. There is a list, and for each item I want to render a partial. So in the parent view model I simply have children view model objects. When passed to the &lt;code class=&quot;highlighter-rouge&quot;&gt;PartialView()&lt;/code&gt; HTML helper, it automatically selects and renders the correct partial view.&lt;/p&gt;

&lt;p&gt;The code also works with sub-classed view models. This enables the use of sub-classes to change the behavior of how a view is rendered without implementing complex switch logic either in the view model or the view itself. It’s probably rare that one would ever do this, but it’s a nice bonus.&lt;/p&gt;

&lt;p&gt;Next time I’ll talk more about view model conventions and share some tricks that have made development and maintenance smoother and safer.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2016/01/05/bridging-aspnet-mvc-part-1</id>
    <published>2016-01-05T08:00:00+00:00</published>
    <updated>
       2016-01-05T08:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2016/01/05/bridging-aspnet-mvc-part-1.html" />
		<title>Aftermarket ASP.NET MVC - Part 1 - Introduction</title>
		<content type="html">&lt;p&gt;This is &lt;strong&gt;part 1&lt;/strong&gt; of a multi-part series on “fixing” some of the inherit design problems with ASP.NET MVC.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-1.html&quot;&gt;Part 1 - Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/05/bridging-aspnet-mvc-part-2-the-view-engine.html&quot;&gt;Part 2 - The View Engine&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/07/bridging-aspnet-mvc-part-3-view-model-conventions.html&quot;&gt;Part 3 - View Model Conventions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/01/13/bridging-aspnet-mvc-part-4-routing-and-urls.html&quot;&gt;Part 4 - Routing and URL Generation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;/2016/02/19/aftermarket-aspnet-mvc-part-5-feature-folders.html&quot;&gt;Part 5 - Feature Folders&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Part 6 - ActionResults and Content Negotiation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Update 2016-02-18: I’ve also setup a &lt;a href=&quot;https://github.com/jdaigle/aspnetmvc5demo&quot;&gt;repository on GitHub&lt;/a&gt; that includes many of these experiments and implementations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ASP.NET MVC&lt;/strong&gt; has been the contemporary framework of choice for backend web development on the .NET stack almost since its first release around 2008-2009. And now here we are, seven years later, and by-and-large the framework’s programming patterns have remained relatively unchanged.&lt;/p&gt;

&lt;p&gt;At the time of it’s initial development the hottest and trendiest web development stack was &lt;a href=&quot;https://en.wikipedia.org/wiki/Ruby_on_Rails&quot;&gt;Ruby on Rails&lt;/a&gt;. So it’s no surprise that Microsoft borrowed a great many of Rails’ conventions when designing ASP.NET MVC. Whether good or bad.&lt;/p&gt;

&lt;p&gt;Over the years people have discussed and debated the patterns (and anti-patterns?) and other short comings of the framework. In fact, “alternative” frameworks such as &lt;a href=&quot;http://fubuworld.com/fubumvc/&quot;&gt;FubuMVC&lt;/a&gt; sprung up as a result. Unfortunately, virtually all of these “alternative” frameworks see little to no adoption.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Arguably the worst part of being a .NET developer is the dependence on and  suffocation by “1st party” frameworks and tools.&lt;/strong&gt; For many dev shops, “3rd party” and open source is never considered an option or is simply forbidden; it’s either built by Microsoft or it doesn’t exist! I think the .NET development world is, in a bad way, unique in this aspect.&lt;/p&gt;

&lt;p&gt;Side note: more recently there’s been a rise in &lt;a href=&quot;https://en.wikipedia.org/wiki/Sinatra_(software)&quot;&gt;Sinatra&lt;/a&gt; style frameworks such as &lt;a href=&quot;http://nancyfx.org/&quot;&gt;Nancy&lt;/a&gt;. I &lt;em&gt;really like&lt;/em&gt; NancyFX. And I hope they stay strong.&lt;/p&gt;

&lt;p&gt;So while I do have many of my own ideas for how I would refactor ASP.NET MVC into something better (in my opinion), I know it’ll see &lt;em&gt;zero adoption&lt;/em&gt;. And it will also be met with heavy resistance for new projects I work on.&lt;/p&gt;

&lt;p&gt;Instead, I’m going to show a few tricks I’ve learned over the past seven years that make ASP.NET MVC much smarter. Over the course of this series I’ll discuss an aspect of the framework I dislike, and show how to make it better. I may also add to the series as I learn new tricks, and as the framework itself evolves.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2015/12/11/aspnet-identity</id>
    <published>2015-12-11T00:00:00+00:00</published>
    <updated>
       2015-12-11T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2015/12/11/aspnet-identity.html" />
		<title>ASP.NET Identity - A Case Study in Monolithic Frameworks</title>
		<content type="html">&lt;h2 id=&quot;abstract&quot;&gt;Abstract&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://aspnetidentity.codeplex.com&quot;&gt;ASP.NET Identity&lt;/a&gt;&lt;/strong&gt; is a monolithic membership framework, especially when combined with &lt;strong&gt;Microsoft.OWIN.Security&lt;/strong&gt; (which is almost a requirement to successfully using it!). As a monolithic framework, the developer eventually suffers when trying to plugin or extend the framework to do something that is no supported out of the box. Developers may also struggle simply using what’s provided &lt;em&gt;in the box&lt;/em&gt; due to severe leaky abstractions.&lt;/p&gt;

&lt;h2 id=&quot;separation-of-concerns&quot;&gt;Separation of Concerns&lt;/h2&gt;

&lt;p&gt;First I want to briefly cover the difference between &lt;em&gt;authentication&lt;/em&gt; and “&lt;em&gt;membership&lt;/em&gt;” in web application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authentication&lt;/strong&gt; specifically refers the mechanism by which a user’s identity is determined from an HTTP request. These days it’s quite common to use an HTTP cookie that serializes some sort of identity; be it a session or user ID, and perhaps identity claims. Often the cookie is encrypted so that only the server application is able to read and/or modify.&lt;/p&gt;

&lt;p&gt;Other authentication mechanisms include &lt;a href=&quot;https://en.wikipedia.org/wiki/Basic_access_authentication&quot;&gt;basic access authentication&lt;/a&gt; (the username/password are encoded into the HTTP header of every single request), or tokens which are often included in an HTTP header or query string parameter.&lt;/p&gt;

&lt;p&gt;In the ASP.NET world the term &lt;strong&gt;membership&lt;/strong&gt; refers to the mechanism by which users are managed. Be it a database or a directory. “Authentication” is sometimes overloaded to refer to the process of validating a token or set of credentials against the user’s membership. This usually occurs during &lt;em&gt;login&lt;/em&gt; and frequently also occurs on each HTTP request to validate the authentication token.&lt;/p&gt;

&lt;p&gt;To make things a more complicated, modern web applications often do not directly deal with user credentials. Instead relying on external authentication via OAuth or SAML (think Facebook, Google, Microsoft, ADFS, etc.). But for this article, they’re slightly out of scope.&lt;/p&gt;

&lt;h2 id=&quot;abridged-history-of-membership-and-authentication-in-aspnet&quot;&gt;Abridged History of Membership and Authentication in ASP.NET&lt;/h2&gt;

&lt;p&gt;Most of what’s existed since the first version of ASP.NET exists as part of &lt;code class=&quot;highlighter-rouge&quot;&gt;System.Web.Security&lt;/code&gt;. That means it’s part of the BCL and shipped with every installation.&lt;/p&gt;

&lt;p&gt;One quick note: some authentication such as Basic and Windows auth are actually implemented natively by IIS and aren’t part of the .NET framework.&lt;/p&gt;

&lt;p&gt;Here’s a pretty good article that covers the old membership providers: &lt;a href=&quot;http://brockallen.com/2012/09/02/think-twice-about-using-membershipprovider-and-simplemembership/&quot;&gt;http://brockallen.com/2012/09/02/think-twice-about-using-membershipprovider-and-simplemembership/&lt;/a&gt;. It also offers a critique which aligns with the goal of this article.&lt;/p&gt;

&lt;h2 id=&quot;enter-aspnet-identity&quot;&gt;Enter ASP.NET Identity&lt;/h2&gt;

&lt;p&gt;Again, to piggy back on good writings, here is Brock Allen again: &lt;a href=&quot;http://brockallen.com/2013/10/20/the-good-the-bad-and-the-ugly-of-asp-net-identity/&quot;&gt;http://brockallen.com/2013/10/20/the-good-the-bad-and-the-ugly-of-asp-net-identity/&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;leaky-abstractions&quot;&gt;Leaky Abstractions&lt;/h2&gt;

&lt;p&gt;Here’s one &lt;a href=&quot;https://aspnetidentity.codeplex.com/workitem/2540&quot;&gt;egregious example&lt;/a&gt;. The &lt;code class=&quot;highlighter-rouge&quot;&gt;UserManager&lt;/code&gt; class exposes &lt;code class=&quot;highlighter-rouge&quot;&gt;IQueryable&amp;lt;TUser&amp;gt; Users&lt;/code&gt;. In this example the developer is using &lt;code class=&quot;highlighter-rouge&quot;&gt;Microsoft.AspNet.Identity.EntityFramework&lt;/code&gt; to provide a concrete implementation for &lt;code class=&quot;highlighter-rouge&quot;&gt;TUser&lt;/code&gt;. However the developer must understand how EntityFramework works and how the entities are implemented in order to use &lt;code class=&quot;highlighter-rouge&quot;&gt;IQueryable&amp;lt;TUser&amp;gt;&lt;/code&gt; correctly.&lt;/p&gt;

&lt;p&gt;I should also point out that the implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;IQueryable&amp;lt;TUser&amp;gt; Users&lt;/code&gt; on &lt;code class=&quot;highlighter-rouge&quot;&gt;UserManager&lt;/code&gt; throws a &lt;code class=&quot;highlighter-rouge&quot;&gt;NotSupportedException&lt;/code&gt; if the &lt;code class=&quot;highlighter-rouge&quot;&gt;IUserStore&amp;lt;TUser&amp;gt;&lt;/code&gt; implementation does not implement the correct interface! This is another perfect example of a leaky abstraction where the developer must understand the implementation in order to use the library.&lt;/p&gt;

&lt;h2 id=&quot;missing-features-and-abandonware&quot;&gt;Missing Features and Abandonware&lt;/h2&gt;

&lt;p&gt;Brock Allen pretty much &lt;a href=&quot;http://brockallen.com/2013/10/20/the-good-the-bad-and-the-ugly-of-asp-net-identity/#ugly&quot;&gt;nails it again&lt;/a&gt; talking about so many security and identity related concerns that the framework simply does not handle.&lt;/p&gt;

&lt;p&gt;I find this quote particularly interesting:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Of course, with this redesign, I think Microsoft is in a much better place to add these features in a future release. But it ain’t there now.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Allen’s article was written over two years ago and new features really &lt;em&gt;have not&lt;/em&gt; been added!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using these monolithic frameworks often results in the developer writing much more “glue” code to get things working that it would take to simply write a non-abstracted version of what they’re trying to accomplish&lt;/strong&gt;. These abstractions allow you to do neat things for demos, such as quickly building a working web application from templates. But for real world production applications? It can get rough.&lt;/p&gt;

&lt;p&gt;I should also point that the current version of the library is effectively &lt;strong&gt;abandonware&lt;/strong&gt;. There are no new updates in the current repository. In fact the repository has &lt;a href=&quot;https://github.com/aspnet/Identity&quot;&gt;moved to GitHub&lt;/a&gt; to be included in ASP.NET 5. But I would like to point out that this is effectively a “port” of current version (as &lt;a href=&quot;https://github.com/aspnet/Identity/commit/aa4787cc67ed02ba0d2c08adecf8ada75b2d7239&quot;&gt;is evident&lt;/a&gt;) since ASP.NET 5 is built on completely new tooling.&lt;/p&gt;

&lt;h2 id=&quot;who-uses-this-stuff&quot;&gt;Who Uses This Stuff?&lt;/h2&gt;

&lt;p&gt;I honestly wonder. Outside of small proof-of-concept or very small line-of-business applications, does anyone use these frameworks?&lt;/p&gt;

&lt;p&gt;My guess is no. Because at the end of the day it’s almost easier to roll your own. You’ll get better performance and you can make it easier for junior developers to consume your API when building new application features. But this comes with an important caveat: &lt;strong&gt;security is hard&lt;/strong&gt;. And &lt;strong&gt;you should not be building your own authentication and security libraries unless you actually know what you’re doing&lt;/strong&gt;. So it’s a tough choice for a small shop that doesn’t have the expertise.&lt;/p&gt;

&lt;h2 id=&quot;next&quot;&gt;Next&lt;/h2&gt;

&lt;p&gt;In a future post I will talk about the &lt;a href=&quot;http://katanaproject.codeplex.com/&quot;&gt;OWIN security components&lt;/a&gt;. These deal with cookie authentication, and provide implementations for external login providers (i.e. OAuth). But as a preview that library shares most of the same criticisms about monolithic frameworks, leaky abstractions, and more.&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2015/12/03/search-for-ultimate-dev-laptop</id>
    <published>2015-12-03T00:00:00+00:00</published>
    <updated>
       2015-12-03T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2015/12/03/search-for-ultimate-dev-laptop.html" />
		<title>Searching for the Ultimate Development Laptop</title>
		<content type="html">&lt;p&gt;Update #1: &lt;a href=&quot;/2016/04/12/all-about-the-pentiums.html&quot;&gt;I’ve written another short article&lt;/a&gt; (dated 2016-04-12) comparing the latest models, focusing on the processor specs. But I’m still waiting for the MacBook Pro refresh.&lt;/p&gt;

&lt;p&gt;Some say it’s a futile quest. But I’m going to try anyway. I’m going to find (or at least pick) the perfect laptop for software development.&lt;/p&gt;

&lt;p&gt;I’m currently writing this article from a 2013-era Lenovo ThinkPad W530. And it is a beast. It’s actually quite a performant laptop with a decent keyboard and screen. But it’s big and it’s heavy. Even the latest W-series models are just too big. I put this laptop in the class of “desktop-replacement” instead of “portable” - it’s not one I would choose for myself or, frankly, recommend.&lt;/p&gt;

&lt;p&gt;I’m looking for a key balance of power and portability.&lt;/p&gt;

&lt;h3 id=&quot;dell-latitude-e5450&quot;&gt;Dell Latitude E5450&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;Dell Latitude 5000 Series&lt;/strong&gt; has been a laptop I’ve thoroughly enjoyed in the past. Particularly the 14 inch model, which is currently the &lt;strong&gt;E5450&lt;/strong&gt;. The 15 inch model is too large for my preferences (and why does a laptop need a number pad anyway!?). Some people may enjoy the extra portability of a 12 inch display, but for me 13 or 14 inches is the sweet spot.&lt;/p&gt;

&lt;p&gt;Of course, Dell’s website is absolutely &lt;em&gt;terrible&lt;/em&gt; in terms of actually trying to customize the configuration I want.&lt;/p&gt;

&lt;p&gt;But let’s look at the specs. I generally max everything out.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;5th Gen Dual Core i7-5600U 2.6ghz&lt;/li&gt;
  &lt;li&gt;14.0” Display FHD (1920x1080)&lt;/li&gt;
  &lt;li&gt;DDR3L 1600MHz, 8GB RAM (but upgradeable to 16GB if you can figure out how)&lt;/li&gt;
  &lt;li&gt;256 GB SSD (should be upgradeable)&lt;/li&gt;
  &lt;li&gt;Nvidia GeForce 840M&lt;/li&gt;
  &lt;li&gt;13.2 x 9.1 x .90 inches&lt;/li&gt;
  &lt;li&gt;4 lbs&lt;/li&gt;
  &lt;li&gt;Around $2,000 depending on configuration and whatever current deals are available.&lt;/li&gt;
  &lt;li&gt;Preloaded with Dell management crapware.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is the &lt;a href=&quot;http://i.dell.com/sites/doccontent/shared-content/data-sheets/en/Documents/CSG-EN-XX-ALL-Latitude-14-E5450-Spec-Sheet.pdf&quot;&gt;official spec sheet&lt;/a&gt; (hopefully the link doesn’t expire too soon).&lt;/p&gt;

&lt;p&gt;It’s worth comparing the 14” model to the 15” model. For reference &lt;a href=&quot;http://i.dell.com/sites/doccontent/shared-content/data-sheets/en/Documents/CSG-EN-XX-ALL-Latitude-15-E5550-Spec-Sheet.pdf&quot;&gt;here are the specs to compare&lt;/a&gt;. If you notice, it has &lt;em&gt;the exact same internal specs&lt;/em&gt;! You just get a bigger screen, &lt;em&gt;but at the same resolution&lt;/em&gt;!&lt;/p&gt;

&lt;p&gt;Note that the Latitudes now have HDMI output instead of DisplayPort. Personally I find this a drawback as HDMI is really intended for consumer electronics while DisplayPort has many other capabilities (display chaining, etc.).&lt;/p&gt;

&lt;p&gt;Dell also makes a &lt;a href=&quot;http://i.dell.com/sites/doccontent/business/smb/merchandizing/en/Documents/32_Latitude_7000_Series_High_Resolution.pdf&quot;&gt;&lt;strong&gt;7000 series&lt;/strong&gt;&lt;/a&gt;, considered an “ultrabook”. It appears that you can get similar specs &lt;em&gt;but without a dedicated graphics card&lt;/em&gt;. And it’s only marginally thinner and lighter (13.3 x 9.12 x .80 inches and 3.5 lbs). Ultimately it does come with an added cost.&lt;/p&gt;

&lt;h3 id=&quot;lenovo-thinkpad-t450s&quot;&gt;Lenovo ThinkPad T450s&lt;/h3&gt;

&lt;p&gt;Apples-to-apples comparison suggests that I should look at the &lt;strong&gt;ThinkPad T series&lt;/strong&gt;. Specifically the &lt;strong&gt;T450&lt;/strong&gt;. Note that there is a T450s, but it has only 1 DIMM and thus a smaller max-memory. It’s kind of a weird laptop.&lt;/p&gt;

&lt;p&gt;Here is latest &lt;a href=&quot;http://www.lenovo.com/psref/pdf/ThinkPad.pdf&quot;&gt;Product Specification Reference&lt;/a&gt; which lists &lt;em&gt;everything&lt;/em&gt; about &lt;em&gt;every ThinkPad&lt;/em&gt;. Which is great for comparing.&lt;/p&gt;

&lt;p&gt;Specs:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;5th Gen Dual Core i7-5600U “up to 3.2gz”&lt;/li&gt;
  &lt;li&gt;14.0” Display FHD (1920x1080) - ISP display&lt;/li&gt;
  &lt;li&gt;16GB PC3-12800 1600MHz (2 DIMMs)&lt;/li&gt;
  &lt;li&gt;256 GB SSD (should be upgradeable)&lt;/li&gt;
  &lt;li&gt;Integrated Graphics only.&lt;/li&gt;
  &lt;li&gt;13.35 x 9.15 x .83 inches&lt;/li&gt;
  &lt;li&gt;“less than 4lbs”&lt;/li&gt;
  &lt;li&gt;Around $2,000 depending on configuration and whatever current deals are available.&lt;/li&gt;
  &lt;li&gt;Preloaded with Lenovo management crapware.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So it’s basically the same as the Dell Latitude 5000 series. Except with DisplayPort instead of HDMI. And there is no option for dedicated graphics card.&lt;/p&gt;

&lt;p&gt;Lenovo also has a 15” T550, which again like Dell, is &lt;em&gt;the same laptop but with a bigger screen&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;apple-macbook-pro-13-retina&quot;&gt;Apple MacBook Pro 13” Retina&lt;/h3&gt;

&lt;p&gt;Apple is interesting when compared to the traditional laptop vendors. They generally don’t allow for customization. Instead, you can “upgrade” the CPU/RAM/disk at the time of purchase.&lt;/p&gt;

&lt;p&gt;They make a 13” and 15” display model. But let’s look at the 13” specs:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Dual Core i7 3.1ghz&lt;/li&gt;
  &lt;li&gt;13” Retina Display, 2560x1600 native&lt;/li&gt;
  &lt;li&gt;max 16 GB 1866MHz (not upgradeable after purchase!)&lt;/li&gt;
  &lt;li&gt;512 GB flash (could upgrade to 1GB for an additional $500 at time of purchase)&lt;/li&gt;
  &lt;li&gt;Intel Iris Graphics 6100&lt;/li&gt;
  &lt;li&gt;12.35 x 8.62 x .71 inches&lt;/li&gt;
  &lt;li&gt;3.5 lbs&lt;/li&gt;
  &lt;li&gt;Pricing is around $2,200.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It’s small, light, sleek. That comes at the cost of not being able to upgrade the memory or hard drive after purchasing. There is a lot less configurability. But the specs are in-line with what you would want.&lt;/p&gt;

&lt;p&gt;The 15” model has similar specs, but it’s quad-core and has the addition of a dedicated graphics chipset. It’s priced about $500 more. It is really attractive looking. It’s obviously bigger and heavier. But the dedicated AMD Radeon R9 M370X graphics and quad-core graphics is appealing. Compared to Dell and Lenovo, the 15” model actually offers a compelling reason to get the bigger model.&lt;/p&gt;

&lt;p&gt;Unfortunately consulting the &lt;a href=&quot;http://buyersguide.macrumors.com/#Retina_MacBook_Pro&quot;&gt;MacRumors Buyer’s Guide&lt;/a&gt; suggests waiting a few months for the new model.&lt;/p&gt;

&lt;h3 id=&quot;windows-and-net-development-on-a-mac&quot;&gt;Windows and .NET Development on a Mac?&lt;/h3&gt;

&lt;p&gt;I proposed this question on reddit &lt;a href=&quot;https://www.reddit.com/r/dotnet/comments/3v4uxp/does_anyone_use_a_macbook_as_their_primary/&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;https://www.reddit.com/r/csharp/comments/3v4uzs/does_anyone_use_a_macbook_or_macbook_pro_as_their/&quot;&gt;here&lt;/a&gt;. And I got a lot of good feedback.&lt;/p&gt;

&lt;p&gt;This is definitely a gray area and I’m still unsure. Fortunately, new MacBook Pro models aren’t expected for another few months so I have time to do further research before I decide to purchase.&lt;/p&gt;

&lt;h3 id=&quot;other-choices&quot;&gt;Other Choices?&lt;/h3&gt;

&lt;p&gt;I know I only covered three vendors, and there are plenty of others. But what other vendor out there makes Laptops suitable for business and software development?&lt;/p&gt;

&lt;p&gt;I do plan on updating this article as I receive new information. And I may publish a followup review after I decide and purchase.&lt;/p&gt;

&lt;p&gt;If you have opinions or comments, please leave them below!&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2015/11/11/cloning-disqus</id>
    <published>2015-11-11T00:00:00+00:00</published>
    <updated>
       2015-11-11T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2015/11/11/cloning-disqus.html" />
		<title>Cloning Disqus - Introducing CommentR</title>
		<content type="html">&lt;p&gt;This blog is &lt;a href=&quot;https://github.com/jdaigle/jdaigle.github.io&quot;&gt;open source&lt;/a&gt; and is built using &lt;a href=&quot;http://jekyllrb.com/&quot;&gt;Jekyll&lt;/a&gt;, a &lt;a href=&quot;https://staticsitegenerators.net/&quot;&gt;static website generator&lt;/a&gt;. One of the interesting side effects of hosting a completely &lt;em&gt;static&lt;/em&gt; website is that I don’t have a &lt;em&gt;dynamic&lt;/em&gt; backend that I can use for comments. Comments, at a minimum, require a) a database b) a form to post comments and c) a dynamically generated view.&lt;/p&gt;

&lt;p&gt;In the world of static websites, a new category of SaaS as sprung up around “blog hosting services”. By far the most popular service is &lt;a href=&quot;https://disqus.com/&quot;&gt;Disqus&lt;/a&gt;, but there are others such as &lt;a href=&quot;https://www.discourse.org/&quot;&gt;Discourse&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Rather than simply pull in one of these services, I decided to try building my own! I decided to base my design on Disqus. Except my service won’t serve ads, does not require creating an account, and won’t track you.&lt;/p&gt;

&lt;p&gt;The bare minimum requirements:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It must be easy to add to a page: i.e., include a single JavaScript reference and a placeholder element.&lt;/li&gt;
  &lt;li&gt;It must allow posting of comments without creating an account: just an author and body input.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Eventually I might add these features:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Moderation: I should be able to delete comments, or approve comments before they’re visible.&lt;/li&gt;
  &lt;li&gt;Moderator comments: My comments should be highlighted in some way.&lt;/li&gt;
  &lt;li&gt;Self-Service: Someone who has just posted a comment should be able to edit or delete that comment.&lt;/li&gt;
  &lt;li&gt;SPAM Detection: I don’t want a CAPTCHA, so I might build some trivial SPAM detector.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I decided to name my project &lt;strong&gt;CommentR&lt;/strong&gt;. It’s open source and available on &lt;a href=&quot;https://github.com/jdaigle/CommentR&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;building-commentr&quot;&gt;Building CommentR&lt;/h2&gt;

&lt;p&gt;Architecturally I knew that CommentR would be a simple API service. So I started with two simple API calls:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;curl -X GET /Comments?permalink=XXX

curl -X POST --data &quot;permalink=XXX&amp;amp;author=YYY&amp;amp;body=ZZZ&quot; /Comment
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;GET&lt;/code&gt; call returns the visible comments for a page (keyed using a &lt;code class=&quot;highlighter-rouge&quot;&gt;permalink&lt;/code&gt; URL) either as JSON or an HTML fragment depending the HTTP Accept header. The &lt;code class=&quot;highlighter-rouge&quot;&gt;POST&lt;/code&gt; call submits a new comment for a page (again keyed using a &lt;code class=&quot;highlighter-rouge&quot;&gt;permalink&lt;/code&gt; URL) and returns the same result as the &lt;code class=&quot;highlighter-rouge&quot;&gt;GET&lt;/code&gt; call.&lt;/p&gt;

&lt;p&gt;And for the simplest level of “security” the API checks the HTTP Refer header from a known whitelist and rejects HTTP requests that are invalid.&lt;/p&gt;

&lt;p&gt;To integrate this into a web page I built a really simple JavaScript file that’s hosted alongside the API which simply loads the comments and appends them to the page along with a form. The form, when submitted, submits a new comment and reloads the comments.&lt;/p&gt;

&lt;p&gt;This approached worked fine on my computer, but I soon as I deployed it to an Azure site and tried it I ran into the dreaded &lt;a href=&quot;https://en.wikipedia.org/wiki/Cross-origin_resource_sharing&quot;&gt;CORS&lt;/a&gt; issue. Rather than open up that can of worms, I decided to change gears and implement CommentR using an IFrame.&lt;/p&gt;

&lt;h2 id=&quot;the-final-design-iframes&quot;&gt;The Final Design: IFrames&lt;/h2&gt;

&lt;p&gt;As it turns out, this is the approach that Disqus uses! It’s actually very simple:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Include a reference to some JavaScript resource. This code is responsible for setting up the IFrame and setting the correct src.&lt;/li&gt;
  &lt;li&gt;The IFrame src is a page that displays the comments specifically for the parent page (keyed using the same &lt;code class=&quot;highlighter-rouge&quot;&gt;permalink&lt;/code&gt; URL as before).&lt;/li&gt;
  &lt;li&gt;All AJAX calls occur from within the IFrame, so the same-origin policy applies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One clever trick I implemented was to have the embedded page “publish” a message whenever the content is loaded with the total scrollHeight of the content. The original JavaScript resource in the parent window responds by dynamically re-sizing the IFrame. So for the user, the comments window is completely seamless.&lt;/p&gt;

&lt;p&gt;You should be able to see the final working version below. Leave a comment!&lt;/p&gt;
</content>
  </entry>

  <entry>
    <id>http://josephdaigle.me/2015/09/16/hello-world</id>
    <published>2015-09-16T00:00:00+00:00</published>
    <updated>
       2015-09-16T00:00:00+00:00
      
    </updated>
    <author>
			<name>Joseph Daigle</name>
		</author>
		<link type="text/html" rel="alternate" href="http://josephdaigle.me/2015/09/16/hello-world.html" />
		<title>Hello World</title>
		<content type="html">&lt;p&gt;Hello World!&lt;/p&gt;
</content>
  </entry>

</feed>
