Coming from a vacation, I have just discovered a new ASP.NET AJAX roadmap. A post by Matt Berseth starts with a summary of discussion done so far.

I have some personal opinions on the question of ASP.NET AJAX since our team worked with it a lot. So I decided to write a post instead of just commenting existing discussion.

I think I have a slightly different approach to this framework, as compared to other posters. I do not have to choose jQuery/prototype/mootools over ASP.NET AJAX. It is obvious that chaining in jQuery makes life easier, and extending element whenever possible is also a friendly approach.

However, I will still use ASP.NET AJAX for the interoperability with ASP.NET architecture — I can have a JavaScript part for any control I have, and pass values between C# and JavaScript. Also the component lifecycle (being able to handle component references easily) is a large win for me.

What I do not like is the cumbersome get_/set_ requirement without a built-in shortcut (I described one solution earlier) and cumbersome event subscription.

Event Subscription

So, let’s start with this roadmap sample:

   1:  $query("textarea.rich")
   2:    .addHandler("focus", function(e) {
   3:      Sys.Debug.trace("focused into " + (e.eventTarget.id || "?"));
   4:    })
   5:    .setStyle("width", function() {
   6:      return (document.body.clientWidth — 10) + "px";
   7:    })
   8:    .create(Contoso.UI.RichTextBehavior, {
   9:      showToolbar: true,
  10:      fonts: ["Arial", "Times", "Courier"]
  11:    });

What we have now in our project for event subscription is similar to this

   1:  with (Auto.Events) {
   2:    when(textarea).gets('focus').call('textarea_got_focus').on(this);
   3:    when(list).has('changed').call(function() { alert('list_changed'); })
   4:  }

Which also alters dispose to remove the event handler (which is something very tedious to do manually).

So the thing I most dislike in new ASP.NET AJAX syntax is that it is not readable (just plain chaining). I see Event.Behavior as a beautiful solution, jQuery’s as acceptable one (not a language, just more precise naming shortcuts), and ASP.NET AJAX as not really usable.

Same goes to $listen — I just can not remember the correct order of arguments unless looking directly to the documentation or IntelliSense.

But I think that $listen is a great idea, and the solution should be very interesting (considering that IE does not support DOM mutation events).

Templates

Most popular post in my blog is about client-side databinding. I can not show a solution that we have built to solve this issue (we have built it specifically for a project which sources I can not show), so this post is somewhat useless.

I am very hopeful about ASP.NET AJAX’s UI Templates, but I am also thinking about several problems we encountered.  The first one is performance — it is absolutely necessary to pre-cache template binding function. The second one is binding repeated template with server controls.

There is a sample in the roadmap document:

   1:  <!--* for (var i = 0; i < features.length; i++) { *-->
   2:    <span>{{ features[i].name }}</span>
   3:    <!--* 
   4:      $create(Contoso.Tooltip, {
   5:        text: features[i].description
   6:      }, {}, {}, $element);
   7:    *-->
   8:  <!--* } *-->

but I am not sure if it is possible to do this:

   1:  <!--* for (var i = 0; i < features.length; i++) { *-->
   2:    <my:Label Text="{{ features[i].name }}" />
   3:  <!--* } *-->

where my:Label is a ASP.NET AJAX control. It was one the most complex problem for our client:Repeater, so I am interested if this would be implemented.

Now, in contrary to Matt Berseth, I am not really concerned with INotifyPropertyChanged, because it is extremely easy to write a meta-helper to auto-implement it for any given object or prototype in JavaScript.

What I am concerned with with is an idea to “expose methods such as insertRow” for Client DataSource. I do not have any rows in presentational model or my JavaScript arrays, so I strongly dislike this terminology.

The dream feature for me would be a Continuous LINQ for JavaScript, where you can dynamically bind to a dynamically filtered collection, bind to products.where(function(p) { return p.Cost > 5; }). We did a basic implementation for this kind of thing, and found it extremely useful for rich web application. You can have a live model behind a complex page, and never explicitly think of updating any part of the page when some collection in the model got changed.

Animation

I am not really interested in that — other frameworks do this kind of thing easier. And if ASP.NET AJAX is going to imitate jQuery syntax, as some people want, why not just use jQuery or mootools?

Other features

I think that built-in Drag&Drop may make my life easier, looking forward to it. Also, ASP.NET MVC integration has always been a must, it is nice to see it is coming.

All IDE changes are also very welcome.

Summary

In general, I like the proposed changes.

I have a feeling that Microsoft should add more meta helpers as Auto.properties. It is easy to do, but not obvious for the people who are not doing a lot of JavaScript. Also the auto-INotifyPropertyChanged and built-in ObservableCollection would fix databinding cumbersomeness in the same situation.

Also, I am interested in how are the specific technical challenges solved, but it too early to think about that right now.

Sometimes, large company is no better than several independent companies.
I always get this thought when looking at ASP.NET AJAX property accessors.

For people not familiar with the matter:
Microsoft ASP.NET AJAX requires developer to use property accessors to encapsulate javascript fields.
This would be a great idea, if only Microsoft IE supported javascript getters and setters.
Mozilla supports them, and Opera will in 9.50, but IE does not (they are not standard).
Also, IE does not have any hacky way to achieve the same effect (except in VBScript, which seems to be limited).

So in ASP.NET AJAX each property requires two functions named get_propertyName and set_propertyName.

Fortunately, javascript is very powerful in class member manipulation.
So I do not have to write things like this:

MyControl.prototype = {
    get_text : function() {
        return this._text;
    },

    set_text : function(value) {
        this._text = value;
    }
}

