Sunday, June 29, 2014

OWIN and Katana, a first look

Since I do quite a lot of web development, I thought it a good idea to take a first look at OWIN and Katana, get a feel of what they both are about and how they can be used in a project. They are both part of a new web hosting model, where OWIN is the specification of this model and Katana is an actual implementation of this specification. In this post I will give you an overview of both and show you how you can build the basis for a web application using the Katana project.

But, let me first give you a small intro on both.

In .NET, when you build a web application, what you typically do, is use ASP .NET (either webforms or MVC) and host your application in IIS. This framework has been around for quite some time, and it has really become big. For some applications, this model can be bloated, since it runs a lot of things you don't really need in your application.

What they wanted to aim for at Microsoft with OWIN and Katana, is build a basis for a framework, that is really light weight, with just the essential things for a web application in it. And if you need extra's you just pull them in as you need them. More or less similar to what you would do to a nodejs server application. Very light weight, but also very powerful.

Along came OWIN, which is a specification for how you can build a web server that can host .NET code. It sits between a hosting environment, which in this case can be either IIS or something else, like a Windows Service, or a simple Console Application, and your actual application code. Any additional middleware, like authentication, can use the OWIN abstraction to be plugged into your application.

So, what does OWIN actually define or specify? Well, the most important part of the OWIN specification is the application delegate, which looks like this:

using AppFunc = Func<
        IDictionary, // Environment
        Task>; // Done

The application delegate has an argument of type IDictionary, which is called the environment dictionary. This dictionary contains information about one single request, its response and any relevant server state. In it, you will be able to find keys like owin.RequestMethod, which can have a value like GET or POST, or owin.RequestPath, which contains the value of the actual called URI. An overview of possible values can be found in the OWIN specification document

The second argument of the application delegate, the actual return type, is a Task, that will be returned once it has finished processing. You will see the usage of this Task once I start building up some more practical examples. What you will notice, with this task, is that the OWIN architecture is asynchronous by design.

The application delegate is a way of hooking into an OWIN server. Meaning that if you want to hook into an OWIN environment, you will need to have a method that complies to the signature of this application delegate.

Now, where OWIN is a specification, Katana is Microsoft's implementation of this specification. In Katana you can find a couple of OWIN hosts either for IIS, or for self-hosting. You will also find a couple of classes that help you with talking to OWIN, so you don't need to, for instance, take values directly from the environment dictionary. And you will also be able to find a couple of middleware components, like authentication, ...

So, let's build a small application with Katana. For this we start of with an empty console application, which we will use as a host for our application. In this we will install the OWIN self host nuget package.


Once we have this, we can start hosting an application. For this we use the WebApp class which represents the self hosting OWIN server and tell it which url it should listen on. We also give it a configuration.

The configuration class is based on convention, it needs a Configuration method that takes an IAppBuilder as an argument.



Now we can start configuring our OWIN host. First thing we will do is a very simple host, which prints out some information of the response that came in, and which returns a string that says Hello OWIN and Katana. For this we use the Run method on the IAppBuilder. This will get a context, which gives us access to the environment variable.

As you can see in the code example, the interface is async by default. The Request and Response properties give us easy access to the data in the environment variable.

When we run this example, we can go to the localhost:4321 uri. It will give us the following response:


And in our Console, we can see the method and URI printed out:


So, that's a really simple example. We can also add some preprocessing or postprocessing to our request. For this you utilize app.Use. This will take 2 arguments, the context, but also a reference to the next middleware delegate in the chain. Whatever you want to do as preprocessing you put before your call to the next delegate. Whatever you want as postprocessing, you put after the call to the next delegate.

This gives us the following output:


Another way of programming this, is with separate classes instead off with delegates. The same example than looks like this:


You create a class with an Invoke method. This method will get the environment dictionary directly. If you want to use the OwinContext instead, you can new it up. Your next delegate this time will not be passed as an argument to the Invoke function, but will be passed as a constructor argument.

With all this you can already do some nice stuff. Beware though, since the API will still be subject to changes. For people wanting to try this on non Windows machines, there's also a Nowin nuget package, that also runs on Mono. Hope this entises you to try some of this stuff out.


Sunday, February 9, 2014

Extending Durandal

Summary: combining Durandal and ASP .Net MVC, getting the best of both worlds


Experience has taught me that, when doing web projects, JavaScript is one of the technologies you will have to learn to live with. It will always be present and it will always bug you (literally). And in each project, you will have devs at your disposal who are better, or worse at writing JavaScript code. It's just a fact that, once you start writing a whole bunch of JavaScript, it can get quite messy, very quickly. 

In my recent project setup, I wanted to be able to avoid such a mess, by providing well structured JavaScript code from the beginning. But, without having to sacrifice the comfortable environment the ASP .Net MVC framework gives to my devs.

For this, I looked into a couple of JavaScript frameworks. Without treading into details here, the framework that suited my situation best was Durandal. It's not that hard to learn, it makes extensive use of RequireJS (which was already known by a lot of my developers) and it uses knockout for its bindings, which, for people coming from for instance XAML, looks quite familiar. 

For people unfamiliar to Durandal, knockout or RequireJS, you can find very good info for getting started with all three of them. 

Now, the problem with my recent project, was the combination of the good parts of ASP .Net MVC and the good parts of Durandal. For instance, what I like about ASP .Net MVC is the fact I can use statically typed helpers in my HTML. They help my devs a lot at being consistent and at keeping the error rate low(er). Kinda like what this stackoverflow question poses. So I started thinking of an easy way to accomplish this. 

My application itself will consist of little mini-SPA's. Meaning that for each part of the application, for instance the detail of a customer, or the overview of payments, ... we will make a Single Page Application (SPA). The starting point of each of these little mini-SPA's will be a .cshtml view which will get returned by an action on a controller. This .cshtml view will contain a div for the applicationHost (this is standard Durandal) and some code to start up an SPA on this page. 


As you can see, this is standard Durandal code. The only thing I did was make my own little module that sets up an SPA for a certain viewmodel, so you don't have to repeat that code over and over again in the application.

Now, what durandal does once you set up an SPA for barcode/shell, is that it starts looking for barcode/shell.js (your viewmodel) and barcode/shell.html (your view) and it links these two together. But the thing is, I actually want to set up a view in which I can use the MVC helpers. That's not possible in an HTML file. 

So, I started digging in the Durandal source code, looking for the part where the viewmodel and the view get linked together. Its in Durandals viewLocator.js file. In here, I added some extra script, giving you the ability to add an extra div (I called it applicationContent, out of convenience) in your original .cshtml file (lines 15 through 18). 


Once you start up you SPA Durandal will now look for the presence of this div and if it can find one, it will put its contents in the applicationHost div. You can now use this abbility in your .cshtml file:


As you can see I can now use things like Html.BeginForm or our Translations resource in the cshtml file. It's all placed in a div called applicationContent. Once my SPA starts up, it will place this content in the applicationHost. You also have the ability to use knockout bindings inside your applicationContent. You can see I did this for the submit binding on the form and for the pdf_url in the iframe. 

If you want to look at this extension of Durandal: I forked the project with my little addition.


Saturday, January 25, 2014

Building a cross platform solution for Windows Phone and Windows 8. Part VI: Behaviors for coping with orientation changes

Previous parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

In the last post we looked at an EventToCommand implementation to easily databind our events to commands, even when we don't have a Command property on a control.

In this post, I will run you through another trick, to ease the development of your views.

One of the behaviors you will probably want in your application is the ability to react to orientation changes. You can easily do this by creating an event handler for the OrientationChanged event in the code behind of your page. You will have to do this in every page you want to be able to react to orientation changes. Resulting in copies of the same piece of code all over the place.

But there is actually a more elegant way of dealing with this, and it is based on behaviors. What you can do is write a specific behavior that does nothing more than attach an event handler to the OrientationChanged event of the associated page. Based on the name of the new orientation, you can now load a specific state of you VisualStateManager.


Of course, in XAML, you now have to create the necessary VisualStateGroups for the specific orientations.


The only thing missing still is a small extra piece of XAML to make use of the OrientationChangedBehavior.


That's it, small and simple little trick. In the next part we'll look at the troubles you can have when your application needs to be tombstoned.

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

Monday, December 23, 2013

Building a cross platform solution for Windows Phone and Windows 8. Part V: Binding events to commands

In the previous part of this series, we did quite a lot. We mocked out any application differences in our ViewModels, we introduced dependency injection and we created base classes for our platform specific pages.

This part will be less complicated, but will again contain a very necessary part if you want to end up with a reusable framework for your Windows Phone and Windows 8 applications. Up until now we have created Views that we can databind to our ViewModels. For this our ViewModels contain either data properties or command properties. It is with this last kind of properties you might have some issues in databinding scenarios. And this doesn't only go for cross platform applications, you will have this issue every time you want to take the MVVM approach.

The thing with command properties is that, out of the box, they are only databindable to, well, Commands. So, a button for instance, poses no problem, since it has a Command property. But what if, for instance, you wish to trigger a command based on a Tap event. This will not be possible by default. But, you can provide some extra pipe-lining to make this possible nonetheless.

What we'll do to get around this, is write our own TriggerAction. A TriggerAction describes an action to perform by a trigger. The good thing is that you can attach a TriggerAction to an EventTrigger. An EventTrigger will then execute your TriggerAction based on a certain event.

To get all this working, first thing you will have to do is add a reference to the Systems.Windows.Interactivity namespace. On Windows Phone you can find this reference under Assembly - Extensions (I had to look for it too). For Windows 8 you will not find this assembly in your references, but you can use this nuget package.

Once you've done this, you will find you can add an EventTrigger for any event you would like. In the following example I have added one for the Tap event on a Border control.



Next step, now that we have our EventTrigger, is write a TriggerAction that translates our event to a command. This is actually not that hard. You notice in the code sample above I use a framework:EventToCommand type, which I provided myself. This is my TriggerAction which has one property, Command. It looks like this.



This class inherits from a TriggerAction for a FrameworkElement (this is just the base class for all possible controls). The first line registers my Command property as a DependencyProperty. This is needed so you can assign values to this property from within your XAML. That is also why, in the actual property, you see the use of GetValue and SetValue - that is just because we are using a DependencyProperty.

The Invoke method in my EventToCommand is more important. It gets executed each time the associated event gets fired. What it does is, it looks wether the Command can be executed and when it does, it executes the Command.

With this, you can more or less databind anything in your views. More or less, because if you want to databind your application bar in a Windows Phone application, you will have to go through some extra effort, which involves a lot more code. You can get a pointer to what needs to be done here.

Next part, I will show you another little trick to easily react to orientation changes.

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

Sunday, December 15, 2013

Building a cross platform solution for Windows Phone and Windows 8. Part IV: Mocking out the differences

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

In the previous part I talked about the MVVM pattern as a great way to share logic in your application. Your ViewModel (and Model) code can be placed in a portable class library, thus making it reusable. But, since it is not possible to put any platform specific code in your PCL, you cannot directly use platform specific services from within a ViewModel (this would make your PCL unsharable between platforms). This poses some challenges, but these can quite easily be overcome. This part in our series will be the most extensive thus far, and will contain the most advanced concepts, like inversion of control, dependency injection, and reflection. But bear with me, it will all be worth it in the end!

Let's first look at one of these platform specific behaviors: Windows Phone and Windows 8 both allow you to navigate from one page to another. The way they do this, however, is different between the two platforms. They both have a Navigate method for this, but the method exists on two different types, and also, the actual parameterlist of this method is different on each platform. You will need to find a solution to get a comparable way of navigating between pages on both platforms. You can do this by wrapping the platform specific functionality with an interface. Your ViewModels can then talk to this interface instead of talking directly to the actual navigation service of each platform.

I have for instance a MainViewModel which acts as start page for my application. From this MainViewModel you can navigate to other pages in the application. For this, the MainViewModel gets a reference to a INavigate interface through its constructor (this is my own INavigate interface, and not the one you can find in the Windows Store or Windows Phone API). Since I will be navigating in my ViewModels and not in my Views, I decided that when I navigate to another page, this is actually the same as navigating to another ViewModel. Also, I want to be able, when I navigate, to send along an additional parameter, which contains extra data for the ViewModel I navigate to.



In the above code you can see it is quite easy to navigate to another ViewModel, and send along extra data (navigate to the SudokuBoardViewModel with a specific game level). But you can also choose not to use this extra data (navigate to the SudokuRulesViewModel).

The interface itself has one extra method for navigating back.



What you will still have to do now is write platform specific implementations of the INavigate service for each platform you want to support. The good thing is, you will need to write this kind of implementations only once. After your first app, you can reuse this effort to a next application (and I will also make sure my own little API will become available on github in the next couple of weeks).


1. Navigating in a Windows Store application


Let's first look at the WindowsStoreNavigator, since this is the easiest to understand. To navigate from one page to the next, you need to make use of your Window.Current.Content property (or rootframe). In a clean Windows Store project you get a reference to this in your OnLaunched event (I set up the entire framework from the OnLaunched handler in the app.xaml.cs file). Next, we will also need some means of associating the ViewModel we wish to navigate to, with a certain View, since navigating in Windows Store applications is done to views and not to viewmodels. For this I will utilize a viewlocator (IKnowWhereYourViewIs). This viewlocator is nothing more than a dictionary that associates views to viewmodels. This way I don't need to code the binding between view and viewmodel directly in the view or in the viewmodel.



As you can see, I ask the viewlocator for the view that is associated with the viewmodel I wish to navigate to. Next I tell the rootframe to actually navigate to this view. The second parameter in the second line of the NavigateTo method instantiates my viewmodel. The inversion of control container has been set up with a list of all my viewmodels. For this I utilized TinyIoc, but you can use any wich IoC you like. The main advantage using and IoC container will be that any dependencies your viewmodel uses, will get injected by the IoC, as long as you registered them at startup.

Navigating with the extra data is a bit more complex. I created a IHandle interface which indicates wether a ViewModel can handle a certain message. If it does, it implements the IHandle interface. Before navigating to the view, I first let the ViewModel handle the actual request.



One more thing missing after navigating to a certain view, is the actual databinding between View and ViewModel. For this I created an extra base class for each View. In the OnNavigatedTo handler, we will bind the NavigationEventArgs, which in our case is our ViewModel, to the Views' DataContext.



And that's it. This allows us to navigate from one ViewModel to another, while sending along data. Also aer we now able to actually databind our ViewModel to the actual View.


2. Navigating in a Windows Phone application


Now that we can navigate in a Windows Store application, let's do the same thing for Windows Phone. As you will see, the API for navigating in Windows Phone is different from the one Windows Store applications use. In Windows Phone you navigate based on a Uri. Also, we will not be able to send along our ViewModel and request as easily. In this case, we will serialize everything before we navigate. Ie. we will serialize our ViewModel type, the actual request and the request type.



Again, we will use a MvvmPage base class, which all our views can inherit from. In its NavigatedTo event handler we will now have to (re)create our ViewModel and request. I pulled out this code to another class which implements ICreateViewModels. Since views cannot use dependency injection, I wrapped the IoC in a singleton, which can give me my viewmodelcreator.



The ViewModelCreator then uses a deserializer and some reflection to recreate the viewmodel and to make it handle the actual request.



The above code is actually the most complex part of the entire framework. An, as said, code like this, you will only have to provide once, after that your can reuse it for your next applications.

Once you got thi plumbing in place, you can navigate between ViewModels in a way that is reusable on Windows Store and Windows Phone applications. It wil make it easier to put your logic code in a shared library and to easily make changes to it that will get reflected on each platform.

Hang on for the next part, where I will talk about some extra helper classes to make MVVM work better for you.


Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

Sunday, December 8, 2013

Building a cross platform solution for Windows Phone and Windows 8. Part III: We need a pattern.

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

In the previous part I talked about portable class libraries and mentioned the need for a pattern in our code. This pattern will be the Model - View - ViewModel pattern, or MVVM for short. It divides the pieces of your application in more sensible parts and allows you to better define the responsibilities of each individual part. The View for instance will be responsible for nothing more than UI related code. This will be your XAML file. When using MVVM, I try to define my entire user interface in the XAML of my application. I hardly ever put anything in the code behind (except maybe for some UI specific code), all application logic will go someplace else.

The Model in this pattern can be either data you need or services you will be using. These will contain quite some logic and we can write them in such a way that they are unit testable.




The ViewModel will sit between the View and the Model and its responsibility will be to shape the data of the Model in a way that is specific for a certain View. As with the Model, it will also be unit testable.

The ViewModel will contain all the properties for the View to databind to. For these properties you can choose to fire the PropertyChanged event - and thus your ViewModel will implement INotifyPropertyChanged.



The above piece of code shows two properties of one of my viewmodels. The first one is for a collection of items. The second one is for a simple property. Both properties fire the PropertyChanged event. As you can see this is done through a lambda expression. I prefer putting this kind of PropertyChanged event wrapping in a base class for my viewmodels and providing the easier lambda syntax. This provides me with compile time checking (and less runtime errors when I make typos). The way to do this, is shown in the following code example.




Next to simple data properties, your ViewModel can also contain command properties. The View can also databind to these (for instance from the Command property of a Button). A command property will ascertain something gets executed in the ViewModel or in the Model.



As you can see, I use a RelayCommand class, which again makes the creation of command properties easier. The RelayCommand class will implement the ICommand interface and will provide an API by which you can createICommands based on lambdas or delegates. The RelayCommand class looks like this:



When creating commands for your view to databind to, you can also use the CanExecute property, to indicate when a command can be fired, and thus, when the button you databind do should be enabled. This is quite a neat way to automatically enable or disable buttons on your view.



Databinding to all this, is now quite easy from the view.



Using this pattern we get a better separation of concerns in our application. The only thing to watch out for is the danger of your ViewModels getting too big. Keep in mind that the ViewModels' purpose is to shape the data of the Model specifically for a certain View. This means that most of the logic will be the responsibility of the Model, and not necessarily of the ViewModel.

The advantage will be that you can put both Model and ViewModel in your portable class library, giving you the ability to reuse all of the logic between different platforms. And since both Model and ViewModel can be unit tested, you gain a great advantage.



But we will still have to add some extra techniques if we want the ViewModel to be able to use platform specific services. For this we will introduce dependency inversion in the next part of this series.

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

Tuesday, December 3, 2013

Building a cross platform solution for Windows Phone and Windows 8. Part II: The class library approach

Previous parts in this series:

Part 0: Intro

Part I: Quick sharing of code

In the previous part of this series, you learned about linked files. While these are a good technique for quickly sharing pieces of code of your application, I prefer using a class library for shared functionality. The problem is however, you cannot use a regular class library in Windows Phone or Windows 8. What you can use though is a portable class library. This is a special kind of class library that makes it possible for you to target multiple platforms.


What you will get when using a portable class library is the greatest common divisor between platforms of functionalities you will be able to use.

For creating one, you can chose 'Portable Class Library' as a project template.



When creating the PCL you will get an additional pop up asking you for the platforms you wish to target with your portable class library.



In our case choosing Windows Phone and Windows 8 will suffice. For Windows Phone you might also choose to target at least version 7.5 or 8. The higher the version you choose the more possibilities you will have in your portable class library. This is due to the fact that Windows Phone 7 doesn't support the entire .Net framework, so you will bump into some coding restrictions when specifying Windows Phone 7. I myself, most of the time, choose at least version 7.5, just for convenience and since I assume most Windows Phone 7 users will have by now upgraded to this free version.

So, now we have a place to put all of our shared code. But, what will this shared code be? It's not like we can put the code behind pages of the XAML files in this class library. So we will have to take the not so conventional path and make use of an additional pattern which will make it possible for us to put the business logic of our application in the shared class library. This pattern will be the MVVM pattern, since it can very easily be used in databinding scenarios and since it gives us a reactive user interface with INotifyPropertyChanged. This will be explained in the next part of this series.

You can find additional information on Portable Class Libraries here.


Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning