Re.Mark

My Life As A Blog

Simple Configuration with IronPython and .NET 4

with 2 comments

Recently I posted a short article about how to do simple configuration with IronPython.  I figured that it would be easier with .NET 4.0 thanks to the dynamic support.  And it is.  Using Visual Studio 2010, create a new Console Application.  Add one file called Configuration.py and set the copy output property to Copy Always.  Here’s the Python code for that file:


configuration.Text = "Hello from IronPython"
configuration.Count = 4

And here’s the code for the Program class:


class Program
{
    static void Main(string[] args)
    {
        dynamic configuration = ConfigureFromIronPython();

        for (int i = 0; i < configuration.Count; i++)
        {
            Console.WriteLine(configuration.Text);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey(true);
    }

    private static dynamic ConfigureFromIronPython()
    {
        dynamic configuration = new ExpandoObject();
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();
        scope.SetVariable("configuration", configuration);
        engine.ExecuteFile("Configuration.py", scope);
        return configuration;
    }
}

For that to work you need add references to IronPython and Microsoft.Scripting (there’s a CTP of IronPython for .NET 4.0 that you can get here.)  You’ll also need a few using statements:


using System.Dynamic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

The two things that make this work are the ExpandoObject and the dynamic keyword.  The ExpandoObject is a dynamic property bag that allows us to set and get members at runtime as needed.  The dynamic keyword means that .NET will resolve the properties at runtime (rather than the traditional behaviour of checking at compile time.)  The result is (I think) more simple and elegant than the configuration code to which I’ve become accustomed.

Advertisements

Written by remark

September 28, 2009 at 12:53 pm

Posted in .NET, c#, Design, Python

2 Responses

Subscribe to comments with RSS.

  1. Hi,

    I am new to IronPython and just wondering if the value would get pick up by the web app when a change is done to Configuration.py at runtime?

    Herman

    April 27, 2010 at 3:31 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: