tsJensen

A quest for software excellence...

Microsoft REST API Guidelines

I’m a big believer in establishing standards for your REST APIs. I like this one from Microsoft but there are others. What I like about this particular guideline is the structural organization and its brevity. The introductory paragraph provides the reasoning and justification behind REST even when there are language specific SDKs made available.

Developers access most Microsoft Cloud Platform resources via RESTful HTTP interfaces. Although each service typically provides language-specific frameworks to wrap their APIs, all of their operations eventually boil down to REST operations over HTTP. Microsoft must support a wide range of clients and services and cannot rely on rich frameworks being available for every development environment. Thus a goal of these guidelines is to ensure Microsoft REST APIs can be easily and consistently consumed by any client with basic HTTP support.

One thing that would be nice to have is a standard for filtering, paging, etc., on the URL as query parameters. These get defined differently by every REST service architect out there. Or so it seems. A good jumping off point for some research and thought.

And I want to thank my friend Pablo for sending me the link to this.

Upgrade to Visual Studio 2015 Update 3 and .NET Core Tooling

Yesterday I installed the Visual Studio 2015 Update 3 and began playing with a new ASP.NET Core API project. But the NuGet packages needed to be updated and when I tried to update them, they could not be found.

Clue: Pay attention to the little black flag in the upper right corner of Visual Studio 2015 (flag) and install the .NET Core 1.0.0. VS 2015 Tooling Preview 2.

tooling

The install took a fair amount of time, but when it was done, I created a new ASP.NET Core API project and bada-bing, everything seems happy.

MSBuild and Web Deployment Just Stops

This super helpful error message and some Googling led to a solution. I really did not believe it when I found it. But some days are like that.

Severity    Code    Description    Project    File    Line    Suppression State
Error        Web deployment task failed. ((6/29/2016 10:07:24 AM) An error occurred when the request was processed on the remote computer.) (6/29/2016 10:07:24 AM) An error occurred when the request was processed on the remote computer. Unable to perform the operation. Please contact your server administrator to check authorization and delegation settings.

And the winning blog post (certainly not MS docs) goes to A Software Guy’s Blog (Eric Kelm).

Summary
When you add Microsoft Web Deploy to an IIS server, the install adds two local user accounts, both with an expiring password. So 90 days, or whatever your expiration policy is, after you install, web deployment just stops working. The trick is to modify both accounts to check “password never expires”.

Thanks, Eric. And thanks, Microsoft. Eric’s post is four years old and this problem still exists. Epic fail.

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.