ASP.NET Web API on Linux and Apache with Mono

We had a requirement at OCC to build a RESTful web service that would be able to run on both Windows and Linux servers. Someone suggested we give Mono a look to see if we would be able to use the ASP.NET Web API framework served up by the Apache Web Server on Linux. That sounded great; we have a lot of experience with the .NET Framework and a lot of experience with Linux but so far have not brought the two together.

Banner showing Mono, .NET, ASP.NET, Apache and Linux logos

Mono is an implementation of the .NET framework that can be used to build applications that run on Linux and OS X in addition to Microsoft Windows. There are further details on Wikipedia.

In the past, some concerns have been expressed regarding licensing, software patents and their possible impact on Mono and the applications that depend upon it. The Mono team have addressed these concerns and recently (April 2014) Microsoft released Roslyn under the Apache 2 license and have committed to working closely with the Xamarin team, whose product is based around Mono, which may further calm concerns.

Getting Started on Linux

If you are lucky your system will have a package available to install Mono, if so then you should use this. At the time I was not so lucky so had to get the latest stable source and build that.

In Practice

Because the Mono team are attempting to keep up with developments by Microsoft the Mono framework does not fully implement the latest .NET framework. This can lead to some headaches where there is a partial implementation which can result in some methods of a class not being available under Mono but often these issues can be worked around.

However, Mono is under very active development and generally manages to keep up surprisingly well.

Pros:

  • Can use Visual Studio for the bulk of development.
  • Once something builds and runs on Windows it runs very reliably on Mono. I’ve only been looking at Web applications so I couldn’t comment on a Desktop application with a GUI.

Cons:

  • NuGet has limited usefulness with Mono. I had to get the necessary binary files and manage a Libraries directory within the project. Not a big issue in my case but could be if large numbers of externals are required.
  • Have to maintain a separate build on the Linux system. I used makefiles which was not too onerous but this might be mitigated by MonoDevelop or Eclipse but it did not seem enough of a problem.

Building Mono

Building Mono from source is pretty straightforward but there are a few gotchas.

First it is necessary to make sure a basic development environment is in place, on a CentOS system that’s something along the lines of:

    yum -y install bison glib2 glib2 freetype freetype-devel \
        fontconfig fontconfig-devel libpng libpng-devel libX11 \
        libX11-devel glib2-devel libgdi* libexif glibc-devel \
        urw-fonts java unzip gcc gcc-c++ automake autoconf \
        libtool wget giflib-devel libjpeg-devel libtiff-devel \
        libexif-devel httpd-devel

Source Code

Get the 2.10 source releases of [libgdiplus][15], [mod_mono][16] and [XSP][14] – at the time of writing the stable build of mono is at version 3.2.3. It is does not appear to be important to have all components with the same version as the main Mono release.

Unpack each in a local directory then configure and build in the following order:

libgdiplus

    cd libgdiplus-2.10
    ./configure --prefix=/opt/mono
    make
    sudo make install

Mono

    cd mono-3.2.3
    ./configure --prefix=/opt/mono --with-libgdiplus=/opt/mono
    make
    sudo make install

Add the /opt/mono/bin path to the system path and also set the PKG_CONFIG_PATH to /opt/mono/lib/pkgconfig through the /etc/profile (do not forget to export the variables). These variables must be set before building xsp as it needs the C# compiler otherwise the configure part of the build will fail.

xsp

    cd xsp-2.10
    ./configure --prefix=/opt/mono
    make
    sudo make install

mod_mono

    cd mod_mono-2.10
    ./configure --prefix=/opt/mono --with-mono-prefix=/opt/mono
    make
    sudo make install
    sudo mv /etc/httpd/conf/mod_mono.conf /etc/httpd/conf.d/

Configuration

It will probably be necessary to add the path to Mono’s shared libraries to the system wide library path. This can be done by either adding the path to /etc/ld.so.conf or, if the /etc/ld.so.conf.d directory exists, by adding a new file there (I suggest following the naming convention used by other files in that directory) with the path to the Mono shared libraries – these will be at /opt/mono/lib. Once this has been done run the ldconfig command as root to update the system.

After building and installing check the installation by running:

    mono-test-install

Making .NET 4.5 work

When building from source code there is a problem when running applications which require the .NET framework 4.5 libraries. The xsp4 and mod_mono shell scripts that are executed (located in the /opt/mono/bin directory) refer to executables in the /opt/mono/lib/mono/4.0 directory. Typically the executables themselves are fine but they refer to the 4.0 libraries which can be missing some of the newer features. This can result in problems of the form:

    Exception caught during reading the configuration file:
    System.MissingMethodException: Method not found: blah blah blah
      at System.Configuration.ClientConfigurationSystem.System..... yack yack

To fix this first make symbolic links in the 4.5 directory to the 4.0 files:

    ln -s /opt/mono/lib/mono/4.0/xsp4.exe /opt/mono/lib/mono/4.5/xsp4.exe
    ln -s /opt/mono/lib/mono/4.0/mod-mono-server4.exe \
        /opt/mono/lib/mono/4.5/mod-mono-server4.exe

Then edit /opt/mono/bin/xsp4 and /opt/mono/bin/mod-mono-server4 to reference the symbolic links.

Fixing errors caused by colons in the virtual path name

In our application the resources managed by the RESTful interface include the colon ‘:’ character. There appears to be a bug which creeps out when using ASP.NET applications in sub directories. The problem appears with the static initialisation in System.Web.VirtualPathUtility which manages to not read the Web.config system.web/monoSettings verificationCompatibility="1" attribute so fixed by setting the monoSettingsVerifyCompatibility member variable false otherwise errors are generated when there is a colon in a virtual path name.

Apache

The Apache mod for Mono passes requests to the mod_mono_server, which is able to support multiple ASP.NET processes.

With the above completed restart Apache web server and verify that mod_mono has been picked up.

    httpd -M

You can also inspect the error log after a restart.

MonoServerPath

Mono’s support for ASP.NET under Apache uses a simple module which delegates requests to the mod-mono-server. The MonoServerPath setting in httpd.conf specifies where the mono server is for each location:

    MonoServerPath default "/opt/mono/bin/mod-mono-server4" 

This configures mono for the default path which for a standard Apache configuration will be /var/www/html. It is also necessary to configure the application and handler:

    MonoApplications "/:/var/www/html"

    <Location "/">
        Allow from all
        Order allow,deny
        SetHandler mono
    </Location>

In addition, the following options can be set:

    MonoSetEnv default MONO_IOMAP=all
    MonoDebug default true

Restart the server and check the error log file.

If other locations need to be configured much the same needs to be repeated, for example, if a /test application were to be created it would be configured as:

    Alias /test "/var/www/test"
    MonoServerPath test "/opt/mono/bin/mod-mono-server4"
    AddMonoApplications test "/test:/var/www/test"

    <Location "/test">
        Allow from all
        Order allow,deny
        MonoSetServerAlias test
        SetHandler mono
    </Location>

Other Directives

It is recommended to disable KeepAlive for performance reasons or at least restrict the time-out to 2 seconds.

    KeepAlive Off

The CentOS installation of Apache web server sets the name for the log files as access_log and error_log; you may want to have the more conventional .log file extension.

Configuration Tool

The mono site has a handy online tool that can help with setting up a basic configuration for either a virtual host or an application.

In conclusion

Building a RESTful ASP.NET Web API with Mono, to run on Windows and Linux servers, was pretty straightforward with only a few problems on the way.

Digital Health Hackday

David Hannaford and Mark Stone attended Digital Health Oxford’s Hackday, held at the Oxford Launchpad in Said Business School, Oxford, over the weekend of 12th and 13th July.

David’s team came 2nd for the data visualization tool they built to enable a doctor to show a patient their survival rate if they are at risk from cardiac issues. The app calculates the survival rate of an individual by looking at data on risk factors, such as age, weight, blood pressure, and whether the patient is a smoker or diabetic.

Screenshot of the app

The technologies used to create the app are JavaScript, jQuery and D3 (D3 is a data visualization JavaScript library).

20140713_140748

David having fun trying out Google Glass

This hackday had a focus on Global Health, Patient Experience, Care, Aging, and Management in Medicine. There was also a  Clinicians’ Challenge and Patients’ Challenge, although participants were free to decide what they’d like to work on. There were mentors to help advise and guide, and an expert panel to judge the projects at the end.

Digital Health Hackdays are weekend events that bring together researchers, developers, clinicians, entrepreneurs, patients, engineers, designers and others interested in Digital Health.

CuPiD demo at Said Business School

Reynold Greenlaw and Andy Muddiman attended the Oxford Startups demo night at Oxford Launchpad in the Said Business School, on 15th May where they demoed the GaitAssist smartphone app that has been developed for the Cupid project. They demoed it pretty much continuously at our very busy table to the many interested attendees and our communications manager Janine Smith joined in to lend a hand.

The app continuously compares the gait of a user with Parkinson’s disease during walking with an “optimal gait” calibrated with a clinician. Based on evaluation of the specific patient, the most important gait parameters (e.g. step length, cadence) are set for future training sessions. The app gives the user feedback on how well they are doing and uses a technique to help Parkinson’s gait called audio cueing.

Cupid demo 3  Cupid demo 1Andy and Reynold demoing the app

Data on gait performance is visible to the clinician who can then adjust the exercise remotely forming a feedback loop between the user and the doctor. You can take a look at the demo itself on this video of Audio Bio-Feedback in action.

This event was organized by the Oxford Academic Health Science Network which brings together clinicians, academics and the public to promote best health in the region.

The Oxford Launchpad was launched in February 2014. It is a new space for entrepreneurial activity housed within the Said Business School, University of Oxford.

EmerGent: Relevance of Social Media in Emergencies

We recently started a new project – EmerGent, which is a 3 year European project researching the impact of social media by emergency services during a crisis.

Emergent logo

Whenever there’s a large fire, riot, earthquake or other crisis a lot of information immediately appears in social media – some valuable, some completely erroneous. With our partners we are developing tools and techniques for mining and validating that content.

The EU-FP7 EmerGent project has received funding from the European Union’s Seventh Framework Programme for research, technological development and demonstration under grant agreement no 608352. Find out more about EmerGent and its partners on the project website.

Finding time to think

A personal blog post from our Director of Consultancy Projects

As well as delivering products, OCC has a team that specialises in custom software development; they are behind the wide variety of case studies on our website. This combination of teams working on custom software and product development & support is, I think, unique.

Once a year I take the custom development team out for a day to discuss how we might write even better software. This time we crossed the road to the Jam Factory for an open discussion and some prepared talks. The talks were:

  • A toolkit for establishing better experience for our users
  • The judicious use of Agile project management
  • A critical look at SOLID principles
  • Lessons on testing from the product development team

The result was a surprise to me. The conclusion of the team was that best way to improve our performance was none of the above but instead improving the office environment. Nothing to do with software at all. The team wanted fewer interruptions, less multitasking  and more time to quietly think through difficult technical problems.

I was surprised and really interested in the conclusion. Our office is already considered calm and quiet. So we’re going to try a few new things. We’re going to experiment with collaboration tools that allow people to raise a “Do not disturb” flag. We’re using instant messaging that reduces disruption, hosted within OCC to keep the data confidential. I’m encouraging staff to book rooms or work from home during intensive design phases. It’s going to be interesting to see how we get on.

Consultancy Away Day

Consultancy Away Day

The OCC Christmas party, in May, in Poland

For our 2013 Christmas do we decided we would visit our colleagues in Poland rather than go for the usual Christmas outing. As Poland tends to be rather chilly in December we opted to hold out until May and hope for some summery weather.

