Re.Mark

My Life As A Blog

Archive for January 2009

An introduction to WPF with IronPython

with 2 comments

I was wondering how easy it would be to create a simple WPF app that was written in IronPython.  I found this article that made it look simple.  Then I found this series on DevHawk that goes into more detail.  Having scanned a few pages, I decided to create a very simple app that included databinding and an event handler.  Armed with Notepad++, XamlPad and a command prompt I set out.

First step was a little C#.  I created a class as detailed here that adds a little dynamic-ness to WPF.  More info on that magic here.  The class is simple enough:

using System;
using System.Windows;
using Microsoft.Scripting.Runtime;

[assembly: ExtensionType(
    typeof(FrameworkElement),
    typeof(Sample.Scripting.FrameworkElementExtension))]

namespace Sample.Scripting
{
    public static class FrameworkElementExtension
    {
        [System.Runtime.CompilerServices.SpecialName]
        public static object GetBoundMember(FrameworkElement e, string n)
        {
            object result = e.FindName(n);
            if (result == null)
            {
                return OperationFailed.Value;
            }
            return result;
        }
    } 
}

References to WindowsBase, PresentationFramework, PresentationCore, Microsoft.Scripting, Microsoft.Scripting.Core and Microsoft.Scripting.ExtensionAttribute were required to compile it.  Once compiled I dropped it (and the other dlls in the bin folder) into a subfolder called lib of the folder I’d created for my Python files.

Next step was to create a simple UI in XAML.  Here it is:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns: x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestApp" Width="640" Height="480">
  <StackPanel>
    <Label>Iron Python and WPF</Label>
    <ListBox Grid.Column="0" x:Name="listbox1" > 
      <ListBox.ItemTemplate> 
        <DataTemplate> 
          <TextBlock Text="{Binding Path=title}" /> 
        </DataTemplate>
      </ListBox.ItemTemplate> 
    </ListBox>
  </StackPanel>
</Window>

With the XAML created – and saved as Main.xaml – I wrote a simple class to hold data (you can spot from the XAML that it’s going to have a title attribute.)  Here’s the first bit of Python code:

class Entry(object):
    def __init__(self, title, description):
        self.title = title
        self.description = description    

The key thing here is to make the class inherit from object – without it the databinding will fail to find the title attribute.  I unimaginatively called this file Entry.py.

Time to tie it all together.  Here’s the Python code that does just that:

import clr
from Entry import Entry

clr.AddReferenceToFileAndPath("lib/WpfExtension.dll")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")

from System.IO import File 
from System.Windows.Markup import XamlReader
from System.Windows import Application

def listbox1_OnSelectionChanged(self, event):
    for item in event.AddedItems:
        print item.title
    
titles = [Entry("Book", "Great For reading"),
Entry("Shelf", "Ideal for storing stuff"),
Entry("Cupboard", "Store and hide stuff")]
    
file = File.OpenRead('Main.xaml')
window = XamlReader.Load(file)
window.listbox1.SelectionChanged += listbox1_OnSelectionChanged
window.listbox1.ItemsSource = titles
Application().Run(window)

 

You can see I called the C# code I compiled WpfExtension.dll.  The interesting stuff here is the event handler and the way it’s hooked up – looks familiar if you’ve done any .NET development.  I called this file main.py.  To run it, type ipy main.py at a command prompt in the folder where the python code (and XAML) is saved.

So, it doesn’t do anything useful, but I can see the potential here.  It feels like a very natural extension of WPF to the dynamic world – there are no clunky workarounds or bodges, it’s as you’d think it should be.  Looking forward to trying some more stuff out now I’ve got the basics covered.

Written by remark

January 27, 2009 at 7:50 pm

Posted in .NET, Python, Windows

Who are you?

with 2 comments

Over the last month or so I’ve been intrigued at how there seems to be a surge of interest in Twitter, which has been accompanied by an influx of celebrities and pretend celebrities.  The ensuing, predictable twaffic trying to establish if each of the neweeters is who they claim to be is interesting as it demostrates just how tricky a subject identity can be.  What is also interesting is the way this problem has been resolved: Jonathan Ross, having established his identity (with photographs on Twitpic) beyond the doubt of most of the tweeple, has been acting as a trusted third party who verifies the claims of the new entrants to the twitterverse by ringing them or emailing them directly.

Oh, and for those interested in twerminology take a look here, here and here.

Written by remark

January 14, 2009 at 8:28 pm

Posted in General

Ruby Tuesday #25 : Automating Office

with one comment

OK, so technically it’s not Tuesday.  But I took Monday off, so today feels like Tuesday.

Getting back to Ruby, I wondered if you could use it to script tasks in Office.  A quick search not only revealed that you can, but there’s a blog that covers using Ruby on Windows that has a lot of examples and information about automating Office with Ruby.  Unfortunately, I haven’t had a chance to try any of the code out yet.  I’ll have to remedy that.

Written by remark

January 14, 2009 at 8:08 pm

Posted in Ruby, Windows