Dev Logging

printf("does this work\n");
in
Creating Objects with Observable Properties in JavaScript

Regular readers will notice that I’m quite taken with JavaScript recently. I’ve been looking at using it to build a really simple role playing game for the browser. Really old school. Think Dragon Warrior. I’ve just gotten started, but I’m already so impressed by the power and flexibility of the language that I had to get on here and yammer about it for awhile.

One of the core ideas in JavaScript is that every object is a hash, a collection of name-value pairs. This is a really simple and powerful concept, but it’s not always clear how to set up more advanced behaviors. For example, I want to have the notion of observable properties in my game. First, let’s define “observable properties.” If you’re familiar with C#, think about the INotifyPropertyChanged interface:

public class Actor : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

So consumers can hook up to an instance’s PropertyChanged event and get notified when something changes. As a side note, look how much it sucks to do this in C#. Suppose I had several properties to raise change notifications on. I’d have to type out that same blob of repetitive and error prone logic for each one, and I can’t really see any good way of compressing this. Why do I have to write so much code to express such a simple idea? I digress.

Anyway, I think this will allow me to factor the game logic cleanly, instead of having a battalion of special cases built into my game engine. Maybe I want to have a status table monitoring the hero’s stats and displaying them, but I also want to have a console logging out events. Or any other number of use cases: I’ll probably want to watch the hero’s hit points and end the game if they ever turn to zero. Maybe some monsters will observe their own hit points and behave differently when they’re low on health.

So I need observable properties. And I definitely don’t need to write seven lines of code per property per object for every single thing ever. Ideally, I’d like to be able to say something like this:

var hero = createObservable({
    name: 'ERDRICK',
    hitPoints: 10,
    strength: 18,
    agility: 12
});

And have it work the way you’d expect, registering all the supplied properties (with the specified defaults) as observable on our new object. So how can we do this? Well, first we need to pull out the mediator/event aggregator/event hub/whatever I talked about here. Here’s the code for it, though I won’t go into detail explaining it here:

var createMediator = function () {
    var events = {};
    return {
        subscribe: function (eventName, callback) {
            events[eventName] = events[eventName] || [];
            events[eventName].push(callback);
        },
        publish: function (eventName) {
            var i, callbacks = events[eventName], args;
            if (callbacks) {
                args = Array.prototype.slice.call(arguments, 1);
                for (i = 0; i < callbacks.length; i++) {
                    callbacks[i].apply(null, args);
                }
            }
        }
    }
};

Calls to createMediator will give us a fresh mediator for subscribing to and publishing events. This is key because each observable object is going to need its own mediator. Now we need to flesh out our createObservable function. To understand it, it’s going to be critical to understand how closures work.

In JavaScript, functions are values. We can pass them around, create new ones inline, and return them from other functions. The last one is really key, and you’ll see why in a second. When we create a function inline, it creates a new scope, but it can still refer to objects from the surrounding scope. Doing so creates a closure. Here’s an example:

var createClosure = function (param) {
    return function () {
        return param;
    };
};
var closure = createClosure('stuff');

createClosure is a function that returns a trivial function. Notice that the inner function we return outlives its parent scope. This means that, while param goes out of scope, it remains alive because the function returned holds a reference to it. Notice also that there’s no way we can change param through our closure object. closure is totally opaque to consumers. This means we can use closures to create private attributes in an object. Hopefully this makes sense; if not, a better explanation can be found here.

Ok, let’s flesh out createObservable. Here’s a shell:

var createObservable = function (properties) {
    var notifier = createMediator(), observable;
    return observable;
};
We have our notifier, which is an instance of our mediator, and we have our observable object, which is currently nothing. Let’s build this out more by defining an interface to an observable object. There are really two things we want to do: register observable properties and observe existing ones. 
var createObservable = function (properties) {
    var notifier = createMediator(), observable;
    observable = {
        register: function () {
            // ???
        },
        observe: function () {
            // ???
        }
    };
    return observable;
};

observe should be pretty obvious, since it’s just going to be a thin wrapper over our notifier’s subscribe function. Let’s fill that in now.

observable = {
    register: function () {
        // ???
    },
    observe: function (propName, observer) {
        notifier.subscribe(propName, observer);
    }
};
Note that, since functions are simply values in JavaScript, we could just say this:
observable = {
    register: function () {
        // ???
    },
    observe: notifier.subscribe
};
I’m a little bit lukewarm on doing this. My gut tells me the more verbose form is clearer, so I’m going to leave things spelled out. (Also, if you’re in an environment with intellisense, it’s nice to have the semantics of propName and observer as your parameter names rather than eventName and callback.)

What about register? register is more complicated. We want something like this:

observable = {
    register: function (propName, value) {
        this[propName] = createObservableProperty(propName, value);
    },
    observe: function (propName, observer) {
        notifier.subscribe(propName, observer);
    }
};

Knowing that all objects in JavaScript are hashes, we hash our object on propName and set it equal to an observable property. Of course, this doesn’t really answer our question, since now we need to define createObservableProperty. Let’s take a look at the big picture:

var createObservable = function (properties) {
    var notifier = createMediator(), createObservableProperty, observable;
    createObservableProperty = function (propName, value) {
        // ???
    };
    observable = {
        register: function () {
            this[propName] = createObservableProperty(propName, value);
        },
        observe: function (propName, observer) {
            notifier.subscribe(propName, observer);
        }
    };
    return observable;
};

We need to fill out createObservableProperty such that it returns something that knows how to handle property change notifications. If you’ve been paying attention, you know that the way we maintain this kind of private state is with a closure. Here’s our implementation:

createObservableProperty = function (propName, value) {
    return function (newValue) {
        var oldValue;
        if (typeof newValue !== 'undefined' &&
            value !== newValue) {
            oldValue = value;
            value = newValue;
            notifier.publish(propName, oldValue, value);
        }
        return value;
    };
};

This function we return is going to act as both a getter and setter (depending on whether or not the optional newValue parameter is passed in). Let’s follow along. First, note that propName and value are both tied up into this closure. This means they’re effectively private variables for our observable property. Our get/set function first checks to see if newValue was passed in (by checking against undefined) and then whether it’s a different value. If it is, we save the old value to a temp variable, set the new value, and then publish an event via our notifier specifying the property name and the old and new values. (If you’ll recall, callbacks to our events can care/not care about those passed parameters as they wish.) We end by returning the value.

This is pretty much all we need! Here’s the complete implementation:

var createObservable = function (properties) {
    var notifier = createMediator(), createObservableProperty, observable;
    createObservableProperty = function (propName, value) {
        return function (newValue) {
            var oldValue;
            if (typeof newValue !== 'undefined' &&
                value !== newValue) {
                oldValue = value;
                value = newValue;
                notifier.publish(propName, oldValue, value);
            }
            return value;
        };
    };
    observable = {
        register: function (propName, value) {
            this[propName] = createObservableProperty(propName, value);
        },
        observe: function (propName, observer) {
            notifier.subscribe(propName, observer);
        }
    };
    return observable;
};

This is really all we need to get going, but you may have noticed that we’re still not doing anything with the properties passed in! Less than ideal. We’ll register them all at once just before returning:

for (propName in properties) {
    observable.register(propName, properties[propName]);
}

Pretty simple. There’s one more thing I’m going to add, but it’s not required. It might be nice (for various reasons) to know what observable properties an object has. Adding this is easy:

observable = {
    register: function (propName, value) {
        this[propName] = createObservableProperty(propName, value);
        this.observableProperties.push(propName);
    },
    observe: function (propName, observer) {
        notifier.subscribe(propName, observer);
    },
    observableProperties: []
};

observableProperties is an array. When we register a new property, we push propName onto the array.

Now, as always, we’re going to wrap everything into a big global object to minimize our footprint on the global namespace. Like so:

var DW = function () {
    var createMediator, createObservable;
    createMediator = function () {
        // ...
    };
    createObservable = function (properties) {
        // ...
    };
    return {
        log: function () {
            var line = $('<div></div>');
            return function (message) {
                $('#console').append(
                    line.clone().text(message)
                );
            };
        }(),
        hero: createObservable({
            name: 'ERDRICK',
            strength: 18,
            agility: 12
        })
    };
}();

Notice that we don’t even expose our createMediator or createObservable objects. We only expose log, a function for writing messages to our console (note the use, as always, of the incomparable jQuery), and hero, our dude with observable properties name, strength, and agility. Notice how easy it is to create observable objects in a clean and concise way, and then go back to the beginning of this post and compare it to the lengths C# makes you go. Absurd.

Let’s add some code on our page to make use of all this nifty stuff.

$(function () {
    DW.hero.observe('strength', function (oldValue, newValue) {
        DW.log('courage and wit have served thee well! thy strength increases from ' + oldValue + ' to ' + newValue);
    });
    DW.hero.observe('agility', function (oldValue, newValue) {
        DW.log('courage and wit have served thee well! thy agility increases from ' + oldValue + ' to ' + newValue);
    });
    
    $('#incStrength').click(function () {
        DW.hero.strength(DW.hero.strength() + 2);
    });
    $('#incAgility').click(function () {
        DW.hero.agility(DW.hero.agility() + 3);
    });
});

This code is really simple. We’re hooking up a couple observers to the strength and agility properties that will simply log messages to the console when the property changes. We then hook up some click handlers to buttons to increase the hero’s strength and agility by arbitrary amounts. Note the use of the observable properties in the click handlers both as getters (to find the current value) and setters. Let’s add some more observers, just to prove we can have lots of people watching at once. This is going to be a little more complicated, but not too bad (I hope):

var i, statName, stats;

stats = DW.hero.observableProperties;
for (i = 0; i < stats.length; i++) {
    statName = stats[i];
    $('#status').append(
        $('<div></div>')
            .attr('id', statName)
            .text(statName + ': ' + DW.hero[statName]())
    );
    DW.hero.observe(statName, function (statName) {
        var selector = '#' + statName;
        return function (oldValue, newValue) {
            $(selector).text(statName + ': ' + newValue);
        };
    }(statName));
}

(This is all still in the jQuery document.ready handler.) This is basically to set up a status area to tell us the hero’s relevant stats. Notice that we’re using observableProperties to get all the relevant properties. We basically set up observers for each one to update the stats. The call to observe is a little complicated. We’re actually passing in the returned function as our parameter. (Notice the immediate invocation of the wrapping function with parameter statName. This is done to avoid a common gotcha with closures—we want statName as it is now, not as it will be at the end of the iteration.)

That’s pretty much it! Let’s fire it up and prove that it works:

image

Hope this helps.

Referring to Enums (and Other Nested Types) in XAML

This is going to be a brief post, because it’s really just about making the XAML parser happy in an obscure case.

I ran into a problem when I tried to refer to an enum in XAML. This isn’t something you need to do often, but sometimes you need the full, qualified name. Suppose I have a class like this:

public class SuperMario2
{
    public enum Characters
    {
        Mario,
        Luigi,
        Toad,
        Princess
    }
}

Now suppose I have a need to refer to these in XAML. I might try something like this:

{x:Static local:SuperMario2.Characters.Mario}

But the compiler complains:

image

I couldn’t figure out why this wouldn’t work, until I realized that the problem isn’t specific to enums. The problem is that nested types aren’t supported in XAML, and this is just one instance of that. Fortunately, I found this post on MSDN that reveals an undocumented trick to make this work. (Scroll about 3/4 of the way down.) It turns out that what you actually want to do is this:

{x:Static local:SuperMario2+Characters.Mario}
And the compiler is happy.

Hope this helps.

Cascading Implicit Styles in WPF

I was all set to write a post detailing a cumbersome workaround for getting implicit styles to cascade in WPF, when I figured out there’s an easier way. Actually, I think it’s probably common knowledge to a lot of people, but I figured I should post it here in case anyone (like me) is in the dark. (After digging around a little, I couldn’t find anything about this in the Sells book. It’s hinted at on p. 315 of WPF Unleashed, but not stated explicitly.)

Implicit style in WPF are styles you don’t need to refer to by name. They simply apply to all elements in scope belonging to the specified type. An example will help.

Suppose I’m writing a new app, and I decide that every TextBlock should have red text. (Warning: I am not a designer.) I might create a style like this in my App.xaml:

<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Application.Resources>

Note that we do not specify a key on the style. We don’t need to. We do need to make sure to specify the target type; otherwise, WPF can’t know which elements we want this style to apply to. Let’s drop some code in to test that this works:

<StackPanel>
    <Grid>
        <TextBlock Text="where my implicit styles at" />
    </Grid>
    <Grid Grid.Row="1">
        <TextBlock Text="where my implicit styles at" />
    </Grid>
</StackPanel>
If we run the app, we can see that it works:

image

Perfect. Now, suppose I want to add another style to apply only to some of my text. I might scope it like this:

<StackPanel>
    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="FontSize" Value="24" />
            </Style>
        </Grid.Resources>
        <TextBlock Text="where my implicit styles at" />
    </Grid>
    <Grid Grid.Row="1">
        <TextBlock Text="where my implicit styles at" />
    </Grid>
</StackPanel>
I’ve created another implicit style to increase the font size of any TextBlocks I place in the top Grid. Let’s try running this and see what happens.

image

Hmm. That’s not quite what we wanted. Our new implicit style seems to have overridden the old one. To understand why, we need to think a little bit about how implicit styles actually work. When we specify a style explicitly, WPF walks up the chain of resource dictionaries and looks for one with the specified key. It returns the first (most local) one it finds. In light of this, it’s not clear how our implicit styles get applied, since we didn’t specify any keys for them. If we think about it a little, we can work it out.

We know the styles have to have some keys; otherwise, how would they fit into the resource dictionaries? What’s not clear is how the key is chosen. One might suspect some randomly generated value to serve as the key, but the answer is much simpler: the target type is the key. (This is mentioned on p. 315 of WPF Unleashed.) Armed with this knowledge, we can easily understand implicit styles. For any elements where the style is not explicitly specified, look for the element’s type in the resource dictionary chain and return the most local one you find. So in our example, we have two such styles: one at the application level and one scoped just to the Grid. It finds the local style first and stops looking.

Now that we have a good understanding of the problem, the solution is pretty obvious. Since we know our implicit style does have a key, we can use it as a base for our new style like this:

<StackPanel>
    <Grid>
        <Grid.Resources>
            <Style TargetType="{x:Type TextBlock}" 
                   BasedOn="{StaticResource {x:Type TextBlock}}">
                <Setter Property="FontSize" Value="24" />
            </Style>
        </Grid.Resources>
        <TextBlock Text="where my implicit styles at" />
    </Grid>
    <Grid Grid.Row="1">
        <TextBlock Text="where my implicit styles at" />
    </Grid>
</StackPanel>

We’ll run the app to make sure it works:

image

Neat.

This isn’t a perfect solution, since we still need to be aware when we’re stomping on our previous styles, but I think the benefits of implicit styles are more than worth the price.

Like I said, I’m sure a lot of people know about this already, but I was oblivious until now, so I thought I’d share.

Hope this helps.

 

EDIT: Just as an addendum, I want to point out that you can have implicit styles with explicit keys. You just need to make sure that the key is the same as it would be if generated implicitly; that is, the key must be the target type. So when you see code like this:

<Application.Resources>
    <Style x:Key="{x:Type TextBlock}" TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red" />
    </Style>
</Application.Resources>

Understand that this is still an implicit type.

Hope this helps.

AJAX Logging with Exponential Backoff

I’ve been on something of a JavaScript kick lately. Despite its flaws, it’s a really expressive language that lacks you pack a lot of functionality into just a little bit of (still readable!) code. To that end, I spent some time this morning fiddling around with client-side logging. Specifically, I wanted to be able to make AJAX calls to log user actions from the browser back to the server. This wasn’t really driven by any actual project need, but I think it could be potentially useful in a few scenarios. Maybe you have a public-facing app, and you want to test usability; something like this could make it easy to figure out how people are navigating around your site. This could be especially useful if the site is AJAX-heavy already, or if it’s some kind of mash-up with a lot of calls to third parties.

How do we get started? Let’s build a simple page with a button:

<input id="btn" type="button" value="Click Me!" />

And this is how we want to make our calls:

CLARITY.log('clicked the button at ' + new Date());
Note the use of a global object to act as our namespace. This is a good idea because it lets you minimize your footprint on the global namespace. (I learned this from JavaScript master Douglas Crockford, who wrote the best book on the subject I’ve come across.) We’ll hook these up using a little jQuery. Don’t fret if you’re not too familiar with it; just believe me when i tell you this code will bind a callback to the button’s click event:
$(function () {
    $('#btn').click(function () {
        CLARITY.log('clicked the button at ' + new Date());
    });
});
Let’s go take a look at how CLARITY.log is defined.
var CLARITY = {
    log: function (message) {
        //do some logging, probably
    }
};

As in previous examples, we’re taking advantage of JavaScript’s support for object and function literals to create an object with a property (“log”) on it. The log property is mapped to a function that takes a message parameter and (we hope!) does something interesting with it. First, let’s define a web method for our logging function to call:

[WebMethod]
public static void Log(string msg)
{
    // logging happens here
}

I’ve just defined this as a page method. If you were really building something like this out, you might make it a web service call, instead. The difference is pretty transparent from the client-side, so I’m not going to go into it here. I’m also not going to flesh this method out. Server-side logging is a pretty well-explored problem. This is the place to do it.

Let’s take a first cut at our JavaScript logging method:

var CLARITY = {
    log: function (message) {
        $.ajax({
            type: 'POST',
            url: 'Default.aspx/Log',
            data: JSON.stringify({ msg: message }),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });
    }
};

We’re using jQuery again to make an AJAX call. I like jQuery’s AJAX interface; I think it strikes a good balance between simplicity and giving you complete control over your request. Many of the parameters we specify here are sort of boilerplate for making AJAX calls to ASP.NET (normally, I wrap AJAX calls in a helper method to mitigate this). For more information on this, Dave Ward’s blog is a great resource (this post in particular). The call to JSON.stringify comes from Douglas Crockford’s JSON utility. It’s kind of overkill in this scenario, but I thought I’d point it out, since it’s pretty useful for formatting data for AJAX calls.

To be honest, this is really all we need for logging. However, I thought it might be cool to add some fault tolerance. Maybe (for whatever reason) you’d prefer not to lose any of these logging messages when your server hiccups. We might try to solve that problem with an error handling function that tries again:

var CLARITY = {
    log: function (message) {
        var tryWrite = function () {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/Log',
                data: JSON.stringify({ msg: message }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                error: tryWrite
            });
        }
    }
};

Note that what we’ve done here is wrap our AJAX call in a function that quasi-recursively specifies itself as the error handler for the call. This means that every returned error message will immediately fire off another attempt. Note also that message is not used as a parameter for tryWrite; this is unnecessary because tryWrite creates a closure with message in scope.

This isn’t bad for a first attempt, but it has obvious problems. What if the server is down for more than a few seconds? This is going be firing off logging attempts continuously, and it will only get worse as the user continues to click around the page. This will tie up their bandwidth and bombard your server (once it recovers). It will also increase the CPU strain from their browser (though my testing shows this may be negligible). All bad things.

What can we do differently? We might try adding a timer to at least give a buffer between attempts. Something like this:

var CLARITY = {
    log: function (message) {
        var tryWrite = function () {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/Log',
                data: JSON.stringify({ msg: message }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                error: function () {
                    setTimeout(tryWrite, 5000);
                }
            });
        }
        tryWrite();
    }
};

Here tryWrite is wrapped in a call to setTimeout specifying tryWrite as the callback to be invoked in 5000ms. This will help to some extent. At least we won’t be firing off requests continuously until we succeed. But this still isn’t ideal. As the life of the page wears on, more and more of these will build up, and things will still eventually bog down. We can alleviate these problems with exponential backoff. You’ve probably seen something like this before. The idea is that, as we keep failing, we introduce longer and longer delays between attempts. This helps us to avoid spamming the server. Here’s a simple implementation:

var CLARITY = {
    log: function (message) {
        var delay = 1000, tryWrite;
        tryWrite = function () {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/Log',
                data: JSON.stringify({ msg: message }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                error: function () {
                    setTimeout(tryWrite, delay);
                    delay *= 2;
                }
            });
        }
        tryWrite();
    }
};

Note that, like tryWrite and message, delay is caught up in our closure, making it something like an implicit parameter. Here we use our delay to set our timer and then double the delay for the next (potential) failure. This guarantees that older failures will remain dormant most of the time, keeping the user from making too many extraneous calls.

This is still a fairly naive implementation, but I thought I’d throw it out there as an example. Hopefully someone can get some ideas from it. A more clever version might be more conservative after a failure (or maybe some small number of failures). It could go into a kind of hibernation state where it pings the server periodically and queues incoming messages to be sent once the server is back online. But that’s probably a topic for another post.

Hope this helps.

Custom Events in jQuery

A reader comment on my last post brought it to my attention that support for custom events actually already exists in jQuery! I decided to take a look at their solution. You can find an example here (click on “Examples” and scroll to the bottom). It’s pretty cool, but there are a couple things I don’t like about it.

Here’s the code from their sample:

$("p").bind("myCustomEvent", function(e, myName, myValue) {
    $(this).text(myName + ", hi there!");
    $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
});
$("button").click(function() {
    $("p").trigger("myCustomEvent", ["John"]);
});

You might not be totally familiar with jQuery, but the interface is pretty fluent, so I think this will be somewhat straightforward. The most important concept in jQuery is the wrapped set. You can basically pass in a string formatted like a CSS selector to grab a bunch of elements from the DOM. The first statement starts off by grabbing all the “p” elements and binding a custom element with a callback. The event is then raised on the button click in the next line. You can mostly ignore the contents of the callback function.

DISCLAIMER: The following complaints are based strictly on a quick look at this sample and a little nosing around in the jQuery source code.

Here’s what I don’t like. First, the custom event is bound directly to a set of DOM elements, and I can’t really think of any time I’d want to do this. If you’re working with custom events, they’re most likely going to be “application” events. “profileUpdated” or “commentSaved” or “itemDeleted”: those sorts of things. It doesn’t make any sense to me to tie something like this to a set of elements. One has nothing to do with the other. Why not just have a generic callback that selects all the “p” elements itself? For that matter, it seems like the usage they have here is pretty inconsistent; the event is bound directly to the “p” elements, but the callback then selects all the “span” elements. Doesn’t that mean those same operations will be carried out on every span as many times as we have p elements? If the callbacks aren’t tied to sets of elements, this problem goes away. Maybe there’s some other use case I’m not thinking of, but the whole thing seems semantically flawed. I think they probably did this to keep the API consistent with the standard DOM events, but I think they would have been better served doing something else.

My second complaint is a little bit of a guess, but the code in the sample seems to back it up. Look at how the event is raised. We’re allowed to pass in event arguments, but we have to pack them in an array ourselves. This is more of a minor complaint, but I do think it makes the API a little less nice to work with. This is kind of a shock. I think jQuery’s intuitive interface is its biggest strength; everything works pretty much exactly the way you’d expect it to. The main thing that allows this is that most functions have a lot of intuitive overloads, which is probably why they had to make this compromise. If you’re accepting an arbitrary number of arbitrary arguments, there’s really no way to tell what’s what. I can understand the compromise, but I don’t really like it.

To disclaim again, I really like jQuery, though I am a little unfamiliar with this part of the API. Just some uninformed thoughts on the subject.

A Lightweight Event Framework in JavaScript

I’ve been working on a project recently that’s very JavaScript heavy. This probably makes some of you cringe, but I think JavaScript is probably one of my favorite languages. True, it has a lot of terrible quirks and gotchas, but the core of the language is light, powerful, and expressive. For an example of this, I’m going to talk a little bit about a lightweight event framework I built in JavaScript for this project.

When I say “events,” I’m not talking about the DOM. This is obviously a solved problem. I’m talking about events in a more general sense; your application grows to a certain size, and it becomes convenient to pass messages around between components. Along the way, we’ll need to learn about a few (ok, several) of JavaScript’s foibles and a few advanced techniques. Let’s get started:

var CLARITY = {
    events: {}
};

Here I’m defining a global object (CLARITY) via object literal syntax. Object literal syntax allows you to define objects inline as a list of key-value pairs. Our object has one property (events), which is itself an empty object literal. This is one of my favorite features of JavaScript, since it gives you a lot of flexibility. You may be wondering why we need to wrap everything in our global object. This is because of a design flaw in JavaScript. It has no concept of namespaces, so everything defined at the top level goes on the global object (window). We can restrict our footprint on the global object by defining our own app-level object to wrap everything. This becomes really important when you start using third party libraries, since you don’t want to clobber someone else’s globals and introduce any subtle bugs.

Let’s flesh out our events object:

var CLARITY = {
    events: {
        subscribe: function(eventName, callback) { },
        publish: function(eventName) { }
    }
};

We’ve added two functions to events: subscribe and publish. Note that we’ve done this via anonymous functions, another really powerful feature of JavaScript. In JavaScript, functions are first-class. This means a function can be treated like any other kind of value. This is going to define our base API for our event framework. You can subscribe by passing an event name and a callback function, and you can publish an event with just the event name. Let’s describe our subscribe function:

var CLARITY = {
    events: function() {
        var events = {};
        return {
            subscribe: function(eventName, callback) {
                events[eventName] = events[eventName] || [];
                events[eventName].push(callback);
            },
            publish: function(eventName) { }
        }
    } ()
};

This is probably the most complicated single step, so don’t worry if it looks a little alien. First, notice that events is no longer a simple object literal. We now have an anonymous function that returns an object literal. This might seem confusing, but notice that it is invoked immediately. So events is really still being assigned the same object literal. We’ve added this extra piece of indirection to take advantage of closures. We’ve defined an empty object called events right inside the function. In JavaScript, scoping is at the function (rather than block) level. When we return the object literal, any references to objects defined within the function are captured. This means our events object lives on inside our subscribe-publish object, but no one else has direct access to it. This is a really powerful concept, and it gives us a lot of power over how we use objects in JavaScript.

Let’s turn our attention to the subscribe function. Our general strategy is going to be to use events as a hash table mapping event names to arrays of callback functions. This way, we can have multiple callbacks for a given event. We can easily accomplish this, because all objects in JavaScript can be thought of as hash tables. In fact, of these two lines, the second is merely syntactic sugar for the first:

events['something'] = function() { };
events.something = function() { };

So the first line of subscribe is checking to see whether a property with this event name exists on events. If not, it assigns an empty array literal. We do this by using the or operator. If the first value is undefined, it evaluates to false, and we take the second value. The or operator is often called the guard operator when used like this. Now that we know there’s an array in place for us to use, we push our callback onto it. This is pretty much it for our subscribe function.

Publish is even simpler:

var CLARITY = {
    events: function() {
        var events = {};
        return {
            subscribe: function(eventName, callback) {
                events[eventName] = events[eventName] || [];
                events[eventName].push(callback);
            },
            publish: function(eventName) {
                var i, callbacks = events[eventName];
                if (callbacks) {
                    for (i = 0; i < callbacks.length; i++) {
                        callbacks[i]();
                    }
                }
            }
        }
    } ()
};

We check to make sure the event exists, then iterate over the array and invoke all our callbacks. Fairly straightforward. We can check that this works with the following simple code:

CLARITY.events.subscribe('something', function() {
    alert('event received!');
});

CLARITY.events.publish('something');

Which produces the following result:

image

Sweet. This works for simple cases, but it would be a lot more useful if we could actually pass some payloads around. It’s not immediately clear how to go about this, but there are ways:

var CLARITY = {
    events: function() {
        var events = {};
        return {
            subscribe: function(eventName, callback) {
                events[eventName] = events[eventName] || [];
                events[eventName].push(callback);
            },
            publish: function(eventName) {
                var i, callbacks = events[eventName], args;
                if (callbacks) {
                    args = Array.prototype.slice.call(arguments, 1);
                    for (i = 0; i < callbacks.length; i++) {
                        callbacks[i].apply(null, args);
                    }
                }
            }
        }
    } ()
};

Notice the reference to arguments that seems to come out of nowhere. Arguments is actually an implicit local variable in every function. It’s an array-like object that holds each argument passed to the function. This allows for some interesting metaprogramming possibilities. JavaScript doesn’t enforce the defined parameters for function calls, so you can pass as many (or as few) as you’d like. They’ll be bound to the defined parameters in the order they’re passed, until you run out of defined parameters. If you want any other parameters, you’ll need to use arguments.

The phrase “array-like object” may stand out. Because of a strange design decision, arguments is not an array, but an object with properties named 0, 1, 2, etc., and a property named length. The first line inside the if statement is a sort of hack to make an array out of arguments. We can call the slice function (which takes a subset from an existing array) directly from Array’s prototype with the call function. These are equivalent:

var array = [1, 2, 3, 4], slice;
slice = array.slice(2);
slice = Array.prototype.slice.call(array, 2);

When we call slice directly from our array instance, the instance is the context of the function invocation. This means that “this” will be bound to the instance. If we were to call slice directly from the prototype:

slice = Array.prototype.slice(2);

“this” would be bound to the global object. (For some reason . . .) The call function allows us to specify a binding for “this” followed by the normal arguments the function is expecting. Arguments is not an array, but it has enough similar properties that the function behaves correctly and returns a new array. Note that we specify 1 as our starting index, so that args is an array of all arguments passed in other than the event name.

Now that we have an array of payload arguments, we need a way to send it to our callback. We could do this:

callbacks[i](args);

But this is less than ideal. This would require our callback function to treat its expected payload as an array, even if it only wanted one value. Fortunately, we have the apply function.

Apply is a sister function to call. It’s the same insofar as allows you to specify a scope binding for the function, but it handles the passed arguments differently. Whereas call expects the parameters separately, apply takes an array. (Well, actually, it takes an array-like object, but arrays are extremely array-like.) The values in the arguments array are then bound to the defined parameters of the function in question, so you can use them as expected. Take this example:

CLARITY.events.subscribe('something', function(one, two) {
    alert('event received with payload: ' + one + ' and ' + two);
});

CLARITY.events.publish('something', 'does this work?', 'you know it!');

This yields the desired result:

image

Note that the parameters don’t need to be strings; they can be any kind of objects:

CLARITY.events.subscribe('something', function(data) {
    alert('event received with payload: ' +
        data.one + ' and ' + data.two);
});

CLARITY.events.publish('something', {
    one: 1,
    two: 'two'
});

With result:

image

I’m not sure if stuff like this already exists. Searching for JavaScript events obviously gets you a lot of stuff about DOM events. Anyway, I thought this was kind of cool, so hopefully someone can get some ideas from it.

Parameter Passing: By Value vs. By Reference

I was reading some old posts on Wil Shipley’s excellent blog the other day, when a subtle (and very common) error caught my eye. I don’t mean to call Wil out by this; I was reading his blog specifically because I think he has great advice about software development. The error in question was talking about some of the problems with the outdated Carbon framework that much of Apple’s older software is built on. The following caught my eye:

Parameters passed into functions are passed by reference, whether they are going to be modified or not, which is just obscure. For example, see SecKeychainItemCopyAttributesAndData(), which takes the input "info" by reference, even though it's read-only!

For those who don’t know, the Carbon framework is written (I believe completely) in C. Can you spot the semantic error? The following quote from K & R will explain:

In preparing for the call to a function, a copy is made of each argument; all argument-passing is strictly by value. A function may change the values of its parameter objects, which are copies of the argument expressions, but these changes cannot affect the values of the arguments. However, it is possible to pass a pointer on the understanding the function may change the value of the object to which the pointer points.

In C, every parameter is passed by value. Now, I’m sure Wil knows the this and simply misspoke, but a lot of people make this mistake, so I’d like to take the time to explain the difference.

All parameters in C are passed “by value.” This means that, when a function is invoked, copies are made of each of its arguments for the function to use freely. When we say a parameter has been passed “by reference,” we mean that the function has received the actual object passed to it and not a copy. It’s easy to mistakenly believe C includes this concept because C++ does; one being a (not quite strict) superset of the other, it takes familiarity with both to know where one stops and the other begins. What Wil is really talking about when he mentions passing parameters “by reference” is passing pointers by value. While the function receives a copy of the pointer passed to it, both still point to the same location in memory. The function can then make changes to the memory pointed to, which the caller will see. This is how shared references between function and caller are done in C. (This also makes the benefits of C++’s added “pass by reference” semantics a little unclear to me.) Let’s explore the differences with a couple concrete examples.

#include <stdio.h>

void chgval(int *ip)
{
    printf("*ip in chgval before change: %d\n", *ip);
    *ip = 5;
    printf("*ip in chgval after change: %d\n", *ip);
}

int main(int argc, char **argv)
{
    int i = 3;
    int *ip;
    ip = &i;
    printf("*ip before chgval: %d\n", *ip);
    chgval(ip);
    printf("*ip after chgval: %d\n", *ip);
    return 0;
}

Here we define a pointer to an int (ip) and assign to it the address of an int (i). If you’re not familiar with the semantics of C, just know that, in this example, “ip” refers to the address of an int, whereas “*ip” is the int itself. Inside the chgval function, we assign a new value to *ip. Note that the address it points to is unchanged, so this reassignment can bubble back up to the caller. When we run this program, we see the expected output:

image

However, if you don’t know that parameters in C are passed by value, you might attempt to make other changes.

#include <stdio.h>

void chgptr(int *ip)
{
    printf("*ip in chgptr before change: %d\n", *ip);
    int i = 5;
    ip = &i;
    printf("*ip in chgptr after change: %d\n", *ip);
}

int main(int argc, char **argv)
{
    int i = 3;
    int *ip;
    ip = &i;
    printf("*ip before chgptr: %d\n", *ip);
    chgptr(ip);
    printf("*ip after chgptr: %d\n", *ip);
    return 0;
}

This code is similar, but it attempts to reassign the pointer itself in the chgptr function. This works, but only within the scope of the function. Since the parameter is a copy of the original pointer, we see this output:

image

The original pointer remains untouched.

These examples have been in C, but the concepts are still important to .NET developers. This is because C# has the unrelated concepts of value/reference types and passing parameters by value/reference. The former is used to talk about what happens when we copy some object. Do we copy its value, or do we just copy a reference to it? The latter is what we’ve been discussing in C, except C# does include the concept of passing parameters by reference (using the “ref” keyword). Consider the following code:

static void Main(string[] args)
{
    object o = "original";
    ChangeObject(o);
    Console.WriteLine(o);
}

static void ChangeObject(object o)
{
    o = 5;
}

You might know that objects in C# are copied by reference and expect the change inside our function call to persist after it returns. Not so! The parameter is still passed by value. What you really need is this:

static void Main(string[] args)
{
    object o = "original";
    ChangeObject(ref o);
    Console.WriteLine(o);
}

static void ChangeObject(ref object o)
{
    o = 5;
}

This specifies that the parameter should be passed by reference.

I’m sure this is common knowledge to a lot of people, but I’ve heard it explained incorrectly enough times that I wanted to clarify.

Hope this helps.

What's the Best Way to Set a "Busy" Indicator in WPF?

On a recent WPF project, we needed to make long-running service calls in multiple places around the app, so we needed to find a good way to clue in the user about what was going on. What we really wanted to avoid was a lot of code like this:

//do something to set a busy indicator
try
{
    //do a bunch of work
}
finally
{
    //do something to clean up the busy indicator
}

Too verbose, too repetitive, too error prone. Fortunately, we were soon able to come up with this as a first cut:

protected void DoWork(Action work)
{
    //do something to set a busy indicator
    try
    {
        work();
    }
    finally
    {
        //do something to clean up the busy indicator
    }
}

We were using a MVVM pattern (Prism, specifically), so we dropped this method into our base modules. A controller class, or potentially your base view-models might also make sense, depending on your specific case. We can then call it like this:

DoWork(() => LoadStuff());

Where LoadStuff() is whatever unit of work you're trying to wrap. So how do we actually indicate that work is being done? Well, we found the Mouse.OverrideCursor property to be pretty useful for this. It pretty much does what you'd expect it to, like so:

protected void DoWork(Action work)
{
    Mouse.OverrideCursor = Cursors.Wait;
    try
    {
        work();
    }
    finally
    {
        Mouse.OverrideCursor = null;
    }
}

The only gotcha is that you need to make sure to set it back to null and not something like Cursors.Normal, because otherwise it will override any cursor styles you have set across the app. Now, this works, but it does have one big problem. Namely, it locks the UI, making the entire app unresponsive while work is being done. This wasn't a big problem for us, since our work was all more or less synchronous. But it's not good for a general solution. Something like this is probably more appropriate:

protected void DoWork(Action work)
{
    Mouse.OverrideCursor = Cursors.Wait;
    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) => work();
    worker.RunWorkerCompleted += (sender, e) => Mouse.OverrideCursor = null;
    worker.RunWorkerAsync();
}

Note that the background worker will swallow exceptions thrown by work, but you can still handle them explicitly in the work completed event. The Error property on the event args holds the exception. There's one more thing we can do that will probably make this a little bit better. It's not too bad to override the mouse cursor here, but it sort of feels like we're mixing UI code into other layers. And if you want some indicator other than the cursor, you risk things getting even uglier. It seems more appropriate to raise events indicating the begin and end of some unit of work. In our app, we were using event aggregation, so we ended up with something like this:

protected void DoWork(Action work)
{
    var workEvent = _eventAggregator.GetEvent<WorkEvent>();
    workEvent.Publish(WorkEventArg.Begin);
    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) => work();
    worker.RunWorkerCompleted += (sender, e) => workEvent.Publish(WorkEventArg.End);
    worker.RunWorkerAsync();
}

Interested parties can subscribe to those events and alter the UI appropriately.

Hope this helps.

Epiphany: Closures are Objects, Objects are Closures

I've spent a lot of time over the past few months learning about functional paradigms and the utility of closures therein. Early in my studies, I came across this hacker kōan:

The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures."

Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress.

On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened.

-- Anton van Straaten

At the time, I didn't understand quite what it meant. It came up again recently, and with a better understanding, I think I'm beginning to understand what they mean. First, a little background. If you're not familiar with closures, here's the short version: closures are functions, but they're also a set of variable bindings based on the scope they were defined in. For instance, we can define a function like this:

int number = 5;
Func<int> closure = () => number;

Notice that the lambda we return takes no parameters, but it is still able to make reference to number. We say the lambda has "closed over" the variable, creating a closure. Note that the lambda has a reference to the actual variable in question instead of just taking a snapshot of the variable in time. For example, here's the classic "gotcha":

var closures = new List<Func<int>>();
for (int i = 0; i < 10; i++)
    closures.Add(() => i);
foreach (var closure in closures)
    Console.WriteLine(closure());

What would you expect this to output? It seems straightforward, but remember that each closure refers directly to i, so we see this result:

image

We can avoid the problem like this:

for (int i = 0; i < 10; i++)
{
    int number = i;
    closures.Add(() => number);
}

This produces the result we actually wanted:

image

Ok, hopefully we now have a decent understanding of what closures are and how they work. Closures are a powerful tool when used correctly, but they do require some care.

Now, what does this have to do with objects? Objects are a familiar concept to most, but they mean different things to different people. Most languages support their own particular flavor of object-oriented programming, and you pretty much work with what they give you. One concept common to most is encapsulation, the idea of private state inaccessible to other objects. Note that we get this for free with closures: when a closure outlives the scope it's defined in (say, as a return value from a function), no one can touch the variables that have fallen out of scope. Like so:

public static Func<int> CreateClosure()
{
    int number = 5;
    Func<int> closure = () => number;
    return closure;
}

When we invoke this function, we get the closure back. number has fallen out of scope, but it persists because our closure has closed over it. In effect, number is private state in our closure. That's kind of cool, but what we really need to make this interesting is some form of method dispatch. This is another common construct in OOP: the idea that objects expose some interface for controlled interactions with private state. Since our object is a function, we only have one point of entry. But if we make that entry point a function that dispatches functions based on messages passed in, we can do some interesting things. Let's see if we can hack something together:

public static Func<string, string> CreateClosure
    (Dictionary<string, Func<string[], string>> methods)
{
    return message =>
    {
        string[] methodWithParams = message.Split(new[] { ' ' });
        string methodName = methodWithParams[0];
        string[] withParams = methodWithParams.Skip(1).ToArray();
        if (!methods.ContainsKey(methodName))
            return "message not understood!";
        return methods[methodName](withParams);
    };
}

The string manipulation code is a pretty ugly, but the premise is simple. First, we accept a dictionary of methods as a parameter. This will hold the public functions that our closure will respond to. Then we define and return our actual closure. This is just a function that receives a message as a string and dispatches the appropriate function. For a trivial (but instructive!) example, we'll use this pattern to create a representation of a pez dispenser.

Let's add some private state and a few methods:

public static Func<string, string> PezDispenserInit(string name)
{
    int count = 0;

    var methods = new Dictionary<string, Func<string[], string>>();
    methods["describe"] = parameters =>
    {
        return string.Format("my favorite {0} pez dispenser - it has {1} pez left", name, count);
    };
    methods["dispense"] = parameters =>
    {
        if (count > 0)
        {
            count--;
            return string.Format("a delicious pez! {0} has {1} pez left", name, count);
        }
        else
        {
            return string.Format("{0} is out of pez . . .", name);
        }
    };
    methods["add"] = parameters =>
    {
        int add = int.Parse(parameters[0]);
        count += add;
        return string.Format("added {0} to {1}! now {1} has {2} pez!", add, name, count);
    };

    return CreateClosure(methods);
}

We've added private data (name and count) and a few methods to call based on messages. Note that each of our public methods is also a closure; the public methods close over our private state, and our method dispatcher closes over the dictionary of methods. To keep things simple, I've adopted the convention that each method takes an array of strings as a parameter and returns a string. The methods themselves are all pretty self-explanatory, so I won't go into detail. Now, let's add a little code to create a simple command line interpreter:

static void Main(string[] args)
{
    var closures = new Dictionary<string, Func<string, string>>();
    while (true)
    {
        Console.Write("> ");
        string[] line = Console.ReadLine().Split(new[] { '.' });
        string name = line[0];
        string message = line[1];
        string result;
        if (message == "init")
        {
            closures[name] = PezDispenserInit(name);
            result = name + " initialized";
        }
        else
        {
            result = closures[name](message);
        }
        Console.WriteLine(result);
    }
}

We have a dictionary for our closure objects allowing us to specify them by name and pass a message. We handle the init message explicitly to create new closures. Kind of a kludge, but this is just an example. Otherwise, we just forward messages onto the appropriate closures. Let's try it out:

image

Pretty cool. Notice that each object maintains its own internal state separate from the other. But is this really useful? All we've really gained is stuff that's built into C#'s type system. What it really gives us is total flexibility. For example, C#'s type system is designed for class-based inheritance (as are many mainstream languages). This is useful in some domains (UI programming, for example), but I don't think it's a great fit in a lot of scenarios. If I wanted to use prototypal inheritance (Steve Yegge has written extensively about this) instead, I'm sort of out of luck. But if I can define my own object system via closures, it's actually pretty simple (look for a future blog post on this).

To close, let's go back to the original point. Objects are a poor man's closures: closures give you complete flexibility to suit your solution to the domain. But the reverse is also true; closures are a poor man's objects. Objects have a slew of advantages over closures because the language (whatever language you're using) is built with its own type system in mind. Even if it's not an ideal model for the problem, the out-of-the-box solution is almost always going to be the correct one for reasons of readability, maintainability, performance, etc. So keep these techniques in mind, but use them very sparingly.

Hope this helps.

Filtering Streams of Random Points Revisited (With Pictures!)

A coworker suggested that my last post would be a lot easier to visualize if it had . . . well, visuals. So I thought I'd revisit it and add some pretty pictures. This post will be pretty to-the-point and light on actual details, since we covered them last time. First, we're going to change around some of the methods in our random generator class:

private static readonly Rect Screen =
    new Rect(new Point(0.0, 0.0), new Point(300.0, 300.0));

public static IEnumerable<Point> GetRandomOnscreenPoints()
{
    foreach (var point in GetRandomPoints(Screen))
    {
        yield return point;
    }
}

This is simply a method to get a bunch of random points on the "screen," which we've arbitrarily defined to be 300x300. Next, we need to filter these values. We'll filter out everything but those points lying on the "border" of the screen:

private static readonly Rect Border =
    new Rect(new Point(10.0, 10.0), new Point(290.0, 290.0));

public static IEnumerable<Point> GetRandomBorderPoints()
{
    foreach (var point in GetRandomOnscreenPoints()
        .Where(p => !Border.Contains(p)))
    {
        yield return point;
    }
}

Now, we need a way to visualize this data. We'll build a simple WPF app with a window:

<Window x:Class="RandomPointFilteringTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Random Point Filtering" SizeToContent="WidthAndHeight">
    <Canvas x:Name="canvas" Height="300" Width="300"/>
</Window>

The window will call our code in its constructor, like so:

foreach (var point in RandomGenerator.GetRandomBorderPoints().Take(2000))
{
    var dot = new Ellipse
    {
        Fill = Brushes.Blue,
        Height = 2.0,
        Width = 2.0
    };
    Canvas.SetLeft(dot, point.X);
    Canvas.SetTop(dot, point.Y);
    canvas.Children.Add(dot);
}

Which yields a frame of little dots around the edge of our window:

image

Nice! To show off the versatility of this pattern, we'll quickly add another method for filtering. This one will filter for points in the corners of the window:

private static readonly Rect HorizontalDivider =
    new Rect(new Point(0.0, 100.0), new Point(300.0, 200.0));
private static readonly Rect VerticalDivider =
    new Rect(new Point(100.0, 0.0), new Point(200.0, 300.0));

public static IEnumerable<Point> GetRandomCornerPoints()
{
    foreach (var point in GetRandomOnscreenPoints()
        .Where(p => !HorizontalDivider.Contains(p))
        .Where(p => !VerticalDivider.Contains(p)))
    {
        yield return point;
    }
}

And we call it like so:

foreach (var point in RandomGenerator.GetRandomCornerPoints().Take(5000))
{
    var dot = new Ellipse
    {
        Fill = Brushes.Blue,
        Height = 2.0,
        Width = 2.0
    };
    Canvas.SetLeft(dot, point.X);
    Canvas.SetTop(dot, point.Y);
    canvas.Children.Add(dot);
}

This yields a nice "cross" pattern:

image

Cool.

Streaming Random Numbers for Effective Filtering

The .NET libraries provide a pretty simple API for generating random numbers. This works well for simple scenarios, but it can quickly result in some clunky and unmanageable tangles of code as the complexity of your problem rises. Specifically, I've found this to be the case when you want to generate multiple, related values. For example, I've been working on a WPF app recently where I needed to generate random, off-screen points for use in animations. For our purposes, "off-screen" means occupying a kind of "frame" around the screen; say, 500 pixels on each side. You can imagine the mess of if-statements that would result from trying to handle this situation directly in code. It occurred to me that it would be really nice to break the problem down into smaller chunks and filter appropriately. Well, why can't we?

When you define a new instance of Random, the result isn't too far off from an iterator: you simply call Next over and over again to process more values. With a little bit of wrapping code, we can treat it just like a stream. Something like this:

   1:  public static class RandomGenerator
   2:  {
   3:      private static Random _rand = new Random((int)DateTime.Now.Ticks);
   4:   
   5:      public static IEnumerable<int> Next(int maxValue)
   6:      {
   7:          while (true)
   8:          {
   9:              yield return _rand.Next(maxValue);
  10:          }
  11:      }
  12:  }

Which we can then evaluate like this:

   1:  static void Main(string[] args)
   2:  {
   3:      foreach (int i in RandomGenerator.Next(10).Take(5))
   4:      {
   5:          Console.WriteLine(i);
   6:      }
   7:  }

This is a pretty trivial example, but it shows you how to define your own infinite stream. Now that we have our random numbers coming back in an enumerable stream, we're free to use LINQ to filter them as we please. Note that filtering is actually required on an infinite sequence; otherwise, you'll end up taking the whole thing, and it's . . . well, infinite. Could take a while. So make sure to restrict your usage down to a finite number of terms (e.g. the Take(5) invocation in this example). Ok, so we have this, and it works:

image

But this isn't exactly interesting by itself. How can we use this to solve our problem? Well, the fact that we can deal with random numbers in streams makes it pretty simple to build smaller functions we can then compose to get what we want. This will also make the code trivially extensible, so reuse will be a snap. Let's take a look by adding a little bit to our RandomGenerator class. First, I'm going to add a couple extension methods to Random that will be useful to us:

   1:  private static double NextDouble(this Random rand, double minValue, double maxValue)
   2:  {
   3:      return minValue + (maxValue - minValue) * rand.NextDouble();
   4:  }
   5:   
   6:  private static double NextDouble(this Random rand, double maxValue)
   7:  {
   8:      return rand.NextDouble(0.0, maxValue);
   9:  }

NextDouble returns a value between 0.0 and 1.0, so you end up writing code like this a lot if you want to map to more interesting values. With that out of the way, let's dive into our problem space. First, we'll add some simple methods to return a stream of points:

   1:  public static IEnumerable<Point> GetRandomPoints
   2:      (double minX, double minY, double maxX, double maxY)
   3:  {
   4:      while (true)
   5:      {
   6:          yield return new Point(
   7:              _rand.NextDouble(minX, maxX), 
   8:              _rand.NextDouble(minY, maxY));
   9:      }
  10:  }
  11:   
  12:  public static IEnumerable<Point> GetRandomPoints(Point min, Point max)
  13:  {
  14:      return GetRandomPoints(min.X, min.Y, max.X, max.Y);
  15:  }
  16:   
  17:  public static IEnumerable<Point> GetRandomPoints(Rect area)
  18:  {
  19:      return GetRandomPoints(area.TopLeft, area.BottomRight);
  20:  }

These are just a few overloads of a function for creating random points within the specified range. Let's try it out, like so:

   1:  foreach (var point in RandomGenerator
   2:      .GetRandomPoints(0.0, 0.0, 100.0, 100.0)
   3:      .Take(5))
   4:  {
   5:      Console.WriteLine(point);
   6:  }

Which produces something like this (results will vary):

image

Ok, not bad. Now we have a stream of points. Let's see what we can do about filtering them. We'll define another method in our static class:

   1:  private static readonly Rect OuterFrame = 
   2:      new Rect(new Point(0.0, 0.0), new Point(100.0, 100.0));
   3:  private static readonly Rect InnerFrame = 
   4:      new Rect(new Point(10.0, 10.0), new Point(90.0, 90.0));
   5:   
   6:  public static IEnumerable<Point> GetRandomOffscreenPoints()
   7:  {
   8:      foreach (var point in GetRandomPoints(OuterFrame)
   9:          .Where(p => !InnerFrame.Contains(p)))
  10:      {
  11:          yield return point;
  12:      }
  13:  }

We've merely layered another enumeration on top of our existing one. It grabs random points and filters based on our predicate. A simple test of our new method shows that it produces points lying in the expected "frame":

image

Of course, enumerations aren't always what you want to deal with, but it's not a stretch to create a wrapper returning a single point:

   1:  public static Point GetRandomOffscreenPoint()
   2:  {
   3:      return GetRandomOffscreenPoints().First();
   4:  }

Once you start thinking in terms of sequences, it's clear that a lot of problems can be solved likewise. My experience has been that this can lead to simple solutions to complex problems. The simplicity in each step makes it easy to verify the correctness of the algorithm. It also makes it really easy to extend for new problems in the same domain, since each step is separated into its own method.

Hope this helps.

Debugging Dependency Properties in WPF: Part 3

In my last couple posts, I've highlighted a way to inject debugging into dependency properties updated via data binding. It seems to work fine, but it's not clear how to apply it in certain scenarios. In our examples, we were attempting to debug a dependency property we defined on our own control. What if we want to debug an inherited property? It's not immediately obvious how to set property metadata in this case, but a little digging turns up some answers. Specifically, we can override default metadata:

   1:  static MyUserControl()
   2:  {
   3:      UserControl.WidthProperty.OverrideMetadata(typeof(MyUserControl), 
   4:          new FrameworkPropertyMetadata(PrintfDebugger()));
   5:  }

And it works:

image

Here we use our control's static constructor to hook into the property changed callback. Notice that we're using FrameworkPropertyMetadata. I originally tried using the normal PropertyMetadata, but this resulted in a runtime exception. Apparently, you can only override metadata with the same type (or a derived type). Since WidthProperty uses FrameworkPropertyMetadata, so must we. Actually, I originally attempted to override metadata on ActualWidthProperty, but it turns out that this is impossible! ActualWidthProperty uses ReadOnlyFrameworkPropertyMetadata, which is an internal class. So we're out of luck if we want to get debug info on read-only properties.

Actually, there is something we can do. We can add a normal event handler to a dependency property descriptor like so:

   1:  public MyUserControl()
   2:  {
   3:      InitializeComponent();
   4:      DependencyPropertyDescriptor.FromProperty(UserControl.ActualWidthProperty, 
   5:          typeof(MyUserControl)).AddValueChanged(this, (sender, e) =>
   6:      {
   7:   
   8:      });
   9:  }

Here we add an event handler that will fire whenever the value changes, allowing us to debug via normal means. This doesn't really fit in with our other solution, and we don't get nearly as much information as with the property changed callback, but I think it's the best we can do. Notice that we're using the regular constructor here and not the static one.

There's still one big scenario I've more or less ignored up to this point. Suppose you want to debug the properties of a child control that's not inherited at all? For example, suppose we host an ellipse in our user control like this:

   1:  <Grid>
   2:      <Ellipse Fill="Red" Height="50" Width="{Binding ActualWidth, ElementName=root}"/>
   3:  </Grid>

How can we debug that property? The Ellipse isn't our class, so it's not obvious how we can hook into its property's metadata. As it turns out, we can override the metadata on other classes:

   1:  static MyUserControl()
   2:  {
   3:      Ellipse.HeightProperty.OverrideMetadata(typeof(Ellipse), 
   4:          new FrameworkPropertyMetadata(PrintfDebugger()));
   5:  }

This yields the desired result, hooking our debugger into the property updates:

image

Something doesn't feel quite right, though, does it? This ellipse already had some metadata, and we just stomped all over it. Our debugging is going to be pretty worthless if it produces any side effects. Unfortunately, ensuring the original metadata stays intact turns out to be much harder than you'd think.

   1:  static MyUserControl()
   2:  {
   3:      var metadata = 
   4:          (FrameworkPropertyMetadata)Ellipse.HeightProperty.GetMetadata(typeof(Ellipse));
   5:      Ellipse.HeightProperty
   6:          .OverrideMetadata(typeof(Ellipse), GetDebugMetadata(metadata));
   7:  }
   8:   
   9:  public static FrameworkPropertyMetadata GetDebugMetadata(FrameworkPropertyMetadata metadata)
  10:  {
  11:      var flags = FrameworkPropertyMetadataOptions.None;
  12:      if (metadata.AffectsMeasure) 
  13:          flags |= FrameworkPropertyMetadataOptions.AffectsMeasure;
  14:      if (metadata.AffectsArrange) 
  15:          flags |= FrameworkPropertyMetadataOptions.AffectsArrange;
  16:      if (metadata.AffectsParentMeasure) 
  17:          flags |= FrameworkPropertyMetadataOptions.AffectsParentMeasure;
  18:      if (metadata.AffectsParentArrange) 
  19:          flags |= FrameworkPropertyMetadataOptions.AffectsParentArrange;
  20:      if (metadata.AffectsRender) 
  21:          flags |= FrameworkPropertyMetadataOptions.AffectsRender;
  22:      if (metadata.Inherits) 
  23:          flags |= FrameworkPropertyMetadataOptions.Inherits;
  24:      if (metadata.OverridesInheritanceBehavior) 
  25:          flags |= FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior;
  26:      if (metadata.IsNotDataBindable) 
  27:          flags |= FrameworkPropertyMetadataOptions.NotDataBindable;
  28:      if (metadata.BindsTwoWayByDefault) 
  29:          flags |= FrameworkPropertyMetadataOptions.BindsTwoWayByDefault;
  30:      if (metadata.Journal) 
  31:          flags |= FrameworkPropertyMetadataOptions.Journal;
  32:      if (metadata.SubPropertiesDoNotAffectRender) 
  33:          flags |= FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender;
  34:   
  35:      return new FrameworkPropertyMetadata(metadata.DefaultValue, flags, 
  36:          PrintfDebugger(metadata.PropertyChangedCallback), metadata.CoerceValueCallback, 
  37:          metadata.IsAnimationProhibited, metadata.DefaultUpdateSourceTrigger);
  38:  }

Pretty ugly, huh? Sorry for the giant wall of code. Here we define another static method to build up a new piece of metadata that's identical save for the injected debugging. The biggest pain is that the flags aren't exposed publicly, so we have to reverse engineer them based on the exposed Boolean properties. We use the bitwise OR operator to build up the flags. (Incidentally, I didn't even realize "|=" was a valid operator in C#; I was pleasantly surprised when I tried it, and it worked.) The rest is pretty straightforward. We pass in all the info from the original metadata and return, preserving the original functionality while injecting our own debugging method.

Debugging Dependency Properties in WPF: Addendum

This is going to be a pretty brief post. I just wanted to mention a small addition to the data binding debugging solution I posted about last time. When we left off, we had a pretty decent solution to debugging via a property changed callback. And here it is:

   1:  public static PropertyChangedCallback PrintfDebugger
   2:      (PropertyChangedCallback propertyChangedCallback)
   3:  {
   4:      return (d, e) =>
   5:      {
   6:          propertyChangedCallback(d, e);
   7:          Console.WriteLine("{0}.{1}: {2}",
   8:              d.DependencyObjectType.Name,
   9:              e.Property.Name,
  10:              e.NewValue);
  11:      };
  12:  }

This works fine, but it's slightly limited. One common scenario where this might not be so useful is if you have several of the same type of control on the same page. This would make it pretty difficult to tell which control is actually receiving the update. What can we do? Well, we can mitigate this by using the name of the element, if it exists.

   1:  public static PropertyChangedCallback PrintfDebugger
   2:      (PropertyChangedCallback propertyChangedCallback)
   3:  {
   4:      return (d, e) =>
   5:      {
   6:          propertyChangedCallback(d, e);
   7:          var elem = d as FrameworkElement;
   8:          string name = elem != null && !string.IsNullOrEmpty(elem.Name) ? 
   9:              elem.Name : 
  10:              d.DependencyObjectType.Name;
  11:          Console.WriteLine("{0}.{1}: {2}",
  12:              name,
  13:              e.Property.Name,
  14:              e.NewValue);
  15:      };
  16:  }

Here we check to see if the dependency object is a FrameworkElement. If it is, and it has a name, we use that. Otherwise, we default to the class name. Note that there are other classes that implement a Name property, but, for the sake of simplicity, I've restricted this to what I believe is the most common scenario. Now, let's see it in action. First, we'll confirm that it still works in our previous case by leaving the control unnamed, like so:

   1:  <Grid>
   2:      <local:MyUserControl MyProperty="{Binding ActualWidth, ElementName=root}"/>
   3:  </Grid>

And running it yields the desired result:

image

Now, let's add a second named control with the same binding.

   1:  <Grid>
   2:      <local:MyUserControl MyProperty="{Binding ActualWidth, ElementName=root}"/>
   3:      <local:MyUserControl x:Name="newControl" MyProperty="{Binding ActualWidth, ElementName=root}"/>
   4:  </Grid>

And the moment of truth:

image

Nice.

Debugging Dependency Properties in WPF with Property Changed Callbacks (or: How I Learned to Stop Worrying and Love printf Debugging)

WPF is a great technology. It's changed the way we write rich desktop apps for Windows. But after using it for an appreciable length of time (eight or nine months), I've come to two conclusions:

1. Data binding sure is swell.

2. Data binding sure is a pain to debug.

I think this is the case with most powerful frameworks. You invoke a few lines of magic, and the tool takes care of all the low level wiring code for you. The problem comes when you treat this process like a black box; when you run into the edge cases where the abstraction starts to break down, it puts you in a tough spot when you try to track down the problem. So it is for debugging data binding with dependency properties in WPF. When a complex chain of bound data isn't working correctly, it can often be difficult to tell where the system is breaking down. To understand why this is, first we need to know a little bit about how dependency properties work in WPF. This is a pretty standard definition of a dependency property:

   1:  public double MyProperty
   2:  {
   3:      get { return (double)GetValue(MyPropertyProperty); }
   4:      set { SetValue(MyPropertyProperty, value); }
   5:  }
   6:  public static readonly DependencyProperty MyPropertyProperty =
   7:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl));

There are a few things to note here. First, the regular .NET property (MyProperty) is simply a wrapper around the dependency property. The actual data will be associated with the dependency property defined just below. Also, take a look at the method calls inside the plain .NET property's get and set methods. These are used to store and retrieve information with our dependency property. More importantly, they will be called directly when our dependency property is updated via data binding. This brings us to the root of the problem: we can't debug dependency properties with our normal techniques, because they are updated with methods we have no insight into. There's nowhere to set a break point.

But there must be something we can do, right? There is. Let's take a closer look at the call to DependencyProperty.Register. This is where we're creating a static definition of the property to be used by instances of our class. You can see that we're currently passing three parameters: the name of the property, the type of the property, and the type of the owning property (i.e. our class). But there's also an optional fourth parameter: property metadata. Property metadata allows you to define some additional behaviors for your dependency property. Among these is the concept of a property changed callback; that is, a method that will run each time your dependency property is updated. This is commonly used for validation or to provide explicit updates to other properties in edge cases when data binding won't do, but we're going to use it to log changes to the console. Doing so is as simple as it sounds:

   1:  public static readonly DependencyProperty MyPropertyProperty =
   2:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl), 
   3:      new PropertyMetadata((d, e) =>
   4:      {
   5:          Console.WriteLine("MyUserControl.MyProperty: {0}", e.NewValue);
   6:      }));

You can see here that we're passing in the additional property metadata, which in turn takes our property changed callback as a parameter. Here we define the callback inline via a lambda method. Our method body is extremely simple: we log a formatted message to the console (your output window, if you're debugging in Visual Studio). This should feel familiar to anyone who's done an appreciable amount of C/C++ development. Welcome back, printf debugging! For demo purposes, I have MyProperty bound to the actual width of the main window, like so:

   1:  <Grid>
   2:      <local:MyUserControl MyProperty="{Binding ActualWidth, ElementName=root}"/>
   3:  </Grid>

No magic here. When we run and resize the window . . .

image

We see the output as expected.

Is this good enough? Maybe for infrequent use, but it's kind of a pain. I know I wouldn't want to be littering my code with snippets like this, nor would I be very excited about manually editing that format string in every instance. I'm likely as not to forget to do it somewhere and end up with bad debugging info, and that's worse than no info at all. How can we make something more reusable? How about this:

   1:  public static readonly DependencyProperty MyPropertyProperty = 
   2:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl), 
   3:      new PropertyMetadata(PrintfDebugger)); 
   4:   
   5:  public static void PrintfDebugger(DependencyObject d, DependencyPropertyChangedEventArgs e) 
   6:  { 
   7:      Console.WriteLine("{0}.{1}: {2}", 
   8:          d.DependencyObjectType.Name, 
   9:          e.Property.Name, 
  10:          e.NewValue); 
  11:  }

