Replace the Default Server of OwinHost.exe with Nowin in Visual Studio 2013

This post will show you how to you can replace the default server of OwinHost.exe with Nowin in Visual Studio 2013
2013-09-27 11:14
Tugberk Ugurlu


Wow, I cannot believe I'm writing this post :) It's really exciting to see that .NET web stack has evolved this much. First, we had a web framework shipping out of band: ASP.NET MVC. Then, we were given a chance to play with hosting agnostic web frameworks such as ASP.NET Web API and ASP.NET SignalR (I know, their names are still confusing and give an impression that those frameworks are still bound to ASP.NET but they are actually not). Recently, we have been embracing the idea of separating the application, server and the host from each other by making our applications OWIN compliant.

By this way, we can easily build our pipeline on our own and switch the underlying host or server easily. Visual Studio 2013 even has a really nice extensibility point to switch the underlying host and still have the F5 experience. OwinHost.exe is one of those hosts that we can use as an alternative to IIS. Today, we can even take this further and completely replace the underlying server (which is HttpListener by default with OwinHost.exe) by preserving the host. There is an OWIN compliant server implementation called Nowin developed by a very clever guy, Boris Letocha. This server uses a raw .NET socket to listen to the HTTP requests coming in through the wire and will respond to them. By looking at the repository's readme file, I can say that this component is not production ready but will work out just fine for demonstration purposes.

I created a mini sample application to show you this cool feature. You can find it on my GitHub OwinSamples repository, too. It only contains the following startup class and initially have two NuGet packages installed: Owin and OwinHost.

using AppFunc = Func<IDictionary<string, object>, Task>;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use(new Func<AppFunc, AppFunc>(ignoreNext => Invoke));
    }

    public async Task Invoke(IDictionary<string, object> env)
    {
        // retrieve the Request Data from the environment
        string path = env["owin.RequestPath"] as string;

        if (path.Equals("/", StringComparison.OrdinalIgnoreCase))
        {
            // Prepare the message
            const string Message = "Hello World!";
            byte[] bytes = Encoding.UTF8.GetBytes(Message);

            // retrieve the Response Data from the environment
            Stream responseBody = env["owin.ResponseBody"] as Stream;
            IDictionary<string, string[]> responseHeaders = 
                env["owin.ResponseHeaders"] as IDictionary<string, string[]>;

            // write the headers, response body
            responseHeaders["Content-Type"] = new[] { "text/plain" };
            await responseBody.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}

I am not sure if you have noticed this but Visual Studio 2013 even has an item template for creating an OWIN startup class:

image

This seems nice but it secretly installs the Microsoft.Owin package, which is unnecessary if you ask me. Owin NuGet package should be enough IMHO.

I also applied the steps explained in my "OwinHost.exe on Visual Studio 2013" post to get my application running on top of OwinHost and here is the result:

image

Here, my host is OwinHost.exe and it uses the Microsoft.Owin.Host.HttpListener as the server by default. At the application level, we don't need to know or care about which server we are on but most of the OWIN server implementations expose their names through the server.Capabilities dictionary:

image

What we want to accomplish here is to keep the host as it is and only replace the server component that it uses underneath. As our host (OwinHost.exe) is OWIN compliant, it can work with any other type of OWIN compliant server implementations and one of them is Nowin. Installing Nowin over NuGet into your project is the first step that you need to do.

image

However, this's not enough by itself as OwinHost.exe has no idea that we want to use Nowin as our server. Luckily, we can manipulate the arguments we pass onto OwinHost.exe. You can configure these arguments through the Web pane inside the Visual Studio Project Properties window. Besides that, OwinHost.exe accepts a few command line switches and one of them is the –s (or –-server) switch to load the specified server factory type or assembly. These are all we needed.

image

After saving the changes we have made, we can run the application and get the same result on top of a completely different server implementation:

image

Also with the same way as we did earlier, we can see that the switch has been made and Nowin is in use:

image

Being able to do all of this is a very big deal; especially if you think that we have been tied to IIS for very long time. I'm so happy to see .NET web stack moving towards this flexible direction.

Pro ASP.NET Web API Book is Shipped and Available on Amazon

Today, I am very proud to say that Pro ASP.NET Web API Book is now shipped and available on Amazon for paperback sales :)
2013-09-25 06:28
Tugberk Ugurlu


You may be aware that I have been working on a book for while now: Pro ASP.NET Web API from Apress. Alexander Zeitler, Ali Kheyrollahi and myself have been hard at work lately to complete this high quality asset for ASP.NET Web API lovers. Today, I am very proud to say that Pro ASP.NET Web API is now available for sale on Amazon as paperback! I would like to thank everybody who put his/her time into this book to make it a really good resource.

Here is a bit information about the book structure:

In Part I, you'll get up to speed on Web API's modern HTTP programming model, asynchronous programming in .NET framework and basic HTTP information. Part II takes you through building a real application so you can see straight away how to put this new technology into practice. The second half of the book features dedicated chapters on topics like routing, controllers, validation and tracing, and we will have chapters on performance, dependency injection and an all-important look at unit testing to help you prepare your application for the real world.

Please leave your comments on Amazon as they are really important for us. Hope you will enjoy the book :)

Resources

Logging in the OWIN World with Microsoft.Owin: Introduction

Microsoft implementation of OWIN (Microsoft.Owin or Katana for now) has a great logging infrastructure and this post will walk you through the basics of this component.
2013-09-18 16:14
Tugberk Ugurlu


Microsoft implementation of OWIN (called Microsoft.Owin or Katana for now) has a great infrastructure for logging under Microsoft.Owin.Logging namespace inside the Microsoft.Owin assembly. Same as all other Microsoft.Owin components, the logging infrastructure is built on top of interfaces and there are two of them: ILoggerFactory and ILogger. The default implementation is using .NET Framework tracing components heavily such as System.Diagnostics.TraceSource and System.Diagnostics.TraceSwitch. You can learn about these components and how to instrument your applications with them through the .NET Development Guide's Tracing section on MSDN.

The responsibility of the logger factory is to construct a new logger when needed. You can see how ILoggerFactory interface looks like below:

namespace Microsoft.Owin.Logging
{
    /// <summary>
    /// Used to create logger instances of the given name.
    /// </summary>
    public interface ILoggerFactory
    {
        /// <summary>
        /// Creates a new ILogger instance of the given name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        ILogger Create(string name);
    }
}

As you can see, the Create method returns an ILogger implementation. The ILogger implementation is solely responsible for writing the logs through its one and only method: WriteCore.

namespace Microsoft.Owin.Logging
{
    /// <summary>
    /// A generic interface for logging.
    /// </summary>
    public interface ILogger
    {
        /// <summary>
        /// Aggregates most logging patterns to a single method.  This must be compatible with the Func representation in the OWIN environment.
        /// 
        /// To check IsEnabled call WriteCore with only TraceEventType and check the return value, no event will be written.
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        /// <returns></returns>
        bool WriteCore(TraceEventType eventType, int eventId, object state, 
            Exception exception, Func<object, Exception, string> formatter);
    }
}

For these interfaces, there are two implementations provided by the Microsoft.Owin assembly for logging: DiagnosticsLoggerFactory (publicly exposed) and DiagnosticsLogger (internally exposed). However, these are the types provided by the Microsoft's OWIN implementation and don't belong to core .NET framework. As it's discouraged to put non-framework types inside the IAppBuilder properties dictionary and request's environment, a Func is put inside the IAppBuilder properties dictionary with a key named "server.LoggerFactory". Here is the signature of that Func.

using TraceFactoryDelegate = 
    Func
    <
        string, 
        Func
        <
            TraceEventType, 
            int, 
            object, 
            Exception, 
            Func
            <
                object, 
                Exception, 
                string
            >, 
            bool
        >
    >;

Through this delegate, you are expected to create a Func object based on the logger name and this Func will be used to write logs. The currently provided extension methods to work with the Katana’s logging infrastructure hides these delegates from you. Here are a few extension methods under Microsoft.Owin.Logging namespace for the IAppBuilder interface:

public static void SetLoggerFactory(
    this IAppBuilder app, ILoggerFactory loggerFactory);
    
public static ILoggerFactory GetLoggerFactory(
    this IAppBuilder app);
    
public static ILogger CreateLogger(
    this IAppBuilder app, string name);

All these extension methods work on the TraceFactoryDelegate Func instance shown above but it’s all hidden from us as mentioned.

So, how we can take advantage of this provided components? It’s quite easy actually. You can create separate loggers for each of your components using one of the CreateLogger extension method overloads for the IAppBuilder interface and use that logger to write log messages. The following is just a little sample to give you a hint:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        Log1(app);
        app.Use<MyCustomMiddleware>(app);
    }

    private void Log1(IAppBuilder app) 
    {
        ILogger logger = app.CreateLogger<Startup>();
        logger.WriteError("App is starting up");
        logger.WriteCritical("App is starting up");
        logger.WriteWarning("App is starting up");
        logger.WriteVerbose("App is starting up");
        logger.WriteInformation("App is starting up");

        int foo = 1;
        int bar = 0;

        try
        {
            int fb = foo / bar;
        }
        catch (Exception ex)
        {
            logger.WriteError("Error on calculation", ex);
        }
    }
}

public class MyCustomMiddleware : OwinMiddleware
{
    private readonly ILogger _logger;

    public MyCustomMiddleware(
        OwinMiddleware next, IAppBuilder app) : base(next)
    {
        _logger = app.CreateLogger<MyCustomMiddleware>();
    }

    public override Task Invoke(IOwinContext context)
    {
        _logger.WriteVerbose(
            string.Format("{0} {1}: {2}", 
            context.Request.Scheme, 
            context.Request.Method, 
            context.Request.Path));

        context.Response.Headers.Add(
            "Content-Type", new[] { "text/plain" });
            
        return context.Response.WriteAsync(
            "Logging sample is runnig!");
    }
}

There are a few things I would like to touch on here:

  • I used generic CreateLogger method to create loggers. This will create loggers based on the name of the type I’m passing in. In view of the default logger implementation provided by the Katana, this means that we will create TraceSource instances named as the full type name.
  • You can see that I receive an IAppBuilder implementation instance through the constructor of my middleware and I used that instance to create a logger specific to my middleware. I can hold onto that logger throughout the AppDomain lifetime as all members of my logger are thread safe.
  • Instead of using the WriteCore method to write logs, I used several extension methods such as WriteVerbose to write specific logs.

This is not enough by default as we didn’t configure what kind of tracing data we are interested in and how we would like to output them. We need to configure Trace Switches and Trace Listeners properly to instrument our application. Microsoft.Owin is root switch and if we enable it, we will see all messages we write through our loggers. The following configuration will enable the Microsoft.Owin switch:

<configuration>
  <system.diagnostics>
    <switches>
      <add name="Microsoft.Owin" value="Verbose" />
    </switches>
  </system.diagnostics>
</configuration>

When we run our application on Debug mode, we can see that the Output window will show our log data:

image

We can take it further and configure different listeners for different switches. The following configuration will enable TextWriterTraceListener for LoggingSample.MyCustomMiddleware SourceSwitch:

<configuration>
  <system.diagnostics>
    <switches>
      <add name="Microsoft.Owin" value="Verbose" />
    </switches>

    <sharedListeners>
      <add name="console" type="System.Diagnostics.ConsoleTraceListener" />
    </sharedListeners>

    <trace autoflush="true" />
    
    <sources>
      <source name="Microsoft.Owin">
        <listeners>
          <add name="console" />
        </listeners>
      </source>

      <source name="LoggingSample.MyCustomMiddleware">
        <listeners>
          <add name="file" 
               type="System.Diagnostics.TextWriterTraceListener" 
               initializeData="traces-MyCustomMiddleware.log" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
</configuration>

Now we can see that our middleware’s logs will only be written into traces-MyCustomMiddleware.log file:

image

I think this post should give you a pretty good understanding of how Katana’s logging infrastructure has been set up and works under the hood. I plain on writing a few more posts on this logging infrastructure. So, stay tuned. Also, as I get used to the concepts of OWIN, I started to think that this logging infrastructure is more fitting as an OWIN extension (just like the SendFile extension) rather than being tied to Katana.

The sample I used here also available on GitHub inside my OwinSamples repository.

Good Old F5 Experience With OwinHost.exe on Visual Studio 2013

With Visual Studio 2013 RC, we are introduced to a new extensiblity point: External Host. This gives us the F5 experience Wwth OwinHost.exe on VS 2013 and this post walks you through this feature.
2013-09-09 14:15
Tugberk Ugurlu


Since the first day I started developing software solutions for web on Visual Studio, I have had the 'F5' experience. It's nice, clean and easy to get up a web application running without digging through a specific exe file to invoke. After Cassini, our development environments have change a little with IIS Express, in a nice way of course. With the introduction of IIS Express, running it through the command line is also possible but we still have the ultimate F5 experience to get it up.

Today, we are still in love with IIS but with the introduction of OWIN, it's now much easier to build your application in an hosting agnostic way and Katana Project is providing components for hosting your application outside of IIS with a very thin wrapper on top of HttpListener. Actually, the HttpListener is one of the options in terms of receiving the HTTP request and sending back the response at the operating system level. The OwinHost.exe even abstracts that part for us. The OwinHost.exe is a very simple tool which will bring your application startup and the host layer together. Then, it will get out of your way.

However, the development environment with a custom executable tool can be very frustrating, especially in .NET ecosystem where we have really great tooling all over the place. Typically, if you would like to host your application with OwinHost.exe in your development environment, here is what you need to do:

  1. Create a class library project and install Microsoft.Owin package from MyGet ASP.NET Web Stack Nightlies feed.
  2. Add your startup class and build your pipeline with several OWIN middlewares inside the Configuration method.
  3. Add an assembly level attribute for OwinStartupAttribute to indicate your start-up class.
  4. Optionally, install the OwinHost.exe from the same feed into your project or install it any other place.
  5. Go to project properties window and navigate the "Build" pane. Change the "Output Path" from "bin\Debug\" or "bin\Release\" to "bin".
  6. Open up a command prompt window and navigate the root of your project.
  7. Execute the OwinHost.exe from the command prompt window you have just opened up and here you have the running HTTP application.

First four steps are the ones that we are OK with but the rest is generally frustrating. What we really want there is to have the F5 experience that we are used to. With Visual Studio 2013 RC, we are introduced to a new extensibility point in Visual Studio: External Host. With this feature, we are now able to replace the host layer completely. Let's see how. First, let's create a new ASP.NET Web Application:

image

If you are new to this "One ASP.NET" idea, this window may seem a bit awkward at first but think this as an open buffet of frameworks and modules. After selecting this, we will see the open buffet window:

image

For our sample application, we can continue our merry way with the empty project template without any core references. However, the Visual Studio project will still include System.Web and its related references as shown in the below picture.

image

Including the web.config file, we can remove all of this System.Web related stuff now to run our pure OWIN based application. In some cases, we may need web.config though as OwinHost.exe uses it for some cases such as binding redirects. After removing these junks, we have a project as seen below:

image

As we mentioned before, Visual Studio 2013 RC has the external host extensibility support for web applications and we can see this extensibility point by opening the Properties window of the project.

image

