Re.Mark

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 Configuration.py 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 Configuration.py.  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();
		DisplayConfiguration(configuration);

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


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

		watcher.EnableRaisingEvents = false;
		watcher.Dispose();

		Console.WriteLine("Exiting...");
	}

	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;
	}

	private static void DisplayConfiguration(dynamic configuration)
	{
		for (int i = 0; i < configuration.Count; i++)
		{
			Console.WriteLine(configuration.Text);
		}
	}
}

By adding a FileSystemWatcher, we can react to changes in Configuration.py 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.

Advertisements

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:

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: