Using C# / .NET libraries within IronRuby

I attended my first VistaSquad meeting on Wednesday. Part of the evening was a very interesting talk from @ben_hall on IronRuby, which among many other things included how to use any .NET CLR libraries direct from your IronRuby script (running via the .NET DLR).

Whilst my example below is extremely trivial, it shows how you might make use of any existing libraries within your Ruby scripts. This same technique applies to any .NET libraries, whether they’re custom, part of the framework, or created by your gran. I don’t think I really need to sell it in – but I love the flexibility that this provides.

So to get to the example, this simple piece of C# displays all the prime numbers between 0 and maxNumber:

[codesyntax lang=”csharp”]public int[] DisplayPrimeNumbers(int maxNumber)
{
int max = maxNumber;
List previousPrimes = new List();
previousPrimes.Add(2);
if (max < 2) return null; // none for (int i = 3; i <= max; i++) { int maxDivisor = (int)Math.Floor(Math.Sqrt(i)); bool foundDivisor = false; for (int j = 0; j < previousPrimes.Count; j++) { if (previousPrimes[j] > maxDivisor) break;
if ((i % previousPrimes[j]) == 0)
{
foundDivisor = true;
}
}
if (!foundDivisor)
{
previousPrimes.Add(i);
}
}
return previousPrimes.ToArray();
}
[/codesyntax]

We can build that up into a class library and using IronRuby, manipulate the return of the method the same as though we had been running native ruby.

[codesyntax lang=”ruby”]require ‘mscorlib’
require ‘CSharpLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’;

prime_numbers = CSharpLib::PrimeNumbers.new

(prime_numbers.DisplayPrimeNumbers 20).each do |num|
puts num
end
[/codesyntax]

You can download the full sample below, a C# console app is also included for completeness (although isn’t a part of the IronRuby process). You will of course, need to download IronRuby first, and add the installed bin/ folder to your path. Then just change to the <sample>/ruby/ directory, and run it with:

ir run.rb

It’s probably worth noting that IronRuby is still a way off from a 1.0 release, but it’s already very usable and looking rather cool. Since it’s on my recent //TODO list, I’ll be doing a few more examples here – next time turning this one its head and executing your ruby scripts from within C#. In the meantime, you can check out Ben’s set of slides from Wednesday on Slideshare.

//TODO: Learn, play, discuss.

Somewhat inspired by Mike Taulty’s blog, I’ve decided I should throw my Tech TODO list at the world, because it might encourage / guilt me into doing some of them, as well as provide a preview on what this blog might be including over the next few months.

So all of these are technologies, packages, or platforms I want to be checking out in the not-to-distant future.  In no particular order, they’re bound to be added to as I go and quite possibly ignored as well.

  • .NET
    • ASP.NET MVC
    • ADO.NET Data Services
    • F#
    • IronRuby
    • Open-sourcing a simple XML resource provider (CodePlex)
    • .NET 4
      • Windows Communication Foundation
      • Entity Framework
      • Parallel Extensions
  • Gallery3
    • Module development
      • Migrate Twitter module
      • Migrate auto-GPS-tagging module
    • Theme development
  • Google Wave

Gallery2 remote API C# wrapper

I stumbled across the Gallery.NET Toolkit on Twitter, while I should have been doing something more useful; some great work from @rmaclean (thanks for sharing / codeplexing  it).

The API wraps up a lot of the Gallery2 remote services into some easy to use C# functions.

[codesyntax lang=”csharp”]Actions a = new SADev.Gallery2.Protocol.Actions(“http://www.blakepics.com”);
string authToken = a.Login(“*************”, “*************”).AuthToken;
a.FetchAlbums(authToken).Albums.ForEach(
album =>
{
Console.WriteLine(album.Title);
a.FetchImages(authToken, album.Name).Images.ForEach(image =>
Console.WriteLine(“\t” + image.Url)
);
}
);
Console.ReadKey();[/codesyntax]

Hopefully I’ll find an excuse to use this one day.

Has the world ended? Is there anyone left to read this but me?

“I liked him before, then all that terrible stuff with the kids”, the receptionist joyfully proclaimed.
Nervously looking at the back of the guy who had just checked in, “oh, yeah” I replied politely.  What kind of people were I about to be sharing a dorm with?
“I mean, it’s worse in England – he had a lot of shows booked there, didn’t he?”
“Sorry, wait, who are we talking about here?” I asked, listening to Thriller playing in the background.
“Y’know, Michael Jackson”, she said, nodding towards the cd player.
It finally clicked.  “Oh, of course, yes, if he ever turns up to any of his shows that is.”
“Well, he definitely won’t now”, she replied, turning her head to one side.  Probably trying to work out if I were about to throw the rented bed linen over my head and run around pretending I was a ghost.
“Why not?”, echoing her feeling that I was talking to someone not quite on the planet.
“He’s dead.”

Ah.

The whole world could end over night, Norway could be the only place left on the planet.  I probably wouldn’t find out until I went to board my flight.  I’m not saying that Michael Jackson’s death is such a comparison, but it’s interesting what news does filter its way through after you’ve spent just 2 days hiking and travelling up and down fjords.  This is the only news that has.  Does Iran still exist?  Has the London economy recovered while I’ve been away?  Is Gordon Brown still prime minister?

It’s nice being shut off from the world for a little while.  I’m sure if anything really big’s happened, I’ll hear about it on Twitter when I get back.

Oslo, Norway – The Home of Communism with Jazz Hands

Having arrived in Oslo yesterday, it didn’t take me long to work my way around the tram system, and find my hostel lugging my backpack to the top of the hill.  I’m quickly learning that there are two very different types of hostel across the world.  There’s the shoe-string student traveler type, often with bar attached and generally coupled with a group of 20-something travellers sitting on the doorstep watching the world go by and picking out newcomers that might be worth speaking to before anyone else does.

Then there’s the ones with endless character-less corridors filled with clean, comfortable and spacious rooms that are behind various different stages of Vegas-like key card check points.

In this case, wanting a more relaxing trip, maybe even with less travelling than Vietnam – this just about suits me.  But I wouldn’t have wanted it anywhere else 😉  Norway, like most of the Scandinavian countries is one of the few places in the world that I as a Londoner can walk around thinking, “damn that’s expensive.”  Actually, with the current strength of the pound there are probably a lot more right now, but Norway is at least consistent.  It’s made me think that I should be freelancing a lot more web sites out here, as well as caused me to struggle to find a 500ml bottle of water for under 2.50.

But it’s not like it wasn’t expected.

So for a mere 6.50, I found myself a 24-hour tram pass which should get me through my first and final full day of Oslo, providing I wake up early enough to get to the train station tomorrow.

The first stop was a Gordon-recommended trip to Frogner Park, which houses Vigelandsparken, a sculpture park featuring hundreds of statues by a man Gordon describes as someone who would most likely have “been put on a register if he was alive today.”  I’m not going to argue.  The statues are all part of a collection that culminate in a central obelisk featuring humanity as Vigeland saw it.  To paraphrase Rough Guides – a writhing mass of playing, fighting, teaching loving, eating and sleep humans all clambering over one another to reach the top.  Other statues around the park represent different parts of this view.  A particular favourite of mine depicting a man balancing four babies on his arms and feet, in a desperate struggle to protect or play.  I’m not entirely sure.  But certainly the man would be on a register, now.

Like many statues in Norway, and I think the same can be said for the style I saw in Iceland, the figures are very much bold, strong figures with chiseled (excuse the pun) jaws and wide thick torsos.  It reminds me a lot of the communistic displays of power I saw across Poland, and dotted throughout Slovenia, Croatia and Bosnia.  But there’s something a lot more human, personable and connected about the ones I’ve seen in Norway.  I worked out how it could be best described today, and I’d really like it if the phrase “communists with jazz hands” caught on.

Onwards from the sculpture park, and I took a trip to the National Gallery to see one of the versions of Edvard Munch’s Scream paintings (the one that wasn’t stolen).  There’s a funny thing about seeing paintings in the flesh – not being a particularly well-scholared art-lover and instead a fully paid-up member of the digital information, more more more age – I can’t really explain it.  There is a certain reverence from seeing the brush strokes up close, and knowing that you are one of millions of people to have stood in the exact same spot staring at the exact same picture.  Every picture tells a different story, and every person sees a different side.

I am starting to get more of an idea of where I’m heading, now.  So tomorrow I’ll try and catch a train west to Myrdal, and take one of the world’s steepest train lines to Flam, then ferry to Gudvangen along the Naerofjord, before heading onwards to Bergen, and a smooth 7.5hr train ride back to Oslo later in the week.  Having said that… I have just read if I go North beyond Trondheim, there is a place called Hell (meaning “good fortune” in Norwegian, but I don’t want to spoil it).  It’s incredibly attractive to ditch all my plans and go there instead.  Not least because if anyone tells me to “Go to hell” in the future, I can assure them I’ve already been, and it was rubbish.  But it probably still wouldn’t earn me any friends.