OWIN and Katana – what’s the big deal?

OWIN stands for The Open Web Interface for .NET. It is a standard for communication between .NET web servers and web applications. It defines required elements for HTTP request (details). It is inspired by Rack from Ruby on Rails World. Katana is implementation of this standard. We can say that it is a lightweight web server for .NET. In fact, it is more than that (more info here).

Demo

First, we need to create application project. Let’s create ‘Empty Web Application’ (it might be also Console App).

OWIN - empty Project

Next, we will install two NuGet packages (using Package Manager Console):

Install-Package Microsoft.Owin.Host.SystemWeb

Install-Package Owin.Extensions

Then, we need to create ‘Startup class’.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Owin;

namespace OwinDemo
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseHandlerAsync((req, res) =>
            {
                res.ContentType = "text/plain";
                return res.WriteAsync("Hello Katana!");
            });
        }
    }
}

Now we are ready to run our web server, but you may get following error:

OWIN - error

Fortunately there is easy fix for that. You need to modify Web.config file, adding following code in configuration section:

<appSettings>
    <add key="owin:HandleAllRequests" value="true"/>
</appSettings>

Then you can run server (CTRL+F5) and you should see:

OWIN - Hello Katana

Summary

So, what is big deal? We have web server in 7 lines of code! We do not need IIS as only one, right choice.

Of course we can do much more sophisticated things. Such as routing, WebAPI or even SignalR. You can also debug it easily.

More info about OWIN and Katana on ASP.NET website: An Overview of Project Katana
There is also screencast on Channel9: The Katana Project – OWIN for ASP.NET (it shows e.g. how to use WebAPI from 35:40).
Here is very nice article how to use SignalR with Katana.

Katana is Open Source and available on CodePlex.


scriptcs – C# in console

It was always bothering me, when I wanted to run one simple command, and I needed to create new C# console project in Visual Studio to do that. With scriptcs I can finally do that in console. Project scriptcs allows you to run single commands and also C# script files.

Installation

The easiest way to install scriptcs is Chocolatey (‘apt-get’ for windows). If you didn’t hear about it, you should definitely try it out. To install Chocolatey run the following command in console:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

Once you have Chocolatey installed, you can install scriptcs:

cinst scriptcs

Chocolatey will install scriptcs to %APPDATA%\scriptcs\. You need to update your PATH accordingly, to easily run it from command line.

Getting started

Once scriptcs is installed and added to your PATH, you can run it with scriptcs command:

C:\> scriptcs
scriptcs (ctrl-c or blank to exit)

> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
>

C:\>

You can also create a script hello.csx:

var message = "Hello, world!";
Console.WriteLine(message);

And run it from command line:

C:\>scriptcs hello.csx
Hello, world!

You can find more about scriptcs on scriptcs.net.

EDIT: You don’t even need Console.WriteLine to print variables (thanks Filip W.):

C:\>scriptcs
scriptcs (ctrl-c or blank to exit)

> var message = "Hello, scriptcs!";
> message
Hello, scriptcs!
> int four = 2 + 2;
> four
4
>


A book that every programmer should read: The Elements of Computing Systems

I would like to say thank you to Scott Hanselman, who tweeted about this book. When I saw the content, I knew I will love it. And I was right.

The Elements of Computing Systems cover

The Elements of Computing Systems: Building a Modern Computer from First Principles is written by Noam Nisan and Shimon Schocken, who are University Professors. They created course based on this book (or wrote this book based on their course :)). The first 6 (out of 12) chapters are available for free at course website.

Why every programmer should read this book? Because it allows you to understand how computer works. It is going from logic gates, through machine code, intermediate code, compilers etc., to high level programming language. At the end of each chapter, there are exercises in which you are ‘building’ parts of the computer.

This book has only 344 pages and of course it doesn’t cover all details. Each chapter is kind of basic overview, however it is sufficient to get the idea and basic understanding before you go more deeply (e.g. into Computer Architecture or Compilers).

I really enjoyed reading this book. It is amazing how all those things we are doing everyday on our machines are done just by adding, subtracting, comparing and copying sequences of zeros and ones.

