Saturday, November 21, 2009

Databinding and WCF Services with IronPython 2.6

One of the important new features in IronPython 2.6 is the __clrtype__ metaclass.The __clrtype__ metaclass allows you to create a real .NET class that backs your Python classes. This is important because there are many .NET features that *require* a real .NET class: which includes databinding and implementing WCF services (Windows Communication Foundation).

The problem with __clrtype__ is that it requires dealing with low level details; namely building the class yourself from IL bytecode. Harry Pierson and Shri Borde have been working on a library ( to make this simpler.

Lukáš Čenovský has looked at this before but hit limitations with what clrtype made possible. In three new blog entries he demonstrates how to use __clrtype__ with databinding in WPF and Silverlight and to implement WCF services.
 INotifyPropertyChanged is important interface for building WPF or Silverlight applications using M-V-VM concept (MSDN article).

In simple language, you have a Model which provides access to your data (e.g in database, files, web, etc.). Then you have a ViewModel that access data in the Model via Model's interface and provides data to a View which is XAML file with UI layout. Linkage between ViewModel and View is done by binding that utilizes PropertyChanged event to properly update all UI elements.

I have found two examples how to implement INotifyPropertyChanged interface in IronPython. The first one uses __setattr__ hook. Personally, I don't like it - it is not clear and easily readable code. The second one is better because it uses properties. But you have to write self.OnPropertyChanged("my_property_name") for every property. Not ideal.

That's why I sit down and write a notify_property.
This article uses the updated clrtype module to apply the databinding technique to Silverlight. The cool thing is that I'm already using this technique for databinding with the Silverlight Toolkit DataGrid in my new job. No more stub C# proxy classes, yay!
 Even using __clrtype__ you still couldn't use WCF (for creating and consuming web services) from pure IronPython because it requires *creating* interfaces, which couldn't be done. With the latest improvements to clrtype it is now possible.
I wrote about implementing WCF service in IronPython a couple of weeks ago. Meanwhile I pushed Shri a little bit with the and he has implemented ClrInterface metaclass there so we can create the whole WCF service in IronPython now.

The IronPython interface implementation is straightforward.
Also switching from C# interface to IronPython interface is easy.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.