You get the IIS Express and Local IIS out of the box with Visual Studio 2013 RC (and yes, Cassini is dead for God's sake). However, it's really easy to get in there and OwinHost NuGet package has the specific installation scripts to register itself as an external host. To get this feature from OwinHost, we just need to add it into our project through NuGet. Today, OwinHost 2.0.0-rc1 package is available on NuGet.org and when we install the package, we get a warning popup from Visual Studio:

image

When we accept the integration, we can see the OwinHost showing up inside the external servers list.

image

If you select the OwinHost option, we can see the option which we can configure if we need to.

image

All these information is stored inside the project file (csproj if you are on C#):

image

Now, I can build my OWIN pipeline and have it running on top of OwinHost.exe just by pressing F5 inside the Visual Studio 2013. For demonstration purposes, I wrote up the following Startup class:

using Microsoft.Owin;
using Owin;
using OwinHostVsIntegrationSample;
using System.IO;

[assembly: OwinStartup(typeof(Startup))]
namespace OwinHostVsIntegrationSample
{
    public class Startup
    {
        public void Configuration(IAppBuilder app) 
        {
            app.Use(async (ctx, next) => 
            {
                TextWriter output = ctx.Get<TextWriter>("host.TraceOutput");
                output.WriteLine("{0} {1}: {2}", 
                    ctx.Request.Scheme, ctx.Request.Method, ctx.Request.Path);

                await ctx.Response.WriteAsync("Hello world!");
            });
        }
    }
}

When I press CTRL + F5, I have my Web application running without debugging on top of OwinHost.exe:

image

Very nice and elegant way of running your application with a custom server! Besides this, we can certainly run our application in debug mode and debug our OWIN pipeline. If you press F5 to run your web application in debug mode, the VS will warn you if you don't have a Web.config file:

image

Not sure why this is still needed but after selecting the first choice, VS will add a web.config file with the necessary configuration and we can now debug our middlewares:

image

Very neat. This sample I demonstrated is also available on GitHub. Enjoy the goodness :)

Owin.Dependencies: An IoC Container Adapter Into OWIN Pipeline

Owin.Dependencies is an IoC container adapter into OWIN pipeline. This post will walk you through the Autofac IoC container implementation and ASP.NET Web API framework adapter for OWIN dependencies.
2013-09-06 07:33
Tugberk Ugurlu


Update on 2013-11-05:

The project has been renamed from Owin.Dependencies to DotNetDoodle.Owin.Dependencies.

Dependency inject is the design pattern that most frameworks in .NET ecosystem have a first class support: ASP.NET Web API, ASP.NET MVC, ASP.NET SignalR, NancyFx and so on. Also, the most IoC container implementations for these frameworks allow us to have a per-request lifetime scope which is nearly always what we want. This's great till we stay inside the borders of our little framework. However, with OWIN, our pipeline is much more extended. I have tried to give some insight on OWIN and its Microsoft implementation: Katana. Also, Ali has pointed out some really important facts about OWIN on his post. Flip also has really great content on OWIN. Don't miss the good stuff from Damian Hickey on his blog and his GitHub repository.

Inside this extended pipeline, the request goes through several middlewares and one of these middlewares may get us into a specific framework. At that point, we will be tied to framework's dependency injection layer. This means that all of your instances you have created inside the previous middlewares (assuming you have a different IoC container there) basically are no good inside your framework's pipeline. This issue had been bitten me and I was searching for a way to at least work around this annoying problem. Then I ended up talking to @randompunter and the idea cam out:

Actually, the idea is so simple:

  • Have a middleware which starts a per-request lifetime scope at the very beginning inside the OWIN pipeline.
  • Then, dispose the scope at the very end when the pipeline ends.

This idea made me create the Owin.Dependencies project. Owin.Dependencies is an IoC container adapter into OWIN pipeline. The core assembly just includes a few interfaces and extension methods. That's all. As expected, it has a pre-release NuGet package, too:

PM> Install-Package DotNetDoodle.Owin.Dependencies -Pre

Besides the Owin.Dependencies package, I have pushed two different packages and I expect more to come (from and from you, the bright .NET developer). Basically, we have two things to worry about here and these two parts are decoupled from each other:

  • IoC container implementation for Owin.Dependencies
  • The framework adapter for Owin.Dependencies

The IoC container implementation is very straightforward. You just implement two interfaces for that: IOwinDependencyResolver and IOwinDependencyScope. I stole the dependency resolver pattern that ASP.NET Web API has been using but this may change over time as I get feedback. My first OWIN IoC container implementation is for Autofac and it has a seperate NuGet package, too:

PM> Install-Package DotNetDoodle.Owin.Dependencies.Autofac -Pre

The usage of the OWIN IoC container implementation is very simple. You just need to have an instance of the IOwinDependencyResolver implementation and you need to pass that along the UseDependencyResolver extension method on the IAppBuilder interface. Make sure to call the UseDependencyResolver before registering any other middlewares if you want to have the per-request dependency scope available on all middlewares. Here is a very simple Startup class after installing the Owin.Dependencies.Autofac package:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        IContainer container = RegisterServices();
        AutofacOwinDependencyResolver resolver = new AutofacOwinDependencyResolver(container);

        app.UseDependencyResolver(resolver)
            .Use<RandomTextMiddleware>();
    }

    public IContainer RegisterServices()
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterType<Repository>()
                .As<IRepository>()
                .InstancePerLifetimeScope();

        return builder.Build();
    }
}

