avatar
Today is Friday
September 3, 2010

August 22, 2010

C# – Dynamic Class Loading

by Michael Clarke — Categories: C#, Mono/.NET, Programming, TutorialsNo Comments

I have noticed since moving this blog that a lot of people are trying to access some of my old posts. In particular, people seem very interested in my posts on C# Dynamic Class Loading. As such, I have decided to re-post the old version here for you. Note that this is a copy-and-paste job from my old blog – there is nothing new except for a few minor typing corrections that were noticed by Chris, a commentator on my old blog – thanks! I hope this is useful for those people trying to find it.

The other day I wrote a small tutorial on getting dynamic class loading working for Java. In that post I mentioned that it could also be done in C# – but that it was more difficult, and from my personal experience, there is less information available about it – so here is how to do it!

First, as with the Java, we need to create our API. However, unlike the Java there is an additional requirement – a ‘module manager’ class needs to be within the API. As such you will need to create these two files…

using System;
using System.Reflection;

namespace com.michaelclarkeblog.dynamic.api {

    public static class ModuleManager {

        public static Module getInstance(String fileName) {

            /* Load in the assembly. */
            Assembly moduleAssembly = Assembly.LoadFile(fileName);

            /* Get the types of classes that are in this assembly. */
            Type[] types = moduleAssembly.GetTypes();

            /* Loop through the types in the assembly until we find
             * a class that implements a Module.
             */
            foreach (Type type in types) {
                if (type.GetInterface("Module") != null) {
                    /* Create a new instance of the 'Module'. */
                    return (Module)Activator.CreateInstance(type);
                }
            }

            return null;

        }

    }

}
using System;

namespace com.michaelclarkeblog.dynamic.api {

    public interface Module {
        String getText();
    }

}

Once you’ve got the two files you can compile them into a library….

api $ mcs -t:library Module.cs ModuleManager.cs
api $ ls -a | grep .dll
Module.dll
api $

Now that we’ve made the API the next thing to write is the application that is going to use it for loading modules. This is a very simple application…

using System;
using com.michaelclarkeblog.dynamic.api;

namespace com.michaelclarkeblog.dynamic.application {

    public class Application {

        public static void Main(String[] args) {

            if (args.Length > 0 ) {
                Module module = ModuleManager.getInstance(args[0]);
                Console.WriteLine(module.getText());
            } else {
                Console.WriteLine("Usage: mono Application module_name");
            }
        }

    }

}

Now we can compile our ‘Application’ against the API…

application $ mcs -reference:../api/Module.dll Application.cs
application $ ls -la | grep exe
-rwxr-xr-x 1 michaelfclarke michaelfclarke 3072 Apr  5 19:32 Application.exe
application $

And now finally we can write a couple of modules!

using System;
using com.michaelclarkeblog.dynamic.api;

namespace com.michaelclarkeblog.dynamic.modules {
  public class Mike : Module {
    public String getText() {
      return "Hello from Mike's Module!";
    }
  }
}
using System;
using com.michaelclarkeblog.dynamic.api;

namespace com.michaelclarkeblog.dynamic.modules {
  public class Another : Module {
    public String getText() {
      return "Hello from Another Module!";
    }
  }
}

Compile the modules…

modules $ mcs -t:library -reference:../api/Module.dll Another.cs
modules $ mcs -t:library -reference:../api/Module.dll Mike.cs
modules $ ls -la | grep dll
-rwxr-xr-x 1 michaelfclarke michaelfclarke 3072 Apr  5 19:36 Another.dll
-rwxr-xr-x 1 michaelfclarke michaelfclarke 3072 Apr  5 19:36 Mike.dll
modules $

There is just one last thing we need to do before we can run our application. We need to copy the Module.dll API from the api directory into the application directory…

modules $ cd ../application
application $ cp ../api/Module.dll .

And now lets try running our dynamic application…

application $ mono Application.exe ../modules/Mike.dll
Hello from Mike's Module!

application $ mono Application.exe ../modules/Another.dll
Hello from Another Module!

application $ mono Application.exe
Usage: mono Application module_name

August 16, 2010

A new look and feel, and new content to match!

by Michael Clarke — Categories: GeneralNo Comments

Those who have on occasion visited my website will be acutely aware that there has been a considerable change in the look and feel. They may have also noticed that all my old posts have evaporated, though they would of-course be forgiven for not noticing (especially considering the last time I wrote anything was September 2009). As it happens I haven’t been hacked; in fact, quite the opposite. I have finally got around to closing down elephant designs, my once prosperous hosting company. Apart from the company no longer making any kind of profit (which is good as far as I’m concerned when it comes to filling in my tax return – though not so good the rest of the year), it was starting to take a lot of time to maintain; something which I fear will soon be in short supply, but more on that shortly. Nevertheless, as a direct consequence of closing down elephant designs I have moved all my clients to “outtherehosting.co.uk” (in short a company owned and run by a friend) and included in those clients was my own blog. So, with “new” webspace (although the same domain) I decided it was time for a new look. Further, whilst I could quite easily have copied over all my old posts, I decided that now would be a good time to start a fresh new blog to boot.

Questions may (or more likely not) be popping into your heads now regarding this need for more time. Surely now I’ve graduated from my degree I should have all the time in the world – I should be working in the day and have my evenings for my own, or perhaps I should be travelling the world, taking a gap year – a whole host of possibilities! Nope, wrong, being the numpty that I am, I have taken up the opportunity of a PhD with Aberystwyth University. Yes, yes, I know – three (ehem, more like four) more glorious years of researching (read as playing), writing papers (also read as playing), rushing towards the day that my viva will come (read as not another exam) and I will have to show the worth of it all. But, until that day, I figured what a better place to record my strife (playtime) than to blog. Now, I know I’ve said this before. Indeed, in the past I have promised great things - particularly during my final year project! All those hours of footage, photos, code updates you were expecting from my MEng dissertation never did materialise. However, this time, as a ‘mature and professional postgraduate student’ I hope that such things will be more… apparent.

It is my wish to keep everyone up to date and informed as I progress through my three years as a PhD student, and indeed hopefully at the end of these three years I will have a valuable resource full with details of experiments, papers, and notes to help me with finishing my thesis. Well that is the cunning plan anyway.

So, to start it might be prudent to give a general idea as to the topic of my PhD and a few more details. Those who know me will be aware that during my final year of my masters degree I became particularly interested in robotics. Until this point robotics had (to me) been a ‘interesting topic’, but one that I didn’t really have much time for. When I say “I didn’t really have much time for”, I don’t mean to suggest I disliked robotics or thought it “wishy-washy”, more that I was far more interested in operating system design and theory. As a result of my masters dissertation I have “found time” for robotics and in the course have managed to get a paper written (due to be published at the Towards Autonomous Robotics Systems (TAROS) conference at the end of August 2010 in Plymouth). So, how does this lead to a PhD? Well, apart from anything else I applied (a good start), and was accepted pretty quickly. But, as anyone who has ever applied for a PhD will know, this is only the start of the story. Funding is the show-stopper!

I made various attempts to get funding – through the Aberystwyth Postgraduate Research Scholarship (APRS), a PhD scholarship with EADS, and even a Research Associate job within the Department of Computer Science at Aberystwyth University. However, all of these attempts were either unsuccessful or are still pending and stuck due to contract issues (most likely intellectual property but I’m not 100% sure myself). So, very kindly, the Computer Science department and Geography Department have agreed to jointly sponsor me for my first year until I can sort out more permanent funding. There is a catch – I am expected to (still within my interests and within the scope of a PhD) work on a project that they want. That project revolves around automated surveying of glaciers, ice caps and the water flows under these massive ice blocks in and around Greenland. As such, my next three years will be spent building robots to collaborate and automate complex and often life-threatening scanning and surveying of such glaciers, etc.

I must admit that my knowledge of ice (as you may have noticed) is somewhat lacking, and so this part is going to be a considerable learning curve. However, I always enjoy a good challenge and am really starting to look forward to my starting date of the 27th September 2010; but before then I intend to take it easy, relax a bit, perhaps start writing my lecture slides (did I mention I’m teaching some of the CS101 Computer Science module this year?) and at some point write my talk for the TAROS conference (I will blog nearer the time and let you all know how it goes).

However, for now, I think I have rambled on long enough and I’m sure you’re all quite board now. So, until the next episode.

© 2010 Michael Clarke Blog All rights reserved - Wallow theme by TwoBeers Crew - Powered by WordPress - Have fun!