Simple ClojureCLR Example

Setting up ClojureCLR, calling it from a .Net console application and printing the results.

I’ve been working on a reasonably complex WPF application lately and threading issues have been getting me down.  Clojure has been making a lot of claims about concurrency lately so I thought I’d give it a try.

”Clojure, being a practical language, allows state to change but provides mechanism to ensure that, when it does so, it remains consistent, while alleviating developers from having to avoid conflicts manually using locks etc.”

Clojure is built for the Java Virtual Machine but there is an ongoing effort to port it to .Net called ClojureCLR.  I had some trouble finding any examples of how to use it so this post describes what I’ve figured out so far.

Building Clojure

First we need a working version of ClojureCLR.  Since it’s still work in progress you need to build this yourself.  The instructions in the wiki are pretty good if you read them carefully.

I didn’t read them carefully and had problems so here’s some extra notes…

When you download the DLR from CodePlex make sure you go to the source code tab and download the latest.  I tried the latest packaged release which did not work.

When I cloned the source with git, I ended up with lots of modified files waiting to be checked in.  To fix this I read the help from github about this and then did the opposite as  I already had the setting on by default:

    git config core.autocrlf false

If you set up your directory structure correctly you shouldn’t need to modify anything to get Clojure to compile.  Mine looks like this

    C
        Development
            clojure-clr
            DLR_Main

This is the easiest way because otherwise you will need to mess with extern aliases on the references.  I did not compile the Clojure.Tests project.

When the compilation instructions say “Do it” what they mean is open the ClojureCLR solution in Visual Studio and build it like a normal project.  No scary build scripts to mess around with.

A Test Project

I added the projects for the Clojure and DLR dependencies directly to my example solution to make compilation and debugging nice and easy.

 Clojure Example

ClojureTest is my example console application.  The scripts directory contains my example Clojure source which looks like this:

(ns test)

 

(defn add [a b]

  (+ a b))

This defines a function called add in the namespace test.  Can you guess what it does?

The clojure directory contains all the bits need to start and run a clojure environment.  This is prepared by the Clojure.Compile project and is a copy of this folder:

clojure-clr\Clojure\Clojure.Compile\bin\Debug\clojure

Select all the files in both the scripts and clojure directories and set their build action to Copy if newer so they end up in your output directory.

Calling Clojure

We’re ready to go!  Here’s my console application in C#:

static void Main()
{
    RT.LoadScript(new FileInfo("scripts/test.clj"));
 
    var add = RT.var("test", "add");
    var result = add.invoke(3, 7);
 
    Console.WriteLine(
"Clojure says 3 + 7 = {0}",
result);
}

First we locate our script and load it into the Clojure environment with RT.LoadScript.  I have an imaginary cookie for anyone who can tell me what RT stands for…

We use RT.var to get a reference to the function we defined.  The first parameter is the namespace and the second is the function name.  Once we have the reference we use .invoke to call it in Clojure.

Wrapping Up

This is a lot of work to set up but that should get easier as the ClojureCLR project matures.  In particular it needs a nice distribution with all the required Clojure files packaged into a .dll.

I was pleased that the final program is reasonably straight forward.  It takes a few seconds to load the Clojure environment but once it is running seems to perform OK.

Now to try and do something useful with it…

22/01/2010 02:36 PM (UTC -08:00)

OpenRasta Documentation

I notice that Google is having a little trouble finding the OpenRasta documentation so I figure it needs a little link love.  Here we go…

OpenRasta Community Documentation

20/10/2009 07:18 AM (UTC -07:00)

Logging Open Rasta Errors With ELMAH

In my previous post I mentioned that I have been using both Open Rasta and ELMAH so this post explains how to make them play nicely together.  To get started you will need to set up both libraries in your project as per their documentation, then follow along below.

Open Rasta actually attempts to handle its errors rather than letting them fall out to ASP.Net’s normal unhandled exception events.  This means that ELMAH never hears about them and doesn’t log them by default.  Fortunately both Open Rasta and ELMAH provide easy hooks for us to easily set this up.

Manually Logging With ELMAH

Sometimes you have exceptions which don’t represent a complete application meltdown but you would like to know about anyway.  ELMAH has an API set up for just such an occasion:

    ErrorSignal

        .FromCurrentContext()

        .Raise(ex);

This simple call grabs the current ELMAH setup from HttpContext and passes it any exception we want.

Injecting A Logger Into Open Rasta

Open Rasta logs exceptions and lots of other useful information while it is running.  By default this information is logged to .Net trace output but we’re going to replace that.  Here’s a simple logger that will do the job:

    public class ElmahLogger : OpenRasta.Diagnostics.ILogger

    {

        public void WriteException(Exception ex)

       {

            ErrorSignal

                .FromCurrentContext()

               .Raise(ex);

        }

 

        public void WriteDebug(string message, params object[] f) { }

        public void WriteWarning(string message, params object[] f) { }

        public void WriteError(string message, params object[] f) { }

        public void WriteInfo(string message, params object[] f) { }

 

        public class OperationContext : IDisposable

        {

            public void Dispose() { }

        }

 

        public IDisposable Operation(object source, string name)

        {

            return new OperationContext();

        }

    }

The important lines are in the WriteException method at the top.  You can use the rest of the methods to gather a full log from Open Rasta’s pipeline to include in the exception details if you want.

Since Open Rasta has a simple dependency injection container built right in, telling it to use our logger simply requires adding these lines to your normal configuration:

    ResourceSpace.Uses

        .CustomDependency<ILogger, ElmahLogger>

        (DependencyLifetime.Singleton);

That wasn’t so bad now was it?

06/09/2009 10:48 AM (UTC -07:00)

Things That Make Me Smile

It’s been a while so I thought I’d start my return to blogging on a happy note.  Here’s a few products I’ve used lately that have made me happy.

Open Rasta

I’ve tried a couple of times to implement a simple REST API using WCF lately and it always frustrates me.  It’s not really hard, it’s just harder than it needs to be.  That’s why I ended up looking for alternatives.

OpenRasta is a resource-oriented framework for .NET enabling easy ReST-ful development of web sites and services.

If you’re a fan of simple convention based frameworks then this is one to keep an eye on.  The framework is built around a customisable pipeline which allows you to easily drop in your own components using a simple fluent API and built in dependency injection.

It’s currently in it’s second beta and is still a bit rough around the edges but I had no problems putting together a simple API and customising it to suit.  The documentation is still lacking but the driver behind the project, Sebastien Lambla, is active on the mailing list and has been a big help getting me off the ground.

The best thing about Open Rasta?  It’s distributed under the very friendly MIT license.

ELMAH

I look after a lot of different ASP.Net web sites sites so it can be weeks before I discover problems with them on my own.  ELMAH (Error Logging Modules and Handlers), has been a great tool for quickly and consistently setting up basic error handling.

Personally I just use it to send all errors as emails to myself but there’s all sorts of features to keep you busy if you have larger requirements.  My favourite feature is the lovingly preserved Yellow Screen Of Death that arrives in my inbox full of details about the failed request.

Composite WPF (Prism)

Why do I like the Composite WPF library so much?  Mostly because I am unfortunate enough that I have to work one of that teams previous products, the Composite Application Block.  This time around the team have managed to present their concepts in a clear and understandable manner that doesn’t make my head hurt.

In particular the complex work items system of previous versions is gone and replaced with a simple application of their IoC container, Unity.  Whether or not you actually need such a framework is up to you to decide but if you have been scared off by CAB in the past don’t be afraid to take another look.

Keep smiling until next time!

03/09/2009 02:29 AM (UTC -07:00)

Can Games Teach You To Program?

After getting severely distracted by a little gem called RoboZZle I'd had to answer with a solid maybe.  The idea behind the game is simple: for each puzzle, program a small robot to collect all of the stars without falling off the map.  Here's a an example of a typical puzzle:

robozzle_designer

What's really cool is that the author, Igor Ostrovsky, has added social features so if you sign up for an account you can rate and vote for puzzles as well as submitting your own.  This frees Igor from having to dream up all the puzzles and adds a lot more variety and a lot more devious minds the mix!

No modern programming language looks anything like the one used in the game, at least, not one anyone uses...  so what could it possibly have to teach us?  Well, solving all of the puzzles will require you to do all of these:

  • Search for patterns.
  • Invent algorithms.
  • Create reusable functions.
  • Understand recursion.
  • Simplify.

There's one item in that list that is essential for solving many of the harder problems, and it's one that still gives a lot programmers headaches in the real world...

Understand Recursion

A function that calls itself, what's so hard about that?  If you think you really understand recursion here's some puzzles to try, starting with something nice and easy and working up to trickier problems:

Made it this far?  Well done.  As a final exam I put together a puzzle of my own.  At the time of writing is remains unsolved, let me know how you get on...

So yes, maybe there is something games can teach us.  If so I'm going to be a genius!  Oh yeah, the game is built in Silverlight too which is just awesome.

27/02/2009 12:54 AM (UTC -08:00)