Campfire Mono: Changing The Culture, Hearts & Minds of .NET Society

Mono in the wildThis year I attended the 1st Ruby conference in Africa, Rubyfuza. I walked out of that conference inspired and envious at the same time, by the scale of the Ruby community’s commitment to take full responsibility, accountability and ownership of Ruby, Ruby products and the event itself. No single big vendor was responsible for the event – everything was done by the developers themselves. Everyone that presented, directly used and contributed to the public products they were using. The community took full responsibility for their shared software. Here was a complete software ecosystem with world class applications and libraries that easily match, and often surpassed, similar offerings from billion dollar corporations, such as Microsoft and Oracle. I was envious that we didn’t see more leadership, responsibility and accountability in the .NET community.

In the .NET community there are many passionate people doing awesome work independently. However I cannot help but feel that the larger part of .NET society is blinded by their biased Microsoft focus, and the things they discuss stay in the context of what Microsoft does and says. It’s sad to know of the great projects out there, yet see so little representation and knowledge at gatherings.

The alternative and open source .NET communities have been growing in leaps and bounds, with the same characteristics as its Ruby counterpart. However it’s still too often perceived as an exotic place in some forsaken village on the .NET map, meant for .NET developers that are desperate to throw their bug ridden night time pet projects at anyone that is willing to hover over their GitHub repository’s link.

Well-well, have I got news for you. There are many open source projects that had rock solid solutions way before Microsoft or other vendors. Consider some of the following examples, that I personally experienced:

  1. In 2005, more than two years before the 1st version of Microsoft’s 1st Object Relational Mapper (ORM), Linq-to-SQL, NHibernate 1.0 was released. At that time the average .NET developer was still confused when you used the term “ORM” in a conversation, and refused to consider using anything else other than DataSets for data access.
  2. In 2004 .NET was open sourced  two years before Java, in the form of Mono.
  3. RESTful. Projects like ServiceStack, and NancyFX have production ready, non-bloated,lightweight RESTful web service frameworks.
  4. Aspect Oriented Programming (AOP). If you want to use AOP, then you have no other choice other than those offered by the open source community like Spring.NET.

The above are all due to the efforts of a vibrant, and prosperous alternative .NET society.

Yet, so many times I have experienced .NET shops:

  1. Where developers are quick to explain at length how rubbish this, or that library is compared to their custom written Yet-Another-Library.
  2. Where developers are completely ignorant, consciously or unconsciously, of the enormous number of actively developed .NET open source projects. You can find almost any project that suits your specific style or requirements. There are projects that are bloated and heavy like the Microsoft Pattern and Practices stuff, and ones highly nimble and lightweight like the Ruby stuff.

Repeatedly during conversations I uncover vast misunderstandings about the opportunity of alternative .NET solutions, and the open source ecosystem most are based on.

I then wonder how many more times are we going to think it’s smart to reinvent yet another insert-library-type-here on our own? Or stick to one of Microsoft’s libraries, even though it might be completely inappropriate for our specific scenario, but we settle for less, just because it’s from Microsoft.

To me this ignorant desire to code everything yourself, or wait passively for Microsoft to deliver the goods while you hack the current implementation, is an indication of an inefficient, selfish and narrow minded software society. Wouldn’t it be better to look beyond these boundaries for something more suitable that (1) you don’t have to do everything yourself and (2) the contribution you make is validated and used by the larger software community?

Talking to .NET developers, I generally hear the following misunderstandings:

  1. The belief that a commercial vendor will forever back a technology or product. Every product from a commercial vendor has a limited time span. No product or technology is forever supported, and continued.
  2. The belief that open source projects are of inferior quality, and that commercial products guarantee superior quality. I have used bad commercial products, and I have used bad open source products. Because something comes from a commercial vendor, definitely does not mean it is guaranteed to be higher quality.
  3. The belief that open source solutions are difficult to use and badly documented. The same argument follows as the previous one.

Okay, so before you think this discussion about open source vs. commercial closed source software. It is not. I am merely trying to prove that there are loads of awesome solutions, libraries and products by people other than Microsoft. These are created by a small, but vibrant and growing community of passionate people that provide competitive alternatives, that are very often much more viable or the only of its kind, than what is currently available in the core .NET or from Microsoft.

I believe there is a lack of recognition and understanding of what these solutions provide, how they are grown and how people can be part of their ecosystem. This lack of understanding is due to:

  1. People’s own resistance to a new way of doing things,
  2. Non-support, or even opposition, to the open source process by commercial vendors. To be fair, it’s not necessarily commercial vendors’ job to support open source projects. It is the developers themselves that must make their projects work and grow.
  3. An actual lack of information about what projects are out there and how they work.

It is time that alternative and open source .NET take its rightful place next to Microsoft .NET. Campfire Mono is a small step in this direction by providing a voice, and forum for alternative .NET developers in the Silicon Cape. Together we can build amazing products, without being restricted to what Microsoft offers. 

Campfire Mono is the place to discuss novel solutions for building .NET applications to run on all platforms by focusing on Mono and open source .NET technologies.

For the 1st Campfire Mono event on 1 August 2011, I will talk about REST Web Services With NancyFX and ServiceStack. It will take place on the 5th floor of the Bandwidth Barn in Silicon Cape:

  • Please RSVP
  • Price: Free.
  • Monoday, 1 August 2011, 18h15
  • Events Room, 5th floor,Bandwidth Barn, 125 Buitengracht Street, Cape Town

REST Web Services with ServiceStack

Over the past month I ventured deep into the alternative side of the .NET web world. I took quite a few web frameworks for a test drive, including OpenRasta, Nancy, Kayak and ServiceStack. All of the aforementioned supports Mono, except OpenRasta, that has it on its road-map. While kicking the tires of each framework, some harder than others, I saw the extent of just how far .NET has grown beyond its Microsoft roots, and how spoiled .NET developers have become with a long list of viable alternative .NET solutions from the valley of open source.

ServiceStack really impressed me, with its solid mix of components that speak to the heart of any modern C# web application. From Redis NOSQL and lightweight relational database libraries, right through to an extremely simple REST and SOAP web service framework. As the name suggests, it is indeed a complete stack.

Anyways, enough with the marketing fluff, let’s pop the bonnet and get our hands dirty. What I’m going to show you isn’t anything advanced. Just a few basic steps to help you to get to like the ServiceStack web framework as much as I do. You can learn the same things I’ll be explaining here by investigating the very complete ServiceStack example applications, but I thought some extra tidbits I picked up working through some of them should make life even easier for you.

Some Background Info On REST

I’m going to show you how to build a REpresentation State Transfer (REST) web service with ServiceStack. RESTful web services declare resources that have a URI and can be accessed through HTTP methods, or verbs (GET, PUT, POST and DELETE), to our domain services and entities. This is different from SOAP web services that require you to expose methods RPC style, that are ignorant of the underlying HTTP methods and headers. To implement a REST resource and its HTTP-methods in ServiceStack requires the use of two classes, RestService and RestServiceAttribute.

Another feature of REST is that data resources are encoded in either XML or JSON. However, the latest trend is to encode objects in JSON for its brevity and smaller size, rather than its more clunky counterpart, XML. We will therefore follow suit and do the same. Okay, I think you’re ready now to write your first line of ServiceStack code.

Create a Web Service Host with AppHostBase

The first thing you have to do is specify how you’d like ServiceStack to run your web services. You can choose to either run your web services from Internet Information Services (IIS) or Apache, or from the embedded HTTP listener based web server. Both of these approaches require you to declare a class that inherits from AppHostBase:

public class AppHost: AppHostBase
{
    public AppHost()
        : base("Robots Web Service: It's alive!", typeof(RobotRestResource).Assembly) {}

    public override void Configure(Container container)
    {
        SetConfig(new EndpointHostConfig
        {
            GlobalResponseHeaders =
            {
                { "Access-Control-Allow-Origin", "*" },
                { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
            },
        });
     }
 }

Class AppHost‘s default constructor makes a call to AppHostBase‘s constructor that takes 2 arguments. This first argument is the name of the web app, and the second argument tells ServiceStack to scan the Assembly where class RobotRestResource is defined, for REST web services and resources.

AppHostBase‘s Configure method must be overridden, even if it’s empty, otherwise you’ll get and exception. If you plan on making cross domain JavaScript calls from your web user interface (i.e. your web interface is written in JavaScript and hosted on a separate web site from your web services) to your REST resources, then adding the correct global response headers are very important. Together the two Access-Control-Allow headers tell browsers that do a pre-fetch OPTIONS request that their cross domain request will be allowed. I’m not going to explain the internals, but any Google search on this topic should yield sufficient info.

Now all that’s left to do is to initialize your custom web service host in Global.asax‘s Application_Start method:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        new AppHost().Init();
    }
}

The last thing you might be wondering about, before we move on, is the web.config of your ServiceStack web service. For reasons of brevity I’m not going to cover this, but please download ServiceStack’s examples and use one of their web.configs. The setup require to run ServiceStack from IIS is really minimal, and very easy to configure.

Define REST Resources with RestService

Now that we’ve created a host for our services, we’re ready to create some REST resources. In a very basic sense you could say a REST resource is like a Data Transfer Object (DTO) that provides a suitable external representation of your domain. Let’s create a resource that represents a robot:

using System.Collections.Generic;
using System.Runtime.Serialization;

[RestService("/robot", "GET,POST,PUT,OPTIONS")]
[DataContract]
public class RobotRestResource
{
[DataMember]
public string Name { get; set; }

[DataMember]
public double IntelligenceRating { get; set; }

[DataMember]
public bool IsATerminator { get; set; }

[DataMember]
public IList<string> Predecessors { get; set; }

public IList<Thought> Thoughts { get; set; }

}

The minimum requirement for a class to be recognized as a REST resource by ServiceStack, is that it must inherit from IRestResource, and have a RestServiceAttribute with a URL template, and that’s it. ServiceStack doesn’t force you to use the DataContractAttribute or DataMemberAttribute. The only reason I used it for the example is to demonstrate how to exclude a member from being serialized to JSON when it’s sent to the client. The Thoughts member will not be serialized and the web client will never know the value of this object. I had a situation where I wanted to have a member  on my resource for internal use in my application, but I didn’t want to send it to clients over the web service. In this situation you have to apply the DataContractAttribute to your resource’s class definition, and the DataMemberAttribute to each property you want to expose. And that’s it, nothing else is required to declare a REST resource ffor ServiceStack.

Provide a Service for Each Resource with RestServiceBase

Each resource you declare requires a corresponding service that implements the supported HTTP verb-methods:


public class RobotRestService: RestServiceBase<RobotRestResource>
{
    public override object OnPut(RobotRestResource robotRestResource)
    {
        // Do something here & return a
        // new RobotRestResource here,
        // or any other serializable
        // object, if you like.
    }

    public override object OnGet(RobotRestResource robotRestResource)
    {
        // Do some things here ...
        // Return the list of RobotRestResources
        // here, or any other serializable
        // object, if you like.

        return new []
        {
            new RobotRestResource(),
            new RobotRestResource()
        };
    }
}

In order for ServiceStack to assign a class as a service for a resource, you have to inherit from RestServiceBase,  specifying the resource class as the generic type. RestServiceBase provides virtual methods for each REST approved HTTP-verb: OnGet for GET, OnPut for PUT, OnPost for POST and OnDelete for DELETE. You can selectively override each one that your resource supports.

Each HTTP-verb method may return one of the following results:

  1. Your IRestResource DTO object. This will send the object to the client in the specified format JSON, or XML.
  2. ServiceStack.Common.Web.HtmlResult, when you want to render the page on the server and send that to the client.
  3. ServiceStack.Common.Web.HttpResult, when you want to send a HTTP status to the client, for instance to redirect the client:
    var httpResult = new HttpResult(new object(), null, HttpStatusCode.Redirect);
    httpResult.Headers[HttpHeaders.Location] = "http://openlandscape.wordpress.com";
    return httpResult;
    

And that’s it. Launch your web site, and call the OnGet methof at /robot?format=json, or if you prefer XML /robot?format=xml. To debug your RESTful service API I can highly recommend the Poster Firefox plug-in. Poster allows you to manually construct HTTP commands and send them to the server.

You might be wondering what the purpose is of RobotRestResource that gets passed to each HTTP-verb method. Well, that is basically an aggregation of the posted form parameters and URL query string parameters. In other words if the submitted form has a corresponding field name to one of RobotRestResource’s properties, ServiceStack will automatically assign the parameter’s value to the supplied RobotRestResource. The same applies for query strings, the query strings ?Name=”TheTerminator”&IsATerminator=true: robotRestResource’s Name will be assigned the value of “TheTerminator” and IsATerminator will be true.

Using ServiceStack’s Built-In Web Service as a Service Host

The above discussion assumed that you’ll be hosting your ServiceStack service in IIS or with mod_mono in Apache. However, ServiceStack has another pretty cool option available, self hosting. That’s right, services can be independently hosted on their own and embedded in your application. This might be useful in scenarios where you don’t want to be dependent on IIS. I imagine something like a Windows service, or similar, that also serves as small web server to expose a web service API to clients, without the need for lengthy and complicated IIS setup procedures.

var appHost = new AppHost();
appHost.Init();
appHost.Start("http://localhost:82/");

To start the self hosted ServiceStack you configure your host as usual, and then call Start(…), passing the URL (with free port) where the web server will be accessed.

Why Use ServiceStack

For me one of the big reasons for choosing ServiceStack is that it has a solid library to build web services running on Mono. However, after using if for a while I found its easy setup and simple conventions very refreshing from the often confusing and cumbersome configuration of Windows Communication Foundation (WCF) web services.ServiceStack also does a much better job of RESTful services, than WCF’s current implementation. I know future versions of WCF will enable a more mature RESTful architecture, but for now it’s pretty much RPC hacked into REST. Another bonus was the complete set of example apps that were a great help to quickly get things working. So if you’re tired of WCF’s heavy configuration and you’re looking for something to quickly implement mature RESTful web services, then definitely give ServiceStack a try.


Follow

Get every new post delivered to your Inbox.