Monday, January 5, 2015

OWIN middleware!

As mentioned, I've followed Scott Allen's pluralsight.com MVC5 trainings to build a .NET Framework 4.5.1 OWIN-flavored console application like so:

using System;
using Microsoft.Owin.Hosting;
namespace MyKatana
{
   class Program
   {
      static void Main(string[] args)
      {
         string uri = "http://localhost:8080";
         using (WebApp.Start<Startup>(uri))
         {
            Console.WriteLine("Started!");
            Console.ReadKey();
            Console.WriteLine("Stopping!");
         }
      }
   }
}

 
 

Also, as mentioned here, there is a Startup class in the mix. Recently, I altered it (from what is at the link I provide) as seen here:

using MyKatana.Middleware;
using Owin;
namespace MyKatana
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.Use<HelloWorldComponent>();
      }
   }
}

 
 

I did this to bring in a component, a piece of middleware that is! In Mr. Allen's video he first builds a piece of middleware like so to show off a common shape:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class HelloWorldComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public HelloWorldComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public async Task Invoke(IDictionary<string, object> environment)
      {
         await _next(environment);
      }
   }
}

 
 

A Func<IDictionary<string, object>, Task> must be taken at the constructor of a componet for it to behave well (or at all really) in the OWIN context, and thus there is a need to write a custom constructor with the signature seen here for each component. We also need an Invoke method. It is important to note that using the await keyword in lieu of a return requires one to also use the async keyword. Mr. Allen suggested that the await/async shape to the Invoke method is the norm. It is not however mandatory, as he went on to refactor what is above to what is below.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class HelloWorldComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public HelloWorldComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public Task Invoke(IDictionary<string, object> environment)
      {
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            return writer.WriteAsync("Hello World!");
         }
      }
   }
}

 
 

We take off async in taking off await! Alright, clearly this piece is intended to the very last in a sequence of steps while the prior shape (which did nothing) was more friendly to being somewhere upstream of a last step. How can we use both shapes and still write a line of copy to the browser?

using MyKatana.Middleware;
using Owin;
namespace MyKatana
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.Use<HelloComponent>().Use<WorldComponent>();
      }
   }
}

 
 

We will run the HelloComponent before the WorldComponent and it looks like so:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class HelloComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public HelloComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public async Task Invoke(IDictionary<string, object> environment)
      {
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            writer.Write("Hello: ");
         }
         await _next(environment);
      }
   }
}

 
 

environment["owin.ResponseBody"] = response; ...was just before the last line of code above is my first pass at this. It turns out I didn't need it after after given that I am altering a reference type however. WorldComponent is just a mild revamp of HelloWorldComponent. It looks like this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class WorldComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public WorldComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public Task Invoke(IDictionary<string, object> environment)
      {
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            return writer.WriteAsync("World!!!");
         }
      }
   }
}

 
 

After I did this, I turned around and mused that HelloComponent didn't really need to interface with owin.ResponseBody the way the last step in the chain (WorldComponent) must. I ended up refactoring it like so:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class HelloComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public HelloComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public async Task Invoke(IDictionary<string, object> environment)
      {
         environment["htmlspool"] = "Hello: ";
         await _next(environment);
      }
   }
}

 
 

This makes WorldComponent change up to accomodate.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class WorldComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public WorldComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public Task Invoke(IDictionary<string, object> environment)
      {
         string htmlspool = environment["htmlspool"] as String;
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            return writer.WriteAsync(htmlspool + "World!!!");
         }
      }
   }
}

 
 

Another part of Mr. Allen's training involves making an AppFunc using statement not unlike a using directive. Here is what one of those looks like:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   using AppFunc = Func<IDictionary<string, object>, Task>;
   
   public class WorldComponent
   {
      AppFunc _next;
      
      public WorldComponent(AppFunc next)
      {
         _next = next;
      }
      
      public Task Invoke(IDictionary<string, object> environment)
      {
         string htmlspool = environment["htmlspool"] as String;
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            return writer.WriteAsync(htmlspool + "World!!!");
         }
      }
   }
}

 
 

At the very end I decided to fall back to using a .Run instead of a .Use to implement the last step in my process. I did so like this:

using MyKatana.Middleware;
using Owin;
namespace MyKatana
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.Use<HelloComponent>().Run(environment =>
         {
            return environment.Response.WriteAsync("World!!!");
         });
      }
   }
}

 
 

That meant that it now made sense to revert the HelloComponent class to its initial shape:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MyKatana.Middleware
{
   public class HelloComponent
   {
      private Func<IDictionary<string, object>, Task> _next;
      
      public HelloComponent(Func<IDictionary<string, object>, Task> next)
      {
         _next = next;
      }
      
      public async Task Invoke(IDictionary<string, object> environment)
      {
         Stream response = environment["owin.ResponseBody"] as Stream;
         using (StreamWriter writer = new StreamWriter(response))
         {
            writer.Write("Hello: ");
         }
         await _next(environment);
      }
   }
}

 
 

install-package Microsoft.AspNet.WebApi.OwinSelfHost ...may be run to bring in the Web API! I added it in a new a step in my component chain like so:

using System.Web.Http;
using MyKatana.Middleware;
using Owin;
namespace MyKatana
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         HttpConfiguration config = new HttpConfiguration();
         config.Routes.MapHttpRoute(
            "MyRoutingRule",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional});
         app.UseWebApi(config).Use<HelloComponent>().Run(environment =>
         {
            return environment.Response.WriteAsync("World!!!");
         });
      }
   }
}

 
 

Now the app will continue to just serve up "Hello: World!!!" unless a legitimate ApiController route is hit at which point behavior differs! http://localhost:8080/api/whatever/ is such a route thanks to this controller:

using System;
using System.Web.Http;
using MyKatana.Objects;
namespace MyKatana.Controllers
{
   public class WhateverController : ApiController
   {
      public Whatever Get()
      {
         return new Whatever()
         {
            MeaningOfEverything = 42
         };
      }
   }
}

 
 

It will cough up an instance of this object:

namespace MyKatana.Objects
{
   public class Whatever
   {
      public int MeaningOfEverything { get; set; }
   }
}

Microsoft and .NET ...is not equal to... nuget.org

Go to: TOOLS > NuGet Package Manager > Package Manager Settings ...in Visual Studio 2013 which will bring up an "Options" dialog box wherein you will see options for "Nuget Package Manager" split into "General" and "Package Sources" and if you pick the second option you will see a list of "Available package sources:" where "nuget.org" may or may not be checked depending upon your settings. With regards to the silly problem I mention in another blog posting here, at the Package Manager Console the "Package source:" dropdown afforded options for NAMEOFMYCOMPANY.nuget and "Microsoft and .NET" and I made the false assumption that "Microsoft and .NET" and "nuget.org" (which was indeed an unchecked checkbox) where the same thing.

Sunday, January 4, 2015

I am enjoying Scott Allen's pluralsight.com trainings!

They are stronger than I expected. I guess this means I need to actually pay for an account instead of trying to just get away with abusing a ten day free trail, huh? Here are some dirty notes I've taken since Friday on OWIN:

  • The AppFunc: Func<IDictionary<string, object>, Task>;
  • A low level OWIN Component is called Middleware!
    public async Task Invoke(IDictionary<string, object> environment)
    {
       await _nextComponent(environment);
    }
  • Keys which MUST appear in the AppFunc Request Environment: owin.RequestBody, owin.RequestHeaders, owin.RequestMethod, owin.RequestPath, owin.RequestPathBase, owin.RequestProtocol, owin.RequestQueryString, owin.RequestScheme
  • MUST appear in the Response Environment: owin.ResponseBody, owin.ResponseHeaders
  • remember setting status codes!
  • look at how he is processing requests!
  • Nancy is for routing on top of OWIN.
  • Both Nancy and Web API do not have dependency on System.Web or ASP.NET
  • IIS Express "is essentally the core of IIS but I can run it from the command line"
  • Microsoft.Owin.Host.SystemWeb ...makes an OWIN app IIS friendly
  • change Console Application to Class Library
  • change Output Path at "Build" to "bin"
  • how was Startup found?
  • Startup.cs in an MVC5 project!
  • There is a by default a middleware component for authentication and there are more components for various types of authentication
  • katanaproject.codeplex.com has the source! ...canned, existing middleware is here

Friday, January 2, 2015

JavaScript templates

A coworker was just telling me about JavaScript templates as a concept. In HTML you have braces (variables in braces) which decry template data kept in a .js file and you use a template tool like Jade to bring it into your HTML, this can improve performance as the .js content will be cached at a browser improving the speed of a web application.

an inability to install anything at all from NuGet!

This and this touch on this error:

There seems to be a suggestion that one may get around it by uninstalling Visual Studio and reinstalling it followed perhaps by a restart of the VM or computer at hand, but I've done this and have had no luck. That said, I noticed that the AttachTo plugin and AnkhSVN were back automatically upon the other side of my wipe and recreate which means my wipe and recreate must have been an imperfect cleansing. I wonder if I need to throw away my VM. How can I use Visual Studio without NuGet?

Addendum 1/5/2015: I made a stupid mistake as it turns out. See: this

I'm down to just one dead end now.

I started an online training on MVC5 today and it delved into OWIN and illuminated a solution for one of the two problems I mention here. One installs Microsoft.Owin.Hosting and Microsoft.Owin.Host.HttpListener from NuGet and one holds open the console application which one spins up like so:

using System;
using Microsoft.Owin.Hosting;
namespace MyKatana
{
   class Program
   {
      static void Main(string[] args)
      {
         string uri = "http://localhost:8080";
         using (WebApp.Start<Startup>(uri))
         {
            Console.WriteLine("Started!");
            Console.ReadKey();
            Console.WriteLine("Stopping!");
         }
      }
   }
}

 
 

It looks a lot like holding open a console application in a general sense, no? Yet, it's a bit different. To get this to work I also need a Startup class and it looks like this:

using Owin;
namespace MyKatana
{
   public class Startup
   {
      public void Configuration(IAppBuilder app)
      {
         app.Run(ctx =>
         {
            return ctx.Response.WriteAsync("Hello World!");
         });
      }
   }
}

 
 

Here are some dirty notes I typed up while listening to the training before I got to the solution above:

  • K. Scott Allen's MVC5 training at Pluralsight (http://www.pluralsight.com/courses/aspdotnet-mvc5-fundamentals)
  • membership and security model in MVC4 is now obsolete
  • Katana is a new project type for ASP.NET
  • a lot of MVC features have been moved into "OWIN middleware"
  • ASP.NET membership providers and simple membership providers are gone.
  • Identity componets which are interface-based provide some more flexibility and understand technologies like OAuth and OpenId and local accounts stored in SQL server databases
  • attribute routing
  • the Microsoft.AspNet.Mvc line item at packages.config should decry what version of MVC one is using
  • the video shows and upgrade from MVC4 to MVC5. The Target framework of the project gets moved from .NET Framework 4 to .NET Framework 4.5.1
  • go to "Manage NuGet Packages"
  • Microsoft.AspNet.Web.Helpers.Mvc has been renamed for MVC5 ... this needs to be uninstalled, then updates run, then the new version installed
  • one may "roll the dice" and pick "Update All" to bring all the packages up to date, or update oneseys and twoseys
  • ugh, the upgrade process is WAY painful
  • Microsoft.AspNet.WebHelpers in the new Microsoft.AspNet.Web.Helpers.Mvc
  • If you unload a .csproj file in Visual Studio you may edit it not unlike editing it in notepad... one then needs to Reload the project
  • particularly in cloud apps where you pay for every byte, there is a need to have things be light
  • Katana is Microsoft's implementation of an open standard named OWIN (Open Web Interface for .NET)
  • web frameworks and web servers should be decoupled
  • MONO is the open source implemenation of .NET
  • System.Web is tied to ASP.NET and IIS as kinda fat instead of fast
  • MVC5 has a reference to Microsoft.Owin and Microsoft.Owin.Security and Owin
  • create a Console Application for Katana to listen to and process HTTP request
  • install-package -IncludePrerelease Microsoft.Owin.Hosting ...to the console app
  • install-package -IncludePrerelease Microsoft.Owin.Host.HttpListener
  • using Owin namespace one may add an IAppBuilder app
  • .Environment in IAppBuilder has a dictionary of things like cookies and headers and server variables, etc.
  • install-package -IncludePrerelease Microsoft.Owin.Diagnostics ...has the welcome page
  • an IDictionary of string,object is an environment
  • as you add extensions with other NuGet Owin packages they will typically add things you may dot off to from an IAppBuilder

VMware snapshots

This suggests (correctly) one may make a snapshot by selecting the tab of the VM to capture and then going to "Take Snapshot..." beneath the "Snapshot" menu beneath the "VM" menu. To revert to a snapshot, per this, do so also at the "Snapshot" menu by picking "Revert to Snapshot: YOURSNAPSHOTNAMEHERE"