So, over a long weekend, we (along with friends and partners) enjoyed the delights of a boat trip, a visit to underground cellars where vodka is made and aged, a walk round a picturesque lake, two lovely dinners, one in a Pomeranian Castle, and also a lively paintball game.

We didn’t have any snow as might normally befit a Christmas trip – the first day was very beautifully sunny and the second very wet, when we had to shelter under a bridge to have our picnic.

OCC has been running a small office in Szczecin for many years and some of our Polish engineers are now experts in UK social care.

CuPiD Technical Workshop

We believe there are many organisations implementing systems that conform to the following pattern:

  • A patient is being supported at home.
  • They wear sensors and/or use a smartphone.
  • Sometimes there is a home unit that wirelessly connects to the sensors/smartphone.
  • The data is securely transferred to a server.
  • There is a browser based application by which a clinician accesses the data.
  • Sometimes the clinician can send data back to the patient via the home unit or smartphone.
  • There may be integration between the server and external systems such as EHR.

We are holding a technical workshop at our offices in the centre of Oxford on the 14th April and inviting projects building similar systems to attend.

We will demonstrate the Cupid system and exercises, and talk openly about what went well and what didn’t. We will also discuss our plans to provide the telemedicine on an open source basis after at the completion of the Cupid project. The Cupid system is nearly complete.

CuPiD Exergaming The workshop will be an open discussion for a technical audience to exchange ideas and information. There will be time to talk about the validating and exploiting telemedicine systems. Please note this is not a marketing or sales event, but an opportunity to network.

So far we have representatives from StrokeBack, CogWatch, Oxford University, Oxford Brookes Movement Science Group and Digital Health Oxford attending.

If you would like to come please contact info@oxfordcc.co.uk

eHealth and the Brain – ICT for Neuropsychiatric Health

Reynold Greenlaw, Director of Consultancy at OCC, recently presented at eHealth and the Brain – ICT for Neuropsychiatric Health held in Brussels on the 5th November 2013. His presentation on Telemedicine and eHealth for Neurology, focused on the OCC’s involvement in the CuPiD Project.

CuPiD is a three year EU project powered by an eight member consortium led by the University of Bologna.

The CuPiD project is developing and field-testing home rehabilitation services for the major motor disabilities caused by Parkinson’s disease. OCC is responsible for transforming these services into telemedicine services, available in the home with remote supervision from a clinician. OCC is also responsible for integrating this system into Electronic Patient Records and systems for procuring health and social care services.

Top Tips in 10 Minutes for Software Engineers

Recently Reynold Greenlaw, our Director of Consultancy Projects, talked to 10MinutesWith about building a career as a Software Engineer. In their interview, Reynold covers the hardest and the best parts of working as a Software Engineer. He also talks about his own career path and gives tips on how to get started and what skills are needed.

10MinutesWith is an educational website, focusing on videos designed to help students and graduates understand different jobs and identify a career path.

Watch the video on our Careers page.

OCC is continually growing as a company; maintaining a steady growth rate of 15 – 20% pa. This month we have welcomed three new Software Engineers, all joining our successful products team. We believe people are a business’ greatest asset so we put a lot of care into finding the best new colleagues and into making the company an enjoyable place to work and learn.

Find out about our products or see the range of our custom software and services we offer.

Tom’s thoughts on AngularJS, TypeScript, SignalR, D3.js and Git

OCC DevCamp has been a great opportunity to put the day-job to one side and try out some new technologies. Here are some thoughts on how I got on with them.

D3, Git, TypeScript, AngularJS and SignalR logos

AngularJS

AngularJS is Google’s offering in the JavaScript application building framework arena. Having previously used Knockout I wanted to use a different framework for comparison. I’ve felt that Knockout isn’t especially well suited to large applications, and it seems to struggle in terms of performance when handling a large number of data bindings.

Angular comes with something of a learning curve (fortunately I shunted most of this on to Mel!) but after a week of use, it feels like a better choice for a larger application. The framework encourages writing code in a modular way, and it seems to be doing less magic in the background; surely good for performance. Data sizes in this application have been small, but there’s never been any indication that Angular has been slowing things down. More research would be possible if we choose to re-write one of our existing Knockout apps, but at first glance it doesn’t seem like that would be cost effective.

