Tales from the Evil Empire

Bertrand Le Roy's blog


Bertrand Le Roy

BoudinFatal's Gamercard

Tales from the Evil Empire - Blogged

Blogs I read

My other stuff


September 2009 - Posts

Ajax Control Toolkit: new controls, bug fixes

(c) Bertrand Le Roy 2006 And we have a new release of Ajax Control Toolkit. I didn’t work on this one but there are some nice things in there nonetheless :)

First, new controls!

SeaDragon: I’ve blogged before about Seadragon, the JavaScript-only way to do Deep Zoom. It became a lot easier to use a few month ago when the need for tools disappeared and you can just point to any image on the web and immediately get the URL and script tag to put on your page:

Now with this release of Ajax Control Toolkit, including and controlling Deep Zoom from an ASP.NET page is also very easy:

<ajaxToolkit:Seadragon ID="Seadragon"
CssClass="seadragon" runat="server"

James Senior just released a screencast on how to create Deep Zoom contents for the new Seadragon control:

AsyncFileUpload: This is by far one of the most requested controls for ACT. File upload fields, while a part of HTML, do not work with Ajax/XHR requests (for security reasons, JavaScript can’t access the contents of the field). The only way to use them is to get the browser to do a real form post.

This new control makes it a lot easier to handle file uploads from your Ajax applications by providing an abstraction on top of the form posting:

OnClientUploadComplete="uploadComplete" runat="server" ID="AsyncFileUpload1"
Width="400px" UploaderStyle="Modern" UploadingBackColor="#CCFFFF"

It works pretty much as advertised: just drop the control on the page, and you can upload files without a full postback. It looks just like Ajax and requires no plug-in of any kind.AsyncFileUpload

The control has client and server-side events that get triggered when the file has been uploaded. On the server-side, you have access to the uploaded file’s byte stream, which you can save to disk (or database, or whatever).

Bug fixes: This release also has some new bug fixes (courtesy of Obout) for some of the top-voted issues.

Download the new release here:

Try the live demos here:

Stephen's in-depth post about this release:

Fun with C# 4.0’s dynamic

(c) Bertrand Le Roy 2003There’s been some debate recently on the new “dynamic” keyword in C# 4.0. As has been the case with many features before it, some love it, some hate it, some say it bloats the language, yadda yadda yadda. People said that about lambdas. Me, I’ll just use it where I see a use case, thank you very much.

In the case of dynamic, another frequent comment is that a statically-typed language should not try to look like a dynamic language. Well, I just don’t believe in that distinction.

Being dynamic is a trait that a language can have, and some have it more than others. But as soon as a language has a dictionary type or indexers, and most modern languages do, it starts having dynamicity. What people call a dynamic language is just one where it’s the only available type.

Now there is type safety of course, but to me that’s a different feature that is not as coupled with “statically-typed-ness” as we usually tend to think. Case in point, many modern JavaScript engines analyze the code in order to apply many of the optimization techniques that static languages have been applying at compile-time.

So just how dynamic was C# before 4.0? Well, there are dictionaries and indexers, as I’ve said, but there are also other interesting and less known features such as custom type descriptors. Go look them up if you don’t know about them. Type descriptors are for example used to provide a level of indirection between a design surface and the components being edited.

But type descriptors can also be built completely dynamically and decide to expose a completely virtual object model that is entirely built at runtime. Of course, the client code for that object has to go through the right APIs to make use of that quasi-dynamic model. And of course those APIs are not simple. Implementing a custom type descriptor in itself is not exactly trivial.

If anything, the dynamic keyword is going to provide a friendlier syntax for this sort of thing. One problem is that it has no relationship whatsoever with custom type descriptors.

So I thought I’d try to bridge that gap. How can we take a type that exposes a custom type descriptor, such as DataRowView, and transform that into something that plays nice with the dynamic keyword? What we want to be able to write is something like the following:

var table = new DataTable("People");
table.Columns.Add("FirstName", typeof(string));
table.Columns.Add("LastName", typeof(string));
table.Columns.Add("Children", typeof(int));
new object[] {"Bertrand", "Le Roy", 2},
LoadOption.OverwriteChanges); var tableView = new DataView(table);
dynamic dynRecord =
new TypeDescriptorDynamicWrapper(tableView[0]);
Console.WriteLine("{0} {1} has {2} children.", dynRecord.FirstName, dynRecord.LastName, dynRecord.Children);

To do that, I built the TypeDescriptorDynamicWrapper that you see being used above. What is does is pretty simple, as it just inherits from DynamicObject and implements TryGetMember as follows:

