After many many years of using good old and reliable Blogengine.net it was time for a change. From time to time I tried Wordpress. After installing it locally (which is so easy now with Web Platform Installer), I would end up wasting several hours searching appropriate theme on various theme sites. Even paid one… But it was just too difficult, I need something simpler, smaller. Static file generators looked interesting, but to be honest, maybe that’s little bit too simple, I have absolutely no experience with them, and probably couldn’t sleep knowing that there’s no even simplest Db behind! Its just too much like “Save as HTML” in Word, and I’m like web developer. People would not take me seriously.

Few months ago I found this blog engine, called just Miniblog, from one Microsoft PM, Mads Kristensen, very famous guy, and very productive guy I must say. He is a developer of Web Essentials, an essential  Visual Studio plugin that every web developer must have. The whole blog engine has maybe 100-150 lines of code in total, and that’s what I like the most – it’s so easy to work with, and if you  have to change, add or remove something, everything is so simple, written inside several Razor .cshtml and .cs files, so easy to change!

For those hundred lines of code, list of features looks quite impressive: https://github.com/madskristensen/miniblog. Its very fast (100/100 on Google Page Speed!), can read Blogengine.net XML files (I just copied those, and that was whole export/import procedure to transfer files from old blog engine), and it plays nicely with Live Writer, the ultimate tool for writing blog posts.  Just don’t know what to ask more, no matter how hard I trySmiješak s namigivanjem

Even if you don’t need a blog engine, I highly recommend reading its source code. It’s a good example of simple approach for a simple problem, with a quality implementation.


Inspired with this blog post: http://grasswire-engineering.tumblr.com/post/94043813041/a-url-shortener-service-in-45-lines-of-scala, here goes c# / OWIN version! Its not meant to be used anywhere, but more as a learning example how to leverage some new tech stuff that’s available.

First example is using Katana, Microsoft implementation of OWIN standard, running as a regular ASP.NET application, meaning on System.Web, meaning with IIS (Express). I didn’t use any high-level class for dealing with requests, http context and response, expect what comes from Microsoft.Owin, in purpose just to show how it looks like without any framework on top of it.  
For database, I picked RavenDb Embedded. At first I planned to use EntityFramework 6, because one of the requirement I put to myself was Async ability of db engine – just to plug that in to async OWIN stuff, but since everybody knows about EF, and not everybody about Raven, I just went with Raven in this example.

App works like this:
To generate short URL, you send a POST request with query string “path” that contains value of URL you want to shorten. For example: http://localhost:12345/?path=http://www.hudosvibe.net. As a result, you should get HTTP status 201 (created), and a hash for this URL.
To use it, just add that hash to the URL: http://localhost:12345/hash-goes-here 
And that’s it, nothing much more going on!

Now, to the interesting part, here’s the code:

The complete source is on Github (https://github.com/hudo/Sample-UrlShortener), where I’ll put other example hopefully in the near future!

How does it work:

For OWIN, well Katana, because OWIN doesn’t specify that, we need an entry point to our application. By convention, that’s the Startup class, and Configuration(IAppBuilder app) method.
As you probably know already, OWIN is series of middlewares that executes in sequence. Middleware is just a function that gets the http context and a reference to the next function. I created only one middleware here, a method closure which will be called for each request.
Just to avoid using IF or SWITCH, because that’s not so cool anymore, I created a dictionary with actions for each Http method, GET and POST. With await actions[ctx.Request.Method](session); appropriate action is executed, based on requests method.
For get request, we’ll try to load a Raven document by Id, and send a redirect to a full Url address. For post, we need to create a hash first. In this simple and naive example, we’ll just create random sequence of 7 characters. There can be conflicts, and document will be overwritten – that’s how Raven works if you manually set Id. We store that document to Raven, with hash and original full Url.

Raven is running in embedded mode, which means you don’t have to have Raven server on your computer, it run in process, with managed store engine (slower, but just fine for this example). It uses Json serialization, so anything that can be serialized can be stored. No need to create a schema, we just store json object, and Raven takes care about the rest.

Think that covers it. Next on the list is example with Nancy and ASP.NET vNext, so stay tuned for updates! 


Možda se nisu oglasile fanfare, ali prije oko godinu dana počelo se raditi na specifikaciji i implementaciji nove verzije ASP.NET frameworka. Ne ASP.NET 5 ili 6, nego bih ja to slobodno mogao nazvati ASP.NET 2.0. Vezija 1 je izašla 2002., a verzija 2 2014!

Ovaj hudo je poludio, sigurno vam je prvo palo na pamet, ali ovako korijenite promjene, gdje se razvoj jezgre, arhitekture i cijelog tehničkog dizajna počeo raditi iz nule, odnosno gotovo od File/New Project, a ne od File/Load “System.Web”, govori o težini i veličini nove verzije. Naravno da Microsoft, poslovično pragmatičan i oprezan što se tiče kompatibilnosti unazad, pokušava i dalje paralelno razvijati WebForms i MVC, a novije frameworke poput WebAPI i SignalR prilagoditi novoj arhitekturi, tako da će tranzicija na OWIN biti najvjerojatnije bezbolna i transparentna. Što to znači?

WebForms i MVC ostaju gdje jesu, ovisni o System.Web dijelu .NET frameworka. Ali sve ostalo što izlazi iz MS radionica će biti OWINizirano.

OWIN (Open Web Interface for dot Net) je najlakše opisati sa ovom linijom koda:

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

niti ostatak specifikacije nije nešto složeniji, uz par pravila i ograničenja sadrži spisak ključeva i tipova koji se kriju iza ove IDictionary<string, object> varijable. Povratni tip Task nam govori da je asinkrono procesiranje ugrađeno u samu specifikaciju.

OWIN i Katana arhitektura

Ali što znači ovaj linija uopće? Najjednostavnije, radi se o pipelineu(cjevovodu?), gdje su komponente (Middlelware) spojene jedna za drugom, prosljeđuju ili prekidaju izvršavanje upita. Jedna komponenta na primjer može biti logiranje, jedna autentifikacija, zatim sam web framework poput Nancyfx, ili REST framework poput WebAPI ili ServiceStack.
Našu aplikaciju čine niz povezanih komponenti, gdje smo mi odabrali samo ono što želimo da se izvršava. Ako nam ne trebasession management, nećemo tu komponentu uključiti u pipeline,samim time niti “platiti” to performansama ili memorijom.

Implementacija OWIN specifikacije od strane Microsofta se ove Katana.Ona omogućava izvršavanje OWIN komponenti u IIS-u ili pak self-hostanu unutar druge aplikacije koristeći HttpListener (Nuget: Microsoft.Owin.Host.HttpListener), koristeći postojeću funkcionalnost unutar System.Web imenskog prostora.
Projekt pod nazivom Helios (Nuget: Microsoft.Owin.Host.IIS)je potpuna zamjena za System.Web u korištenju IIS-a, gdje su svi nativni pozivi na IISu nanovo napisani, a sve to zajedno donosi agilnost, puno brži release cycle, i svakako puno bolje performanse.

Evo kratki primjer kako dodati OWIN-baziranu web aplikaciju u postojeći projekt (WPF ili konzolna aplikacija, da stvar bude zanimljivija). Prvo dodajte Nubget pakete: 


Pokretanje Katana web servera na portu 12345:


Sama Startup klasa prema konvenciji mora imati metodu Configuration. U njoj smo definirali 3 middleware komponente

Za LoggingMiddleware koristili smo baznu klasu, i napravili vlastitu komponentu:

Ovaj vrlo jednostavni primjer će potom raditi i na IIS-u, IIS expressu, ili pak nekom drugom serveru (Linux), jer korištene komponente ne referenciraju niti jednu klasu iz System.Web imenskog prostora.

Postojeći WebForms i MVC frameworci najvjerojatnije se nikada neće moći pokretati na nekom OWIN hostu, ali postoji i niz drugih odličnih frameworka koji ih mogu više ili manje uspješno zamjeniti (Nancy, Simple.Web, …)

Šlag na kraju je lakoća in-memory testiranja, bez potrebe za pokretanjem servera i otvaranjem portova, upotrebom Nuget paketa Microsoft.Owin.Testing i xunit-a

Nadam se da je ovaj kratki prikaz OWIN pomogao u njegovom shvaćanju, i da će te pronaći scenarij za iskoristiti ga!