Browsing the blog archives for the year 2009.

Just passing through

work safe

Continuation Passing Style is a functional pattern where all work that can’t be passed into a tail recursive function call is passed in as an additional argument via a closure or anonymous function, delaying execution.

What got me confused for years on this was the explanation, almost like a mantra, “A continuation is like a callback.” I don’t use callbacks much and I believe that phrase is actually expressing a different pattern, simple first-class functions. So what do I think a continuation is? It is a promise to get to it later, after a tail call. I do agree with the literature that it turns the function inside out. And Don Syme’s reasoning that you’re trading heap to avoid spending stack.

I know you hate fibonacci, but it’s simple to explain. Here it is in all it’s glory.

let rec fibonacci n =
  match n with
  | 0 -> 0
  | 1 -> 1
  | _ -> (fibonacci (n-1)) + (fibonacci (n-2))

simple_fib.fs on GitHub

You note, however, that since the results of two recursive calls need to be stored, we can’t dump the stackframe and tail optimize the call, right? We could pass around two accumulators, essentially mimicking the imperative for-loop solution to the problem

let fibonacci n =
  let rec loop current a b =
    if current == n
    then a + b
    else loop (current+1) b (a+b)
  match n with
  | 0 -> 0
  | 1 -> 1
  | _ -> loop 2 0 1

accum_fib.fs on GitHub

This works because the Fibonacci sequence is just that, a sequence. It can also be represented by a tree, and that’s what’s causing it to be a problem for recursion in the first place. We are still left with, “How do I process a tree without risking a blown stack?” That’s what Continuation Passing hopes to solve by using a continuation (read: anonymous function) that wraps our core functionality in a heap object so we don’t call down one leve. I’m not making this clear, so I’ll show this in pictures.

Continutation Passing Style, step one.

Step One: We’re abstracting the problem to it’s simplest form

Step Two: We're making a promise to do something later

Step Two: We’re making a promise to do something later

Step Three: We're expanding the first abstraction

Step Three: We’re expanding the first abstraction

Step Four: We're expanding the second abstraction

Step Four: We’re expanding the second abstraction

Step Five: Fill in the base-cases for both our promise, and the function.

let fibonacci n =
  let rec fib_cps n cont =
    match n with
    | 0 -> (cont 0) // <-- even the base cases need to keep the promise
    | 1 -> (cont 1)
    | _ -> (fib_cps (n-1) (fun a -> fib_cps (n-2) (fun b -> cont(a+b)) ) )
  fib_cps n (fun x -> x) // <- this anon function is our base continuation

fibonacci_cp.fs on GitHub

And now for the punchline. Why do I care? This goes back to the spreadsheet challenge I talked about earlier. I was evaluating my abstract tree and noticed a lot of code that looked like: | Sum(a,b) -> eval a + eval b and I knew it wasn’t going to scale past my toy problem. I had a few tests, so I branched it with Git and tried replacing it with a tail recursive version. I know a spreadsheet doesn’t need that, but it really didn’t add any complexity once I figured out what it was actually doing. Just thought I’d share.

Software Estuaries: Programming Environmentalism

work safe

I’ve been thinking about IronRuby and WPF and this means I’ve been seeing some differences between how a staticly typed language like C# builds APIs and dynamic languages. It basically boils down to the use of primitive types at the perimeter.

Let’s look at a simple C# API

   public MyDoc GetDocFromUrl(Url address){
      // do stuff here
   }
   public static void Main(String[] args){
      GetDocFromUrl(new Url("http://some.site/some.doc"));
   }

And now the Ruby version

  def get_doc_from_url(url)
     # do stuff
  end
  get_doc_from_url("http://some.site/some.doc")

what’s the difference? In the C# version, you need to insert a url. In the ruby version, you need to pass in a string.