public override bool TryGetMember(
GetMemberBinder binder, out object result) {
var name = binder.Name; var property = _properties.Find( p => p.Name.Equals(name, binder.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); if (property == null) { result = null; return false; } result = property.GetValue(
_descriptor.GetPropertyOwner(null)); return true; }

As you can see, the method just finds the right property on the type descriptor and delegates to it if it finds it. I didn’t implement the setting of properties but it would be fairly easy to do so.

Using that simple wrapper, the program above just works and displays:

Bertrand Le Roy has 2 children.

That was easy. Now what about the reverse, getting any dynamic object to expose a custom type descriptor?

Well, that’s where things get tricky.

The dynamic capabilities of C# 4.0 are targeted at two things:

  1. Providing syntactic sugar for getting to dynamic members that looks like accessing statically-defined ones.
  2. An easy way to create dynamic types by implementing a form of method_missing.

But there is one thing that exists in DLR but didn’t make it to C# yet, which is the ability to easily reflect on dynamic objects (other than by using the #1 syntactic sugar above).

For example, in JavaScript, a.foo and a[“foo”] are exactly the same thing, which enables easy reflection: you can enumerate the members of an arbitrary object and do stuff like a[someStringVariable].

Doing the same thing with C# on dynamic objects is much more difficult. The equivalent of a.foo is easy, but not the equivalent of a[someStringVariable].

Forget about using reflection, it doesn’t work on dynamic objects because dynamic really is a compiler trick. There is no such thing as a “dynamic” type to reflect on. It’s a keyword that tells the compiler to relax type-checking and generate code to access those dynamic members at runtime. If you try to reflect on an instance of one of the dynamic-friendly type, such as ExpandoObject, you’ll see the statically-defined members of that type, but not the dynamic ones. In a way, you’re looking at the messenger instead of the message.

This is a problem because in order to wrap an arbitrary dynamic object into a custom type descriptor, we need to be able to reflect on the dynamic members of that object.

To solve the problem, and with some help from the nice folks who are building the DLR, I compiled a simple program that sets and gets a property on a dynamic object, an then I looked at the generated code from Reflector (“luckily”, Reflector is not yet aware of dynamic and shows the generated code instead of something closer to the actual code you wrote).

I was then able to refactor that code and replace the string constants for the accessed member with a method parameter, thus creating a generic way to access dynamic object properties:

public static object GetValue(
object dyn, string propName) {
// Warning: this is rather expensive,
// and should be cached in a real app
var GetterSite =
CallSite<Func<CallSite, object, object>>
.Create( new CSharpGetMemberBinder(propName, dyn.GetType(), new CSharpArgumentInfo[] { new CSharpArgumentInfo(
CSharpArgumentInfoFlags.None, null) })); return GetterSite.Target(GetterSite, dyn); } public static void SetValue(
object dyn, string propName, object val) {
// Warning: this is rather expensive,
// and should be cached in a real app
var SetterSite =
CallSite<Func<CallSite, object, object, object>>
.Create( new CSharpSetMemberBinder(propName, dyn.GetType(), new CSharpArgumentInfo[] { new CSharpArgumentInfo(
CSharpArgumentInfoFlags.None, null), new CSharpArgumentInfo(
CSharpArgumentInfoFlags.LiteralConstant | CSharpArgumentInfoFlags.UseCompileTimeType,
null) })); SetterSite.Target(SetterSite, dyn, val); }

Once we have that, implementing the custom type provider is relatively straightforward. The only part that is not immediately obvious is how to enumerate the properties of the dynamic object.

This is done as follows. Dynamic objects implement IDynamicMetaObjetProvider, which has a GetMetaObject method, which returns a DynamicMetaObject object on which you can call GetDynamicMemberNames to get the list of members.

We can now take any dynamic object and for example present it in a property grid, which is one of those components that know how to handle custom type descriptors but not the new dynamic objects:

dynamic person = new ExpandoObject();
person.FirstName = "Bertrand";
person.LastName = "Le Roy";
person.Children = 2;
propertyGrid1.SelectedObject = 
new DynamicTypeDescriptorWrapper(person);

And here’s what the results look like:PropertyGrid displaying a dynamic object.

In conclusion, I’d say that although we are having a healthy debate on the dynamic keyword (and we should have that debate), I’m confident that in one or two years, we’ll have some incredibly imaginative uses of the feature that will simply blow us away and will make the current conversation a little sillier than it seems today. The feature itself is also in its infancy and not only will the use cases emerge way beyond what even its designers envisioned, it will also grow and become more usable with future versions of the language, as is made clear by the gap in functionality that still exists today with the full DLR project.

You can download the code for this article here:

Why Guitar Hero is dead to me

(c) Bertrand Le Roy 2007 I bought the new Guitar Hero 5 because I needed a new fake plastic guitar and Activision’s guitars are the best that are not outrageously expensive. The Rock Band guitars I just can’t stand. So as I was going to buy a guitar from them, I thought I might as well get a (couple of) cheap game(s) with it.

At first, I really liked what they did with GH5, especially when compared to the mediocre World Tour. The party mode, for example, is a very nice idea: the game acts as a media player and plays songs on its own; but you can jump in at any time and start to play any instrument. Being able to play any instrument in any number is also a nice touch, seeing as few people like to sing in public, but most are not afraid of the guitar or drum set.

I also liked the tapping sections and the bass’ sixth note.

Problem is, that’s about it. The game has 85 songs but they’re not good. Going through the career mode feels like you’re grinding through mediocre song after horrible song. And when there’s one good song (there are a few), it is usually spoiled by an absurd, deliberately “challenging” partition. “Challenging”, in Activision’s mind of course means they have to make extra-sure you’ll have no fun playing the song.

After passing most songs, I heard myself thinking “this is a song I’m never going to play ever again”.

And the design… Will somebody please do something about the ugliness and get out of that uncanny valley? The rest of the industry has, one way or another. Guitar Hero is generally very consistent about the bad taste.

Contrast that with the elegant and subdued design of Rock Band, their well-balanced, well-designed, fun partitions that have the appropriate difficulty (no song is harder in medium than another in expert for example).

And of course, until EA and Activision realize the consumer’s interest is theirs and it’s absurd to limit the songs you sell to only one media player, there can be only one. Nobody wants to switch games in the middle of a party. But that is unlikely to happen as Activision can’t even manage to be compatible with their own games: 35 songs out of World Tour’s 85? WTF? It’s as if Apple was selling iTunes 2008 and iTunes 2009 but you couldn’t play on 2009 all the songs you bought on 2008. And you had to pay again to play those few “old” songs that you bought only a year earlier.

Don’t even get me started on how they milk the franchise, from inane band-specific titles to ridiculous toy-versions.

There can be only one in each home, and for me that one is going to be, for now and I suspect for a long time, Rock Band.

Posted: Sep 15 2009, 12:14 AM by Bertrand Le Roy | with 3 comment(s)
Filed under:
Building a class browser with Microsoft Ajax 4.0 Preview 5

(c) 2004 Bertrand Le Roy The Microsoft Ajax Library 4.0 Preview 5 is the first release of Microsoft Ajax that I didn’t participate in: I left the team a few months ago. But that doesn’t mean I don’t love what’s in there, and I really do. And by the way I’ve also seen what’s in Preview 6 too and man that will seriously rock.

So I thought I’d write a little something to celebrate the new preview. The new features include recursive templates, which is pretty much begging us to implement a treeview with it, and we’ll do just that in this post.

There is also an intriguing capability, which enables you to dynamically set what template to render for each data item, and where to render it. At first, this doesn’t look like the most useful thing in the world, but it actually opens up some very interesting possibilities, which we’ll also show in this post.

The sample code that I’m going to write for this post is a rudimentary class browser. It will render a treeview representing the hierarchical structure of namespaces and classes in Microsoft Ajax, and clicking one of the tree nodes will render a details view for it: a list of classes and subnamespaces for namespaces, and a grouped list of members for classes.

Let’s start with the tree. It will be rendered as nested unordered lists by a simple recursive DataView:

<ul id="tree" class="tree"
    dataview:data="{{ Type.getRootNamespaces() }}"
    dataview:oncommand="{{ onCommand }}">

<ul id="nodeTemplate" class="sys-template">
    <a href="#" onclick="return false;"
      {{ getSimpleName($dataItem.getName()) }}
    <ul sys:attach="dataview"
        dataview:data="{{ getChildren($dataItem) }}"
        dataview:oncommand="{{ onCommand }}"></ul>

On the first UL, which is the outer DataView for the tree, you can see that we set the data property to Type.getRootNamespaces(), which returns the set of root namespaces currently defined.

We also set the template to point to the “nodeTemplate” element, which has to be outside the DataView itself when doing recursive templates. Note that the outer node of the template, the UL, won’t actually get rendered into the target ul (tree). It is only a container.

The command event of the DataView is hooked to the onCommand function, and we’ll get back to that when we couple the tree with the detail view.

In the template itself, you can see we have a link with the select command so that clicking it will trigger the nearest onCommand event up the DOM.

The text of that link is the results of a call to getSimpleName, which will extract the last part of the fully-qualified name of the namespace or class.

After that link, we find another DataView control. The data property of that control points to an array of namespaces and classes under the current object. But the nice part here is that the template property points to “nodeTemplate”, its own parent, enabling the recursive nature of the tree.

In other words, we’ve morphed a simple DataView control into a tree, with minimal effort and code.

There is just one thing missing to the tree, and that is the +/- buttons that will collapse and expand the tree nodes. This is actually very easy to set-up using CSS and some simple script. First, let’s collapse the tree by default. This is done by defining the style of the tree as follows in our stylesheet:

.tree ul 
    padding: 0;

This has the effect of collapsing all unordered list nodes under the tree.

The +/- button is created by adding the following to the template, right before the existing link:

<a class="toggleButton" href="#"
   onclick="return toggleVisibility(this);">+</a>

The button is a simple link whose rendering is conditioned by whether the current data item is a namespace: only namespaces can be expanded, classes are leaf nodes.

The toggling function itself is fairly simple:

function toggleVisibility(element) {
    var childList = element.parentNode
.getElementsByTagName("ul")[0], isClosed = element.innerHTML === "+"; childList.style.display =
isClosed ? "block" : "none"; element.innerHTML = isClosed ? "-" : "+"; return false; }

This just toggles the display style of the first child UL between none and block, and the text of the link between + and –.

So there it is, we have built a simple tree by simply making use of the recursive capabilities of DataView and some very simple script.

Before we look at the details view, let’s look at the code that gets called when the user selects a node in the tree:

function onCommand(sender, args) {
    var dataItem = sender.findContext(
args.get_commandSource()).dataItem; $find("details").set_data(dataItem); }

That code gets a reference to the data item for the selected node from the template context that we can get from the sender of the event (the inner DataView that contains the selected node) using the command source as provided by the event arguments (that source is the element that triggered the command). We can then set the data of the details DataView to that data item, which will trigger that view to re-render.

Now let’s build the details view. The details view will display the child namespaces and classes if a namespace is selected in the tree, and the properties, events and methods (instance and static) in the case of a class.

For each case, we’ll use a different template: “namespaceTemplate” for namespaces, and “classTemplate” for classes,  but we’ll do so from the same DataView. This dynamic template switching is done by handling the onItemRendering event of the DataView:

function onDetailsRendering(sender, args) {
    var dataItem = args.get_dataItem();
    args.set_itemTemplate(Type.isNamespace(dataItem) ?
        "namespaceTemplate" : "classTemplate");

This code gets the data item from the event arguments and sets the itemTemplate property depending on its type.

Each of these two templates will have to display the contents of the selected object. But, and that will be the tricky part, we want all those to be neatly grouped into separated lists.

One way to do that would be to have one DataView per list but where would the fun be in that? Here, we are going to enumerate only once through the data items to display and dispatch them dynamically to this or that placeholder depending on their nature.

Once more, the key to doing that will be handling the onItemRendering event:

function onNamespaceChildRendering(sender, args) {
    if (Type.isClass(args.get_dataItem())) {

This code is simply changing the rendering place holder for the curent item from the default (the DataView’s element) to “classPlaceHolder” if the current data item is a class (instead of a namespace). The template itself looks like this:

<div id="namespaceTemplate" class="sys-template">
   <h1>{{ $dataItem.getName() }}</h1>
   <div class="column">
     <ul sys:id="namespacePlaceHolder"
         dataview:data="{{ getChildren($dataItem) }}"
"{{ onNamespaceChildRendering }}"> </
ul> </div> <div class="column"> <h2>Classes:</h2> <ul><li sys:id="classPlaceHolder"></li></ul> </div> </div> <ul id="namespaceChildTemplate" class="sys-template"> <li>{{ $dataItem.getName() }}</li> </ul>

As you can see, there really is only one DataView in there, and thanks to the code above, it can dispatch its rendering to different places if necessary. The template for the items of that DataView happens to be the same in all cases (namespaceChildTemplate) but it could be easily different, as it was for the parent details view.

The template for displaying classes is essentially the same thing, but with four placeholders instead of two.

So here’s what it looks like in the end:

Class Browser

Key takeaways of this post are that it’s now super-easy to render hierarchical data structures with DataView, and that you can do some interesting grouping of data on the fly by handling the item rendering event.

You can play with the class browser live here:

And you can download the code here:

Microsoft Ajax 4.0 Preview 5:

Jim and Dave’s posts on Preview 5:

More Posts