My Life As A Blog

Dynamic Configuration with IronPython and .NET 4

leave a comment »

A while back I posted a simple way of using IronPython to configure a .NET application.  The I spotted Herman’s question about whether the application would react to a change in the file.  The way I wrote the original sample the configuration is read in once.  But it’s fairly simple to modify the code to react to changes in  Here’s the modified Program class:

class Program
	static void Main(string[] args)
		FileSystemWatcher watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "*.py");
		watcher.EnableRaisingEvents = true;
		watcher.NotifyFilter = NotifyFilters.LastWrite;
		DateTime modified = DateTime.Now;

		Console.TreatControlCAsInput = true;
		dynamic configuration = ConfigureFromIronPython();

		watcher.Changed += (sender, eventArgs) =>
			if (DateTime.Now - modified > TimeSpan.FromMilliseconds(100))
				modified = DateTime.Now;
				configuration = ConfigureFromIronPython();

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

		watcher.EnableRaisingEvents = false;


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

	private static void DisplayConfiguration(dynamic configuration)
		for (int i = 0; i < configuration.Count; i++)

By adding a FileSystemWatcher, we can react to changes in and update the application configuration.  (If you’re wondering the check of when the last modification occurred is to prevent handling the same change twice which can occur when using the FileSystemWatcher.)  The only other change is a minor refactoring to extract a method that displays the configuration.


Written by remark

April 30, 2010 at 8:44 pm

Posted in .NET, c#, Python

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: