Greg Malcolm

Everything but the Perl

  Home  |   Contact  |   Syndication    |   Login
  15 Posts | 0 Stories | 14 Comments | 0 Trackbacks

News

Twitter












Archives

Saturday, March 17, 2012 #

I maintain Python Koans on mirrored on both Github using git and Bitbucket using mercurial. I get pull requests from both repos but it turns out keeping the two repos in sync is pretty easy. Here is how it's done...

Assuming I’m starting again on a clean laptop, first I clone both repos

~/git $ hg clone https://bitbucket.org/gregmalcolm/python_koans
~/git $ git clone git@github.com:gregmalcolm/python_koans.git python_koans2

The only thing that makes a folder a git or mercurial repository is the .hg folder in the root of python_koans and the .git folder in the root of python_koans2. So I just need to move the .git folder over into the python_koans folder I'm using for mercurial:

~/git $ rm -rf python_koans/.git
~/git $ mv python_koans2/.git python_koans
~/git $ ls -la python_koans
total 48
drwxr-xr-x  11 greg  staff   374 Mar 17 15:10 .
drwxr-xr-x  62 greg  staff  2108 Mar 17 14:58 ..
drwxr-xr-x  12 greg  staff   408 Mar 17 14:58 .git
-rw-r--r--   1 greg  staff    34 Mar 17 14:54 .gitignore
drwxr-xr-x  13 greg  staff   442 Mar 17 14:54 .hg
-rw-r--r--   1 greg  staff    48 Mar 17 14:54 .hgignore
-rw-r--r--   1 greg  staff   365 Mar 17 14:54 Contributor Notes.txt
-rw-r--r--   1 greg  staff  1082 Mar 17 14:54 MIT-LICENSE
-rw-r--r--   1 greg  staff  5765 Mar 17 14:54 README.txt
drwxr-xr-x  10 greg  staff   340 Mar 17 14:54 python 2
drwxr-xr-x  10 greg  staff   340 Mar 17 14:54 python 3

That’s about it! Now git and mercurial are tracking files in the same folder. Of course you will still need to set up your .gitignore to ignore mercurial’s dotfiles and .hgignore to ignore git’s dotfiles or there will be squabbling in the backseat.

~/git $ cd python_koans/
~/git/python_koans $ cat .gitignore 
*.pyc
*.swp
.DS_Store
answers
.hg            <-- Ignore mercurial

~/git/python_koans $ cat .hgignore 
syntax: glob
*.pyc
*.swp
.DS_Store
answers
.git            <-- Ignore git

Because both my mirrors are both identical as far as tracked files are concerned I won’t yet see anything if I check statuses at this point:

~/git/python_koans $ git status
# On branch master
nothing to commit (working directory clean)

~/git/python_koans $ hg status
~/git/python_koans

But how about if I accept a pull request from the bitbucket (mercuial) site?

~/git/python_koans $ hg status
~/git/python_koans $ git status
# On branch master
# Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#	modified:   python 2/koans/about_decorating_with_classes.py
#	modified:   python 2/koans/about_iteration.py
#	modified:   python 2/koans/about_with_statements.py
#	modified:   python 3/koans/about_decorating_with_classes.py
#	modified:   python 3/koans/about_iteration.py
#	modified:   python 3/koans/about_with_statements.py

Mercurial doesn’t have any changes to track right now, but git has changes. Commit and push them up to github and balance is restored to the force:

~/git/python_koans $ git commit -am "Merge from bitbucket mirror: 'gpiancastelli - Fix for issue #21 and some other tweaks'"
[master 79ca184] Merge from bitbucket mirror: 'gpiancastelli - Fix for issue #21 and some other tweaks'
 6 files changed, 78 insertions(+), 63 deletions(-)
~/git/python_koans $ git push origin master

Or just use hg-git?

The github developers have actually published a plugin for automatic mirroring:

http://hg-git.github.com

I haven’t used it because at the time I tried it a couple of years ago I was having problems getting all the parts to play nice with each other. Probably works fine now though..


Saturday, January 15, 2011 #

codemash

I just got back from Codemash yesterday, and still on an adrenaline buzz. Here's my take on this years encounter:

Photobucket

The Awesome

Nearly everybody in one place

Codemash is the ultimate place to catch up with community friends. This is my 3rd year visiting and I've got to know a great number of very cool people through various conferences, Give Camps and other community events. I'm finding more and more that Codemash is the best place to catch up with everybody regardless of technology interest or location. Of course I always make a whole bunch more friends while I'm there! Yay!

Open Spaced

I found the open spaces didn't work so well last year. This year things went a lot smoother and the topics were engaging and fresh.

While I miss Alan Steven's approach of running it like an agile project, it was very cool to see that it evolving. Laptops were often cracked open, not just once but frequently!

For example:

  • Jasmine - Paired on a javascript kata using the Jasmine javascript test runner
  • J - Sat in on a J demo from local J enthusiast, Tracy Harms
  • Watir - More pairing, this time using Ruby with the watir-webdriver through cucumber. I'd mostly forgotten that Cucumber runs just fine without Rails. It made a change to do without.

The other spaces were engaging too, but I think that's enough for that topic.

Javascript Shenanigans

I've already mentioned that I attended a Jasmine kata session. Jasmine is close to my heart right now every since I discovered it while on the hunt for a decent Javascript testing framework for a javascript koans project earlier this year. Well, it also got covered in the Java Precompiler and Pillar's vendor session, which was great to see.

Node.js was also a reoccurring theme. Node.js in a nutshell? It's an extremely scalable Event based I/O server which runs on Javascript. I'd already encountered through a Startup Weekend project and have been noticing increasing interest of late. After encountering more node.js driven excitement from my peers at codemash I absolutely had to attend the open space on it. At least 20 people turned up and by the end we had some answers, a whole ton of new questions and an impromptu user group in the form of a twitter channel (#nodemash). I have no idea where this is going to go or how big it is going to become, but if it can cross the chasm into the enterprise it could become huge...

Scala Koans

I'm a bit of a Koans addict, and I really need more exposure to functional languages so I gave the Scala Koans precompiler a try. Great fun! I'm really glad I attended because I found I had a whole ton of questions. Currently the koans are available here, and the answers are here.

Opportunities

While we're on the subject can we change the subject now?

Hai Gregory,

You really need to keep the drinking for later in the day. I mean seriously, you're 34 and you still do this every single time! Sure, you made it to Chad Fowler keynote ok, but you looking a rather pale weren't you? Also might have been nice to attend 'Netflicks in the Cloud' instead of 'Sleeping It Off For People Who Should Know Better'.

Kthxbye

PS: Stop talking to yourself

Not that I entirely regret it, I've had some of my greatest insights through late night drunken conversations at the CodeMash bar. Just might be nice to reign it in a little and get something out of the next morning too.

Diversity

This is something that is in the back of my mind because of conversations at Codemash as well as throughout the year; I'm realizing more and more how discouraging the IT

profession is for women. I notice in the community there has been a lot of attention paid to stamping out harrasment, which is good, but there also seems to be a massive PR issue.

I really don't have any solutions, but I figure it can't hurt to pay more attention to whats going on...

And in Other News

  • I now have a picture of Chad Fowler giving me more cowbell! Sadly I managed to lose the cowbell later on. Hopefully it's gone to a Better Place.

    ... and if Chad Fowler wants more cowbell, we should probably give him more cowbell!!
  • The Womack Family Band joined in with the musicians jam this year. There's my cowbell again! Why must you hide from me?

  • I also finally went in the water for the first time in all the I've been coming to codemash. Why did I wait so long?!?

 


Monday, April 5, 2010 #

Recently a Python developer friend with whom I was pair programming with suggested that I show him how to write a little Ruby. I responded by telling him to check out Ruby Koans as a starting point.

However I wanted to try that in reverse at the same time with me learning some Python. I did a bit of googling, and sure enough someone had started writing some Python Koans. It just needed finishing...

So, a few weeks later Python Koans is now complete and ready for action!

Python Koans Screenshot

It is available through Mercurial on Bitbucket:

http://bitbucket.org/gregmalcolm/python_koans/wiki/Home

It is also mirrored on Github:

http://wiki.github.com/gregmalcolm/python_koans/

Converting it was fairly easy. Aside from the differing philosophical approaches behind the two languages, Ruby and Python are fairly similar. We had to come up with completely new material for a few subjects like multiple inheritance and decorators, but for most features in Ruby there is something roughly comparable in Python.

I highly recommend writing tests (or koans) as a means to lean a new language or framework. I've learned a lot from doing this.


Friday, November 6, 2009 #

Right now IronRuby Microsoft is not planning on integrating IronRuby in Visual Studio 2010. Want to do something about that? Sign this petition:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=479957


Same deal with IronPython too:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=475830


Thursday, November 5, 2009 #

<< Part 2 – A quick look at IronRuby

Gambling with Cucumbers

In part 2 we demonstrated how we can mix .NET and Ruby though IronRuby. The question is, why would you want to do that? It is probably easier to stick with one language for most projects. Why combine them?

The problem with BDD in .NET

One area where Ruby currently has a clear advantage over.NET is in the realms of Behavioral Driven Development (BDD).

You can write Unit Tests and Integration Tests in .NET just fine, but what about when you want to make tests based on actual user stories?  Specifications written as word documents and UML diagrams have a tendency to evolve separately to the actual product. If you could replace the specifications with human readable tests specifications it could easier to keep the product’s functional requirements in sync with the actual implementation.

The problem with this is that not everyone involved with the product is necessarily going to be a programmer. For example, this NUnit test a poker hand that should make up “One Pair”:

[TestFixture]
public class DemoTests
{
    Hand _hand;

    [SetUp]
    public void SetUp()
    {
        _hand = new Hand();
    }

    [Test]
    public void Should_show_one_pair_for_3c_3s_Jc_9d_As()
    {
        _hand.AddCard("3 clubs");
        _hand.AddCard("3 spades");
        _hand.AddCard("J clubs");
        _hand.AddCard("9 diamonds");
        _hand.AddCard("A spades");
        Assert.AreEqual("One Pair" , _hand.EvalScore());
    }

    .
    .
    .
}

This makes plenty of sense to developers, not so much to business professionals. And this is a relatively readable test, what if theres mocking and other distractions?

Now compare that with the popular Ruby BDD framework, RSpec:

# hand_spec.rb

require 'IronPoker'

describe Hand do
  it "show a score of 'One Pair' if player has " +
  "3 Clubs, 3 Spades, J Clubs, 9 Diamonds and A Spades" do
    20.times { bowling.hit(0) }
    bowling.score.should == 0
   
    hand = IronPoker::Hand.new
    hand.add_card "3 Clubs"
    hand.add_card "3 Spades"
    hand.add_card "J Clubs"
    hand.add_card "9 Diamonds"
    hand.add_card "A Spades"
   
    score = hand.eval_score
    score.should = "One Pair"  
  end
end

Much cleaner!

And you can also use command line tools to generate reports:

$ spec hand_spec.rb --format specdoc

Hand
- show a score of 'One Pair' if player has 3 Clubs, 3 Spades, J Clubs, 9 Diamonds and
  A Spades

Finished in 0.007534 seconds

There have been attempts at creating similar frameworks for .NET, but there are syntactical constraints that make it difficult to keep the readability. For example, my favorite .NET BDD framework is MSpec (also known as Machine Spec). Here is what an MSpec spec looks like:

// machine.spec (mspec) sample

using IronPoker;

[Description]
public class Player_showing_their_hand
{
    static Hand _hand;

    Context before_each = () =>
    {
        _hand = new _Hand();
    };

    When 3_clubs_and_3_spades_and_J_clubs_and_9_clubs_and_A_Spades_are_dealt = () =>
    {
        _hand.AddCard("3 clubs");
        _hand.AddCard("3 spades");
        _hand.AddCard("J clubs");
        _hand.AddCard("9 diamonds");
        _hand.AddCard("A spades");

        _result = _hand.EvalScore();
    };

    It should_show_a_score_of_One_Pair = () =>
    {
        _result.ShouldEqual("One Pair");
    };
}

Sure it looks a bit like RSpec, but notice how the When…It… descriptions have to be separated by underscores, and the use of the unsightly “= () =>” lambda syntax at the end of each clause? There are other BDD frameworks, but they all have to make compromises somwhere. (In fairness to MSpec, it does at least have a tool which generates very nice html RSpec style reports though!).


Cucumber, Finally!

As nice as RSpec is, we can do even better when it comes to turning user stories into tests. Cucumber is an RSpec extension that lets you write tests like this:

Feature: Player shows their hand
  In order to finish the round
  The player
  Needs to show their hand

Scenario Outline: Play is dealt a card
  Given I have a <card_1> in my hand
  And I have a <card_2> in my hand
  And I have a <card_3> in my hand
  And I have a <card_4> in my hand
  And I have a <card_5> in my hand
  When I am dealt a card
  Then the result should be <output> on the screen

Examples:
  |   card_1   |   card_2   |   card_3   |   card_4   |   card_5   |      output     |
  | 3 Clubs    | 3 Spades   | J Clubs    | 9 Diamonds | 3 Spades   | One Pair        |


Makes sense, right? The first section, “Feature” describes in plain English the story and use case. The scenario is described in the what appers to be plain English, but actual confirms to a “Given… When… Then”  structure. And final the table of examples directly correlates to the parts of the Scenario bracketed names (card_1, card_2 etc).

Because part Cucumber is part of RSpec this means it also implemented in Ruby. Sounds like a job for IronRuby!

Lets try it out!

IronPoker tutorial

For this demonstration we are going to try out Cucumber on an incomplete .NET application application I’m calling “IronPoker”. I got as far as writing the code to analyse poker hands written TDD style using NUnit. Lets switch and let Cucumber have a go!

The IronPoker code is in  github:

http://github.com/gregmalcolm/IronPoker

You can either checkout the code using Git, or click on the Download button to retrieve the it  in the form of a .zip file. The solution file is in Visual Studio 2008 format, but don’t worry if you don’t have it, we are going to work with Cucumber from the windows command interpreter.

Incidentally if you build and running IronPoker from Visual Studio there is not much to see there. The executable is a stub:
 
IronPoker Stub App Screenshot

The bulk of code currently written is all in the ‘IronRuby’ class library. Its just logic to calculate scores. Feel free to poke around in ‘IronPoker.Tests’ if you want to get a feel for it does. But we’re here for the cucumber, right? Open up a command prompt, navigate to this folder:

IronPoker\src\IronPoker.Cucumber

and we’ll run the cucumber test found in the subfolder:

.\Features\PlayHand.Feature

by running:

icucumber.bat Features

Note: if you start seeing “[36” spread liberally through the output, this means that the console colors do not work in your version of ruby. I have the same problem. See the Cucumber installation comment in Step 1 of this guide for details on how to turn it off.

Anyway, here are the results (in boring monochrome):
 
1st Cucumber Test Results Screenshot

Cucumber parsed the “feature” file, but didn’t find an implementation. Generously, it hass given us some code to get started with!

We have an implementation file already, but it is empty. It is here:
 
.\Features\steps\ironpoker_steps.rb

Copy and paste the implementation so far. (Copy and paste is available from the top left menu of the command window).
 
Initial Implementation Screenshot

As you may have gathered, this is ruby code. Next we need to figure out how to drive our IronPoker .NET code from IronRuby. This is where the “IIRB” tool comes in handy! (Reminder, its accessed by running “iirb.bat” from the windows command interpreter).

First off we need access to IronPoker.dll, which can be built from the “IronPoker” class library. You don’t need build it though because a copy of it is already in the IronRuby.cucumber folder, just to keep things simple! We can load it with:

require 'IronPoker'

Next we need to test the IronPoker.Hand class, as found in IronRuby\Hand.cs. So lets make an instance of it:

hand = IronPoker::Hand.new

Which of course is the same as saying “var hand = new IronPoker.Hand()” in C#.

Remember that NUnit sample we looked at earlier? We’re looking to do the same thing with Cucumber. So we need access to AddCard() and EvalScore() methods to run our tests. We can inspect which methods are available to us by running method called methods. Every ruby object has this:

Hand.methods Screenshot 

There they are! Only because the function names have been rubyized, they have become add_card and eval_score.

Let try playing a hand:
 
Straight Flush in IIRB Screenshot

Yep, Ace, 2, 3 ,4 and 5 of spades is indeed a ‘Straight Flush’.

Now we just have to do something similar for Cucumber. Time to go back to implementing ironpoker_steps.rb. First off stick this at the top of the code before the Given statements:

require 'IronPoker' # IronPoker.dll

Before do
  @hand = IronPoker::Hand.new
end

The Before clause is the equivalent of the “SetUp” method in typical unit testing frameworks. In other words, It is the function that gets called before each test. In this case the “hand” object is a member instance rather than a local instance so it has the extra @ at the front.

Next we need to to call add_card for each of the 5 given statements. We can actually reduce it down to one statement though thanks to regular expression:

Given /^I have a (.*) in my hand$/ do |c|
  # c = (.*)

  @hand.add_card c
end

In ruby, regular expressions are encapsulated between forward slashes. So we just have one given statement with a regular expression wildcard (.*) on the part that changes, the card descriptions. The body of the Given block assign the text from the wildcard to the variable “c” and uses it as the argument for “@hand.add_card”.

This will be the When block:

When /I am dealt a card/ do
  @result = @hand.eval_score
end

Which is saying that when the player receives a card it will be evaluated and stored in @result. In the case of the test, this applies for when the player has all 5 cards.

Finally in the Then block we evaluate whether or not the conditions of the test are met:

Then /the result should be (.*) on the screen/ do |score|
  @result.should == score
end

So @result is compared to the wildcard (which was assigned to “score”). So its roughly the same as an Assert in a unit testing framework.

Put it all together and we have:
 
Implemented Tests Screenshot

Save that and we can run our cucumber test again:

 
Failed Test Screenshot

The test completed! Only problem is  the result was “Three of a kind” instead of “One pair”. It actually is a Three of a kind, so the test is wrong!

Easily fixed, change one of the 3s to an A and it should pass.

Also why not add some more examples to the examples talbe in ‘PlayHand.Feature’? Try changing the examples section to this:

    Examples:
      |   card_1   |   card_2   |   card_3   |   card_4   |   card_5   |      output     |
      | 3 Clubs    | 3 Spades   | J Clubs    | 9 Diamonds | A Spades   | One Pair        |
      | 9 Diamonds | J Diamonds | Q Diamonds | K Diamonds | A Diamonds | Royal Flush     |
      | 8 Spades   | J Diamonds | 8 Diamonds | K Spades   | 8 Hearts   | Three of a Kind |
      | 8 Spades   | J Spades   | 8 Spades   | K Spades   | 8 Spades   | Flush           |
      | 2 Spades   | 2 Diamonds | 8 Diamonds | 2 Clubs    | 2 Hearts   | Four of a Kind  |
      | A Hearts   | 2 Diamonds | 3 Spades   | 4 Clubs    | 5 Spades   | Straight        |
      | 9 Diamonds | A Hearts   | 9 Clubs    | A Spades   | A Hearts   | Full House      |
      | 4 Hearts   | 5 Hearts   | 6 Hearts   | 7 Hearts   | 8 Hearts   | Straight Flush  |
      | A Spades   | 4 Diamonds | 5 Diamonds | 9 Diamonds | 8 Diamonds | High Card       |
      | A Spades   | 4 Diamonds | A Diamonds | 4 Clubs    | 8 Clubs    | Two Pair        |

Giving us:

 Completed Tests Screenshot

And that’s a wrap! (I would say "cucumber wrap" but there are Laws...)


Reference Sources

These are some of the sites which I used to research the tutorial, and a few more that you may find helpful:

Installation

Ruby - http://www.ruby-lang.org/
IronRuby - http://ironruby.net
Cucumber - http://wiki.github.com/aslakhellesoy/cucumber/ironruby-and-net


IIRB/DLR

http://msdn.microsoft.com/en-us/magazine/dd434651.aspx
http://silverlight.net/content/samples/sl2/dlrconsole/index.html


TDD/BDD

NUnit - http://www.nunit.org/index.php
Machine Spec - http://codebetter.com/blogs/aaron.jensen/archive/2008/05/08/introducing-machine-specifications-or-mspec-for-short.aspx
RSpec - http://rspec.info/
Cucumber - http://cukes.info/

<< Part 1 - Installing IronRuby and Cucumber

A quick look at IronRuby

Background

IronRuby is an implementation of Ruby which runs on .NETs Dynamic Language Runtime platform (the DLR). Languages hosted on the DLR are interpreted at runtime, rather than compiled then executed (like C# applications).

One benefit is that code can be invoked on the fly from a command line shell. This is handy when debugging or figuring out how to do something. Other popular DLR hosted languages include IronPython and Silverlight.

DLR Diagram

Messing around with Interactive IronRuby Shell (IIRB)

In standard ruby the interactive shell is invoked by running “IRB”. With IronRuby we prefix it with an extra “I", giving us “IIRB”.

Let's try that. From a windows command prompt type iirb.bat<enter>:

IIRB Prompt Screenshot 

This looks exactly like the standard Ruby IRB, but the unfortunate delay on loading is a giveaway. Hopefully that delay will reduce as the framework matures!

First off, lets confirm that it is a Ruby interpreter. Try making it interpret some basic ruby expressions:

"live racecar !"
"live racecar !".reverse
"live racecar !".reverse * 5
("live racecar !".reverse * 5).split(" racecar ")
("live racecar !".reverse * 5).split(" racecar ").map {|x| result = "We" + x}

These are the result I got:
IIRB showing ruby commands executed screenshot
 
Yep, it looks just like conventional Ruby so far! Of course there is a lot more to Ruby, but we’re not going to cover it here. Try these resources instead:

http://tryruby.sophrinix.com/
http://ruby-doc.org/docs/ProgrammingRuby/


So, how about something you can’t do in standard Ruby? How about we use IIRB to show a .NET MessageBox?


Showing .NET MessageBoxes

First we need access to the .NET libraries. For accessing a message box in .NET app we would need to add a reference to a library like ‘PresentationFramework.dll’.

In IronRuby we do this through the require keyword. Excute this from the IIRB:

require 'PresentationFramework'

Now we can have access to the message box. Try this next:

System::Windows::MessageBox.Show("Mein fruhstuck ist sehr langweilig!",
  "IronRuby Demo")

You should now see this:
 
MessageBox screenshot

This is almost the same as using the MessageBox object from C#, except that we are using “::” instead of “.” to separate namespaces and there is no semicolon at the end.

Personally I don’t want to keep referring to MessageBox namespace every single time I use it. Let's create another
MessageBox object with a shorter name:


MessageBox = System::Windows::MessageBox
MessageBox.show 'Mein fruhstuck ist noch immer sehr langweilig!',
  'IronRuby Demo'

You may notice that I also switched over to using the Ruby style lowercase version of “Show()” method and that I dropped the parenthesis. I also switched to apostrophes instead of quotes. This is just another way of doing the same thing in Rubyland.

So... we can now can show a message box. Big deal! How about we modify the class at runtime? Ruby has this neat mixins feature which allows classes to be modified at any time. Here goes:

class MessageBox
  def self.wide_show(msg)
    MessageBox.show msg, 'This message box is ' + ('very ' * 8) +
      ' wide, is it not?'

  end
end

MessageBox.wide_show 'Testing 123...'

… and we now have a customized “extra wide” MessageBox at our disposal
 
Wide Messagebox Screenshot

As you may have already figured out, we extended the MessageBox class, “def” defines a function, and the putting the “self.” prefix is similar to using “static” or “shared” in .NET. It makes it a “class method”


WPF

Quit out of irrb (type “quit:), start it up again afresh (“iirb”). Copy and paste the following:


require 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
require 'PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

require 'PresentationFramework, Version=3.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35'
require 'PresentationCore, Version=3.0.0.0, Culture=neutral,
  PublicKeyToken=31bf3856ad364e35'

Windows = System::Windows

Media = Windows::Media

redBrush = Media::SolidColorBrush.new( Media::Colors.Red )
blackBrush = Media::SolidColorBrush.new( Media::Colors.Black )

redButton = Windows::Controls::Button.new
redButton.content = "Do NOT press!"
redButton.font_size = 40
redButton.font_weight = Windows::FontWeights.bold
redButton.Width = 600
redButton.Height = 400
redButton.background = redBrush
redButton.click do |sender, args|
  Windows::MessageBox.show 'Please do not press this button again!',
    'Why would you even do that?!?',

    Windows::MessageBoxButton.OK, Windows::MessageBoxImage.exclamation
end

warningWindow = Windows::Window.new
warningWindow.content = redButton
warningWindow.title = "Example WPF Window"
warningWindow.background = blackBrush

app = Windows::Application.new
app.run warningWindow


Yep, this demonstrates how you can create a WPF window on the fly:

 
WPF Screenshot

One last thing for this segment, the DLR is designed so that programs hosted on it can interact with each other regardless of which languages the different parts are written in. There is a rather cool Silverlight sample out there called “DLRConsole” which demonstates how you can modify Silverlight elements from IronRuby or IronPython in the same browser window.

This is the URL:

http://silverlight.net/content/samples/sl2/dlrconsole/index.html

Note: it could move at any time without warning. Just google on “DLRConsole” if this happens.

DLR Console

In Part 3 we will have at a partical use for IronRuby, BDD with Cucumber

This tutorial is based on a short demo/talk I gave at the Columbus .NET Developers Group (CONDG) on IronRuby. It’s mostly designed for the .NET professional and making no assumptions of prior Ruby experience.

Installer In Part 1 we get everything installed.

IIRB In Part 2 we take IronRuby for a test drive

Cucumber In Part 3 we use it to integrate with Cucumber.


Installing IronRuby

Before we get started, my instructions are more or less the same as this:

http://wiki.github.com/aslakhellesoy/cucumber/ironruby-and-net

… but with a little bit more elaboration on how to install the MRI and IronRuby.

If you already have it all installed, go straight to Part 2!


Step 1 – Install MRI (Matz’s Ruby Interpreter)


We will need the standard Ruby language installed so we have access to the Gems package installer. This makes it really easy to install additional Ruby libraries, like Rails and Cucumber.

Install the latest stable Windows version of Ruby from here:

http://www.ruby-lang.org/en/downloads/

I used the one click installer. At the time of writing the one-click installer installs Ruby 1.8.6.

Afterwards make sure you have the Ruby bin folder in your system path (It will probably be C:\Ruby\Bin):

 Ruby Path Screenshot



Step 2 – Install IronRuby

IronRuby is currently available on Codeplex and Github. Grabbing it from Codeplex is probably the easiest approach:

http://ironruby.net/Download


This will allow you to download the MSI Installer version. The current installer at this time or writing is ironruby-0.9.2.msi.

Also make sure IronRuby’s bin folder is now in the system path (mine is called C:\Program Files\IronRuby 0.9.2\bin):

 IronRuby Path Screenshot



Step 3 – Install Cucumber


The cucumber installation instructions on the Cucumber Github wiki are here:

http://wiki.github.com/aslakhellesoy/cucumber/ironruby-and-net

I can’t really improve much on these remaining instructions. Just open a command prompt and do everything it says, with the exception of downloading and installing MRI and IronRuby. So just run all the commands, and create the icucumber.bat script file.

Our version will probably look more like this:

ECHO OFF
REM This is to tell IronRuby where to find gems.
SET GEM_PATH=
c:\ruby\lib\ruby\gems\1.8
@ "
C:\Program Files\IronRuby 0.9.2\bin\ir.exe" "c:\ruby\bin\cucumber" %* --no-color


NOTE: The --no-color option is a workaround for an issue with showing color in command terminals that exists in ruby at the moment on windows. You can try it with colors turned ont, but if its not fixed you will start seeing “←[36” symbols all your cucumber test output.

In Part 2 we will have a quick look at what you can achieve with IronRuby.

 
 

 


Tuesday, July 14, 2009 #

Today, just after 1:00pm I completed the US Naturalization Oath. I am now an American Citizen! Well technically a dual citizen, because my British citizenship still stands.

American FlagIt felt really strange handing over the green card. It has been my constant companion for 5 1/2 years and I've just got used to having it around. Nevermind, I'm sure it has gone to a better place (or at least places. Most likely it got shredded. Eep.)

The oath ceremony was fun. The 45 immigrants present each had to stand up and address the judge with something along the lines of "Good afternoon your honor, I am David Hasselhoff and I'm from Elbonia!"

The first person forgot the "Good afternoon" part, so nobody (myself included) included that part of the greeting until about half way through when somebody finally reintroduced it when we were about half through!

Every nation had subtly different ways of introducing themselves. The Polynesians approach was the most impressive; they made a point of yelling out their country of origin!

In case you are wondering we didn't get to sing the Star Spangled Banner. I'm sure the attempt would have been highly entertaining...


I just gave a short presentation at ColArc earlier on User Interface patterns. I got someone to film it, but unfortunately there is no audio. I just wasn't loud enough.


That’s ok though, it gives me an excuse to write it up!


User Interface Patterns

 

Smart UI (Anti-pattern)

 

A Smart UI is what you get when your GUI has no separation of concerns. That is, when the user interface and business logic are all mixed together. For example, if you take a form, throw a bunch of widgets on it and add some code in the event handlers.

 

This kind of approach is not always bad. It is fine if you want something quick and simple that isn’t going to change. For example if you want to create a quick demo, or explore how something works.

 

However, most of the time an application will change and that’s where things will get messy, particular if you have a lot of Smart UIs in one application.

 

Maintenance will get difficult. A supposedly simple change could affect anything else associated with the same class. Over time the code will likely messier and messier as more maintainers work with the same code.


Office clutter 


Writing tests for this kind of code is typically very difficult. User interface code is the hardest part to test and if the business logic is mixed in it can make the job near impossible.

 

It’s called an anti-pattern for a reason.

 

 

Model View Controller (MVC)

 

The most famous user interface design pattern, MVC, has been around for quite a while. It was devised in the late 1970s for use in the development of Smalltalk-80. The problem its designers were initially trying to solve was that of how to bridge the gap between the human user’s mental model and the digital model of the computer.

 

Eventually they whittled it down to the famous MVC triad we know today representing 3 key concerns:


MVC Triad 


Controller – Represents interactions, typically with the mouse or keyboard, or in the case of web applications, in the form of HTTP requests.

 

View – Renders the graphical output of the application

 

Model – Everything else. In particular this includes the data and business logic.


 

There are numerous other “triad” style user interface patterns. They all tend to feature some kind of concept of model and view, but the 3rd part (in this case the Control) tends to vary.

 

The other distinct trait of the MVC is that it is extremely loosely coupled. The Model knows nothing of the View or Controller, and similarly the View knows knows nothing of the controller either. One particularly useful side effect is that it is possible (and completely normal) to have multiple views for any given model. It is also relatively easy to change out parts (for example the viewing technology).

 

Testing is relatively easy. The Model and Controller are easy to test.

 

 

Model View Presenter (MVP)

 

During the 90s not everybody was satisfied with Model View Controller. In particular some developers working with rich application interfaces were creating GUI’s with highly detailed state changes and high degree with user control over the environment. At that time the typical MVC implementations did not handle this kind of activity as efficiently.

 

The creators of MVP ended up with a new model by shifting the MVC responsibilities around in what they called “Twisting the Triad”.

 

Twisting of the Triad

 

So instead of a controller, you get a presenter instead. The presenter has much of the computational logic of the View, but also takes over the Application Model aspects of the Model. That is, the part of the model in charge  view state changes, such as which widgets are visible or not visible.

 

The other twist is “Controller” behavior is moved into the View.

 

This gives us this:

 

MVP Triad

The MVP architecture works really well from a testing point of view. First you develop the model with a full set of tests. On getting that working you write the Presenter to handle as much of the viewing logic as you can, but out showing anything. This part two is therefore very easy to test. The actual view code is typically difficult to test, but in this architecture the view code is kept to a bare minimum, with events getting delegated to the Model. This means the untestable code is being kept to a bare minimum.

 

The code reuse is good too. A single presenter can be reused with multiple views if the functionality is similar. Because the View and the Presenter are tightly coupled it is easy to support databinding.

 

There is one complication I have not covered yet. There are actually 2 variants of this pattern:

 

MVP - Passive View and Supervising Controller

 

The style I have described up till now is closest to the Passive View variant. The Supervising Controller variant typically is used when you want to bind the view to model directly.

 

 

Presenter-Abstraction-Control (PAC)


Presenter-Abstraction-Control Hierachy

 

This pattern is a little more specialized; it is designed for rendering hierarchical views quickly.

For example, suppose you have a form based application. The form is the top triad node. Descending nodes might include the titlebar and client frame. The client frame in turn may have a number of widgets. Some of these widgets may in turn be composed of more widgets.

 

Each triad is similar to the MVC parts:

 

Abstraction = Model

Presentation = View

Control = Controller

 

The Control handles communications with the Abstraction and Presentation, also with other Controls in thee hierarchy.

 

The clever bit is that the Abstraction and Presentation parts are completely isolated from the outside world. This means they work really well in a multitasking context.

 

 

Hierarchical Model View Controller (HMVC)

 

In 1987 JavaWorld magazine published an article on HMVC, which looks almost identical to PAC. Apparently the authors were unaware PAC already existed. HMVC is very similar to PAC but there are some small differences. In particular, it is less strict about isolating the Abstraction and Presentation; they are allowed to communicate with each other from within a triad.

 

 

Model-View-ViewModel (MVVM)

 

This pattern is very specialized, it is designed for use in .NET’s WPF and Silverlight frameworks.

 

Model View ModelView Triad


Both these frameworks configure the View in the form of XML based properties (XAML). In a way working with XAML can be a bit like developing for Webforms, it is possible to respond to events in the Code-Behind. That of course would give you a Smart UI, so not ideal. Implementing classic UI patterns such as MVC or MVP would be very difficult. Instead these frameworks offer an alternative by allowing a ViewModel class to be referenced as a resource in the XAML.

 

Using the ViewModel we get a slightly unconventional triad structure:

 

The ViewModel class is able to work part of the UI in the form of Command objects for handling state interactions. Also it gets access to part of the Model data needed for the specific view. This model data is transitory, and can be committed back into the model when the view changes are complete.

 

A common question with MVVM is “How is it different to MVC and MVP”?

 

The MVC parts are extremely loosely coupled. Also the Controller does not do much more than pass messages to the Model or View while the ViewModel is responsible for doing a lot more.

 

The MVP looks similar at a glance, but in MVP the Presenter is the more dominant than the View. In MVVM the View owns the ViewModel. Also the ViewModel only exists if there is a View, while in MVP there can be multiple views to a Presenter.

 

 

Conclusions

 

So which do you use? Well, personally I would almost always stick the MVC pattern because there are many great frameworks available:

 

Ruby on Rails, Spring MVC, ASP.NET MVC, Monorail, etc

 

I think MVP looks useful, but I only know of one a couple of frameworks:

 

MVC#

Web Client Software Factory - MVP Bundle  (Thanks Jeronimo for point this one out!)

Yes, peculiar as it might sound, MVC# is actually an MVP framework.

 

However, if I had to implement a pattern myself, it could go either way. I have recently spent time refactoring a “Smart UI” into an MVC structure in a Windows C++ application. In hindsight I think it would have been easier to refactor it into a MVP structure, because it’s hard to separate controller logic from the view with CWnds andit would involve less refactoring steps.

 

I think PAC/HMVC sounds very cool but I doubt I would ever run into a scenario where the optimization would be make it worth while. Looks like it could be fun to play with though.

 

And of course MVVM is pretty much the only game in town if you want to write a WPF or Silverlight application.

 

Sources


Everything described here was pieced together from various places. Here are some of the them:


General


http://haacked.com

http://ctrl-shift-B.com


SmartUI 

http://blog.codeville.net/


PAC 

http://www.dossier-andreas.net


MVVM

http://www.acceptedeclectic.com

 

 

Tuesday, June 30, 2009 #

Cool Sessions


Experience Agile Practices - Don Gray


Agile with lego! We split into teams of 6-7 people (one of which being the product owner) and worked on projects to build a lego animal, with an enclosure and vehicle (although our enclosure ended up being the vehicle. It met requirements!).


Work was split into iterations (design, build, retrospective), with a set of story cards for each rounds. Stuff like:


“It must have two legs”

“It must have wings”

“It must be have a single color”

“It must have four legs”.


Lego AnimalIt was a blast! And yes 2 of the requirements contradicted. Because that would never happen in real life! And of course on completing the first round of iterations we got a bunch of new story cards which required changing. just about everything! If only we’ed thought to ask the product owner about future plans first…


If anyone is looking to for Agile Training, I thoroughly recommend looking up Don. His webpage is here.

 


Inside Linq – Jim Wooley

Cooking curry

When I’ve been out drinking, I sometimes get the urge to go out for a really hot curry at the local indian restaurant. I know full well its going to be to spicy for me but I just can’t resist the challenge. See where I’m going with this?


“Inside Linq” was listed as Advanced in the convention program. And yep, it was plenty spicy, like advertised! A lot of it went over my head, I think I at least got the gist. Mostly it boiled down to an explanation of how Linq works under the covers using IEnumerable and IQueryable and how you can see this through Reflector.


My mind imploded a bit on but I think I at least got the gist. I think I’d understand the rest if I just take the time to play around a bit.



Introducing the MVVM Pattern – Brian Genisio


I haven’t done much with WPF or Silverlight yet, but I couldn’t resist looking in on this presentation because I’ve recently being investigating various User Interface patterns for a future lightning talk.


Brian’s talk gave me quite a bit of added insight on MVVM that I hadn’t picked up in my previous research, and the examples of mini code patterns used to implement MVVM. I would have liked to have attended the Open Space Brian hosted immediately on the topic immediately afterwards, but I really needed to go see that Mono presentation…


Mono, Making .NET portable – Dennis Hayes


I’ve had a soft spot for Mono ever since my lightning talk at CONDG, so it was a great opportunity to totally geek out. It was good to know that it’s a lot easier to get up and running for development nowadays and I learned that there is now a Live CD and downloading VMware. Maybe I’ll go play with Mono more sometime soon…

 


Open Spaces


I already raved lots about Open Spaces in my CodeMash report, so not going to say too much about it this time. One difference, I hosted my own session this time around, on Pomodoro. Predictably it didn’t quite go as I envisioned, instead of learning about how to fine tune Pomodoro, I ended up teaching about what it is and how it works which was fun. Also got to see some neat Pomodoro clients. Shame they were for the mac!

 OpenSpace Session

As with last time, credit goes to Alan Stevens for making the event work.

 


Parties

I think it’s safe to say I had fun:

Drink!


Party!


Acknowlegement: CodeStock photos are courtesy of Alan Barber and Alan Stevens. As everyone knows all Alans are keen photographers...