The book is available at amazon. There is also a website with more information about it (e.g. 10 minutes overview video), and software created for exercises (which you can find at the end of each chapter).


Single Page Apps (SPA): Rich Internet Apps with HTML5 and Knockout

A rich Internet application (RIA) is a Web application that has many of the characteristics of desktop application software.

We used to create Rich Internet Applications in Silverlight. Now, JavaScript frameworks (e.g. Knockout, Angular) are getting more popular for such purpose. Everything because of HTML5, which combined with them can easily provide nice development environment and rich experience.

However, all of those frameworks just take advantage of AJAX calls. So, what’s big deal?

There is a few reasons. First one is the fact, that HTML5 data-* attribute allows to bind variables to HTML elements. We do not need to select them using id or class attributes. Another reason is variety of frameworks, which makes all of those AJAX calls behind the scenes. Additionally they do lot of other work such us serializing, models binding etc. They are just higher level of abstraction than jQuery.

KnockoutJS

One of the most popular JavaScript Framework is Knockout. It applies MVVM pattern. Its key features are:

  • Declarative bindings (easily associate HTML elements with model)
  • Automatic UI Refresh (when data changes)
  • Dependency Tracking (chains of relationships)
  • Templating (easily generates UI depends on model data types) – e.g. we can use for loops in HTML

KnockoutJS is open source framework, created by Steve Sanderson.

If you want to get started with SPA I recommend you knockoutjs.com website and John Papa’s series at Pluralsight.net: Building HTML5 and JavaScript Apps with MVVM and Knockout and Single Page Apps JumpStart (in this course John is taking advantage of various JS libraries to create consistent Single Page Appliation).

The biggest advantage of all JS libraries from my point of view is the possibility to do more (functionalities) with less (code). In other words: avoid rewriting boilerplate code.

EDIT: You should also check John Papa’s HotTowel project template for Visual Studio, which gives you great start point for building SPA. It contains many JS libraries (e.g. Knockout and Durandal) for Rich Internet Apps development. More info on John’s blog. Thanks to nilphilus and Piotr Ptak for mentioning about it in comments.


PyGTK, Multithreading and progress bar

Multithreading in Python seems to be very simple. Let’s look at the example:

import threading
import time

global_var = 0

class ThreadClass(threading.Thread):
	def run(self):
		global global_var
		while True:
			print global_var

class ThreadClass2(threading.Thread):
	def run(self):
		global global_var
		while True:
			time.sleep(1)
			global_var += 1

t1 = ThreadClass()
t1.start()

t2 = ThreadClass2()
t2.start()

t1.join()
t2.join()

Thread 1 is printing the global_var and Thread 2 is incrementing it by 1, every second.

Recently I needed to use threads in PyGTK to display progress bar. Off course the state of progress bar was dependent on the other thread. It had to be updated after each subtask call. This is the code:

import threading
import time
import gtk

def init_progressbar():
    main_box = gtk.VBox()
    progressbar = gtk.ProgressBar()    
    progressbar_box = gtk.HBox(False, 20)
    main_box.pack_start(progressbar_box, False, False, 20)
    progressbar_box.pack_start(progressbar)    
    info_box = gtk.VBox()
    main_box.pack_start(info_box, False, False, 10)    
    info_label = gtk.Label("Running...")
    info_box.pack_start(info_label)
    return main_box, progressbar, info_label


def run_tasks(pb, info_label):
    task_list = ['task1', 'task2', 'task3', 'task4']
    task_no = 0
    for task in task_list:
        pb.set_fraction(float(task_no)/len(task_list))
        run_task(2, task, info_label)        
        task_no += 1
    pb.set_fraction(float(task_no)/len(task_list))
    info_label.set_text('Finished')


def run_task(delay, task, info_label):
    info_label.set_text(task + ' is running...')
    time.sleep(delay)   # simulation of running the task


win_pb, pb, info_label = init_progressbar()
win = gtk.Window()
win.set_default_size(400,100)
win.add(win_pb)
win.show_all()
win.connect("destroy", lambda _: gtk.main_quit())
t = threading.Thread(target=run_tasks, args=(pb,info_label))
t.start()
gtk.main()

And…it was not working. The progress bar (and the label) did not get updated after task calls. Why?

It was caused by the fact, that PyGTK is not thread safe. Fortunately we have function threads_init() in gobject module, which can handle it. We just need to call gobject.threads_init() before first thread creation. Corrected (working) code looks like that:

import threading
import time
import gobject
import gtk

def init_progressbar():
    main_box = gtk.VBox()
    progressbar = gtk.ProgressBar()    
    progressbar_box = gtk.HBox(False, 20)
    main_box.pack_start(progressbar_box, False, False, 20)
    progressbar_box.pack_start(progressbar)    
    info_box = gtk.VBox()
    main_box.pack_start(info_box, False, False, 10)    
    info_label = gtk.Label("Running...")
    info_box.pack_start(info_label)
    return main_box, progressbar, info_label


def run_tasks(pb, info_label):
    task_list = ['task1', 'task2', 'task3', 'task4']
    task_no = 0
    gobject.threads_init()
    for task in task_list:
        pb.set_fraction(float(task_no)/len(task_list))
        run_task(2, task, info_label)        
        task_no += 1
    pb.set_fraction(float(task_no)/len(task_list))
    info_label.set_text('Finished')


def run_task(delay, task, info_label):
    info_label.set_text(task + ' is running...')
    time.sleep(delay)   # simulation of running the task


win_pb, pb, info_label = init_progressbar()
win = gtk.Window()
win.set_default_size(400,100)
win.add(win_pb)
win.show_all()
win.connect("destroy", lambda _: gtk.main_quit())
t = threading.Thread(target=run_tasks, args=(pb,info_label))
t.start()
gtk.main()

I wanted also to be able to cancel program computation, by the cancel button. To do that I needed shared variable to be a status flag informing, whether computation should be cancelled or continued. It had to be accessible in task loop and cancel event.

In Python there are mutable and immutable objects. Mutable are passed by reference, but immutable – by value. More about that on this StackOverflow question. Boolean type is immutable, but there is a way around this: use list (mutable type) with one element (boolean variable). I know it is awful solution, but I did not find any better. If you know one, let me know!

This is the app with cancel button:

import threading
import time
import gobject
import gtk

def init_progressbar():
    main_box = gtk.VBox()
    progressbar = gtk.ProgressBar()    
    progressbar_box = gtk.HBox(False, 20)
    main_box.pack_start(progressbar_box, False, False, 20)
    progressbar_box.pack_start(progressbar)    
    info_box = gtk.VBox()
    main_box.pack_start(info_box, False, False, 10)    
    info_label = gtk.Label("Running...")
    info_box.pack_start(info_label)
    cancel_box = gtk.HBox()
    info_box.pack_start(cancel_box)
    cancel_button = gtk.Button("Cancel")
    cancel = [False]
    cancel_button.connect("clicked", cancel_counting, info_label, cancel)
    cancel_box.pack_start(cancel_button, False, False, 20)
    return main_box, progressbar, info_label, cancel


def run_tasks(pb, info_label, cancel):
    task_list = ['task1', 'task2', 'task3', 'task4']
    task_no = 0
    gobject.threads_init()
    for task in task_list:
        if cancel[0]:       
            pb.set_fraction(0)
            info_label.set_text('Canceled')
            return
        pb.set_fraction(float(task_no)/len(task_list))
        run_task(2, task, info_label)        
        task_no += 1
    pb.set_fraction(float(task_no)/len(task_list))
    info_label.set_text('Finished')


def run_task(delay, task, info_label):
    info_label.set_text(task + ' is running...')
    time.sleep(delay)   # simulation of running the task


def cancel_counting(widget, info_label, cancel):
    cancel[0] = True
    info_label.set_text("Cancelling...")


win_pb, pb, info_label, cancel = init_progressbar()
win = gtk.Window()
win.set_default_size(400,100)
win.add(win_pb)
win.show_all()
win.connect("destroy", lambda _: gtk.main_quit())
t = threading.Thread(target=run_tasks, args=(pb,info_label, cancel))
t.start()
gtk.main()

To make above code working on your machine you need to have Python and PyGTK installed. To find out the details, how to install Python and/or PyGTK check my Python jump start post.