Tuesday, May 27, 2014

Nerd Food: Using Mono In Anger - Part III

Nerd Food: Using Mono In Anger - Part III

In which we discuss the various libraries and tools used.

This is the third part of a series of posts on my experiences using Mono for a fairly demanding project. For more context please read part 1 and part 2.

In this instalment we shall focus more on the libraries, tools and technologies that I ended up using.


I've mentioned Castle a few times already. It appears to be the de facto IoC container for .Net, so its very important to have a good story around it. As I explained on the previous post, I added NuGet references to Castle Core and Castle Windsor and after that it was pretty much smooth sailing. I setup Windor Installers as described by Mark Seemann in his post IWindsorInstaller and that worked as described. My main program does exactly as Mark's:

var container = new WindsorContainer();
container.Install(new MyModule.WindsorInstaller(), new OtherModule.WindsorInstaller());
return container.Resolve<IEntryPoint>();

Basically, I have a number of IWindsorInstallers (e.g. MyModule.WindsorInstaller() etc.) that get installed, and then all that needs to be done is to resolve the "entry point" for the app - e.g. whatever your main workflow is.

All of this worked out of the box without any tweaking from my part.


I've used MongoDB as the store for my test tool; I'll give a bit of context before I get into the Mono aspects. Mentally, I picture MongoDB somewhere in between PostgreSQL and Coherence / MemCached. That is, it's obviously not a relational database but one of those NoSQL specials: a schemaless, persistent, document database. You can do a lot of this stuff using hstore, of course, and it now even sports something similar-but-not-quite-the-same-as BSON - JSONB, in the usual humorist Postgres way. MongoDB's setup is somewhat easier than Postgres, on both replicated and non-replicated scenarios. It also offers Javascript-based querying which, to be fair, Postgres also does. I'd say that, if you have to choose between the two, go for MongoDB if you need a quick setup (replication included), if you don't care too much about security and if you do not need any RDBMS support. Otherwise, use latest Postgres. And RTM. A Lot.

MongoDB is obviously also much easier to setup than Coherence. Of course, if you go for the trivial setup, Coherence is easy; but once you get into proper distributed setups I found it to be an absolute nightmare, requiring a lot of expertise just to understand why your data has been evicted. That's excluding the more complex scenarios such as invocation services, backing maps and so on. Sure, you can get the performance and the scalability, but you really need to know what you are doing. And let's not mention the licence costs. Basically, for the plain in-memory cache job with an easy setup, just use Memcached.

But let's progress with MongoDB. Regrettably, there are no packages in Testing for it, but the wiki has a rather straightforward set of instructions under Install MongoDB on Debian. It boils down to:

# apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
# echo 'deb http://downloads-distro.mongodb.org/repo/debian-sysvinit dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
# apt-get update
# apt-get install mongodb-org

Since I'm using systemd I was a bit apprehensive with their control scripts. As it turns out, it worked out of the box without any problems. I did find the installation to vary depending on the machines: on some I got journaling by default, but on my really low-end NetBook it was disabled. Also, the other thing to bear in mind is that if you have a small root or var partition - e.g. the one storing /var/lib/mongodb - you may run into trouble. I ended up symlinking this directory to a drive that had more space just to avoid problems.

Once MongoDB was up and running, it was time to find a management UI. Unfortunately, MongoVue - the UI that all the Windows cool kids use - is not available on Linux. This is a bit disappointing because it seems rather full featured and well funded and - just to rub salt in the wounds - it's a .Net application. The old lack of cross-platform mentality surfaces yet again. Undeterred once more, I settled on RoboMongo instead. Not quite as matured, but seemed good enough for my needs. Simple to setup too:

$ wget -O robomongo-0.8.4-x86_64.deb http://robomongo.org/files/linux/robomongo-0.8.4-x86_64.deb
$ gdebi-gtk robomongo-0.8.4-x86_64.deb

If you don't have gdebi-gtk any other debian installer would do, including dpkg -i robomongo-0.8.4-x86_64.deb.

If you are an emacs user, be sure to install the inferior mode for Mongo. Works well on Linux but has the usual strange input-consumption problems one always gets on Windows.

Going back to Mono, all one needs to do is to use NuGet to install the CSharp Mongo Driver. Once that was done, reading, writing, updating etc all worked out of the box.


Paradoxically, where I thought I was going to have the least amount of trouble ended up being the most troublesome of all of my dependencies. Getting log4net to work was initially really easy - the usual NuGet install. But then, not happy with such easy success, I decided I needed a single log4net.config file for all my projects. This is understandable since all that was different amongst them was the log file name; it seemed a bit silly to have lots of copy and paste XML lying around. So I decided to use Dynamic Properties, as explained in this blog post: Log4net Dynamic Properties in XML Configuration. This failed miserably.

As everyone knows, log4net is a pain in the backside to debug. For the longest time I didn't have the right configuration; eventually I figured out what I was doing wrong. It turns out the magic incantation is this (I missed the type bit):

        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <file type="log4net.Util.PatternString" value="APrefix.%property{ApplicationId}.log" />

Just when I thought I was out of the woods, I hit a Mono limitation: CallContext.LogicalGetData is not yet implemented in Mono 3.0. It is available on later versions of Mono, but these are not yet in Debian Testing. Undeterred, I decided to try to compile Mono from scratch. It turned out to be rather straightforward:

$ git clone https://github.com/mono/mono
$ cd mono
$ ./autogen.sh --prefix=${YOUR_INSTALL_LOCATION}
$ make -j${NUMBER_OF_CORES}
$ make install

Replace (or set) ${YOUR_INSTALL_LOCATION} and ${NUMBER_OF_CORES} as required. Once you got it installed, you need to tell MonoDevelop about the new runtime. Go to Edit, Preferences then choose .Net Runtimes and click on Add. Point to the top-level directory containing your installation (e.g. ${YOUR_INSTALL_LOCATION}) and it should find the newly built Mono. I then set that as my default. Incredibly enough, from then on it all just worked.


Runtimes in MonoDevelop


As mentioned in the previous post, you should replace the NUnit references you get from MonoDevelop with NuGet ones. This is because you may be using some of the newer features of NUnit - which are not available with the version that ships with Mono. At any rate, it just gives you more confidence on the dependency rather than depending on the environment.

Another problem I found was disabling shadow copying. This does not seem to be an option in the MonoDevelop UI or the solution. It is rather annoying if you need to have some log4net config files in the test directory - as I did, due to the Dynamic Properties mentioned above.

Other than that, NUnit worked very well.

Libraries Overview

Compiling Mono from source is obviously not ideal, but perhaps the main thing to worry about is how to get latest Mono packages. As with MongoDB, it perhaps would be better to have a repository supported by the Mono community that offers more up-to-date packages, at least for the more intrepid users. Although some of these existed in the past (particularly Ubuntu PPAs) they all seem to have gone stale.

Having said that, there are still no showstoppers - the code is working on both Visual Studio 2013 and Mono.

Date: 2014-05-27 22:29:38 BST

Org version 7.8.02 with Emacs version 23

Validate XHTML 1.0

Nerd Food: Interesting...

Nerd Food: Interesting…

Some interesting stuff I bumped into these last couple of weeks.


  • Banksy - Webby Awards Video: Banksy at his usual irreverent best. Hat-tip Emanuel Ferreira.
  • Listen to “Brian Eno Day”: a 12-Hour Radio Show Spent With Eno & His Music (Recorded in 1988). If you like ambient it's a must listen. Hat-tip Joao Santos.
  • Snowpiercer: To be fair, didn't yet get a chance to watch it yet, but the comments from Bruno Antunes were so glowing it went up on my list of must-watch movies.
  • Beware of Mr. Baker: Frigging amazing. I just can't believe I had never heard of this guy until I watched the movie. I mean, he played with Fela, Clapton, all the Jazz greats that were still alive. No words to describe it - just watch it. Crazy, crazy guy. Blind Faith are one of the many bands he was in.
  • Surfwise: Surf movie, but with a twist - or should I say nine. Crazy family with a crazy dad that decided one day that he'd spent the rest of his life surfing, and the world be damned. Amazing movie. It's also interesting because it outlines the consequences of such "heroic" decisions on the family.
  • Makthaverskan: Started listening to this rocky Swedish band.
  • El Empleo / The Employment: Great animation. Perfect description of the modern world.
  • The Expert: Like El Empleo, a dark take on the modern world, but this time as a dark comedy. Hilarious, but yet again, very painful.


Other Programming Topics

Start-ups and Business


  • Com os Holandeses: Encontrei um autor portugues que nunca tinha ouvido falar, mas que parece ser bastante conhecido na holanda. Na lista de livros a ler.

Date: 2014-05-27 12:14:54 BST

Org version 7.8.02 with Emacs version 23

Validate XHTML 1.0

Monday, May 26, 2014

Nerd Food: Using Mono In Anger - Part II

Nerd Food: Using Mono In Anger - Part II

In which we setup our working environment.

On Part I we explored the reasons why I decided to use Mono in anger. In this part we shall get ourselves a working environment comparable a Visual Studio 2013 setup.

First things first:

  • whilst this post presumes that you may not know everything about Linux, it does expect a minimum familiarity with the terminals, desktop, etc.
  • having said that, we try to keep things simple. For instance note that commands that start with # need to be executed as root and commands that start with $ should be executed as an unprivileged user. Also \ means the command should really be one big line.
  • my distribution of choice is up-to-date Debian Testing, which is where all the commands have been tested; hopefully most things will work out of the box for you - especially if you are using Debian or Ubuntu - but its better if you understand what the command is trying to achieve, just in case it doesn't quite work.
  • Finally, I presume you know about .Net and its libraries - although I do try to give some minimal context.

Without further ado, lets set our Mono environment.

Installing Mono

We start off by following the instructions on installing mono for Debian available in the Mono project wiki:

# apt-get install mono-complete

It's worth mentioning that whilst the Mono page above mentions v2.10.8.1 for Debian Testing, v3.0.6 has actually already been migrated from Unstable so that is what you will be getting. A note on versions here: with Mono, latest is always greatest. The project moves at such a fast pace that getting an old version is almost always a bad idea.

If everything has gone as expected, you should now see something along the lines of:

$ mono --version
Mono JIT compiler version 3.0.6 (Debian 3.0.6+dfsg2-12)
Copyright (C) 2002-2012 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           __thread
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug
    LLVM:          supported, not enabled.
    GC:            Included Boehm (with typed GC and Parallel Mark)

To make sure we have a fully working setup, lets compile a simple hello world:

$ echo 'class Program { static void Main() { System.Console.WriteLine("HelloWorld!"); }}' > hello.cs
$ mcs hello.cs
$ ./hello.exe

Installing MonoDevelop

Of course, no self-respecting Windows .Net developer will code from the command line; they will ask for an IDE. The IDE of choice for Mono is MonoDevelop - sometimes called Xamarin Studio because they are the main company behind it, and have a commercial product based on it.

It's pretty straightforward to install it on Debian:

# apt-get install monodevelop monodevelop-nunit monodevelop-versioncontrol \
     monodevelop-database monodevelop-debugger-gdb \
     libicsharpcode-nrefactory-cecil5.0-cil \
     libicsharpcode-nrefactory-cil-dev \
     libicsharpcode-nrefactory-csharp5.0-cil \
     libicsharpcode-nrefactory-ikvm5.0-cil \
     libicsharpcode-nrefactory-xml5.0-cil \

You will most likely get MonoDevelop v4.0. Alas, v4.2 has already been released but not yet hit Debian. As with Mono, latest is always greatest. Note that I went a bit overboard here and install a lot of stuff - you may just want to install monodevelop. I added the NUnit integration and the Version Control integration as well as the refactoring tools.

Once its installed you can start it from the main menu. It should look vaguely like this:


MonoDevelop's main window

The very next thing we need to do is to install the NuGet add-in for MonoDevelop. To do this:

  • Go the Tools menu, Add-in Manager;
  • Click on the Gallery tab;
  • Click on the Repository combo-box and select Manage Repositories…;
  • Click on the Add button and select Register an on-line Repository
  • Paste the repository from the page above, e.g.: http://mrward.github.com/monodevelop-nuget-addin-repository/4.0/main.mrep and click Ok.


MonoDevelop Add-in Repository

You should now be able to find the NuGet add-in by searching for it on the search box at the top of the dialog:


Installing NuGet Add-in

In my case its already installed - in your case you should get an Install option. Unfortunately we're not out of the woods just yet. We need to setup the certificates to allow us to download packages:

# mozroots --import --sync
# certmgr -ssl -m https://go.microsoft.com
# certmgr -ssl -m https://nugetgallery.blob.core.windows.net
# certmgr -ssl -m https://nuget.org

Now, to be perfectly honest there are still some setup issues for NuGet that I don't quite understand, but we'll leave that for later.

Setting up a Solution

To create a solution go to the File menu, New and choose Solution…:


Creating a new solution

This will create a solution with a project. Now, on the main screen create a second project, say MyProject.Tests, by right-clicking the solution, click on Add then Add New Project… and then fill in the project details: NUnit project and the name.


Adding a new NUnit project

To be perfectly frank, as with Visual Studio, I tend to create projects and solutions from the UI and then edit the raw .sln and .csproj files to get them in my preferred directory layout. At any rate, for this really simple solution we just get the following:


The HelloWorld solution

Now go to both project options by right-clicking on the project and then Options and find General. There update the target framework to Mono .Net 4.5.


Using .Net 4.5

You will get some blurb about project file changes, just accept it. The other thing to do is to use xbuild, Mono's equivalent of msbuild to do the building. To do so go to Edit, Preferences and Build. Then tick the xbuild check box:


Using xbuild

Now all we need is to setup all of the required NuGet packages. This is where things become a bit complicated. As I said previously, we set up all the required certificates so things should just work. In practice we still get a few issues. To see what I mean, right-click on a project's references, then Manage NuGet Packages…. The following message comes up:


NuGet certificate problem

If you click yes, you should then get the full blown list of NuGet packages. But it's a bit annoying to have to do that since apparently we have installed all of the required certificates. Also, as we shall see, the NuGet restore fails due to certificate problems but we'll leave that one for later. Once you waited for a bit, the packages screen will come up, and you can use the search box to search for packages and once happy, click on Add:


Adding Log4Net in NuGet

Using this workflow, add all the required packages. For example, in my case I added:

  • Main project: Log4net, Castle Core, Castle Windsor, Mongo CSharpDriver, Newtonsoft.Json
  • Test project: NUnit. I removed the reference that Mono added and forced it to go via NuGet. This saves you from a lot of problems related to incorrect NUnit versions.

A few points to note here. NuGet works but it's a little rough around the edges. When you are using it in anger, the following things will become annoying:

  • the whole certificate thing, which seems to make the initial NuGet window slower. Fortunately this appears to happen only once for a running session.
  • the inability to use NuGet restore is a pain; it means every time you swap machines you need to faff around to re-download packages. I use a dummy project for this - e.g. add packages to a project that does not have them and then remove them.
  • the NuGet add-in ignores the .nuget configuration; instead uses a "hard-coded" package directory at the same level of the solution. This is a bit painful because your Windows developers will see the packages in one location (i.e. where the .nuget config states it should be) but it will be elsewhere in Mono. Best not to use these until they are supported in Mono.
  • NuGet add-in doesn't seem to work when there is no network connection. This is a bit painful because it means that you can't add a dependency to a project that had already been added to another project without being online. In this scenario the easiest thing to do is to edit the .csproj and packages.config files manually.

A Note on F#

As I spent a considerable time describing the F# setup in the past (Adventures in F# Land Part 1, Part 2 and Part 3), it's only fair we cover how things are done these days. First install the required packages:

# apt-get install fsharp libfsharp-core4.3-cil libfsharp-data-typeproviders4.3-cil

Again, YMMV - I always go a bit overboard and install everything. Then in MonoDevelop install the Add-in. To do so simply go to Tools, Add-in Manager then click on Gallery and expand Language Bindings. Click on F# and then install.


Adding F# Support

It is that easy these days. We may have to do a F# in anger series later on, to see how well it stacks up.

Setup Review

First I'd like to say that there are a lot of positives in the setup experience. For example, I just spent the best part of two days getting Visual Studio to work due to some licensing issues - it just wouldn't accept my key for some reason. Also Visual Studio 2013 is rather demanding hardware wise, whereas MonoDevelop seems to hover on the 200 MB range (my actual solution has around 12 projects).

And on the main, the polish on MonoDevelop is quite good, with many things just working out of the box as they do in Visual Studio. And, once you get past some of it's minor quirks, Matt Ward's NuGet Add-In does work; I have been using it in anger for 3 weeks and I can attest to that. But it could be argued that NuGet is such a central component in the .Net experience that it should warrant thorough QA - perhaps by Xamarin - to try to bullet-proof it, at least for the hot use cases.

On the main, we're still very happy campers.

Date: 2014-05-26 20:12:12 BST

Org version 7.8.02 with Emacs version 23

Validate XHTML 1.0

Nerd Food: Using Mono In Anger - Part I

Nerd Food: Using Mono In Anger - Part I

In which we convince ourselves that it is time to use Mono in anger.

I've always been a Mono fan from the early days. Sadly, my career as a Mono developer never amounted to much - not even a committed patch - but I remained a loyal lurker and supporter. It's not so much because I thought it was going to change the face of Free Software, but because I wondered if it would allow Linux to gain a foothold in Windows-only companies. Having been working for this lot for such a long time, I desperately yearned for a bit of serious Linux interaction in my professional life, so I kept on playing around with Mono technology to evaluate progress. For instance, a few years back I wrote Adventures in F# Land Part 1, Part 2 and Part 3, based on my experiences in setting up F# in Mono1. I continually did this kind of mini-experiments, mucking around with tiny programs to query the state of the world. But what I really wanted to do was to test the whole infrastructure in anger2.

As you can imagine, I was extremely excited when I read Miguel's tweet:

Microsoft has open sourced the new generation of http://ASP.NET http://github.com/aspnet

Another blog post had more details: ASP.NET vNext. Microsoft was to start testing code against Mono, at least for ASP.Net. To me this was nothing short of revolutionary. Not to the average Linux developer, of course - barely a yawn from that camp. But to the average .Net developer this is - or should be - earth shattering news. When you couple this with the .Net Foundation announcements, it signals that Microsoft now gives the official blessing for developers to start thinking of .Net as cross-platform.

It may surprise you, but the average .Net developer does not spend days and nights awake, worrying about how to carefully design their architecture to maximise cross-platform code. They do not have Mono on their CIs. They tend not to care - or even be aware of - all the latest and greatest features that the Linux kernel sports, or how cool Docker, Chef and Puppet are. Those that are aware of this are in a minority, and most likely have been exposed to the other side via the Javascript infiltration that is now taking place. A fairly recent comment in a Castle issue should give you a flavour of this thinking:

I don't think anyone is actively pursuing Mono support at the moment. Reality with Mono historically has been that no one cared enough to properly bring it to parity with .NET and keep it that way.

Having said that, we're more than happy to improve our Mono support (…)

For those not in the know, Castle is an Open Source project that provides an IoC (Inversion of Control) container. It is really popular in .Net circles. As we shall see later, Castle actually works really well with recent versions of Mono - but the fact that the Castle team didn't have a CI with Mono is indicative of the state of the world in Windows .Net.

This is not to say that Linux is not on the Windows developer's radars - quite the opposite, and the progression has been nothing short of amazing. During my working life I've spent around 70% of my time working for Windows shops; to be honest, I still find it surprising when look at the past and compare it to the present. Things went from "Linux, what's that?" to "Linux is a nerd's toy, it will never make it" to "That's for Java guys" and finally, to "We run things on Linux where it is good at, but not everything". Things being Java and Coherence, Grid Engines, Javascript stacks and so on - no mention of .Net.

In fact, the .Net revolution hampered the Linux strategy a lot. Java was a good Trojan horse to force developers to think cross-platform, and many a Windows shop turned to Linux because of Java. However, once you had a competitive (read "enterprise-ready") .Net framework, Java receded in Windows people's minds and it was back to business as usual. Even a strong and capable Mono was not enough; a lot of the .Net code was so incredibly intermingled with Windows-only code that portability was impossible without great effort. Many a hero tried and failed to compile massive code bases on Linux.

Things started to change over the last five years. Three separate trends unified. First was the new focus on SOA. Windows developers finally found out what the UNIX geeks knew all along: that services are the way forward. And because their view of SOA was closely linked to REST and Web development, suddenly the code bases became a lot less Windows dependent and a lot more self-contained; no more WPF, no more third-party closed-source controls. The second important development was that Windows developers found Free and Open Source Software. A lot of the libraries they rely on are open source, and thus much more Mono friendly. The final trend was the rise and rise of Javascript and Linux-only tools. Every other Windows developer is now familiar with Node.js, Mongo, Redis et al, and have at least rudimentary knowledge of Linux because of it.

However, the Linux developer on a Windows-land is still stuck, and all because of a tiny little detail: IIS and ASP.Net are still a pain in the backside. Mono has provided ASP.Net support for a while now, but to be honest, the applications I've seen in the wild always seem to use some features that are either not yet supported or not supported very well. There is just so much coupling that happens when you pull in IIS that is hard to describe, and a lot of it happens without people realising - it's that lack of cross-platform mentality all over again. So for me the one last little piece of the puzzle was IIS and ASP.Net. This was anchoring the entire edifice to Windows.

Now you can see why having a fully open source ASP.Net stack is important; especially one that does not depend on IIS directly, but uses OWIN for separation of concerns and is tested on Mono by Microsoft. Code bases designed on this stack may be able to compile on Mono without any changes - or, more likely, with a few small changes - opening the floodgates for Linux and OSX .Net development. Of course, don't let me get too carried away here. There is still much, much to be done for a totally cross-platform environment: Powershell, KPM, etc. But this is a very large step in the right direction, and it covers a large amount of use cases.

A final point is worth making about the corporate ecosystem that evolved around Mono. This is not really a marketing ploy, although I do wish them all the best. Companies such as Xamarin, Unity and projects such as MonoGame are instrumental in the progress of Mono. By creating funded start-ups around Mono, with products that are used by a large number of developers, they engineered a dramatic increase of quality in the entire ecosystem. And in turn this raised its visibility, bringing more developers on board, in the usual virtuous circle of open source.

So for all these reasons and more, it seemed like Mono deserved another good look. As it happened, I was trying to develop a fairly large test tool for work in my copious free time. Since I needed to code from home, I thought this would be the right project to give it a far old whack. And you, dear reader, will get to know all about it in this series of posts.


1 Mind you, all of it is to be ignored as its now trivial to setup F#.

2 For the non-British speakers out there, using something in anger just means "to give it a good go" or "to really push it" rather than writing a hello world.

Date: 2014-05-26 17:24:40 BST

Org version 7.8.02 with Emacs version 23

Validate XHTML 1.0