Browsing the archives for the wpf tag.

Crouching Donny, Iron Cucumber – An Experiment in Functional Testing

work safe

I accidentally agreed to give a talk later this month. The subject is IronRuby and it’s application in the .NET ecosystem. Seems simple enough. So, to jazz things up, I want to have a host of demo applications. This is about one.

A while back, I posted an article with an example of using IronRuby and the White framework. In it, I appear to have made a promise.

I’ll get to Cucumber. I’ll publish examples. I promise.

I’m going to talk a lot about Donny. You’ll meet Donny, but just be aware, he’s compiled in Debug, so he’s a bit shy. Donny is an app written to give me something to test. He does nothing of real import, he doesn’t even save his data to disk. As for why “Donny”, I still don’t know. I was in a mood yesterday when outlining my presentation and “Donny” stuck.

Cucumber - n, A functional testing framework for ruby. Cucumber uses Features and Step Definitions to drive an application via it’s full stack.

Cucumber does work with IronRuby, but by default it’s runner has some idiosyncrasies for which you’ll need to compensate. The cucumber.bat file lives, for me, in c:\IronRuby\lib\IronRuby\gems\1.8\bin. Another oddity is that it belives I have a color console. This is mostly true, but Win32Console doesn’t work for IronRuby, so you’ll need to use the --no-color option. For now. I have my features in a directory I’m calling “features” with an embedded step definitions directory. Once I finish the presentation, I’ll have the whole damn thing published and you can look at it then. Until then, here’s the command line I used; cucumber --no-colors features.

Feature - n, A tightly formatted Business Natural Language used to describe the preconditions, actions, and expected results in a business scenario. See also, Story.

I have two basic scenarios; Donny starts with no data, and Donny moves data from the task form to the task list.

Feature: New Task
  In order to correctly bill my client
  as an SEP employee
  I want to add a task to the list

  Scenario: Starting the app
    Then all fields are blank
    And the list contains 0 entries

  Scenario:  Add a new Task
    Given I describe my task as Doing work on the Donny app
    And I'm working on project Academy
    And the day is Monday
    And I worked from 10 to 10:30
    When I press the button
    Then all fields are blank
    And the list contains 1 entry
    And the last entry is Monday 10-10:30 Academy Doing work on the Donny app

Step Definition - n, a ruby script used to match lines in the Feature BNL to actual executable code. They can be reused across features.

For each Given, When, or Then I have to have a matching step. These are essentially ruby functions that use a helper to encapsulate my usage of the White library. Here is donny_steps.rb

require 'spec/expectations'
require File.dirname(__FILE__) + "/../../donny_helper.rb"

Before do
  @app = Application.launch "Donny/bin/Debug/donny.exe"
  @win = @app.get_window "Window1"
  @tf = TaskForm.new(@app, @win)
  @tl = TaskList.new(@app, @win)
end

After do
  @win.close
end
Given /I describe my task as (.*)/ do |description|
  @tf.description = description
end

Given "I'm working on project $proj" do |proj|
  @tf.project = proj
end

Given "the day is $day" do |day|
  @tf.day = day
end

Given /I worked from (.*) to (.*)/ do |start_time, end_time|
  @tf.start_time = start_time
  @tf.end_time = end_time
end

When "I press the button" do
  @tf.commit
end

Then "all fields are blank" do
  @tf.description.should be_empty
  @tf.project.should be_empty
  @tf.day.should be_empty
  @tf.start_time.should be_empty
  @tf.end_time.should be_empty
end

Then /the list contains (.*) entr(?:y|ies)/ do |n|
  @tl.task_count.should == n.to_i
end

Then /the last entry is (.*)/ do |result|
  @tl.tasks.last.text.should == result
end

Um, you’re missing a piece. The part that uses White. Remember the screens? This time, I didn’t call them screens, and I don’t have a full window proxy, but I still have two helper objects. Now, with some metaprogramming, I could cut down the code size by defining an attribute and describing the type and automation ID of it’s associated control, but I’m lazy. Maybe for the presentation, but I’m not making any promises.

white_loc = (File.dirname(__FILE__) + "/White_Bin_0.18/")
puts white_loc
$LOAD_PATH << white_loc
require "White.Core.dll"

Application = Core::Application
ComboBox = Core::UIItems::ListBoxItems::ComboBox
ListBox = Core::UIItems::ListBoxItems::ListBox
Window = Core::UIItems::WindowItems::Window
include Core::UIItems

class Window
  def get_button(*args)
    self.method(:get).of(Button).call(*args)
  end
  def get_textbox(*args)
    self.method(:get).of(TextBox).call(*args)
  end
  def get_combobox(*args)
    self.method(:get).of(ComboBox).call(*args)
  end
  def get_listbox(*args)
    self.method(:get).of(ListBox).call(*args)
  end
end
class TaskList
  def initialize(app, win)
    @app = app
    @win = win
  end
  def tasks
    @win.get_listbox('tasklist').items.to_a
  end
  def task_count
    tasks.size
  end