Recommendation: I would recommend using this again over Knockout. It would be good to see it put to work on a real project.

TypeScript

I’d been wanting to try out TypeScript for some time, since the prospect of writing JavaScript with straight-forward classes, modules, interfaces, etc. and compile-time type checking was a big draw. Again, I found there to be something of a learning curve, but it has been well worth it. There have been plenty of occasions when compiling my TypeScript file has revealed errors in code that I wouldn’t have found until running the application in a web browser if I’d been using vanilla JavaScript; obviously that adds up to a lot of time saved.

A couple of gotchas:

  1. You’ve got to keep remembering to build your solution in order to rebuild the associated JavaScript file. [Edit: it seems like it ought to be possible to get this working with compile-on-save, but this didn't work out of the box for me]
  2. If working with other JavaScript libraries – and let’s face it you will be – you’ll need to remember to download the associated TypeScript definitions files or face compilation failures. Fortunately these are easy to find on NuGet, as long as you remember to go looking for them, e.g.:

Screenshot of loading the AngularJS TypeScript Definition

Recommendation: TypeScript is definitely worth using. You can start by just renaming your existing files with the .ts extension, and if it all gets too much you can simply drop back to plain old JavaScript.

Example: The best example of the benefits of writing well laid-out code with TypeScript and AngularJS together was when I wanted to drop Poll Graphs into three different web-pages served by our application. One had the main presentation and associated JavaScript, the other didn’t. The following code was sufficient to drop graphs into all three pages with no further work:

Angular code to add polls to the presentation

SignalR

SignalR is a library for real-time web functionality. In the best circumstances it will use a WebSocket between server and client, but will seamlessly fall-back to older client-server mechanisms if required.

This was very easy to get started with, and has been very powerful. The code in our Hub class, which receives messages and broadcasts responses, is very clear and concise. The documentation from Microsoft is surprisingly good. However, we’ve seen issues with connections being dropped, messages getting delayed, and there have been problems along the way with the architecture of our application which was at times getting into circular message->broadcast->message chains. That said, I invested very little time in trying to make robust the Hub backbone to our application.

Recommendation: I don’t think that any of the issues we’ve come across couldn’t be resolved given more development time and production servers. The application architecture needs to be right no matter which library we use for real-time calls. If I had the need to develop real-time interaction I’d give SignalR a chance: it’s a great starting point and builds in a lot of powerful features.

D3.js

D3.js is a JavaScript library for manipulating documents using data, with very powerful capabilities. We only scratched the surface of this, but it produced some very nice bar charts for us. Once I got my head around the syntax, changes to the graphs presentation and scaling were very easy to make; a sure sign of a well thought out library.

Screenshot of a D3.js poll chart

Recommendation: I’d definitely use this library again if I have client-side graphing needs. In fact, I just want an excuse to use it on something more complicated than a bar chart!

Git & GitHub

Distributed source control in its own right is definitely a good thing. The ability to pull incoming changes locally, handle them and commit a properly recorded merge action is valuable. I’d already scaled the learning curve for using a distributed source control system when trialling Mercurial some time ago. The concepts came back to me fairly quickly so I didn’t have to waste time on that this week.

I ended up using a few tools to work with our Git repositories:

  • GitHub for Windows client: The UI was very confusing and anything but the simplest functions required dropping out to the command line. Shiver. I quickly stopped trying to use it.
  • Visual Studio integration was ok for simple actions but often seemed to get completely stuck when conflicts needed to be resolved; perhaps there will be fixes for this in the future.
  • TortoiseGit: by the end of the week I was solely using TortoiseGit. Not only because it was very similar to the TortoiseSVN toolset I’m used to, but also because it worked: it did what it had to do, when it had to do it.

Recommendation: I’d still recommend using distributed source control over non-distributed in general. I’d use Tortoise clients if we decided to do this at work.