The first time I realized this was working with WPF trying to get a picture to update. The Xaml code had an attribute Source="blah.png" but the C# code to change this after the fact was horrific. Starting , I need to call System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(...). Why was that my job? For those playing at home, this is why extension methods exist. The code to do all that junk has a spiritual home on the WPF control, not in my application.

        private static void ShowFile(string FileName)
        {
            var win = new Window();
            var stack = new System.Windows.Controls.StackPanel();
            var bmp = new System.Drawing.Bitmap(fileName);
            var img = System.Windows.Controls.Image();
            img.Source = System.Windows.Interop.Imaging.CreateBitmap.SourceFromHBitmap(
               bmp.GetHbitmap(),
               IntPtr.Zero,
               Int32Rect.Empty,
               System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            img.Stretch = System.Windows.Media.Stretch.None;
            win.Content = img;
            win.SizeToContent = SizeToContent.WidthAndHeight;
            win.ShowDialog();
        }

When I started writing this post, I was going to make a point about static vs dynamic languages. After chatting with Jon Fuller one night and chewing it over for a few days, I think the typing is a red herring. He mentioned that the rails source code seems to have a certain layer structure. The public facing APIs take the primitive types and then convert them to internal representations. You can do this in C#. So, why not?

WPF, for example, has to serve many masters. Let’s start by thinking about where you can get the images for your WPF application.

  • Files
  • Filtered Files
  • Generated
  • Taken from the web
  • Taken from gopher

I see a pattern. The API would have a large number of transformers from all the possible sources, so instead of supplying any, they supply none. From the point of view of the API developer this is less work and easy, but in they eyes of the application developer, this bleeds your API concerns into the application. It fuzzes the layer boundary. To be blunt, Earlier this week I tweeted comparing this style of APIs to a sea-cucumber spewing its guts into the surrounding water.

A better metaphor is the realization that software contains estuaries, places where the fresh water of your application mixes with the marine conditions of the APIs and frameworks you use. Seawater kills freshwater animals, and very few organisms thrive in the swirling mix. The difference is where the estuaries are contained. In Ruby APIs, we tend to keep the estuary behind the API letting the API provider manage the conversion from one type to the other. In C# APIs, we see the estuary on the application side. The thing to be aware of with the application biased estuaries is that they tend to reach farther up stream than you may realize. Abstraction layers and extensions on the API can help manage the mix of waters. Be ecologically minded, save the programming environment and code green!

State Makes It Easy: a Test-First Parable

work safe

Just some background on how I got the the problem I’ll be discussing. Recently, the twitters where talking about the Spolskey / Martin feud over TDD and whether or not it can be useful for every class of problem. In addition there’s been a lot of talk about Katas as a form of practice. This lead me to a 2002 article by William Wake describing a test-first spreadsheet. And, Michael Feathers is writing Vi in Haskell.

So, I started the test first spreadsheet challenge in C# because it’s super easy to work in a language you know. For the record, I completed the engine but not the application. Part of the problem is building an expression parser to evaluate formulas. While I’m not proud of what I wrote, my parser works and passes all the tests. The parser is a horrible hack that has no place in polite society and I’m not sure it should be called a parser. I blindly implemented the worst thing that could possibly work. It does have a clever little pivot to control operator precedence, but it’s ugly. That was intentional as part of this exercise was to explore the Sudoku issue from the TDD dust-up (TDD can(’t) be used for mathematically important solutions) and see if I can build a parser without paying attention to what defines a parser in my opinion of the eyes of the rest of the world.

So, that was fun, but I wanted to play with F# since it’s been a while. The spreadsheet challenge would be an interesting experiment for me in Functional programming and TDD. I remember reading about the Haskell vim project and saying, “You can do that?” So, I wanted to find out how. It went fairly smoothly until I hit the parser, then I hit a wall. Almost literally, since it was the “)” that set me back. I was ashamed of myself. I wrote a parser for my FSharp talk that was as complex or more than this. I’m a huge fan of DSLs. Am I going to have to admit that test-first is a failure? No, I just need to look a bit deeper and discover what I think of test first.

But I did it in C#, why? In C#, I scattered information about the state of the parser all over my classes. It was easy to bang your way out of a corner if you can throw state at it. F# also has state, but I was trying to be as stateless as possible, even with a spreadsheet, and I was doing pretty damn good up until this point. I took a hard look at what Test-first means, then I took some time and relearned everything I knew about parsers up until that point.

I’m avoiding terms like BDD, TDD, and Context-Specification because they have very specific meanings to very vocal people from whom I still plan on learning. What do I mean by test-first?

  • Try not to write code until you have a need.
  • Those needs are expressed as executable tests.
  • Your code should only express the needs of the tests.

Test-First agile design gets a bad wrap in some corners as “no-design” when it really is about controlling assumptions. My instincts said I’d need a parser to evaluate the formula, but I stubbornly threw them away. I was thinking about a parser framework like I built up in my FSharp talk. This is way too much and I couldn’t justify it. Assumptions here are: I need a parser framework vs. parsers will fall out. Both assumptions are wrong. A true parser is a small thing that you can test quickly and easily. I needed just enough parser to get the job done. The trick is not to ignore a solved problem, but control scope of the solution.

What is a parser? When reading the Graham Hutton Haskell book that Eric Meijer is using in his lecture series, I found a poem. A parser for a thing / is a function that from a strings / to lists of pairs / of things and strings. I’m not returning a list of things, but still. In a fit of assumption, I changed string to token-stream (I’m not a saint) and I was off. I started with a simple parser, operating on a token stream.

type expression =
  | Empty
  | Number of int
let expression stream =
  match stream with
  | [] -> Empty, stream
  | h::t -> Number( Int32.Parse(h)), t
let evaluate expr =
  match expr with
  | Empty -> failwith "Empty Expression"
  | Number(a) -> a

You’ll notice here that I have to return a tuple, the expression and the remainder of the parser. Since I’m programming in the functional style, I have to carry my state with me constantly. This means my functions start growing arguments, but I’m way more aware of the data I’m actually using. This became much more apparent as I started carrying a set of visited cells to prevent circular references.

The thing that tweaked my mind about it was how I didn’t need all the parser combinators I wrote over a year ago when I was parroting Mark Jason Dominus’ example from Higher-Order Perl. Even this time, trying to write test-first, I have far too much in the final solution. (Not Quite, I spent some of the weekend deleting code, but the point remains; I had code to delete, not refactor).

My final note; I think the test-first style is about controlling assumptions. It is okay to make some assumptions, but the purpose of the tests is to verify and document they are valid in the system you’re designing.

Usul’s Words Have Power, Part 1: Refactor

work safe

Words have power. For those who practice the Weirding Way (from Dune), this is to be taken for granted. Some agree with the Humpty Dumpty (Through the Looking Class Ch. 6) and a word means exactly what they choose it to mean. But, to counter that point, I offer the following description of my dinner last night; “Proxy Flu quickly house Cabbage’s”. Communication is based on a shared understanding, so let’s share. More correctly, I’m going to share with you what I mean. Then we’ll communicate.

People are still confusing Refactor with Redesign.

As we bound through the local community and the wider internet, it is all too common we hear something like, “We have no time to Refactor, It’s a nice to have, but we can’t”. I have also heard, “We give our team one month a year to refactor and do stuff for us.” I humbly submit, “You’re doing it wrong!” I understand that’s an inflammatory statement. I intend to back up those words, so bear with me through a metaphor.

I’m baking a cake. I was making a five course meal for the in-laws when they suggest that a cake would be nice. I really want to get that cake out and onto their plates, and I want to impress them. I look around the kitchen and realize that I’ve just used my last big bowl making the batter. I need to frost the cake, but I need the big bowl to make the icing. I reach for the nearest bowls I can find, four small bowls of different sizes. Now I have to make several small batches of icing to get the same amount. I have risks. My calculations of the ingredient proportions could be wrong. I can underestimate the size of the bowls. I can combine the ingredients in an inconsistent manner. Worse, it take four times as long to make the icing, because the time it takes to make icing isn’t directly related to the amount you make.

That was one option. Another option is to stop everything and clean all the dishes at once. But I would very literally be starving my in-laws. The last plan is to clean the big bowl and maybe a beater and spatula I could use, but only those that I need. Then, when I’ve finished, I could clean up the dishes I used for the cake. That is Refactoring.

What is implied by the statement, “we don’t have time,” is that they want to stop and clean everything. That is a redesign.

In pondering why the misunderstanding exists, I can only blame myself and other proponents (not really, but I’m making a point about misunderstandings). When talking about Refactoring, we usually start with a complete program and make changes. We don’t have a choice because we want to isolate the Refactoring act for pedagogical reasons. But it tells only half the story. A half that gives the impression this is a post-development effort. In addition, when talking about the power of small steps adding up we mention it’s possible to redesign from a series of Refactorings. But the point to drive home in that situation is lost. The code never stops being developed. We do this to express the notion that if you clean the dishes as you go, you’ll never have to wash all the dishes in the house.

When do we Refactor? At one extreme, the TDD side, you Refactor after every passing test. On the other extreme I should get my feature working, check in, Refactor and check-in again. I don’t wait until the end of the quarter. That is a Redesign, not Refactoring.

Let’s lay down one more time why we Refactor. Our first pass at solving a problem is littered and strewn with a confused jumble of ideas. Refactoring gives us a chance to solidify our abstractions, improve readability, increase reuse, manage dependencies, increase testability, and clarify APIs.

How do you start in an existing project? Clean the code you’re currently using. Not to make it perfect, but to reduce the risks of spaghetti code. If you start with a pile of dirty dishes and clean only what you need, you won’t clean all the dishes, but you will clean the ones you use most often, and they will always be clean when you need them. You didn’t mean to write bad code, you just forgot to wash the dishes.

C# Lies. But You Knew That, Right?

work safe

Mark posted a question about using the MenuItemBy method on White’s MenuBar class from ruby. But there’s a problem. While the examples show C# code being used with two parameters as below, it is a lie. That method uses the params keyword, which means the rest of the CLR sees that as an array. You’re just lucky in C#. The literal translation of the code below to IronRuby will fail. 2 arguments for 1. Because it expects a typed array, not multiple parameters.

  win.MenuBar.MenuItemsBy(SearchCriteria.ByText("Task"), SearchCriteria.ByText("New"))

So, we can just wrap our criteria objects in a ruby array and pass them in? Nope. Not in 0.9, and not without some meta magic. We need a Core.UIItems.Finders.SearchCriteria[], so we’ll get one by detouring through a generic list. Oh! this is a great time to notice that CLR classes use the [] operator to return parameterized instances of themselves, like the C# <type> syntax. Here’s what my cucumber step definition looks like for creating a new task via a menu.

When "I click Task -> New" do
  l = System::Collections::Generic::List[Core::UIItems::Finders::SearchCriteria].new
  l.add(Core::UIItems::Finders::SearchCriteria.by_text("Task"))
  l.add(Core::UIItems::Finders::SearchCriteria.by_text("New"))
  @win.menu_bar.menu_item_by( l.ToArray ).click
end

This works. I admit it ain’t the prettiest, but it is expanded for demonstration purposes. Yeah, that’s it. I’m kinda rushing to get some stuff done (and posting for breakfast), so I’d like to revisit this later and clean it up with metaprogramming. Maybe next month?

I also want to note something. I thought including namespaces was so damn cool, but White and WPF use similar names and I’m not sure ruby’s modules are doing the isolation I want, so I’m avoiding it until I need it. Also something else to look into.

Disposable Code

work safe

I took a quick look at some WaitN examples this morning to see if there was anything I needed to fear when doing an example of WaitN in IronRuby. Then I saw it. IDisposable. More correctly, a using statement. What would that look like in IronRuby?

module System::IDisposable
  def self.use_these(*disposers, &block)
    block.call(*disposers)
    disposers.each {|d| d.dispose}
  end
  def using(&block)
    block.call(self)
    self.dispose
  end
end

class DisposableHero
  include System::IDisposable
  attr :name
  def initialize(name = "Jed")
    @name = name
  end
  def do_something_to(other)
    puts "#{@name} washes a car for #{other.name}"
  end
  def do_something
    puts "#{@name} doing something"
  end
  def dispose
    puts "#{@name} is being disposed"
  end
end

DisposableHero.new.using do |d|
  d.do_something
end

System::IDisposable.use_these(DisposableHero.new("Tony"), DisposableHero.new("Ryan")) do |t, r|
  t.do_something_to(r)
end

I added a using method to any IDisposable object that handles scoping. In addition, I added a multi-object disposing use_these block so I don’t have to nest my using blocks. It’s not perfect, but for five minutes of thinking, it’s not too bad.

It’s like Sports Center, but Not.

work safe

Do you know how many RBIs have been hit against Cal Ripkin? How many times was a Manning sacked by a running back last year?

To put it a different way, who has the most Oscars for cinematography in a tv series?

I’m pretty sure those questions make no sense. I’m not passing judgment on sports fans, or movie buffs. I choose to spend my time doing other things. This crystallized while I was talking with Ryan. Some people have different information acquisition profiles. A few months back I saw an interview from RailsConf of Tim Ferriss, the author of the four-hour work week. He mentioned he had stopped pro-actively acquiring information because by the he needed it, he’d forgotten it. If we couple this with the acknowledgement that we can’t learn everything, what’s the best way to gain knowledge? The thesis of the interview was “just in time knowledge.”

The Internet, and your local library, make this possible. With a network of friends, it’s not a bad idea. But there is a catch. How do you know if there is something out there to know?

Recently, a coworker asked me about sending data over a modem. I couldn’t help him solve his problem, but I gave him enough to start looking. But in a sea of data, where can I find a library to tell me the frequency of a sound? Which XML library should I use? How do I know to use MVVM or IOC? Where do I start?

I’ll let you figure that out. We started to identify three patterns of acquisition; Infovore, tasker, and opportunist. These patterns depend on a combination of the person and the area of interest.

An infovore collects information for the sake of information. It’s a news hound. It’s a super fan. It’s how I approach programming. It is my hobby, but it might not be yours.

A tasker starts researching around the edges of their task. Think an informed patient. Researching cars when you need a new ride. Looking at testing frameworks when you’re a developer tester.

An opportunist only learns what they need when they need it. I’m so here with car repair. I’ve been known to watch a soccer game on TV, but I have no idea who’s playing this week, or when.

The interesting thing about this is that different people fit different profiles for different topics. A fantasy football player is likely either an infovore or a tasker regarding their team. But most of us are taskers or opportunists when it comes to health insurance.

Let’s look at three RPG players. One spends time on the Wizards boards tweaking min-max builds all weekend. Another looks at the books when it’s time for build a character or level, but still enjoys the game. The last loves hanging out with his friends, but still has to ask (though not as often) what does he roll for that again? Who’s fun is wrong-bad? I can’t tell you that.

I think the interesting part is to realize the categories of interest in our lives and determine what are acquisition profile is in those categories. Then, accordingly, determine if we’re okay with that.

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.