Archive | November 2013

What really is Katana and owin?

What really is really Katana? How about Owin? After playing around with Katana, I really found it worthywhile to post about what I have found regarding them. OWIN ( initials for Open Web Interface for .NET )is a set of specifications that defines a stardand interface between which .NET web servers and web applications communicates. Katana on the hand is an implementation of the OWIN.

A little history of ASP NET is that it was released in early 2002 or sometime around then, with .NET framework 1.0 and it was meant to bring a web experience for customers who included classic asp  and desktop line of business application developers like VB 6.

There were alot of stuff and concerns brought forward by these two customers, which meant that the framework was to be monolithic leading to inclusion of all concerns in one single package, System.Web.  The package included just to mention a few features, Modules, handlers, sesssion, cache, web forms and controls. And all this was meant to run on IIS.

With time the System.Web package became complex because with every new requirement it was added to the package. By default most of the features were turned on by default to seamless intengration .

By then, IIS was the only hosting for ASP NET and most of the features for ASP NET runtime map one to one with those found on the IIS. This was a problem and in around 2008 ASP NET MVC was released which atleast enabled rapid developement and was distributed via nuget. Come 2012 ASP NET WEB APi was released , and unlike ASP NET MVC, WEB API does not rely on System.Web in anyway. Initially WEB API was started by the WCF team, which later was sent to ASP NET  team who added capabilities like self hosting.

Thats a little background and history of a few players which brought the idea behind katana. In a modern web application, you  can expect to have at least some static files, web api, rendering engine perhaps MVC razor, and perhaps SignalR for some real time communication. And the question is perhaps, couldn’t it be awesome to be able to compose all these or other multiple frameworks together to create a single server?

And there comes Katana which is a set of components for building and running web applications on a common abstraction which is, OWIN…

The primary interface in OWIN is a application delegate or simply AppFunc, which is a delegate that takes IDictionary<string,object> and returns a Task, and the signature is like Func<IDictionary<string,object>,Task>

Katana is meant to offer the following

Portability by reducing to the least primitives as possible

Composability ->Its really easy to compose modules together that will participate in all aspect of the incoming requests.

Performance and scalability -> Uses Async throughout and there is total decoupling of web application and host.

A typical Owin enabled application should have the following layers.

1. Application ->This is your application which could be like ASP NET MVC

2. Application framework -> These could be regular OWIN component implementation giving simple to use API to developers to easily plug-in to the pipeline. For example, we have signalR and Web API, though currently SignalR uses OwinHost.

3.Server –> This is responsible to binding to a port and channels request to the pipeline for processing. e.g SystemWeb, HttpListener o or the new Weblistener

4.Host –> This is a process managers that spans new process call to your code and provides and puts the pipeline in place eg this could be IIS if you will be hosting on IIS, could be OwinHost.exe which is the katana implementation or even you custom process.

Currently, katana embraces conventions over configuration. So when you install owin, when you code runs it goes through you code via reflection looking for a class with name of Startup and a method named “Configuration” taking IAppBuilder interface as the only parameter. IAppBuilder is an interface used to compose modules together. There are alot of extension methods built on top of IAppBuilder which we will explore at a later post.

To recap, let write a simple application and host on a console application. I am using visual studio 2013. Open VS 13, File -> New Project ->Console Application, give a nice name and click Ok. This is  a simple console application with nothing to do with Owin. So open Package Manager Console and install the following nuget packages

Install-Package Microsoft.Owin.

install-package microsoft.Owin.Host.HttpListener.

install-package microsoft.owin.hosting

And at least it should be close to

Package-isntallation

With in we will now add the basic code to host our application. And just as we said we will need to add a class with a name “Startup” and a method “Configuration”. Quickly let to that. After we finish setting up the nuget packages then copy and paste following code to your program.cs file as is

using System;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));
 }
 }
}

Run the code and open you favourite browser and paste http://localhost:8080/. The result which would be “We are just testing this application” printed on the browser. This means that you have successfully written you first owin application hosted on a console application.
Katana is utilized in the ASP NET MVC 5 project template for authetication. In our case we have utilized the simplest method ever to write something on the response stream. But there is alot of extensibility and capabilities with katana where you can plug your own middleware or component in the pipeline, which is how the authetication is plugged in the ASP NET MVC 5. Another post regarding this soon.

But just to point out is that all you really need to write a katana module, is to write a class which has a constructor takes one arguement of type  Func<IDictionary<string,object>,Task>, and this represent the next module in the pipeline which you manually call from your component.

Just to demonstrate lets a middleware component that prints some message to the response

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 app.Use();
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));

//Plug our component here

 }
 }

public class HelloWorld
 {
 private Func<IDictionary<string, object>, Task> _next;
 public HelloWorld( Func<IDictionary<string,object>,Task> next)
 {
 _next = next;
 }

public Task Invoke(IDictionary<string, object> environment)
 {
 var response = environment["owin.ResponseBody"] as Stream;

using (var writer = new StreamWriter(response))
 {
 return writer.WriteAsync("Hello!!");
 }
 }
 }
}

Its as easy as that, and now when you run the application you see “Hello!” on the browser. Something worthy noting here is “owin.ResponseBody”, which’s one of the key in the Environment dictionary. For now take that dictionary as the HttpContext which contains all the information about a request. There are more Owin specific keys in the dictionary which we will explore in a later post.

That’s it for now, there is more to come on this same topic especially on how to write to write and hook up your own modules in the pipeline. You may also be interested in Checking-out-the-Helios-IIS-Owin-Web-Server-Host which I may recommend to get some information on the topic.

Happy coding and kindly get involved via comments, questions or suggestions. Thanks for reading 🙂

Advertisements

Abstract classes or interfaces?

Many of the times, I have seen the question of what factors should one consider either to implement a functionality in terms of abstraction, and this narrows down to if one should employ abstract class or interfaces.  A few days ago I was surprised when reviewing some code and just to brainstorm the developer,  I asked him a simple question, why did you choose to use abstract class rather than an interface?  Guess the response.. I just thought its good to use abstract class rather than interfaces. I didn’t have any other question for him but found it useful to demisfy this here for him, and others who would have the same kind of response to such a question.

I do agree that the choice of using any of them can be a daunting task.I will try to summarize what I have and wha I have found useful on the internet on this post. But  lets start at looking at the definitions of each:

An abstract class is a class that cannot be instantiated but must be inherited. The class can contain some default implementation for the child classes to use, and this methods should be non abstract methods. If an abstract method need exist, then it should be modified with abstract keyword and does not contain a body.

An interface on the hand is a type definition similar to class except that it purely represent a contract between an object and its user. And so its just a collection of members definitions e.g method, properties, events etc without any implementation.

So this brings to the question of who support or does what? Here are do’s and don’ts for each of them.

  1. Instantiation: Abstract classes cannot be instantiated away from their derived classes, meaning that there constructor are called only by their derived classes. Interfaces on the hand cannot be instantiated.
  2. Abstract classes can provide abstract members which base class MUST implement while all interfaces members MUST be implemented in the base class. So you can not implement partial interface, if you don’t need an implementation or you will not use some interface members you may need to leave stubs. e.g ConvertBack method for IValueConverter is usually not implemented but most implementation of the interface leave a stub, and this bring to the Interface Segragation Principle
  3. Extensibility: Abstract classes are more extensible than interface. You can alter an abstract classes without breaking any version compatibility. And note this extensibility is for non-abstract members. Interfaces on the other hand, if you have to extend you will have to create a new interface, otherwise you break the existing clients. Consider a situation where you are employed and after sometime you get a pay rise, you actually and should sign a new contract which looks the same as the previous with with the new  salary figures appear.
  4. Virtual members: Abstract classes allows for virtual members with default implementation for the deriving classes while for interfaces all members are automatically virtual and cannot contain any implementation.
  5. Accessibility modifiers: You can control accessibility of some members in abstract classes while all members of an interface are public by default.
  6. Inheritance: Being a rule in C# specification multiple class inheritance is not supported meaning that a class cannot inherit from more than one classes. On the contrary multiple inheritance is supported with interfaces

With that in place there are some guideline you should follow when deciding which one to use and when to use it.

  1. If you anticipate to create multiple versions of a component you may use abstract classes reason being it’s easy to create and version your components. For example by changing or updating the base class all inheriting classes are automatically updated whilst in interfaces they do not support versioning. Once an interface is created it cannot be changed you will have to create a new one. The analogy being once you sign a contract with your employer, and happens you get a pay rise you sign a new contract, you don’t manipulate the previous.
  1. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  2. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  3. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

So too much of theory lets dive and see how we can establish some, if not all of the aforementioned points. So we are going to use an aspect of polygons. Basically we have a number of polygons which have different ways of calculating their areas. So we will employ both, interface and abstract class concepts.

 public interface IRegularPolygon
 {
 int NumberOfSides { get; set; }
 int SideLength { get; set; }

double GetArea();
 }
 public class Octagon : IRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public Octagon(int length)
 {
 NumberOfSides = 8;
 SideLength = length;
 }

public double GetArea()
 {
 return SideLength * SideLength * (2 + 2 * Math.Sqrt(2));
 }
 }

We also have an abstract class approach of the same.

 public abstract class AbstractRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public AbstractRegularPolygon(int sides, int length)
 {
 NumberOfSides = sides;
 SideLength = length;
 }

public abstract double GetArea();
 }
 public class Triangle : AbstractRegularPolygon
 {
 public Triangle(int length) :
 base(3, length) { }

public override double GetArea()
 {
 return SideLength * SideLength * Math.Sqrt(3) / 4;
 }
 }

Assuming that  you have implemented you get a requirement that you need to add a way to calculate the perimeter of the polygons. And knowing that, to calculate the perimeter of a polygon is just multiplying the number of sides with the length of one side.  With the abstract class implementation it really straight forward all you need to do is as below:

 public double GetPerimeter()
 {
 return NumberOfSides * SideLength;
 }

With the interface implementation you cannot just add the function declaration since this will break the existing clients. An easier way is to have a new interface with all the previous declaration or rather employ interface inheritance where you create a new interface with the new perimeter function inheriting from the IRegularPolygon. I would go with the latter.

Just to keep the post short, we end by looking what is in the framework which employs abstract classes and intefaces. In the BCL we have System.IO.Stream class, which is an abstract class. It contains some implementation of various methods as well as abstract and virtual methods which deriving classes implements. Some of the deriving classes include:

  • MemoryStream
  • FileStream
  • BufferedStream

With the interface, we have List<T> class which implements a list of interfaces which also show interface inheritance and best application of Interface Segregation Principle. Some of the interface it implements are

IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

So we end the post to make sure its not too long,  having demonstrated a couple of points I leave it to you to try the rest and poke me if any issue arises or if you need some clarity or some of technical engagement.

Its my hope you will consider the above mentioned points next time you find yourself in a dillema of which one to use, abstract or interfaces.

Again happy coding  and bye for now 🙂

%d bloggers like this: