Upgrading to .NET Core RTM and CamelCasing

This post is primarily a place holder and reminder to review Rick Strahl’s post on this topic a few more times.

The change in default serialization does not yet affect me because I was not relying on RC2 for anything serious. However it is critical to note this default behavior for future reference because many of my APIs serialize “as is” so most of my JSON is PascalCase and changing that midstream would bork every client that relies on case sensitivity in the data.

I particularly like Rick’s take on this:

“Personally I prefer to see stuff like this as an easily accessible option, and not something that is rammed down your throat - serialization shouldn't arbitrarily change the naming of properties. While that is often desirable I'm betting there are plenty of scenarios (especially when dealing with .NET to .NET) where you'd much rather have the serialized content reflect the original naming.

“It's especially frustrating in that this doesn't just affect server code where you could easily refactor, but client side code that may already be running. It also makes it harder to port existing code to ASP.NET core and it's not exactly something that's super easy to find if you're searching unless you already know that there serializer settings being sent to JSON.NET somewhere in the framework.”

Well, now the real play begins with .NET Core 1.0 RTM.

ASP.NET Web API and IDisposable Aspect with ActionFilterAttribute

I needed to apply an aspect to my ASP.NET Web API 2 services on every controller. The trick was that I needed an IDisposable object to be created before the action method executed and then disposed when the action method completed. It’s easy enough to write an ActionFilterAttribute to do something at the beginning or at the end of a controller’s action method being called. But how to you maintain state between the OnActionExecuting and the OnActionExecuted events? That’s what this little snippet does.

public class DisposableActionFilterAttribute : ActionFilterAttribute
{
  private readonly IDisposableProvider _provider;

  public DisposableActionFilterAttribute()
  {
    _provider = IoC.Instance.Container.Resolve<IDisposableProvider>();
  }

  public override void OnActionExecuting(HttpActionContext actionContext)
  {
    base.OnActionExecuting(actionContext);
    IDisposable obj = _provider.CreateDisposableObjectMethod() as IDisposable;
    actionContext.Request.Properties[Consts.DisposableObjectPropertyKey] = obj;
  }

  public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
  {
    base.OnActionExecuted(actionExecutedContext);
    IDisposable obj = actionExecutedContext.Request.Properties[Consts.DisposableObjectPropertyKey]
      as IDisposable;
    if (null != obj) obj.Dispose();
  }
}

And now you wire it up and presto change-o, you’ve got an IDisposable created before execution and disposed after execution. And here’s the simple wire up for global application of the attribute in the Global.asax.cs code:

public class WebApiApplication : System.Web.HttpApplication
{
  protected void Application_Start()
  {
    //..
    GlobalConfiguration.Configuration.Filters.Add(
      new DisposableActionFilterAttribute());
    //..

I do realize there are many examples of the ActionFilterAttribute and this technique, but it’s easier to search my own blog later when I need to remember how to do this. Happy Monday!

Castle Windsor, ASP.NET MVC and Web API in the Same Project

Many thanks to the original source by ArtisanCode on GitHub I’ve enjoyed for solving this problem. You may also enjoy Radenko’s post and Raymund’s post. I hope that you will find what I have learned from these sources helpful. The requirement was running ASP.NET MVC and Web API in the same project with a single inversion of control (IoC) container shared by both, though I never ended up using injection for my MVC controllers as I had planned.

My personal preference in the past has been Castle Windsor, in part because I like the ability to do interception so easily. More on interception in a future post. For now, have a look at how easy it is to wire up. First, we wire up the container in the Application_Start method in your Global.asax.cs class that inherits from System.Web.HttpApplication:

IoC.Instance.Container.Install(new DependencyConfig());
IoC.Instance.Container.BeginScope();	
GlobalConfiguration.Configuration.DependencyResolver = 
   new CastleDependencyResolver(IoC.Instance.Container);

Then we wire up the DependencyConfig class mentioned in the above snippet.

public class DependencyConfig : IWindsorInstaller
{
   public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      //... config stuff ... blah blah blah

      //register a component with a custom interceptor for capturing some aspect
      container.Register(Component.For<IMyComponent>()
         .ImplementedBy<MyComponent>()
         .LifestyleSingleton()
         .Interceptors(InterceptorReference.ForType<MyInterceptor>())
         .Anywhere);

And implement your interceptor with something like this:

public class MyInterceptor : IInterceptor
{
   public void Intercept(IInvocation invocation)
   {
      //do something before the call is executed
      //execute the call
      invocation.Proceed();
	  //do something after the call is executed
   }
}

Now put it all together and you have ApiControllers injecting your components for you. And you can get components directly when you need them using the IoC singleton I wrote like this:

var mycomp = IoC.Instance.Container.Resolve<IMyComponent>();

Here’s the IoC singleton:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.Windsor;

namespace MyCastle
{
   public class IoC
   {
      private static volatile IoC _instance;
      private static object _syncRoot = new object();

      private readonly WindsorContainer container;

      private IoC()
      {
         container = new WindsorContainer();
      }

      public static IoC Instance
      {
         get
         {
            if (null == _instance)
            {
               lock (_syncRoot)
               {
                  if (null == _instance)
                  {
                     _instance = new IoC();
                  }
               }
            }
            return _instance;
         }
      }

      public WindsorContainer Container { get { return container; } }
   }
}

And where does the CastleDependencyResolver and CastleDependencyScope classes come from? That’s the fun part. First, you’ll need two NuGet packages:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Castle.Core" version="3.3.3" targetFramework="net45" />
  <package id="Castle.Windsor" version="3.3.0" targetFramework="net45" />
</packages>

Then you just need the ArtisanCode code for those two classes. For my own use, I’ve modified them a bit in my own projects but you may find that you can use them right out of the box or even adopt the entire WebApiCastleIntegration library.

There you have it.

Bad Code Leads to Worse Code

It is 100% my fault. I wrote a small library for accessing files in Azure Storage. It has an Exists method. But rather than returning false when the path does not exist, it throws a 404 Not Found exception. This is bad code. It should just return false. And not having time to fix it, I wrote the following worse code.

try
{
   var exists = await _blobIo.Exists(fileName);
}
catch (Exception e)
{
   if (null != e.InnerException && e.InnerException.Message.Contains("404"))
   {
      fileName = $"other/{key}/{id}.{ext}";
      try
      {
         var exists = await _blobIo.Exists(fileName);
      }
      catch (Exception ie)
      {
         if (null != ie.InnerException && ie.InnerException.Message.Contains("404"))
         {
            throw new HttpResponseException(
               new HttpResponseMessage(HttpStatusCode.NotFound)
               {
                  Content = new JsonContent(new 
                  { 
                     Error = "Not Found", 
                     Message = "Content not found." 
                  })
               });
         }
      }
   }
}

I hang my head in shame. Lesson: fix the bad code. Don’t write worse code to work around the bad code.

Update
Once the fire was put out, I fixed the original library and now have this code. It's better. Could be improved, but it's not as ugly as before.

if (false == await _blobIo.Exists(fileName))
{
   fileName = $"other/{key}/{id}.{ext}";
   if (false == await _blobIo.Exists(fileName))
   {
      throw new HttpResponseException(
         new HttpResponseMessage(HttpStatusCode.NotFound)
         {
            Content = new JsonContent(new 
               { 
                  Error = "Not Found", 
                  Message = "Content not found."
               })
         });
   }
}

Second lesson: Don't let stinky code lie around too long. Clean up your messes.

Context Switching and Task<Result>.ConfigureAwait Method

While heavily involved in a few ASP.NET Web API 2 projects over the past year, I’ve learned from experience that context switching, marshaling between threads when using the async and await constructs in C# can be undesirable.

To avoid the context switching which is undeniably needed in a UI application where you’re offloading work from the UI thread, the default value of “true” for the ConfigureAwait Method on the Task<Result> class, one must set the “continueOnCapturedContext” to false. Like this:

var user = await repo.GetUser(id).ConfigureAwait(false);

There is some debate as to whether this is helpful in an ASP.NET application given the request is handled on a thread pool thread which is returned to the pool while the asynchronous task is running.

The issue I’ve noticed is that in some cases setting the “continueOnCapturedContext” to false, eliminates the need to marshal the continuation of your code back to the original context and use of another thread pool thread. While there are no noticeable performance advantages, I have noticed that I experience fewer threading exceptions when I allow the execution to continue on the thread that just executed my asynchronous work.

Exploring .NET Core 1.0

After a busy year working on coding up REST services with ASP.NET Web API 2.0 and doing zero blogging, I’m finally taking a little time to explore the .NET Core 1.0 bits released recently in RC2 and watching a number of presentations. I’m very excited about what I’m learning and will blog more about it but here’s a list of links that I’ve found most instructive and useful.

First, the announcement of RC2: announcing-asp-net-core-rc2

Next, the install: https://www.microsoft.com/net 

The unforgettable Scotts at TechEd: Introducing ASP.NET Core 1.0 

And the ASP.NET Core Deep Dive into MVC that followed.

After some experimentation with the preview tooling, trying to figure out how to create a .NET Core class library NuGet package was made easier with this very helpful article: how-to-create-a-nuget-package-with-your-library

And understanding the IIS deployment story was made so much more clear just the other day by the always helpful Rick Strahl: Publishing-and-Running-ASPNET-Core-Applications-with-IIS

Then I went looking for something similar for using Apache as the reverse proxy in front of a Kestrel app and found this: linuxproduction

Which finally led me to clone the KestrelHttpServer.

Exploring the code and the repo has been interesting. I especially noted with interest the recent pull request to Downtarget Kestrel to NETStandard 1.3.

The comment that Kestrel needed no functionality beyond 1.3 and that this allowed greater flexibility with current scenarios was very interesting.

The most important piece of learning so far has been the very brief discussion of the Libuv library used by Kestrel: http://libuv.org/

This amazing little library is used by Node.js and now by the ASP.NET Core web server called Kestrel and according to reports in Microsoft presentations has served up 3.2 million requests per second on a single bare metal machine. Even with a beefy machine, that is impressive.

Seeing how Kestrel uses Libuv is even more interesting and makes me think I ought to explore it as the next engine for a ServiceWire and ServiceMq implementation that could be deployed as a Docker container.

I was especially interested to see how .NET Core 1.0 utilizes native libraries in the Kestrel integration and use of Libuv as a NuGet package: KestrelHttpServer Internal Networking

The runtimes contained in the Libuv package used by Kestrel were also interesting to note:

libuv_runtimes

This concludes about a week of research on the side where I could sneak in an hour or two here or there. I’m eager to keep learning.

MongoDB C# Driver 2.0 AsQueryable Alternative

I’m a fan of LINQ and the IQueryable<T> interface power to compose dynamic queries based on input parameters. So when I needed to compose just such a query in a repository for a MongoDB collection, I found that the MongoDB C# 2.0.1 driver is currently missing the AsQueryable method which is slated for 2.1 release of the driver.

After a little searching, I found the Filter Definition Builder documentation and a happy alternative to building up or composing a query based on the presence of query parameters.

And here is a code sample:

public async Task<IEnumerable<MyData>> GetByQuery(MyDataQuery query)
{
    var filter = ComposeFilter(query);
    if (!query.Ascending)
    {
        var responses = await _invoiceCollection
            .Find(filter)
            .SortByDescending(x => x.TransactionDate)
            .Skip(query.Index)
            .Limit(query.Limit)
            .ToListAsync();
        return responses;
    }
    var ascResponses = await _invoiceCollection
        .Find(filter)
        .SortBy(x => x.TransactionDate)
        .Skip(query.Index)
        .Limit(query.Limit)
        .ToListAsync();
    return ascResponses;
}

private FilterDefinition<MyData> ComposeFilter(MyDataQuery query)
{
    var builder = Builders<MyData>.Filter;
    var filter = builder.Eq(x => x.CustomerId, query.CustomerId);
    if (query.StartDate.HasValue)
    {
        filter = filter & builder.Gte(x => x.TransactionDate, query.StartDate.Value);
    }

    if (query.EndDate.HasValue)
    {
        filter = filter & builder.Lt(x => x.TransactionDate, query.EndDate.Value);
    }

    if (query.InvoiceId != null)
    {
        filter = filter & builder.Eq(x => x.InvoiceID, query.InvoiceId);
    }

    if (query.ItemId != null)
    {
        filter = filter & builder.Eq(x => x.ItemID, query.ItemId);
    }
    return filter;
}

So now you have a dynamic query based on composition logic. Of course this is a very simple example and there are bound to be far more sophisticated ways of doing the same thing, but I found this one worked very well for me.

Microsoft Graph Engine

This tweet from Scott Hanselman caught my eye because I spent nearly all of 2014 working on a graph solution for my employer that had it’s genesis in my study of Neo4J but primarily in my reading of this Microsoft Research paper (Sakr, Elnikety, and He) produced in 2012.

graphtweet

The essence of the Microsoft Research paper is storing edges (node relationships) in memory. So that’s what I did with unmanaged memory allocated in blocks using the Marshal.AllocHGlobal method. My own efforts were very specific with respect to my employer’s needs at the time and not really useable as a general purpose tool, so I was very pleased to see that Microsoft Research had an ongoing project called Trinity working to produce a more general purpose tool based on many of the same concepts originally explored by Sakr, Elnikety and He.

That tool was recently quietly released as the Microsoft Graph Engine. I’ve only had a little time to explore and understand it and look forward to spending more time using it soon. The essence is the same. Store the data in sequential chunks in raw unmanaged memory. Graph Engine uses Visual Studio to generate code on the fly using a meta language called Trinity Specification Language (TSL). Have a look through the documentation. If you’re considering graph database work, put Microsoft’s Graph Engine on your list of items to evaluate.