DHH: The Great Surplus

There’s a great recording of a David Heinemeier Hansson talk (the Rails guy) on ITConversations. I think he’d make a great keynote speaker, though I’m not expecting to see him at the Tech.ED 2009 keynote. The talk is titled the Great Surplus, and although the talk description paints it as a heavy Rails talk, it’s a very interesting talk on framework design in general, and more importantly, about reinvesting the savings you make in picking good technology by investing in yourself.

Bindable LINQ: Getting Started

Continuing the documentation theme, this is the "getting started" page from the CHM. Please note that some of the links are broken; they’re designed to link to different pages within the CHM which I haven’t written yet. Question: should I include a VB.NET version of the guide (on a different page)?

This step-by-step guide will walk you through setting up your first project using Bindable LINQ.

Scenario

In this walkthrough you will create a new Windows Presentation Foundation project which uses Bindable LINQ to filter an array of strings as a user types.

Window1

Requirements

Bindable LINQ is compatible with the .NET Framework version 3.5 and above. To follow this guide, you will need to install Microsoft Visual Studio 2008 Standard edition, or you can install the free editions of Microsoft Visual C#/VB.NET 2008 Express.

Steps

  1. Download Bindable LINQ
    You can either download the latest stable release from the Codeplex releases page, or download the latest source code and build it yourself. To compile the project yourself, read the section "Building Bindable LINQ".
  2. Create a new WPF Application project
    Using any edition of Visual Studio 2008 which supports WPF, create a new WPF Application project using either C# or VB.NET.
    NewProject
  3. Add a reference to Bindable LINQ
    Extract the downloaded archive of Bindable LINQ to a folder of your choosing, or if you built it yourself, locate the build outputs folder (see the Building Bindable LINQ page for details). From Visual Studio, select Add Reference…
    AddProject
    From the Browse tab, navigate to the Bindable LINQ directory and add a reference to Bindable.LINQ.dll. This is the only reference you will need.
    AddReference2
  4. Build the GUI
    You will need a ListBox to show the list of names, and a TextBox to filter them.
    <DockPanel>
        <TextBox x:Name="_textBox1" DockPanel.Dock="Top" />
        <ListBox x:Name="_listBox1" />
    </DockPanel>
  5. Add a using directive for the core Bindable LINQ namespace

    In order to use Bindable LINQ, you will need to add a "using" entry for the Bindable.Linq namespace:

    using Bindable.Linq;
  6. Initialize a list of names and write the query 

    Create an array of first names, and then use a Bindable LINQ query to filter and order them.

    public Window1()
    {
        InitializeComponent();
    
        var names = new [] { "Paul", "Michael", "Sally", "Sally", "Mary" };
        _listBox1.ItemsSource = from n in names.AsBindable()
                                where n.StartsWith(
                                    _textBox1.Text,
                                    StringComparison.CurrentCultureIgnoreCase
                                    )
                                orderby n
                                select n;
    }
  7. Run!

    The application should compile and run at this point. As you type in the TextBox, Bindable LINQ will detect changes to the TextBox (since you called it from your "where" query), and will re-evaluate the items in the collection.

It’s that easy. To see the experience of using standard LINQ to Objects, remove the "AsBindable" call and run the query again.

To see more ways to use Bindable LINQ, see the Examples, Sample Applications, or Bindable LINQ Patterns pages.

Bindable LINQ: F# is Overhyped

Edit: This post was written tounge-in-cheek to suggest that developers currently excited about the sudden interest in functional programming may find reactive programming interesting also. It was not meant to seriously suggest that F# or functional programming is “useless”, or that the people responsible for F# are in any way wasting their time. I think F# is a brilliant language, and I apologize if anyone was offended by this post.

You can’t walk down the street these days without being told that F# is the next big thing. It’s easy to be taken in by the pomp and pageantry surrounding the functional programming paradigm, and in many ways it’s a bit of an emperor’s new clothes dilemma: most people can see functional programming is, for the most part, useless, but no one wants to admit it :)

What some people (mostly people on the CLR and C# language team) forget, is that there are alternatives to console applications. Here’s the typical User Experience of an F# program:

image

There’s only one thing that’s constant in our world: change. Inputs change, assumptions change. So why is everyone so enthralled with a programming paradigm that has such abysmal support for handling change?

Your highly concurrent, lambda powered, currying pattern-matching data analysis algorithm, running over 87 threads and 8 cores, is a pretty good effort. But once it’s analysed the 3,000,000 visits to your web site and told you what products to put on discount, what happens to the 3,000,001′th visitor? Well, once your functional code arrived at a result, it kinda forgot how it got there. So you have to run the whole thing again for a minor change in the inputs.

Wouldn’t it be great if you could write code in a functional programming language, but which automatically detected changes and re-evaluated itself? A kind of event stream processor. As visits come in your algorithm is being constantly evaluated, quickly, and the results updated. It’s the difference between being able to react in real-time, and having to wait for the hourly report to be generated.

As it turns out, there’s a paradigm for that: it’s called functional reactive programming. And unlike normal functional programming, it actually has uses outside of console applications :)

F# developers go gaga over pattern matching:

let getWarningMessageAboutTooManyToppings toppings =
  match toppings with
  | 0 -> "You didn't select any toppings"
  | 1 -> "You should have more toppings"
  | _ when toppings < 5 -> "That's a healthy number of toppings"
  | _ -> "Too many toppings on your pizza, fatboy" 

Now that’s great, but what happens when I select a new topping? I guess that’s what "Refresh" buttons are for.

Here’s a functional reactive version of pattern matching, supported via Bindable LINQ’s Switch operator (you’ll find this in the PizzaLinq sample application in the Bindable LINQ code).

_healthWarningMessage = _selectedToppings.Count().Switch(
    Case.When<int, string>(toppings => toppings < 1,
        "Surely you would like more toppings?"
        ),
    Case.When<int, string>(toppings => toppings >= 3,
        "You have too many toppings!"
        ),
    Case.Default<int, string>(
        "Just right!"
        )
    );

In Bindable LINQ, when I select a topping on the UI the result of the Count() call will change, which will re-evaluate the Switch operator and return me a different message. There’s no Refresh buttons and no code to wire it up. It’s functional, but it’s also useful.

If you could get enough programmers working on a reactive .NET language, it’s conceivable that you could combine the implicit parallelism of functional languages with reactive languages in order to process changes and have a result that’s continually updated from multiple threads. Unfortunately, all the smart developers are focused right now on a paradigm that’s severely limited to back-end or discreet, point-in-time operations, rather than a more wide-ranging paradigm like that of functional reactive programming.

If you’re a language wonk and you’re considering learning F# and functional programming for fun, consider reactive programming instead.

Bindable LINQ: What is Bindable LINQ?

I am writing a set of documentation for Bindable LINQ which will be available via the web or as a downloadable CHM. I’ll blog each part as I go for feedback. Here’s an outline:

image

Below is the "Bindable LINQ/Background" page, which describes what Bindable LINQ is. What do you think?

Overview

Bindable LINQ bridges the object-oriented world of .NET, and the paradigm of reactive programming. While the procedural, object oriented or functional programming paradigms focus on discreet evaluation of code, the reactive programming paradigm instead focuses on continuous evaluation, and propagation of change. Bindable LINQ leverages the syntax of LINQ and the platform support of Data Binding to enable advanced scenarios that would otherwise require reams of code.

Bindable LINQ is not a library for querying databases or web services. For more information on where Bindable LINQ fits into your application architecture, see the section on Bindable LINQ patterns.

Reactive Programming

To understand the difference between discreet and continuous evaluation, consider the following C# code:

decimal total = 0;
IList<LineItem> lineItems = ...;
foreach (var item in lineItems)
{
    total += item.Quantity * item.Price;
}

The value of the total is derived from the lineItems collection. But in this case, once the foreach loop has completed and the total variable assigned, this relationship is lost. If the lineItems collection, from which the total was derived from, changes, the total will not change. You can think think of this code as representing a "point-in-time" snapshot of the total.

In a reactive programming language, the relationship between the source - lineItems - and the destination - total - should be maintained at all times, and changes to the source should be propagated.

Bindable LINQ allows you to use the familiar syntax of LINQ queries in a reactive programming way. For example, the order totaling code above could be written in Bindable LINQ as:

ObservableCollection<LineItem> lineItems = ...;
IBindable<decimal> total = lineItems.AsBindable().Sum(li => li.Quantity * li.Price);

LINQ

LINQ to Objects is an implementation of LINQ that ships with the .NET Framework and allows querying over in-memory collections such as generic Lists or Arrays. However, once the query has been evaluated and the results have been yielded, subsequent changes to the source collection are not propagated. LINQ to Objects is a purely discreet evaluation and assignment construct.

Bindable LINQ follows the same rules as other LINQ providers and works in-memory, just like LINQ to Objects, except the relationship to the source collection is changed. When the source collection raises events indicating that something has changed, Bindable LINQ will propagate the changes throughout the LINQ query, evaluate the changes, and any derived values will be updated.

Data Binding

Data Binding is a UI platform technology that allows properties of UI controls to be synchronized with properties of objects. To facilitate propagation of change, these objects can implement a number of interfaces, primarily INotifyPropertyChanged, IBindingList and INotifyCollectionChanged.

Bindable LINQ queries implement these data binding interfaces so that UI controls can be connected and kept in-sync with Bindable LINQ queries automatically. This leverages the platform’s support for data binding, while removing the limitation of data binding patterns as a UI-control level only concept.

Summary

Bindable LINQ leverages the familiar syntax of LINQ and the platform’s support for data binding to bring reactive programming to the .NET Framework. You express what you need, and Bindable LINQ takes care of wiring up event handlers, detecting changes and the complexities of propagating those changes.

WPF: Colour Blindness Shader Effect

How does your application look to people with colour blindness?

Joseph Cooney launched a community project last week to create a repository of useful pixel shader effects for WPF. It’s already got a number of effects, including a very cool radial blur effect. Rather than just blogging a link, I wanted to contribute to the library and build a shader that I’ve been thinking about for a while.

Twelve percent of Australian men, and 0.5% of women have some degree of colour vision deficiency, which makes up a significant segment of the audience for many applications. To aid in testing, the ColorBlindnessEffect allows you to simulate how your WPF application will look under various classifications of colour vision deficiencies. Here are some images of Joseph’s sample application running with Normal, Protanopia (loss in the red-yellow-green spectrum) and Tritanopia (loss in the blue-yellow spectrum):

clip_image001clip_image001[5]clip_image001[7]

The effect provides eight filters:

  1. Protanopia
  2. Protanomaly
  3. Deuteranopia
  4. Deuteranomaly
  5. Tritanopia
  6. Tritanomaly
  7. Archromatopsia
  8. Archromatomaly

You can learn more about colour blindness on Wikipedia.