end
class TaskForm
  def initialize(app, win)
    @app = app
    @win = win
  end
  def description
    get_tb 'task'
  end
  def description=(text)
    set_tb 'task', text
  end
  def project
    @win.get_combobox('project').selected_item_text
  end
  def project=(proj)
    @win.get_combobox('project').select proj
  end
  def day
    get_tb 'dayofweek'
  end
  def day=(day)
    set_tb 'dayofweek', day
  end
  def end_time
    get_tb 'endtime'
  end
  def end_time=(et)
    set_tb 'endtime', et
  end
  def start_time
    get_tb 'starttime'
  end
  def start_time=(st)
    set_tb('starttime', st)
  end
  def commit
    @win.get_button('commit').click
  end

  private
  def set_tb(auto_id, value)
    @win.get_textbox(auto_id).set_value value
  end
  def get_tb(auto_id)
    @win.get_textbox(auto_id).text
  end
end

And some for some context, Meet Donny!
Donny

And, after I enter a task, Donny looks like this.
Donny

That’s really all there is to using Cucumber with IronRuby. Have fun!

A letter to the editor – Do you even READ the internets? More IronRuby and WPF

work safe

I’m writing this in response to a recent post I wrote on my website, A Ruby Cast In Steel. While I appreciated the insight my experiments gave me into both IronRuby and WPF, the author ended up with a few conclusions I’d like me to revisit.

Data Binding

You implied that Data Binding IronRuby is broken. This is untrue as noted by both members of the IronPython team and the IronRuby team. As you can see here, WPF Data Binding relies on the ICustomDataDefinition, which IronRuby objects implement. Building on the xaml tools I developed last time, here is an example of Data Binding at work.

require 'rubygems'
require 'builder'
require 'PresentationCore'
require 'PresentationFramework'
require 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeytoken=b77a5c561934e089'

module XamlTools
  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.page(hash, &block)
      create(hash) do |xaml|
        xaml.Page(hash, &block)
      end
    end
    def self.user_control(hash, &block)
      create(hash) do |xaml|
        xaml.UserControl(hash, &block)
      end
    end
    def self.window(hash, &block)
      create(hash) do |xaml|
        xaml.Window(hash, &block)
      end
    end
  end
end

xamltools.rb on GitHub

require 'xamltools.rb'
require 'PresentationFramework'

class ViewModel
  attr :greeting, true
  def initialize(greet)
    @greeting = greet
  end
end

view = XamlTools::Xaml.window(:Width => 450, :SizeToContent => :Height) do |w|
   w.TextBlock(:FontSize => 48, :HorizontalAlignment=> :Center, :Text => "{Binding Path=greeting}")
end

view.data_context = ViewModel.new( "I'm Bound!" )

System::Windows::Application.new.run(view)

bind_example.rb on GitHub

I would have updated the xaml tools to use load_assembly instead of strong names, but strong names are the only thing that work on my Win7 box. This is nicely outlined in the IronRuby tutorials that come with the distribution. I might try them. I could learn a lot.

Combining Classes and Xaml

I found an article about combining an IronRuby class with xaml. However, this example was suitable for Silverlight 1.0 (look at the control box) and doesn’t work for me. I’ve examined the new Application api that’s suitable for 3.5, but I’m not able to generate a suitable Uri for the file. The Uri needs to be relative, not absolute, and the pack: Uris didn’t seem to work, probably due to a fundamental misunderstanding on my part.

Looking at the other side, I’ve not yet found a way to force an IronRuby class out of the engine into the CLR proper, the x:Class should work just find with an existing CLR class.

More importantly, code-behind is a compromise. Not even a good one at that. The development style I used was perfectly acceptable for utility style applications, but larger applications should have a complete divorce between the view and the rest of the code, connected only by binding. By introducing code-behind into the equation, I’m letting the rest of my application infect my view, coupling it tightly.

To be fair, my last post was written using IronRuby 0.9, and due to the ICommand interface implementing an event, you’ll need a more recent build.

require 'xamltools.rb'

class MyCommand
  include System::Windows::Input::ICommand
  def add_CanExecuteChanged(h)
    @change_handlers << h
  end
  def remove_CanExecuteChanged(h)
    @change_handlers.remove(h)
  end
  def can_execute(args)
    @can_execute
  end
  def execute(arg)
    puts "I'm being commanded"
    @can_execute = false
    @change_handlers.each{ |h| h.Invoke(self, System::EventArgs.new) }
  end
  def initialize
    @change_handlers = []
    @can_execute = true
  end
end
class ViewModel
  attr :my_command, true
  def initialize
    @my_command = MyCommand.new
  end
end

view = XamlTools::Xaml.window( :Width => 450, :SizeToContent => :Height) do |w|
  w.Button( :Content => "Click Me!", :Command => "{Binding Path=my_command}")
end

view.data_context = ViewModel.new

System::Windows::Application.new.run(view)

using_commands.rb on GitHub

In summary, The concerns for writing WPF apps in IronRuby at the end of my last post have been addressed or made redundant, with out pulling my favorite fear-mongering golden hammer and resorting to Code-Dom.

Thank me for my time,
me


On a more serious note, I’ve learned a lot this past week, with a little bit of the googles and the tutorials. I think I can start writing a “REAL” application in IronRuby, at least as a prototype. The remaining question is which itch am I going to scratch?

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.