Here we extract out our inline declaration into a reusable method. Note also that all class and property name information comes directly from the parameters themselves. If you try this out, you'll find that everything still works as expected. Astute readers will notice a minor problem with this approach. Our original solution was versatile in that it could fit inside any previously declared property changed callbacks. Here, with our debugging method in place, it seems like we can't run any other code when the dependency property changes.

There is an elegant solution, but it requires us to borrow an idea from functional programming: composition. Composition is the idea of using functions that take functions as parameters and return functions upon invocation; this is a popular technique in functional programming because it allows you to chain methods together in such a way as to easily inject new functionality. It's a perfect fit for our case. However, it's a little bit confusing, if you're not familiar with the concept, and my poor explanation probably doesn't help much. So let's jump into some code:

   1:  public static readonly DependencyProperty MyPropertyProperty =
   2:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl),
   3:      new PropertyMetadata(PrintfDebugger((d, e) =>
   4:          {
   5:              if ((double)e.NewValue > 700.0)
   6:                  MessageBox.Show("wide load!");
   7:          })));
   8:   
   9:  public static PropertyChangedCallback PrintfDebugger
  10:      (PropertyChangedCallback propertyChangedCallback)
  11:  {
  12:      return (d, e) =>
  13:      {
  14:          propertyChangedCallback(d, e);
  15:          Console.WriteLine("{0}.{1}: {2}",
  16:              d.DependencyObjectType.Name,
  17:              e.Property.Name,
  18:              e.NewValue);
  19:      };
  20:  }

This might be a lot to take in all at once, so let's break it down. Look at the PrintfDebugger method's signature. It takes a PropertyChangedCallback and returns one. It may seem a little odd, but it seems intuitively correct; if we're going to be chaining methods like this, both ends need to match up (hint: think of it like an extension cord). Moving on to the body, you can see that we're creating a PropertyChangedCallback inline and immediately returning it. Inside the body of our return function, you can see that we're invoking the actual callback function (passed to us as a parameter) and then logging out our debug info.

At this point, you may be feeling slightly uneasy about something you can't quite put your finger on. It's probably the invocation of propertyChangedCallback. We're not passing it in as a parameter to our inline function; instead, we're capturing a reference to it through a technique known as closure. Because the callback is in scope when our inline function is declared, it has access to it. And because it chooses to make use of it, the callback will remain in existence as long as our inline function exists. This is another powerful technique in functional programming that really makes the rest of it possible. We'd have a pretty tough time building up functions dynamically like this without closures.

Moving on to our dependency property, you can see that we're passing our own (trivial) callback to our PrintfDebugger method. Running the program, we see that everything works as we expect it to:

image

For completeness, let's add an overload to PrintfDebugger with no parameters:

   1:  public static readonly DependencyProperty MyPropertyProperty =
   2:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl),
   3:      new PropertyMetadata(PrintfDebugger()));
   4:   
   5:  public static PropertyChangedCallback PrintfDebugger()
   6:  {
   7:      return PrintfDebugger((d, e) => { });
   8:  }

This simply calls the other method with an empty delegate as the parameter. It also allows me to highlight a crucial point: we are not passing PrintfDebugger as the parameter to PropertyMetadata. We're passing the invocation of PrintfDebugger. To put it another way, PropertyMetadata takes a PropertyChangedCallback as a parameter, and PrintfDebugger is not one. Rather, PrintfDebugger is a function that builds PropertyChangedCallbacks. Here's some code to clarify:

   1:  // this works: PrintfDebugger is invoked and returns a method
   2:  public static readonly DependencyProperty MyPropertyProperty =
   3:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl),
   4:      new PropertyMetadata(PrintfDebugger()));
   5:   
   6:  // this doesn't: we attempt to pass PrintfDebugger as a delegate
   7:  public static readonly DependencyProperty MyPropertyProperty =
   8:      DependencyProperty.Register("MyProperty", typeof(double), typeof(MyUserControl),
   9:      new PropertyMetadata(PrintfDebugger));

Anyway, I hope this helps some of you to ease the occasional pain WPF development can be.

Building a Column-Major UniformGrid in WPF

A colleague of mine posed an interesting problem to me the other day. He was building a prototype in WPF that involved two columns of equally sized items. The UniformGrid panel seemed a natural fit, but there was a small problem: the UniformGrid adds everything in row-major order, whereas he required items to be displayed in column-major order. Setting aside more practical or robust suggestions (a Grid with attached row and column properties set programmatically or a custom panel, respectively), he was looking for a quick and dirty hack to get the desired result. Here's what he had (left) and what he was looking for (right):

What he had: a UniformGrid in row-major order. The desired result: the same UniformGrid in column-major order.

After considering the problem briefly, I decided the best strategy would be to employ the seldom-used LayoutTransform. For doing transformations in WPF, RenderTransforms are usually the default choice, and with good reason, but it's important to understand the distinction. Transforms are usually used to tweak the size, location, and orientation of elements on the screen; in such situations, affecting the layouts of other elements is rarely the desired outcome. RenderTransforms are a good fit for this scenario, because they take effect after layout and just before rendering. Here's an example of RenderTransforms in action:

RenderTransforms in action! 

   1:  <StackPanel>
   2:      <Button Background="Red" Content="2" Foreground="White"/>
   3:      <Button Background="Green" Content="5" Foreground="White" RenderTransformOrigin="0.5 0.5">
   4:          <Button.RenderTransform>
   5:              <RotateTransform Angle="45"/>
   6:          </Button.RenderTransform>
   7:      </Button>
   8:      <Button Background="Blue" Content="6" Foreground="White"/>
   9:  </StackPanel>

Notice how the middle element can rotate freely without affecting the layout of the screen or paying heed to the restrictions of the space provided for it. In contrast, LayoutTransforms take effect just before layout:

LayoutTransforms in action! 

In this case, the transformation has an effect on the layout of the screen and on the button's size. If we had rotated to a full 90 degrees . . .

The button expands to fill the space given to it during layout.

   1:  <StackPanel>
   2:      <Button Background="Red" Content="2" Foreground="White"/>
   3:      <Button Background="Green" Content="5" Foreground="White">
   4:          <Button.LayoutTransform>
   5:              <RotateTransform Angle="45"/>
   6:          </Button.LayoutTransform>
   7:      </Button>
   8:      <Button Background="Blue" Content="6" Foreground="White"/>
   9:  </StackPanel>

The button would expand to fill the space given to it. This may not be totally intuitive, but it's important to our original problem. If you recall, we were thinking of ways to hack a UniformGrid into adding objects in column-major order. So what happens if we simply apply a 90 degree LayoutTransform to our UniformGrid?

The UniformGrid rotated 90 degrees.

Hmm . . . not quite what we were hoping for, but promising. In particular, it's nice to see the elements resize themselves to take advantage of the space provided automatically. But there are two problems to note here. The obvious one is that the contents of the buttons are sideways. The more subtle flaw in our solution is that it's backwards: the first column is on the right instead of on the left. We'll tackle the latter first by adding flipping the UniformGrid via a ScaleTransform:

The same panel reversed in the X direction.

   1:  <UniformGrid Rows="2" Columns="4">
   2:      <UniformGrid.LayoutTransform>
   3:          <TransformGroup>
   4:              <RotateTransform Angle="90"/>
   5:              <ScaleTransform ScaleX="-1"/>
   6:          </TransformGroup>
   7:      </UniformGrid.LayoutTransform>
   8:      <Button Background="White" Content="1"/>
   9:      <Button Background="Red" Content="2" Foreground="White"/>
  10:      <Button Background="Orange" Content="3"/>
  11:      <Button Background="Yellow" Content="4"/>
  12:      <Button Background="Green" Content="5" Foreground="White"/>
  13:      <Button Background="Blue" Content="6" Foreground="White"/>
  14:      <Button Background="Violet" Content="7"/>
  15:      <Button Background="Black" Content="8" Foreground="White"/>
  16:  </UniformGrid>

Ouch. Two steps forward, one step back. Now the numbers are not just sideways, but also backwards! We can solve both problems by applying transformations to the buttons reversing our earlier manipulations:

The buttons are corrected by applying opposite transformations.

   1:  <Style TargetType="Button">
   2:      <Setter Property="LayoutTransform">
   3:          <Setter.Value>
   4:              <TransformGroup>
   5:                  <RotateTransform Angle="-90"/>
   6:                  <ScaleTransform ScaleY="-1"/>
   7:              </TransformGroup>
   8:          </Setter.Value>
   9:      </Setter>
  10:  </Style>

Note here that we've scaled the buttons in the Y direction, whereas the panel is scaled in the X direction. As a result of the transforms applied to the panel, the Y axis from the elements' perspective goes from left to right.

Of course, as we noted before we began, this represents a quick, hacked together solution. Happily, this was enough for my friend's prototype. If you have any questions or better solutions, be sure to leave a comment.