Saturday, January 8, 2011

Implementing a simple configuration file in Python for a C# application

Combining IronPython and C# can bring very interresting things. For example implementing configuration. In this first post I am implementing a configuration file by using IronPython global variables. I am using C# 4.0 which make things easier but this can be done with C# 2.0.

The configuration file Configuration1.py.

 """
     Configuration of my application
 """ 
 Server      =    "TOTO" 
 Database    =    "Rene" 
 Debug       =    True
 Users       =    ["rdescartes",  "bpascal",  "cmontesquieu"] 
 

How to read this configuration variables in C# 4.0.

 static void Demo() {
 
     ScriptRuntime  PythonScriptRuntime = Python.CreateRuntime();
     dynamic        PythonScript        = PythonScriptRuntime.UseFile("Configuration1.py" );
 
     Console .WriteLine(PythonScript.Server);
     Console .WriteLine(PythonScript.Database);
     Console .WriteLine(PythonScript.Debug);
 
     foreach (string u in PythonScript.Users){
 
         Console .WriteLine(u);
     }                                    
     Console .ReadLine();
 }
 

You will need to install IronPython 2.6 For .NET 4.0 and reference the following assemblies:

IronPython.dll
Microsoft.Dynamic.dll
Microsoft.Scripting.dll

Here are the namespaces used:

using  Microsoft.Scripting.Hosting;
using  IronPython.Hosting;
using  Microsoft.Scripting;

No comments:

Post a Comment