Using Mono.CSharp to evaluate code at runtime

When I read the first time about Mono.CSharp I thought that it was pretty cool and that for sure I will have a use for it soon.

In the past months I have been playing around with a few ideas to make gbrainy extensible using external definition files (something that I did for verbal analogies time ago). I considered using a DSL but I discarded it, at least for the medium term, since I still do not have clear the full set of actions that I would like to expose to users.

I decided finally to use XML plus Mono.CSharp to allow people to describe new games with no limitations. Mono.CSharp allows to evaluate code at runtime and then access the variables to get your results, and also, allowing to select the assemblies to expose. In the case of gbrainy I use it in the game defintion. As example:

<game>
        <_name>Tennis game</_name>
        <type>Logic</type>
        <difficulty>All</difficulty>
        <svg file = "tennis.svg" x = "0.25" y = "0.25" width = "0.5" height = "0.5"/>
        <variant>
            <variables>
                int games = 5 + random.Next (5);
                int rslt = (int) Math.Pow (2, games);
            </variables>
            <_question>There are [games] tennis games played simultaneous.
                 How many different forecast are possible?</_question>
            <answer>[rslt]</answer>
            <_rationale>Every game is an independent event with 2 possible results.
               The total number of possibilities is 2 at the power of [games].
            </_rationale>
        </variant>
</game> 

Notice how you can insert your own code between the variables tags and then reuse the results (referencing it between brackets) in different sections giving a great flexibility in terms of defining new games without full coding.

This really brings a very powerful way of extending your applications to your users, gbrainy is just one of the many use cases for this.

Starting from gbrainy 1.5x all the new games are going to be defined in this way, allowing people to extend, customize and fix them more easily.

jordi Tuesday 22 June 2010 - 8:35 pm | | Default

One comment

Gabriel Burt

Keep in mind that other languages have different rules for pluralization. I think you’ll want to provide something equivalent to Catalog.GetPluralString.

Gabriel Burt, (URL) - 22-06-’10 23:15
(optional field)
(optional field)

Remember personal info?
Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.