A Ruby Set in Steel – WPF and IronRuby

work safe

One of the first examples of using IronRuby on the web, possibly the first since it was the announcement of the project, was Scott Guthrie announcing the project and using WPF way back in 2007.

We’ve come a long way since then. But that’s all been internal to IronRuby. In addition, I’ve not seen the community truly embrace IronRuby as it has had some growing pains. I don’t mean to dis those working on the project, just look at my non-existent commit log to see how much of a leg I have to stand on if I where to dis them. I mean to say that I’ve not seen many people talking about using it in production. And until we see production IronRuby, we won’t be able to tell the wider .NET world how awesome working in ruby really is.

Enough groundwork, what’s on today’s menu? I started writing a quick search box for my chat logs at work. I picked up IronRuby, since I loves it so, and threw down some WPF. Then I stood in shock and horror that the commensurate C# code would be much nicer. Here is IronRuby draft one.

require 'PresentationCore'
require 'PresentationFramework'

Application = System::Windows::Application
HorizontalAlignment = System::Windows::HorizontalAlignment
SizeToContent = System::Windows::SizeToContent
Thickness = System::Windows::Thickness
Window = System::Windows::Window

Button = System::Windows::Controls::Button
Label = System::Windows::Controls::Label
ListBox = System::Windows::Controls::ListBox
Orientation = System::Windows::Controls::Orientation
StackPanel = System::Windows::Controls::StackPanel
TextBox = System::Windows::Controls::TextBox

window = Window.new
window.title = "Lef' Frontal Lobe"
window.size_to_content = SizeToContent.height
window.width = 450

stack = StackPanel.new
stack.margin = Thickness.new(15)
window.content = stack

search_ctl = StackPanel.new
search_ctl.orientation = Orientation.horizontal
stack.children.add search_ctl

search_box = TextBox.new
search_box.width = 380
search_ctl.children.add search_box

search_button = Button.new
search_button.content = "Go"
search_ctl.children.add search_button

results_label = Label.new
results_label.font_size = 24
results_label.content = "Results"
results_label.horizontal_alignment = HorizontalAlignment.center
results_label.margin = Thickness.new(5)
stack.children.add results_label

results_list = ListBox.new()
stack.children.add results_list

search_button.click do |sender, event|
  results_list.items.clear
  results_list.items.add search_box.text
end

Application.new.run(window)

bad_example.rb on GitHub

Notice the “Left-Side/Right-Side” code. In C#, we fixed this with object initializers. That’s what I want in my code, so I added a method to FrameworkElement to use a hash for initialization. Then I went after how I’m adding stuff to my StackPanels. In Ruby, the idiom to add children is the « operator, so I’ll add that to Panel, the super class for all layout elements. Finally, the explicit aliasing in just crazy talk. Using a namespace is similar to including a ruby Module, so I’ll just include the namespaces I need. And the code got better. I was, in fact, proud of it for a few hours.

require 'PresentationCore'
require 'PresentationFramework'
include System::Windows
include System::Windows::Controls

class FrameworkElement
  def self.create_new( hash )
    elem = new()
    hash.each_pair do |key, value|
      elem.send( "#{key}=".to_sym, value)
    end
    elem
  end
end
class Panel
  def <<(new_children)
    if new_children.respond_to? :each
      new_children.each do |child|
        self.children.add child
      end
    else
      self.children.add new_children
    end
  end
end

window = Window.create_new(:title => "Lef' Frontal Lobe",
                           :size_to_content => SizeToContent.height,
                           :width => 450 )

window.content = stack = StackPanel.create_new(:margin => Thickness.new(15))

search_ctl = StackPanel.create_new( :orientation => Orientation.horizontal )
search_box = TextBox.create_new( :width => 390 )
search_button = Button.create_new(:content => "Go")
search_ctl << [search_box, search_button]

results_label = Label.create_new(:font_size => 24,
                         :content => "Results",
                         :horizontal_alignment => HorizontalAlignment.center,
                         :margin => Thickness.new(5))

results_list = ListBox.new()

stack << [search_ctl, results_label, results_list]

search_button.click do |sender, event|
  results_list.items.clear
  results_list.items.add search_box.text
end

Application.new().run( window )

Rubish WPF step one.rb on GitHub

Then I started wondering, WPF uses Xaml to be declarative. Can’t I find a way to declare my UI, then add stuff to it? I can write Xaml, can’t I? Well, I can also use Ruby’s XmlBuilder to make xaml look like I’m declaring my UI in ruby. I’ll want to wrap some boilerplate to build the xml with xaml specific things, then turn it into a real CLR window. Then how do I hook up buttons and actions? I can call find_name on a window to find a child with the x:Name attribute. More correctly, I can wrap it with Ruby’s [] operator.

require 'rubygems'
require 'builder'
require 'PresentationCore'
require 'PresentationFramework'
require 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeytoken=b77a5c561934e089'
include System::Windows
StringReader = System::IO::StringReader;
XamlReader   = System::Windows::Markup::XamlReader
XmlReader    = System::Xml::XmlReader;

class System::Windows::Window
  def [](arg)
    self.find_name(arg.to_s)
  end
end
class Xaml
  def self.add_xaml_ns(hash)
    if not hash.key? "xmlns:x"
      hash["xmlns:x"] = "http://schemas.microsoft.com/winfx/2006/xaml"
    end
  end
  def self.add_presentation_ns(hash)
    if not hash.key? :xmlns
      hash[:xmlns] = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    end
  end
  def self.create(hash, &block)
    add_presentation_ns hash
    add_xaml_ns hash
    xaml = Builder::XmlMarkup.new(:indent => 2)
    yield(xaml)
    XamlReader.load(XmlReader.create(StringReader.new(xaml.target!.to_clr_string)))
  end
  def self.window(hash, &block)
    create(hash) do |xaml|
      xaml.Window(hash, &block)
    end
  end
end

window = Xaml.window( :Title => "Lef' Frontal Lobe",
                   :Width => 450, :SizeToContent => :Height) do |w|
   w.StackPanel :Margin => 15 do |layout|
     layout.StackPanel(:Orientation => :Horizontal) do |search_control|
       search_control.TextBox(:Width => 390, "x:Name" => "SearchBox" )
       search_control.Button(:Content => "Go", "x:Name" => "SearchButton")
     end
     layout.Label(:FontSize => 24, :Content => "Results",
                  :HorizontalAlignment => "Center", :Margin => 5 )
     layout.ListBox("x:Name" => "ResultsList")
   end
end

window[:SearchButton].click do |sender, args|
  items = window[:ResultsList].items
  items.clear
  items.add window[:SearchBox].text
end
Application.new().run(window)

xamlbuilder.rb on GitHub

At first blush, it seems like the code is getting bigger, but the Xaml class can be gemmed up and reused. That leaves our application fairly small, which is nice considering it’s a small window. The thing that’s left that’s getting on my nerves is the fact I’m not declaring my click action in the Xaml. Which leads me to the next questions, how do I get Commands and Binding tied in to this? At that point, I’m almost doing this “right”.

Well, I ran some experiments, and here’s what doesn’t work.

  • Data binding doesn’t work. I tried to set a ruby object to a windows DataContext, and the labels didn’t bind.
  • x:Class doesn’t play well with XamlReader.Load(xmlReader). More exactly, I can’t create a class in ruby and expect XamlReader to pick up on it.
  • Adding Click="DoClick" to a button tag causes the XamlReader to blow chunks
  • Trying to add xmlns:l="clr-namespace:Frontal" and rooting the window on l:Lobe, a ruby class in the Frontal module, doesn’t work. XamlReader can’t find the namespace.

No example code, because that would confuse the issue.

I want to get this posted, so I don’t have a solution yet. But I’ve got some ideas percolating. Unfortunately, most of them involve C# run time code generation (code dom), or writing my own WPF builder and bypass the XamlReader all together. I really should take a break from getting WPF “perfect” and start working on using Lucene.NET to do the actual work for my brain in a box.