Thursday, June 24, 2010

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.

Read more: Jordi's English Bloc

Posted via email from .NET Info