After registering the dependency resolver into the OWIN pipeline, we registered our custom middleware called "RandomTextMiddleware". This middleware has been built using a handy abstract class called "OwinMiddleware" from Microsoft.Owin package. The Invoke method of the OwinMiddleware class will be invoked on each request and we can decide there whether to handle the request, pass the request to the next middleware or do the both. The Invoke method gets an IOwinContext instance and we can get to the per-request dependency scope through the IOwinContext instance. Here is the code:

public class RandomTextMiddleware : OwinMiddleware
{
    public RandomTextMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        IOwinDependencyScope dependencyScope = 
            context.GetRequestDependencyScope();
            
        IRepository repository = 
            dependencyScope.GetService(typeof(IRepository)) 
                as IRepository;

        if (context.Request.Path == "/random")
        {
            await context.Response.WriteAsync(
                repository.GetRandomText()
            );
        }
        else
        {
            context.Response.Headers.Add(
                "X-Random-Sentence", 
                new[] { repository.GetRandomText() });
                
            await Next.Invoke(context);
        }
    }
}

I accept that we kind of have an anti-pattern here: Service Locator. It would be really nice to get the object instances injected as the method parameters but couldn't manage to figure out how to do that for now. However, this will be my next try. Here, we get an implementation of the IRepository and it is disposable. When we invoke this little pipeline now, we will see that the disposition will be handled by the infrastructure provided by the Owin.Dependencies implementation.

image

So far so good but what happens when we need to integrate with a specific framework which has its own dependency injection implementation such as ASP.NET Web API? This is where the framework specific adapters come. I provided the APS.NET Web API adapter and it has its own NuGet package which depends on the Microsoft.AspNet.WebApi.Owin package.

PM> Install-Package DotNetDoodle.Owin.Dependencies.Adapters.WebApi -Pre

Beside this package, I also installed the Autofac.WebApi5 pre-release package to register the API controllers inside the Autofac ContainerBuilder. Here is the modified Startup class to integrate with ASP.NET Web API:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        IContainer container = RegisterServices();
        AutofacOwinDependencyResolver resolver = 
            new AutofacOwinDependencyResolver(container);

        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");

        app.UseDependencyResolver(resolver)
           .Use<RandomTextMiddleware>()
           .UseWebApiWithOwinDependencyResolver(resolver, config);
    }

    public IContainer RegisterServices()
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<Repository>()
               .As<IRepository>()
               .InstancePerLifetimeScope();

        return builder.Build();
    }
}

I also added an ASP.NET Web API controller class to serve all the texts I have. As ASP.NET Web API has a fist class DI support and our Web API adapter handles all the things for us, we can inject our dependencies through the controller constructor.

public class TextsController : ApiController
{
    private readonly IRepository _repo;

    public TextsController(IRepository repo)
    {
        _repo = repo;
    }

    public IEnumerable<string> Get()
    {
        return _repo.GetTexts();
    }
}

Now, when we send a request to /api/texts, the IRepository implementation is called twice: once from our custom middleware and once from the Web API's TextsController. At the end of the request, the instance is disposed.

image

The source code of this sample is available in the Owin.Dependencies repository on GitHub. I agree that there might be some hiccups with this implementation and I expect to have more stable solution in near future. Have fun with this little gem and give your feedback :)