And I do not have to wait for auto properties as it is the case for C#.

Instead I just made an helper object named Auto and do things this way:

MyControl.prototype = {…}
Auto.properties(MyControl.prototype, [
    'text',
    'value',
    …
]);

Code for this helper can be very simple.
(in actual project I have additional complexity like Auto support for INotifyPropertyChanged).

var Auto = {
    property : function(prototype, name) {
        var getter = function() { return this['_' + name]; };
        prototype['get_' + name] = prototype['get_' + name] || getter;

        var setter = function(value) { this['_' + name] = value; };
        prototype['set_' + name] = prototype['set_' + name] || setter;
    },

    properties : function(prototype, names) {
        names.forEach(function(name) { 
            Auto.property(prototype, name);
        });
    }
}

This also requires forEach method on Array, but that one is pretty obvious.

I like to show this code when I hear about Javascript being assembly language and whatever-to-javascript compilation.

CSS container class trick

October 8th, 2007

Recently I had a debugging session with one of my colleagues and I remebered a simple trick I use often.
Imagine that you have a list of items, and you want to simultaneously change them in response to a user action.

For example, what if you have this list:

<ul class="Contacts">
  <li>Andrey <span>Shchekin<span></li>
  <li>Nina <span>Philippova<span></li>
  <li>Gordon <span>Freeman<span></li>
</ul>

And you want to show/hide (expand/collapse) all spans in javascript.

One way to do this would be to go through all spans and change their className.
But that can be quite slow on large list.

The better way is to use something like addClassName (from prototype.js) on <ul>.

So you change it to <ul class="Contacts AllCollapsed"> and then apply styles to .AllCollapsed li span.

This way the browser is responsible for finding all contained elements, which should be faster.
Also, if elements are added dynamically, you do not have to process them.

Evaluating Javascript in WatiN

September 5th, 2007

The WatiN framework is quite cool, but it lacks two important things.
First one is searching by CSS selectors, or, at least, classes.
Find.ByCustom(“className”, “X”) is way too ugly. Or am I missing something?

The second (more important) one is a weak access to Javascript.
First thing I wanted to do with WatiN was to change something and then check some script state.
And getting some values from script was not obvious.

I didn’t want to use Ayende’s evil hack (no harm intentended, it gets the work done) — putting javascript state into DOM is not pretty and too string oriented.
I thought that browser COM interfaces should definitely have a way to get Javascript objects outside, that is just the way MS/COM people think.
Thanks to Jeff Brown’s comment for explaining last obstacles.

So here goes the code.
It is quite basic, but it allows you to get value of any Javascript evaluation.
As you can see, I hadn’t included any error handling, I had no time to look into it.

    public static class JS {
        public static object Eval(Document document, string code) {
            IExpando window = JS.GetWindow(document);
            PropertyInfo property = JS.GetOrCreateProperty(window, "__lastEvalResult");

            document.RunScript("window.__lastEvalResult = " + code + ";");

            return property.GetValue(window, null);
        }

        private static PropertyInfo GetOrCreateProperty(IExpando expando, string name) {
            PropertyInfo property = expando.GetProperty(name, BindingFlags.Instance);
            if (property == null)
                property = expando.AddProperty(name);

            return property;
        }

        private static IExpando GetWindow(Document document) {
            return document.HtmlDocument.parentWindow as IExpando;
        }
    }

Nitpicking:
By the way, Ayende, getting permalinks to comments in your blog is not obvious (I used View Source).

Recently I got an optimization problem in ASP.Net.
To be short, I had a Repeater with custom (somewhat complex) template on my Page, and I wanted to reload it asynchronously.

The first solution was XP and didin’t consider performance at all: wrap Repeater inside an UpdatePanel.
The problem was that the entire Page had to be repopulated on server just to get to the Repeater.

That gave me a choice of two headaches:

  1. Put all Page/Controls data into ViewState and bloat bandwidth.
  2. Query all additional data on the reload request and increase load on database to get data that will be thrown away.

To be honest, I could solve (2) with server-side cache, but, in my opinion, caching does not make ugly solutions any better, just faster.

So, naturally, my thought was to query the data-only WebService and then populate the Repeater on client.

And it was interesting to find out that Microsoft already has a client-side data binding solution within ASP.Net AJAX Futures.
I have found an excellent article on this matter by Xianzhong Zhu, “Unveil the Data Binding Architecture inside Microsoft ASP.NET Ajax 1.0″ (Part 1, Part 2).

I will now give a quick summary on the overall client-side binding architecture.
In essence it is quite similar to the smart DataSource controls of ASP.Net 2.0:
There is a DataSource javascript component and a ListView javascript control with html template.
ListView passes data from/to DataSource control, and DataSource talks with a JSON Web Service as a backend.
Controls and their relations are described in text/xml-script (Futures-only feature).

Everything seems quite straightforward and easy to use, I was quite happy to find it.
One thing that bothers me is the performance of text/xml-script (it is parsed on client).
But it is a concern not related to the current story.
The other question is what to do when I want to databind a complex list (consisting of several embedded server user controls) ?
I am going to find it out real soon.

Along the way, I have also noticed Sys.Preview.Data also introduces DataSets/DataTables to javascript.
That is quite funny. Personally, I never really considered DataSets acceptable anywhere above Persistence layer.
But I already thought about Persistence/DataAccess concept in javascript when I saw Gears.
And DataSets seem to fit ‘nicely’ to some GoogleGearsDataSource (it would be quite an experience to actually see one in real code).

Well, javascript O/R Mapper, anyone ?