AJAX-Style Web Development Using ASP.NET
Taking asynchronous Web forms to the next level
In the past few months, the design pattern of combining Asynchronous JavaScript and XML (AJAX) to develop highly interactive Web applications has been growing in popularity. High-profile Web applications such as Google Maps and A9 are currently leveraging the combination of these technologies to produce rich client-side user experiences. The individual technologies that compose AJAX are not recent developments; they have been around for some time and have been continuously updated and improved. However, it is the recent confluence of these technologies that is leading to interesting possibilities.
I have three goals in this article. First, I want to provide a high-level overview of AJAX-style applications. My second goal is to provide a detailed description of asynchronous callback features of ASP.NET 2.0. Finally, I want to provide an insight into upcoming enhancements of tools and frameworks for building AJAX-style applications.
AJAX-style Web applications exhibit the following characteristics:
The big difference between an AJAX application and a traditional Web application is that every user interaction does not result in an HTTP request being sent to the Web server. Instead, browser-based logic implemented in JavaScript receives control that, in turn, decides whether to handle the request locally or to make an asynchronous call to the server. Upon the completion of the asynchronous call to the server, the client-side logic appropriately updates the relevant sections of the UI. This approach provides the following benefits:
For all the pros, AJAX-style applications have a number of cons associated with them as well. AJAX-style development is difficult because of the absence of framework (a collection of UI classes similar to the MFC toolkit for Windows) and IDE support (i.e., debugging, visual designers, etc.). One has to know at least two languages well (DHTML and JavaScript). Further, AJAX-style applications take longer to code because of the additional testing required to support multiple browser versions and types. Finally, as the JavaScript-based source is accessible to the end user, threat analysis becomes very important.
Fortunately, the arrival of things such as Atlas, AJAX.NET, and the Google Maps API etc. is a sign of better support for building AJAX-style applications in the future. In the next section, we will look into how the support for building AJAX applications is evolving over time and what to expect from the newly announced toolkits such as Atlas.
Let's start with the XMLHttp object, which was introduced by Microsoft and later implemented on other platforms including Mozilla and Apple's Safari browser. XMLHttp enables asynchronous requests to the Web server, which allows Javascript- based logic on the client to call the Web server without the need to reload the page.
In other words, it is possible to have interaction with the Web server in the background without causing a page reload - a side effect of the exchange between the browser and the Web server.
Using the XMLHttp object is straightforward. For the sake of simplicity, let's just consider IE specific syntax. The syntax for XMLHttp implementations on other browsers is similar.
request = new ActiveXObject("Microsoft.XMLHTTP");
if (request)
{
request.onreadystatechange = CallbackHandler;
request.open("GET", URL, true);
request.send();
}
function CallbackHandler()
{
if ((request.readyState == 4) && (request.status == 200)
{
string response = request.responseXML;
// Update the relevant sections of the UI
}
}
In the code snippet shown above, the first step is to instantiate the Microsoft.XMLHttp class. Next, we set the properties on the XMLHttp instance we just created, including the address of callback function that will get control when the XMLHttp request is complete. The callback function address is needed because we are making asynchronous calls to the server (an intent conveyed by setting the third parameter on the open method call to true). Inside the implementation for the callback function, we make additional checks to make sure that the request is complete.
As you can see from the above code sample, it is quite simple to use the XMLHttp object in a stand-alone manner. However, integrating the XMLHttp into the rest of the HttpPage life cycle is difficult - for example, how does one ensure that the server-side method being called has access to the state of other controls on the page? For the state of the controls to be correctly initialized, the callback handling on the server needs to go through a similar HttpPage life cycle as the postback. The other challenge in using the XMLHttp object directly is that as developers we need to account for different browser types. Fortunately, ASP.NET 2.0 provides a reusable pattern that makes the callback functionality easily accessible. Note that several controls that ship with ASP.NET 2.0, including GridView, TreeView, etc., leverage the callback capability.
Figure 1 depicts how the callbacks are implemented in ASP.NET 2.0. Let us start from the server side. A new interface, ICallBackEventHandler, has been defined. Any ASPX page (or a control that intends to support client callbacks) needs to implement the ICallBackEventHandler interface. ICallBackEventHandler defines one method called RaiseCallbackEvent. This method takes one parameter of type string as the argument and returns a string.
On the client side, to initiate the callback, a special Javascript function needs to be invoked. You can obtain a reference to this special Javascript function by calling ClientScriptManager.GetCallbackEventReference (see the second and third entries in the References section). The call to GetCallbackEventReference results in a reference to callback. When invoking the callback, you pass one parameter of type string. This is consistent with server-side RaiseCallbackEvent signature. That is all you need to set up callbacks from the client. The rest of the magic to hook up the client callback to the server-side RaiseCallbackEvent method of ICallBackEventHandler is done by the framework. The aforementioned special Javascript function for initiating callback uses two additional parameters to be included as part of the postback data - __CALLBACKPARAM and __CALLBACKID, which represent the string parameter to pass to the call and the ID of the control, respectively. On the server, ASP.NET detects the presence of the two additional parameters and routes the request to the appropriate control, resulting in the invocation of the RaiseCallbackEvent method on the target control. To solve the aforementioned problem related to initialization of controls on the page, ASP.NET runtime follows a trimmed-down version of HttpPage life cycle when servicing a callback. This includes going through the specific stages of page initialization, view state loading, page loading, and callback event handling. Once the callback event is handled by the control, the rest of the HttpPage life cycle stages are skipped.
To help better understand the ASP.NET 2.0 callbacks, included is a simple progress bar control that relies on callbacks to determine the status of a given task on the server. Listing 1 displays the code for the ProgressBar control. To support client callbacks, this control implements the ICallbackEventHandler interface. For the purpose of the demo, the RaiseCallbackEvent method implementation simply looks up a counter stored in the session, increments the counter by one, and returns the new value to the client. Finally, Listing 2 is the Javascript code that is responsible for initiating the callback. It uses this.Page.ClientScript.GetCallbackEventReference to obtain a safe reference to the function needed to initiate the callback.
Using client callbacks provided in ASP.NET 2.0, it is relatively straightforward to implement the progress bar control, since the data passing between the control and the client is a simple string. However, as soon as we start adding other datatypes to the mix, we will run into mismatches between Javascript and .NET-type systems. Unfortunately, the callback implementation in ASP.NET 2.0 does not help with this issue. Applications that want to use multiple datatypes, simple and complex, will need to implement a custom scheme on their own.
Fortunately, this limitation can be overcome by using an open source library called AJAX.NET (see the fourth entry in the References section), AJAX.NET implements a proxy-based approach for calling the server-side functions. AJAX.Net defines a custom attribute called AJAXMethod. When a server-side method is decorated with the AJAXMethod, a Javascript-based client proxy is automatically generated by the HttpHandler that is part of AJAX.NET library. Unlike ASP.NET 2.0, which supports a single parameter of type string for callbacks, AJAX.Net supports integers, strings, double, DateTime, DataSets, etc.
An alternative to AJAX.NET for dealing with differences between the Javascript and .NET-type system is suggested by Bertrand Le Roy (see the fifth entry in the References section). He has created a server-side control called EcmaScriptObject that recreates the Javascript type system in .NET. The idea is to reproduce a client-side object graph in .NET. This approach makes better sense as the conversion is happening on the server.
Even if we have a type-safe way to invoke callbacks, more challenges remain. Javascript is the glue that holds all the pieces of the AJAX application together. Thus, there is increased reliance on Javascript. Unfortunately, even though Javascript is a powerful and versatile language, it does not lend itself easily to well-known object- oriented principles. This means it is harder to achieve code reuse. Please refer to the sixth entry in the References section for syntactic sugar added around Javascript to make it appear as traditional OO language. Even then, it is hard to implement features available in managed languages such as events and delegates.
The other difficulty, as discussed earlier, is the lack of a reusable framework to make the Javascript development more productive. For example, wouldn't it be nice to have access to a Javascript-based UI framework that hides the differences between different execution environments? Another example would be a set of classes that make it easy to invoke Web services in a secure manner (as opposed to hand coding the SOAP packets and using XMLHttp to transport them).
The most recent announcement from Microsoft about the Atlas Project promises to address some of these difficulties. Atlas will be an open-source framework based on ASP.NET 2.0. It is an attempt to greatly simplify AJAX-style development by providing, over time, a Javascript framework that includes (note - the following is based on a preliminary announcement from Microsoft and is subject to change): UI Toolkit - commonly used controls with support for features such as drag and drop and databinding; SOAP stack for invoking Web services; browser compatibility layer that hides the differences between browser types; and client building blocks such as local cache. Further, the ASP.NET team plans to make some of the building blocks for ASP.NET such as profiles, membership, etc. available as Web service endpoints, to make them accessible from Javascript directly. For example, personalization information can be easily accessible on the client. Finally, the Atlas project plans to extend the Javascript syntax to include interfaces, lifetime management, and multicast events.
The next few months promise to be very exciting for those interested in building AJAX-style Web applications. I hope this article has peaked your interest in AJAX enough for you to consider it for the next Web application you build.
References