The AJAX Revolution

Overview

Gone are the days when a Web application could be architected and implemented as a collection of related and linked pages. The advent of the so-called AJAX model is radically modifying the user’s perception of a Web application, and it is subsequently forcing developers to apply newer and richer models to the planning and implementation of modern Web applications. But what is the AJAX model, anyway?

AJAX is a relatively new acronym that stands for Asynchronous JavaScript and XML. It is a sort of blanket term used to describe highly interactive and responsive Web applications. What’s the point here? Weren’t Web applications created about a decade ago specifically to be “interactive,” “responsive,” and deployed over a unique tool called the browser? So what’s new today?

The incredible success of the Internet has whetted people’s appetite for Web-related technology beyond imagination. Over the years, the users’ demand for ever more powerful and Webexposed applications and services led architects and developers to incorporate more and more features into the server platform and client browser. As a result, the traditional pattern of Web applications is becoming less adequate every day. A radical change in the design and programming model cannot be further delayed.

At the current state of the art, the industry needs more than just an improved and more powerful platform devised along the traditional guidelines and principles of Web applications-a true paradigm shift is required. AJAX is the incarnation of a new paradigm for the next generation of Web applications that is probably destined to last for at least the next decade.

From a more developer-oriented perspective, AJAX collectively refers to a set of development components, tools, and techniques for creating highly interactive Web applications that give users a better experience. According to the AJAX paradigm, Web applications work by exchanging data rather than pages with the Web server. From a user perspective, this means that faster roundtrips occur and, more importantly, page loading and refresh is significantly reduced. As a result, a Web application tends to look like a classic desktop Microsoft Windows application and has advanced features such as drag-and-drop and asynchronous tasks, a strongly responsive and nonflickering user interface, and other such features that minimize user frustration, provide timely feedback about what’s going on, and deliver great mashed-up content. (Hold on! This doesn’t mean AJAX Web applications are the same as desktop applications; they simply allow for a few more desktop-like features.)

AJAX is the philosophy that has inspired a new generation of components and frameworks, each designed to target a particular platform, provide a given set of capabilities, and possibly integrate seamlessly with existing frameworks. Microsoft ASP.NET AJAX Extensions is the AJAX addition to the ASP.NET 2.0 platform. In the next major release of the .NET Framework platform ASP.NET AJAX Extensions will officially fuse to ASP.NET and the rest of the Microsoft Web platform and application model. The next release of Microsoft Visual Studio (code-named “Orcas”) will also integrate ad hoc design-time support for AJAX-specific features.

In this chapter, I’ll dig deeper into the motivation for and driving force behind AJAX and then review the basic system requirements common to all AJAX frameworks.


The Paradigm Shift

We are all witnessing and contributing to an interesting and unique phenomenon-the Web is undergoing an epochal change right before our eyes as a result of our actions. As drastic as it might sound, the Web revolutionized the concept of an application. Only eight years ago, the majority of developers considered an application far too serious a thing to reduce it to an unordered mix of script and markup code. In the late 1990s, the cost of an application was sweat, blood, tears, and endless debugging sessions. According to the common and semiserious perception there was neither honor nor fame for the “real” programmer in writing Web applications.

  Note 

In the late 1990s, though, a number of Web sites were designed and built. Some of them grew incredibly in the following years to become pillars of today’s world economy and even changed the way we do ordinary things. Want some examples? Google, Amazon, eBay. Nonetheless, a decade ago the guys building these and other applications were sort of avant-garde developers, perhaps even just smart and game amateurs.

Since then, the Web has evolved significantly. And although 10 years of Web evolution has resulted in the building of a thick layer of abstraction on the server side, it hasn’t changed the basic infrastructure-HTTP protocol and pages.

The original infrastructure-one that was simple, ubiquitous, and effective-was the chief factor for the rapid success of the Web model of applications. The next generation of Web applications will still be based on the HTTP protocol and pages. However, the contents of pages and the capabilities of the server-side machinery will change to provide a significantly richer user experience-as rich as that of classic desktop Windows applications.

  Note 

As we’ll see in greater detail in Chapter 8, “Building AJAX Applications with ASP.NET,” AJAX applications have a number of plusses but also a few drawbacks. Overall, choosing an AJAX application rather than a classic Web application is simply a matter of weighing the trade-offs. An AJAX application certainly gives users continuous feedback and never appears held up by some remote operation. On the other hand, AJAX applications are not entirely like desktop applications, and their capabilities in terms of graphics, multimedia, and hardware control are not as powerful as in a regular (smart) client. In the end, AJAX applications are just one very special breed of a Web application; as such, they might require some code refactoring to deliver the expected performance and results.

Classic Web Applications

Today Web applications work by submitting user-filled forms to the Web server and displaying the markup returned by the Web server. The browser-to-server communication employs the classic HTTP protocol. As is widely known, the HTTP protocol is stateless, which means that each request is not related to the next and no state is automatically maintained. (The state objects we all know and use in, say, ASP.NET are nothing more than an abstraction provided by the server programming environment.)

Communication between the browser and the Web server occurs through “forms.” From a user’s perspective, the transition occurs through “pages.” Each user action that originates a new request for the server results in a brand new page (or a revamped version of the current page) being downloaded and displayed.

Let’s briefly explore this model a bit further to pinpoint its drawbacks and bring to the surface the reasons why a new model is needed.

Send Input via Forms

Based on the URL typed in the address bar, the browser displays a page to the user. The page is ultimately made of HTML markup and contains one or more HTML forms. The user enters some data, and then instructs the browser to submit the form to an action URL.

Using the local Domain Name System (DNS) resolver in the operating system, the browser resolves the specified URL to an IP address and opens a socket. An HTTP packet travels over the wire to the given destination. The packet includes the form and all its fields. The request is captured by the Web server and typically forwarded to an internal module for further processing. At the end of the process, an HTTP response packet is prepared and the return value for the browser is inserted in the body.

Get Output through Pages

When a request is made for, say, an .aspx resource, the Web server passes it on to ASP.NET for processing and receives the resulting HTML markup in return. The generated markup comprises all the tags of a classic HTML page, including

,

, and. The page source is embedded in the HTTP response and tagged with a Multipurpose Internet Mail Extensions (MIME) type to instruct the browser how to handle it. The browser looks at the MIME type and decides what to do.

If the response contains an HTML page, the browser replaces the current contents entirely with the new chunk of markup. While the request is being processed on the server, the “old” page is frozen but still displayed to the client user. As soon as the “new” page is downloaded, the browser clears the display and renders the page.

Capabilities and Drawbacks

This model was just fine in the beginning of the Web age when pages contained little more than formatted text, hyperlinks, and some images. The success of the Web has prompted users to ask for increasingly more powerful features, and it has led developers and designers to create more sophisticated services and graphics. As an example, consider advertising. Today, most pages-and often even very simple pages, such as blog pages-include ad rotators that download quite a bit of stuff on the client.

As a result, pages are heavy and cumbersome-even though we still insist on calling them “rich” pages. Regardless of whether they’re rich or just cumbersome, these are the Web pages of today’s applications. Nobody really believes that we’re going to return to the scanty and spartan HTML pages of a decade ago.

Given the current architecture of Web applications, each user action requires a complete redraw of the page. Subsequently, richer and heavier pages render slowly and as a result produce a good deal of flickering. Projected to the whole set of pages in a large, portal-like application, this mechanism is just perfect for unleashing the frustrations of the poor end user.

Although a developer can build a page on the server using one of many flexible architectures (ASP.NET being one such example), from the client-side perspective Web pages were originally designed to be mostly static and unmodifiable. In the late 1990s, the introduction of Dynamic HTML first, and the advent of a World Wide Web Consortium (W3C) standard for the page document object model later, changed this basic fact. Today, the browser exposes the whole content of a displayed page through a read/write object model. In this way, the page can be modified to incorporate changes made entirely on the client-side to react to user inputs. (As we’ll see, this is a key factor for AJAX and ASP.NET AJAX solutions.)

Dynamic HTML is a quantum leap, but alone it is not enough to further the evolution of the Web.

AJAX Based Web Applications

To minimize the impact of page redraws, primitive forms of scripted remote procedure calls (RPC) appeared around 1997. Microsoft, in particular, pioneered this field with a technology called Remote Scripting (RS).

RS employed a Java applet to pull in data from a remote Active Server Pages (ASP)-based URL. The URL exposed a contracted programming interface through a target ASP page and serialized data back and forth through plain strings. On the client, a little JavaScript framework received data and invoked a user-defined callback to update the user interface via Dynamic HTML or similar techniques. RS worked on both Internet Explorer 4.0 and Netscape Navigator 4.0 and older versions.

Later on, Microsoft replaced the Java applet with a Component Object Model (COM) object named XMLHttpRequest and released most of the constraints on the programming interface exposed by the remote URL-for example, no more fixed ASP pages. At the same time, community efforts produced a range of similar frameworks aimed at taking RS to the next level and building a broader reach for solutions. The Java applet disappeared and was replaced by the XMLHttpRequest object.

What Is AJAX, Anyway?

The term AJAX was coined in 2005. It originated in the Java community and was used in reference to a range of related technologies for implementing forms of remote scripting. Today, any form of remote scripting is generally tagged with the AJAX prefix. Modern AJAX-based solutions for the Windows platform are based on the XMLHttpRequest object. Google Maps and Gmail are the two most popular Web applications designed according to AJAX patterns and techniques. For AJAX, these were certainly the killer applications that established its usefulness and showed its potential.

Two combined elements make an AJAX application live and thrive. On one hand, you need to serve users fresh data retrieved on the server. On the other hand, you need to integrate new data in the existing page without a full page refresh.

Browsers generally place a new request when an HTML form is submitted either via clientside script or through a user action such as a button click. When the response is ready, the browser replaces the old page with the new one. Figure 1-1 illustrates graphically this traditional approach.

image from book
Figure 1-1: Browsers submit an HTML form and receive a new page to display.

The chief factor that enables remote scripting is the ability to issue out-of-band HTTP requests. In this context, an out-of-band call indicates an HTTP request placed using a component that is different from the browser’s built-in module that handles the HTML form submission (that is, outside the traditional mechanism you see in Figure 1-1). The out-of-band call is triggered via script by an HTML page event and is served by a proxy component. In the most recent AJAX solutions, the proxy component is based on the XMLHttpRequest object; the proxy component was a Java applet in the very first implementation of RS.

Update Pages via Script

The proxy component (for example, the XMLHttpRequest object) sends a regular HTTP request and waits, either synchronously or asynchronously, for it to be fully served. When the response data is ready, the proxy invokes a user-defined JavaScript callback to refresh any portion of the page that needs updating. Figure 1-2 provides a graphical overview of the model.

image from book
Figure 1-2: Out-of-band calls are sent through a proxy component, and a JavaScript callback is used to update any portion of the page affected by returned data.

All browsers know how to replace an old page with a new page; until a few years ago, though, not all of them provided an object model to represent the current contents of the page. (Today, I can hardly mention a single modern, commercially available browser that doesn’t expose a read/write page DOM.) For browsers that supply an updatable object model for HTML pages, the JavaScript callback function can refresh specific portions of the old page, thus making them look updated, without a full reload.

The Document Object Model

The page Document Object Model (DOM) is the specification that defines a platform- and language-neutral interface for accessing and updating the contents, structure, and style of HTML and XML documents. A recognized standard ratified by the W3C committee, the DOM is now supported by virtually all browsers. The DOM provides a standard set of objects for representing the constituent elements of HTML and XML documents. All together, these objects form a standard interface for accessing and manipulating child elements of HTML pages and, more in general, XML documents.

Note that although the first working frameworks for remote scripting date back to a decade ago, the limited support browsers have had for dynamic changes in displayed documents slowed down the adoption of such technologies in the industry. Until now.

The Role of Rich Browsers

As shown in Figure 1-2, the AJAX model has two key requirements as far as browsers are concerned: a proxy component and an updatable page DOM. For quite a long time, only high-end browsers (also known as rich, up-level browsers) provided support for both features. In the past few years, only companies that could exercise strict control over the capabilities of the client browsers were able to choose the AJAX model for their sites. For too long, a rich browser also has meant a browser with too limited reach. For too long, using such a browser was definitely a bad choice for most businesses because the limited reach excluded significant portions of the customer base.

Rich vs. Reach

Perhaps due to a rare and likely unrepeatable astral conjunction, today more than 90 percent of browsers available on the market happen to have built-in support for the advanced capabilities that the AJAX model requires. Internet Explorer since version 5.0, Firefox, Netscape from version 6 and onward, Safari 1.2, Opera starting with version 8.0, and a variety of mobile devices are all browsers that fully support the AJAX programming model.

For the very first time, a rich browser is not synonymous with a limited reach browser. Finally, you don’t have to choose a particular browser to enjoy advanced, programming-rich features. Designing highly interactive Web applications that implement remote scripting techniques is no longer an impossible dream to chase but a concrete opportunity to seize-whatever browsers you and your clients use.

Each platform and each vendor might have a particular framework and tool set to offer, but this doesn’t change the basic fact that living the AJAX lifestyle is now possible with 90 percent of the browsers available today. It’s a real breakthrough, and it is now possible to build and distribute applications that were not possible before.

Required Capabilities

Exactly what are the capabilities required of a browser to run AJAX functionalities? As mentioned, a browser needs to provide two key capabilities: a proxy mechanism to make client code able to place out-of-band HTTP calls, and an updatable DOM.

There’s a W3C ratified standard for the updatable DOM. A W3C standard for the proxy component is currently being developed. It takes the form of the XMLHttpRequest object and is devised as an interface exposed by the browser to allow script code to perform HTTP client functionality, such as submitting form data or loading data from a remote Web site. The latest working draft is available at http://www.w3.org/TR/XMLHttpRequest.

In addition, browsers must support JavaScript and preferably cascading style sheets (CSS).

In the end, the AJAX lifestyle is possible and affordable for virtually every developer and nearly 90 percent of the Web audience, regardless of the platform. The tools required to make AJAX work are becoming as ubiquitous as HTML/XML parsers, HTTP listeners, and JavaScript processors. To paraphrase the catch phrase of a popular advertising campaign, I’d say that “AJAX is now.” And as far as the Windows and ASP.NET platforms are concerned, AJAX takes the form of Microsoft ASP.NET AJAX Extensions.


The AJAX Core Engine

AJAX is not a particular technology or product. It refers to a number of client features, and related development techniques, that make Web applications look like desktop applications. AJAX doesn’t require any plug-in modules either and is not browser specific. Virtually any browser released in the past five years can serve as a great host for AJAX-based applications. AJAX development techniques revolve around one common software element-the XMLHttpRequest object. The availability of this object in the object model of most browsers is the key to the current ubiquity and success of AJAX applications. In addition to XMLHttpRequest, a second factor contributes to the wide success of AJAX-the availability of a rich document object model in virtually any browser.

Originally introduced with Internet Explorer 5.0, the XMLHttpRequest object is an internal object that the browser publishes to its scripting engine. In this way, the script code found in any client page-typically, JavaScript code-can invoke the object and take advantage of its functionality.

The XMLHttpRequest object allows script code to send HTTP requests and handle their response. Functionally speaking, and despite the XML in the name, the XMLHttpRequest object is nothing more than a tiny object designed to place HTTP calls via script in a non-browser-led way. When users click the submit button of a form, or perform any action that ends up invoking the submit method on the DOM’s form object, the browser kicks in and takes full control of the subsequent HTTP request. From the user’s perspective, the request is a black box whose only visible outcome is the new page being displayed. The client script code has no control over the placement and outcome of the request.

The XMLHttpRequest Object

Created by Microsoft and adopted soon thereafter by Mozilla, the XMLHttpRequest object is today fully supported by the majority of Web browsers. As you’ll see in a moment, the implementation can significantly differ from one browser to the next, even though the top-level interface is nearly identical. For this reason, a W3C committee is at work with the goal of precisely documenting a minimum set of interoperable features based on existing implementations.

  Note 

The XMLHttpRequest object originally shipped as a separate component with Internet Explorer 5.0 back in the spring of 1999. It is a native component of all Microsoft operating systems that have shipped since. In particular, you’ll certainly find it installed on all machines that run Windows 2000, Windows XP, and newer operating systems.

The Internet Explorer Object

When the XMLHttpRequest object was first released, the Component Object Model (COM) was ruling the world at Microsoft. The extensibility model of products and applications was based on COM and implemented through COM components. In the late 1990s, the right and natural choice was to implement this new component as a reusable automation COM object, named Microsoft.XmlHttp.

Various versions of the same component (even with slightly different names) were released over the years, but all of them preserved the original component model-COM. Internet Explorer 6.0, for example, ships the XMLHttpRequest object in the form of a COM object. Where’s the problem?

COM objects are external components that require explicit permission to run inside of a Web browser. In particular, to run the XMLHttpRequest object and subsequently enable any AJAX functionality built on top of it, at a minimum a client machine needs to accept ActiveX components marked safe for scripting. (See Figure 1-3.)

image from book
Figure 1-3: The property window used to change the security settings in Internet Explorer

The XMLHttpRequest object is certainly a safe component, but to enable it users need to lessen their security settings and accept any other component “declared” safe for scripting that is around the Web sites they visit.

  Important 

The internal implementation of XMLHttpRequest is disjointed from the implementation of any AJAX-like frameworks, such as Microsoft ASP.NET AJAX. Under the hood, any framework ends up calling the object as exposed by, or available in, the browser.

The Mozilla Counterpart

Mozilla adopted XMLHttpRequest immediately after its first release with Internet Explorer 5.0. However, in Mozilla-equipped browsers the XMLHttpRequest object is part of the browser’s object model and doesn’t rely on external components. Put another way, a Mozilla browser such as Firefox publishes its own XMLHttpRequest object into the scripting engine and never uses the COM component, even when the COM component is installed on the client machine and is part of the operating system. Figure 1-4 shows the different models in Internet Explorer (up to version 6.0) and Mozilla browsers.

image from book
Figure 1-4: XMLHttpRequest is a scriptable component exposed by the browser in Mozilla and an external COM component in Internet Explorer (up to version 6.0)

As a result, in Mozilla browsers XMLHttpRequest looks like a native JavaScript object and can be instantiated through the classic new operator:

// The object name requires XML in capital letters
var proxy = new XMLHttpRequest();

When the browser is Internet Explorer, the XMLHttpRequest object is instantiated using the ActiveXObject wrapper, as shown here:

var proxy = new ActiveXObject("Microsoft.XmlHttp");

Generally, AJAX-style frameworks check the current browser and then decide about the route to take.

Needless to say, as implemented in Mozilla browsers the XMLHttpRequest functionality is somewhat safer, at least in the sense it doesn’t require users to change their security settings for the browser.

XMLHttpRequest in Internet Explorer 7

Implemented as a COM component for historical reasons on Internet Explorer browsers, the XMLHttpRequest object has finally become a browser object with Internet Explorer 7.0. All potential security concerns are removed at the root, and AJAX frameworks can be updated to use the same syntax for creating the XMLHttpRequest object regardless of the browser:

var proxy = new XMLHttpRequest();

In addition, this change in Internet Explorer 7.0 completely decouples AJAX-like functionality in ASP.NET from an ActiveX-enabled environment.

An HTTP Object Model

I spent quite a few words on the XMLHttpRequest object and its expected behavior, but I still owe you a practical demonstration of the object’s capabilities. In this section, I’ll cover the members of the component, the actions it can perform, and details of the syntax.

As mentioned, the XML in the name of the component means little and in no way limits the capabilities of the component. In spite of the XML prefix, you can use the object as a true automation engine for executing and controlling HTTP requests, from client code generated by ASP.NET pages or the Windows shell, or Visual Basic 6.0 or C++ unmanaged applications. Using the XMLHttpRequest COM object from within .NET applications is nonsensical, as you can find similar functionality in the folds of the System.Net namespace in the .NET Framework.

  Important 

If you’re going to use Microsoft ASP.NET AJAX Extensions or any other AJAX-like framework for building your applications, you’ll hardly hear about the XMLHttpRequest object, much less use it directly in your own code. ASP.NET AJAX Extensions completely encapsulates this object and shields page authors and application designers from it. You don’t need to know about XMLHttpRequest to write great AJAX applications, no matter how complex and sophisticated they are. However, knowing the fundamentals of XMLHttpRequest can lead you to a better and more thorough understanding of the platform and to more effective diagnoses of problems.

Behavior and Capabilities

The XMLHttpRequest object is designed to perform one key operation: sending an HTTP request. The request can be sent either synchronously or asynchronously. The following listing shows the programming interface of the object as it results from the W3C working draft at the time of this writing:

interface XMLHttpRequest {
 function onreadystatechange;
 readonly unsigned short readyState;
 void open(string method, string url);
 void open(string method, string url, bool async);
 void open(string method, string url, bool async, string user);
 void open(string method, string url, bool async,
 string user, string pswd);
 void setRequestHeader(string header, string value);
 void send(string data);
 void send(Document data);
 void abort();
 string getAllResponseHeaders();
 string getResponseHeader(string header);
 string responseText;
 Document responseXML;
 unsigned short status;
 string statusText;
};

Using the component is a two-step operation. First, you open a channel to the URL and specify the method (GET, POST, or other) to use and whether you want the request to execute asynchronously. Next, you set any required header and send the request. If the request is a POST, you pass to the send method the body of the request.

The send method returns immediately in the case of an asynchronous operation. You write an onreadystatechange function to check the status of the current operation and, using that function, figure out when it is done.

Sending a Request

Most AJAX frameworks obtain an instance of the XMLHttpRequest object for the current browser using code that looks like the following:

var xmlRequest, e;
try {
 xmlRequest = new XMLHttpRequest();
}
catch(e) {
 try {
 xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
 }
 catch(e) {
 }
}

The code first tries to instantiate the internal XMLHttpRequest object and opts for the ActiveX object in the case of failure. As you can see, the creation of the object requires an exception to be caught when the browser is Internet Explorer 6.0 or any older versions. Such a code will work unchanged (and won’t require any exception) in Internet Explorer 7.0.

  Note 

Checking the browser’s user agent and foregoing the exception is fine as well. However, ASP.NET AJAX Extensions uses the preceding code because it makes the overall library independent from details of user agent strings and browser details. In this way, you do “object detection” instead of “browser detection.” The final result, though, is the same. The exception is fired only if the browser is Internet Explorer older than version 7.0 or any other browser that doesn’t support AJAX functionalities. If you’re building your own AJAX framework, you need to check the user agent only against Internet Explorer.

The open method prepares the channel for the request; no physical socket is created yet, though. To execute a POST statement, you need to add the proper content-type header. The Boolean argument indicates whether the operation is asynchronous:

xmlRequest.open("POST", url, false);
xmlRequest.setRequestHeader("Content-Type",
 "application/x-www-form-urlencoded");
xmlRequest.send(postData);

The send method opens the socket and sends the packet. In the preceding code snippet, the method returns only when the response has been fully received.

An asynchronous request requires slightly different code:

xmlRequest.open("POST", url, true);
xmlRequest.onreadystatechange = CallbackComplete;
xmlRequest.setRequestHeader("Content-Type",
 "application/x-www-form-urlencoded");
xmlRequest.send(postData);

The CallbackComplete element is a placeholder for a JavaScript function that retrieves and processes the response generated by the request.

Note that the function assigned to the onreadystatechange member will be invoked whenever readyState changes value. Possible values for the state are the integers ranging from 0 through 4, which mean “Uninitialized,” “Open method called successfully,” “Send method called successfully,” “Receiving data,” and “Response received,” respectively. The CallbackComplete framework-specific function will generally check that state and proceed.

Receiving a Response

The response of the request is available in two formats: as raw text and as an XML document. The responseText property is empty if the state is 0 through 2-that is, no data has been received yet. When the state transitions to 3 (receiving data), the property contains the data received so far, interpreted using the character encoding specified in the response. If no character encoding was specified, it employs UTF-8.

The responseXml property is not available until the full response has been downloaded and successfully parsed to an XML document. If the body of the response is not XML or if the parsing fails for any reason, the property returns null. It is important to note that the construction of the XML document takes place on the client once the raw HTTP response has been fully received.

Roll Your Own (Little) AJAX Framework

As mentioned, you don’t need to use the straight XMLHttpRequest object in your AJAX-based application, regardless of the framework (for example, ASP.NET AJAX) you end up using. For completeness, though, let’s briefly review the steps required to use the object in a sample ASP.NET 2.0 page. The same code can be used with ASP.NET 1.x as well. The following code represents the minimal engine you need for building homemade AJAX solutions.

  Note 

Although a homemade AJAX framework might not be recommended, it’s not impossible to write. The fact that more than 100 AJAX frameworks have been counted just demonstrates that writing AJAX homemade solutions is not a mission-impossible task. Personally, I would consider it only as a way to enrich existing applications with quick and dirty AJAX functionality limited to placing remote, non-browser-led calls.

Executing an Out-of-Band Call from an ASP.NET Page

Web pages that shoot out-of-band calls need to have one or more trigger events that, when properly handled with a piece of JavaScript code, place the request via the XMLHttpRequest object. Trigger events can only be HTML events captured by the browser’s DOM implementation.

The JavaScript code should initiate and control the remote URL invocation, as shown in the following code:


 

The sample function accepts two strings: the URL to call and the parameter list. Note that the format of the query string is totally arbitrary and can be adapted at will in custom implementations. The URL specified by the programmer is extended to include a couple of parameters. The first parameter-named outofband in the example-is a Boolean value and indicates whether or not the request is going to be a custom callback request. By knowing this, the target page can process the request appropriately. The second parameter-named param in the example-contains the input parameters for the server-side code.

The host ASP.NET page looks like the following code snippet:


 

Testing Out-of-band

Demonstrate Out-of-band Calls

<%=Request.Url%>



The code-behind class is shown in the following listing:

public partial class _Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 if (IsOutOfBand())
 return;
 if (!IsPostBack)
 PopulateList();
 } 

 private bool IsOutOfBand()
 {
 bool isCallback = false;
 isCallback = String.Equals(Page.Request.QueryString["callback"],
 "true",
 StringComparison.OrdinalIgnoreCase);
 if (isCallback)
 {
 string param = Request.QueryString["param"].ToString();
 Response.Write(ExecutePageMethod(param));
 Response.Flush();
 Response.End();
 return true;
 }
 return false;
 } 

 private void PopulateList()
 {
 SqlDataAdapter adapter = new SqlDataAdapter(
 "SELECT employeeid, lastname FROM employees",
 "SERVER=(local);DATABASE=northwind;UID=...;");
 DataTable table = new DataTable();
 adapter.Fill(table); 

 EmployeeList.DataTextField = "lastname";
 EmployeeList.DataValueField = "employeeid";
 EmployeeList.DataSource = table;
 EmployeeList.DataBind();
 }
 string ExecutePageMethod(string eventArgument)
 {
 return "You clicked: " + eventArgument;
 }
}

A couple of issues deserve more attention and explanation. The first one is the need to find out whether the request is an out-of-band call or a regular postback. Next, we need to look at the generation of the response. The IsOutOfBand method checks the outofband field in the posted form. If the outofband field is found, the request is served and terminated without going through the final part of the classic ASP.NET request life cycle-events for changed values, postback, pre-rendering, view-state serialization, rendering, and so forth. An out-of-band request is therefore short-circuited to return more quickly, carrying the least data possible.

What does the page do when an out-of-band call is placed? How does it determine the response? Most of the actual AJAX-based frameworks vary on this point, so let’s say it is arbitrary. In general, you need to define a public programming interface that is invoked when an out-of-band call is made. In the sample code, I have a method with a contracted name and signature-ExecutePageMethod-whose output becomes the plain response for the request. In the sample code, the method returns and accepts a string, meaning that any input and output parameters must be serializable to a string.

string param = Request.QueryString["param"].ToString();
Response.Write(ExecutePageMethod(param));
Response.Flush();
Response.End();

As in the code snippet, the response for the out-of-band request is the output of the method. No other data is ever returned; and no other data except for the parameters is ever sent. In this particular implementation, there will be no view state sent and returned.

  Important 

Although you’ll probably never get to write any such code, be aware that thus far I’ve just provided a minimal but effective description of the underlying mechanism common to most frameworks that supply AJAX-like functionality. Each framework encapsulates a good number of details and adds new services and capabilities. At its core, though, this is how AJAX libraries work.

Displaying Results

One more step is missing-what happens on the client once the response for the out-of-band call is received? The following snippet shows a piece of client code that, when attached to a button, fires the out-of-band call and refreshes the user interface:

function MoreInfo()
{
 var empID = document.getElementById("EmployeeList").value;
 var xml = SendRequest("default.aspx", empID);

 // Update the UI
 var label = document.getElementById("Msg");
 label.innerHTML = xml.responseText;
}

According to the code, whenever the user clicks the button a request is sent at the following URL. Note that 1 in the sample URL indicates the ID of the requested employee. (See Figure 1-5.)

default.aspx?outofband=true¶m=1

image from book
Figure 1-5: A manually coded out-of-band request in ASP.NET 1.x and ASP.NET 2.0

Displaying results correctly on most browsers can be tricky. Internet Explorer, in fact, supports a number of nonstandard shortcuts in the DOM that just don’t work with other browsers. The most common snag is retrieving references to HTML elements using the document.getElement-ById method instead of the direct name of the element. For example, the following code works on Internet Explorer but not on Firefox and other Mozilla-equipped browsers:

// Msg is the ID of a  tag.
// This code works only with Internet Explorer
Msg.innerHTML = xml.requestText;

In summary, cross-browser JavaScript code is required to update the currently displayed page on the client. At the same time, a number of assumptions must be made on the server to come up with a working and effective environment. For this reason, frameworks are the only reasonable way of implementing AJAX functionalities. Different frameworks, though, might provide a different programming interface on top of an engine that uses the same common set of parts.

The Switch to the Document Object Model

Microsoft has pioneered updatable Web pages since the late 1990s. With Internet Explorer 4.0 (released back in 1997), Microsoft introduced Dynamic HTML (DHTML), which is a powerful combination of HTML, style sheets, and scripts that allows programmatic changes to any displayed page. Several companies since then have worked out their own DHTML object model-often referred to as the Browser Object Model (BOM). The W3C committee worked hard to bring vendors to agree on an interoperable and language-neutral solution for exposing Web pages through an updatable programming interface. The result is the Document Object Model (DOM), as opposed to a browser-specific BOM.

The DOM is a platform-independent and language-neutral representation of the contents of a Web page that scripts can access and use to modify the content, structure, and style of the document.

For AJAX, it’s all about exchanging data with a remote server. But once the data is downloaded out-of-band on the client, what can you do with that? The DOM provides an outlet for the data to flow into the current page structure and update it.

Representation of a Document

The DOM is a standard API exposed by the browser in which a displayed page has a treebased structure. Each node in the logical tree corresponds to an object. On the other hand, the name “Document Object Model” hints at an object model in the common interpretation of the object-oriented design terminology. A Web page-the document-is modeled through objects. The model includes the structure and behavior of a document. Each node in the logical tree is not static data; rather, it is a live object with a known behavior and its own identity.

DOM Implementation

The W3C DOM consists of three levels that indicate, for the browser, three different levels of adherence to the standard. For more information, take a look at http://www.w3.org/DOM.

The DOM is made of nodes, and each node is an object. For a Web page, each node maps to an object that represents an HTML tag. The object, therefore, has properties and methods that can be applied to an HTML tag. There are three fundamental operations you can accomplish on a node: find the node (including related nodes such as children, parent, or sibling nodes), create a node, and manipulate a node.

Identifying a particular node is easy as long as the page author knows the ID of the corresponding element. In this case, you use the following standard piece of code:

var node = document.getElementById(id);

In particular, if there are multiple elements sharing the same ID value, the method returns the first object in the collection. This method is supported in the DOM Level 1 and upper levels. Another interesting method to find elements is the following:

var coll = document.getElementsByTagName(tagname);

The method retrieves a collection of all objects based on the same HTML tag. For example, the method retrieves a collection of all

or all tags in the page.

Related DOM objects are grouped in node lists. Each node has a name, type, parent, and collection of children. A node also holds a reference to its siblings and attributes. The following code snippet shows how to retrieve the parent of a node and its previous sibling:

var oParent = oNode.parentNode
var oPrevious = oNode.previousSibling

How can you modify the contents of a node? The easiest and most common approach entails that you use the innerHTML property:

var node = document.getElementById("button1");
node.innerHTML = "Hey click me";

The innerHTML property is supported by virtually all browsers, and it sets or retrieves the HTML between the start and end tags of the given object. Some browsers such as Internet Explorer also support the innerText property. This property is designed to set or retrieve the text inside of a given DOM object. Unfortunately, this property is not supported by all browsers. It exists in Internet Explorer and Safari but, for example, it is not supported by Firefox. Firefox, on the other hand, supports a property with a similar behavior but a different name-textContent.

  Note 

The advent of the Microsoft AJAX Client Library (discussed in Chapter 2, “The Microsoft Client Library for AJAX”) shields developers from having to know much about the little differences between the DOM implementation of the various browsers. For example, you should know about innerText and textContent if you’re embedding your own JavaScript in the page; however, you don’t have to if you rely on the AJAX Client Library to refresh portions of the displayed page.

  Note 

Finally, note that you should not check the user agent string to figure out whether the current browser supports a given feature. You should check the desired object instead. For example, to know whether the browser supports innerText, you’re better off running the following code:

var supportsInnerText = false;
var supportsInnerText = false;
if (temp != undefined)
supportsInnerText = true;
...

In this way, you directly check the availability of the property without having to maintain a list of browsers.

Nodes are created using the createElement method exposed only to the document object. Alternatively, you can add new elements to the document hierarchy by modifying the innerHTML property value, or by using methods explicit to particular elements, such as the insertRow and insertCell methods for the table element. Here’s an example:

// Create an  element
var oImg = document.createElement("");
...
// Create a new option for the SELECT element
var oOption = new Option(text, id);
control.options.add(oOption);

With this information, I have only scratched the surface of the DOM implementation in the various browsers. Nonetheless, the DOM is a key part of the AJAX jigsaw puzzle and deserves a lot of attention and skilled use. For a primer, you can take a look at http:// msdn.microsoft.com/workshop/author/dom/domoverview.asp.

Be Pragmatic: DHTML vs. DOM

In the beginning, only the browser’s support for the DHTML object model provided JavaScript developers with the ability to update the page contents dynamically. The success of DHTML led to the definition of a standard document object model-the W3C’s DOM. Quite obviously, the DOM evolved from DHTML and became much more generalized than DHTML. As mentioned, the DOM provides a tree-based model for the whole document, not just for an individual HTML tag.

Most browsers, though, support a mix of DOM and DHTML. Which one should you use? In particular, to update some contents, should you obtain a reference to the textual child node of the node that matches the intended HTML tag (the DOM way) or just grab a reference to a node and use innerHTML (the DHTML way)? Likewise, to add a new element, should you create a new element or just stuff in a chunk of updated HTML via innerHTML? Admittedly, one of the most interesting debates in the community is whether to use DHTML to manipulate pages or opt for the cleaner approach propounded by the DOM application programming interface (API).

The key fact is that the DOM API is significantly slower than using innerHTML. If you go through the DOM to generate some user interface dynamically, you have to create every element, append each into the proper container, and then set properties. The alternative only entails that you define the HTML you want and render it into the page using innerHTML. The browser, then, does the rest by rendering your markup into direct graphics.

Overall, DHTML and DOM manipulation are both useful depending on the context. There are many Web sites that discuss performance tests and DHTML is always the winner. Anyway, DOM is still perfectly fast as long as you use it the right way-that is, create HTML fragments and append them to the proper container only as the final step.

Be Pragmatic: Use Events

Let’s make it clear: without events, there would be no point in adding JavaScript to Web pages. To be effective, therefore, scripts have to react to some user action as well as to actions generated by the browser, such as when loading the page. Events and event handlers are old companions to Web pages, as they appeared the first time with Netscape 2.

For quite some time, largely incompatible event models lived and thrived in different browsers-mainly in Internet Explorer and Netscape. A few years ago, the W3C standardized the event model with a paper that you can read at http://www.w3.org/TR/2000/ REC-DOM-Level-2-Events-20001113/events.html.

With Internet Explorer and Netscape having their own original event model, and making themselves compatible to the W3C standard, you understand that writing model-agnostic event handlers is going to be a hard task. There are a lot of events, but not all of them are supported by all browsers. The following categories of events can be considered standard: user interface events (blur, focus, scroll), device events (click, keydown), and form events (submit, select). The second big point concerns how you set event handlers. The most reliable way is still the following:


 

<a href="page.aspx" onclick="doClick()">An excellent paper that discusses the theme of events in JavaScript can be found here: http:// www.quirksmode.org/js/introevents.html. </a>

  <a href="page.aspx" onclick="doClick()">Tip </a>

<a href="page.aspx" onclick="doClick()">If you’re looking for a great Web site to learn about the various aspects of JavaScript, DHTML, DOM, CSS and client-side programming in general, the right place to go is http://www.quirksmode.org. </a>

<a href="page.aspx" onclick="doClick()">Existing AJAX Frameworks for ASP NET</a>

<a href="page.aspx" onclick="doClick()">Today, quite a few APIs exist to implement AJAX functionality in ASP.NET, and one of these APIs is already integrated into ASP.NET 2.0. Other APIs come from third-party vendors or take form from open-source projects. I’ll briefly look at some of these APIs. Note, though, that as long as ASP.NET is your development environment, the most reasonable choice you can make is Microsoft ASP.NET AJAX Extensions. However, ASP.NET AJAX Extensions can coexist pretty well with a large number of the existing alternative AJAX frameworks. ASP.NET AJAX is not a mutually exclusive choice.</a>

<a href="page.aspx" onclick="doClick()">Since early 2005, some aggressive independent software vendors (for example, Telerik, Infragistics, and ComponentArt) have integrated AJAX functionality into their existing suite of controls for rapid and rich Web development. In the beginning, each vendor developed its own internal and proprietary AJAX engine and integrated it with the product. The advent of ASP.NET AJAX Extensions will likely prompt vendors to offer native ASP.NET AJAX controls or, at a minimum, provide controls that work seamlessly with ASP.NET AJAX.</a>

<a href="page.aspx" onclick="doClick()">Let’s review some of the options you have today for developing AJAX-enabled ASP.NET Web applications. As you can see, the list is not exhaustive and features libraries from both independent software vendor (ISV) companies and open-source projects started by outstanding members of the ASP.NET community.</a>

<a href="page.aspx" onclick="doClick()">ASP.NET Script Callbacks</a>

<a href="page.aspx" onclick="doClick()">ASP.NET 2.0 contains a native API, named ASP.NET Script Callback, to implement out-of-band calls to the same URL of the current page. This API makes the out-of-band request look like a special-case page request. It transmits the view state along with original input fields. A few additional input fields are inserted in the body of the request to carry extra information. Once on the server, the request passes through the regular pipeline of HTTP modules and raises the expected sequence of server-side events up to the pre-rendering stage.</a>

<a href="page.aspx" onclick="doClick()">Just before the pre-rendering stage, the page method is executed, the return value is serialized to a string, and then the string is returned to the client. No rendering phase ever occurs, and the view state is not updated and serialized back.</a>

<a href="page.aspx" onclick="doClick()">ASP.NET Script Callback provides its own JavaScript API to wrap any needed calls to XMLHttpRequest. As a developer, you are not required to know about this API in detail. As a developer, you should instead focus on the programming interface of the GetCallbackEvent-Reference method of the Page.ClientScript object. This method simply returns the JavaScript code to attach to a client-side event handler to place an out-of-band call. The JavaScript code also references another piece of JavaScript used to update the page with the results generated on the server. But what happens on the server when the secondary request is made? Which page method is executed?</a>

<a href="page.aspx" onclick="doClick()">ASP.NET Script Callback defines an interface-the ICallbackEventHandler interface-that any server object that is the target of an out-of-band call can implement. The target of the out-of-band call can be either the page or any of its child controls. The execution of an out-of-band call is divided into two steps: preparation and results generation. The RaiseCallbackEvent method of the ICallbackEventHandler interface is invoked first to prepare the remote code execution. The GetCallbackResult method is invoked later in the request life cycle when it is time for the ASP.NET runtime to generate the response for the browser.</a>

<a href="page.aspx" onclick="doClick()">All in all, the programming interface of ASP.NET Script Callback is a bit clumsy. Although the programming interface shields developers from a lot of internal details, it still requires the programmer to have good JavaScript skills and is articulated in a bunch of boilerplate server code. You need server code to bind HTML elements to client-side event handlers, and you need ad hoc server code to publish a programming interface that is callable from the client. Each request carries with it a copy of the original view state and rebuilds the last known good state on the server. In other words, the original value of all input fields in the currently displayed page (regardless of any changes entered before the out-of-band call is made) are sent to the server along with any parameters for the server method. Any out-of-band calls are processed as a regular postback request up to the pre-rendering stage, meaning that all standard server events are fired: Init, Load, LoadComplete, and so on. Before the pre-rendering stage, the callback is prepared and executed shortly after. The requests ends immediately after the server method executes. The view state is not updated to reflect the state of the page after the out-of-band call and subsequently, it is not sent back to the client.</a>

<a href="page.aspx" onclick="doClick()">The advantage of using ASP.NET Script Callback is that it is a native part of ASP.NET and can be easily encapsulated in server controls. For example, the TreeView control in ASP.NET 2.0 uses script callbacks to expand its nodes.</a>

<a href="page.aspx" onclick="doClick()">ASP.NET Script Callback is not free of significant issues, however. In particular, the server method is constrained to a fixed signature and can only take and return a string. Sure, you can place any contents in the string, but the serialization and deserialization of custom objects to the string is something you must take care of entirely on your own. In addition, a page based on ASP.NET Script Callback can have only one endpoint for remote calls. This means that if a client page needs to place two distinct calls to the same remote page, you have to implement a switch in the implementation of the ICallbackEventHandler interface to interpret which method was intended to be executed.</a>

<a href="page.aspx" onclick="doClick()">The AJAX.NET Professional Library</a>

<a href="page.aspx" onclick="doClick()">To effectively implement out-of-band calls in application-wide scenarios, a kind of framework is required that hides all the nitty-gritty details of HTTP communication and exposes additional and higher-level controls and services. </a>

<a href="page.aspx" onclick="doClick()">AJAX.NET Professional (AjaxPro) is a pretty popular open-source library that adds a good layer of abstraction over the XMLHttpRequest machinery. Written by Michael Schwarz, the library creates proxy classes that are used by client-side JavaScript to invoke methods on the server page. The AjaxPro framework provides full data type support and works on all common Web browsers, including mobile devices. Nicely enough, the library can be used with both ASP.NET 1.1 and ASP.NET 2.0.</a>

<a href="page.aspx" onclick="doClick()">The key tool behind the AjaxPro library is an HTTP handler that hooks up any HTTP requests generated by the client-side part of the library:</a>

<a href="page.aspx" onclick="doClick()">

 
</a>

<a href="page.aspx" onclick="doClick()">Once the web.config file has been correctly set up, you write JavaScript functions to trigger and control the out-of-band call. Each call targets a JavaScript object that represents the publicly callable method on the server ASP.NET page. A client-callable method is just a public method decorated with a specific attribute, as shown here:</a>

<a href="page.aspx" onclick="doClick()">
[AjaxPro.AjaxMethod]
public DateTime GetCurrentTimeOnServer()
{
 return DateTime.Now;
}</a>

<a href="page.aspx" onclick="doClick()">The class with public methods, as well as any custom types used for I/O, has to be registered with the framework to have the corresponding JavaScript proxy created:</a>

<a href="page.aspx" onclick="doClick()">
protected void Page_Load(object sender, EventArgs e)
{
 AjaxPro.Utility.RegisterTypeForAjax(typeof(YourAjaxClass));
}</a>

<a href="page.aspx" onclick="doClick()">If you do this, the handler guarantees that any managed .NET object that is returned by a server method will be serialized to a dynamically created JavaScript object to be seamlessly used on the client. You can return any managed type, your own classes, or enum types as you would do in plain .NET code. No view state is available during the AJAX request, meaning that you can’t do much with page controls. In light of this, it is recommended that you create callable methods as static methods preferably, though not necessarily, on a separate class.</a>

<a href="page.aspx" onclick="doClick()">AjaxPro has some key advantages over the ASP.NET Script Callback API. It uses an attribute to mark server methods that can be called from the client. This means that you have the greatest flexibility when it comes to defining the server public interface callable from the client. In particular, you don’t have to change the flow of the code or add new ad hoc methods just to comply with the requested programming interface. </a>

<a href="page.aspx" onclick="doClick()">In addition, you can register server types for use on the client, which provides for a strongtyped data transfer. The AjaxPro infrastructure serializes .NET types to JavaScript objects and vice versa. The AJAX.NET hooks up and replaces the standard request processing mechanism of ASP.NET-the page handler. As a result, you won’t receive classic ASP.NET server events such as Init, Load, and postback. At the same time, you won’t have the view state automatically transmitted with each out-of-band request. An AjaxPro request, though, is still processed by the ASP.NET HTTP runtime, meaning that the request is still subject to the modules registered with the HTTP pipeline, including session state management, roles, and authentication.</a>

<a href="page.aspx" onclick="doClick()">For more information about the AjaxPro library, you can take a look at http://www.ajaxpro.info. There you will also find a link to the CodePlex Web site to get the source code of the library.</a>

<a href="page.aspx" onclick="doClick()">The Anthem.NET Framework</a>

<a href="page.aspx" onclick="doClick()">Anthem.NET is a free, cross-browser AJAX toolkit for both ASP.NET 1.1 and 2.0, written by Jason Diamond. The library is made of a number of server controls that use XMLHttpRequest to post back. It sets itself apart from AjaxPro because it fully integrates with the classic life cycle of each ASP.NET request. The view state is sent across the wire, and server-side page and control events such as Init, Load, and PreRender are regularly fired. As a result, you write a page using the same programming model of ASP.NET, you are not required to write any JavaScript yourself, and you still leverage the beauty of the AJAX model. The only difference with a traditional ASP.NET application is that you use a different set of server controls, most of which are just subclassed versions of the original ASP.NET controls.</a>

<a href="page.aspx" onclick="doClick()">Extremely lean and easy to use, Anthem.NET implements AJAX functionalities through the “partial rendering” model applied at the control level. The partial rendering model is the same model that ASP.NET AJAX pushes hard. (See Chapter 4, “Partial Page Rendering.”) For more information, check out http://www.anthemdotnet.com.</a>

<a href="page.aspx" onclick="doClick()">The ComfortASP.NET Framework</a>

<a href="page.aspx" onclick="doClick()">Conceptually similar to Anthem.NET, but significantly different in its implementation, is Daniel Zeiss’ ComfortASP.NET framework. ComfortASP.NET uses a manager server control to inject script code in the client page. Invisible to the page author, the script code hooks up client postbacks and replaces them with calls to XMLHttpRequest.</a>

<a href="page.aspx" onclick="doClick()">Once back on the server, the manager component takes control of the operations and determines the delta between the current page and the page resulting from the processing of the current request. The markup that describes the changes in the displayed page is sent back and used to dynamically modify the page contents on the client via the previously emitted script. The server life cycle of the page is executed as usual, and events such as Init and Load are fired when expected. </a>

<a href="page.aspx" onclick="doClick()">The ComfortASP.NET framework refers to this technique as “selective update;” but in the end it is just another term to indicate what ASP.NET AJAX calls “partial rendering.” (We’ll cover partial rendering in Chapter 4.)</a>

<a href="page.aspx" onclick="doClick()">Using ComfortASP.NET couldn’t be easier and faster. It only requires you to tweak the web.config file to add an HTTP handler for ASP.NET requests and add a manager control to each page you intend to expand with AJAX capabilities. The manager control features a few interesting properties such as compression, automatic form disabling during postback, and request timeout handling.</a>

<a href="page.aspx" onclick="doClick()">Taken alone, the manager control works on the page as a whole. The framework also includes a PanelUpdater control for you to selectively update specific portions (panels) of the page. You can learn more about the ComfortASP.NET Framework at http://www.comfortasp.de/.</a>

<a href="page.aspx" onclick="doClick()">The Telerik r.a.d.controls for ASP.NET Framework</a>

<a href="page.aspx" onclick="doClick()">Telerik r.a.d.controls for ASP.NET is a suite of versatile user-interface (UI) components, which offer complete interoperability with Microsoft ASP.NET AJAX Extensions. The product allows developers to build a sophisticated and largely customizable user interface based on ASP.NET AJAX. This means that r.a.d.controls are safe for use inside of any ASP.NET AJAX page and interact smoothly with any built-in ASP.NET AJAX controls.</a>

<a href="page.aspx" onclick="doClick()">Telerik is currently working on a special update of the r.a.d.controls suite, which will leverage the complete capabilities of the ASP.NET AJAX Framework. The new version of the product should be available by the time you read this book. Among the novelties, you can certainly expect a client-side object model that is consistent with the Microsoft AJAX Client Library conventions and controls that fully participate in the client life cycle of the request. (See Chapter 2.) In addition, the r.a.d.controls suite has rich type information similar to the .NET type descriptors, easy component discoverability and enumeration, and optimized resource management and disposal on partial page updates.</a>

<a href="page.aspx" onclick="doClick()">Apart from that, Telerik offers its own AJAX framework, called r.a.d.ajax. The purpose of the product is to eliminate the complexities of building JavaScript-intensive AJAX applications so that developers can take advantage of this new technology with no additional learning curve to climb. Complexities are eliminated by encapsulating the AJAX engine and all surrounding logic, including scripts, into classic ASP.NET server components, which can be configured visually with convenient builders in Visual Studio 2005. As a result, developers can simply write regular postback-based applications and turn them into AJAX-enabled ones without writing any JavaScript or server-side code.</a>

<a href="page.aspx" onclick="doClick()">The Telerik engine completely preserves the life cycle of the ASP.NET page, which is imperative for the proper operation of your application. The view state, event validation, and client-side scripts are also preserved as if a normal postback takes place. All form values are automatically sent to the server for processing. Telerik’s framework is based on a patentpending technology that manages AJAX postbacks internally. </a>

<a href="page.aspx" onclick="doClick()">For more information, visit http://www.telerik.com.</a>

<a href="page.aspx" onclick="doClick()">The ComponentArt Web.UI Framework</a>

<a href="page.aspx" onclick="doClick()">ComponentArt features Web.UI for ASP.NET AJAX-the first suite of controls designed specifically for ASP.NET AJAX. The library has a variety of advanced user interface controls for use in sophisticated Web applications-for example, grids, splitters, tree views, and drop-down lists. The Callback control, on the other hand, provides base AJAX capabilities.</a>

<a href="page.aspx" onclick="doClick()">The Web.UI library goes beyond mere compatibility or basic interoperability with ASP.NET AJAX. Rather, it offers deep integration into the new Microsoft AJAX framework. You find a bunch of server controls enriched with a client-side object model that fully leverages the Microsoft AJAX Client Library type system. (We’ll cover the Microsoft AJAX Client Library in Chapter 2.) In particular, all controls inherit from the Sys.UI.Control client-side base class and expose extensive client-side methods and attributes to be invoked and set via script. Controls participate in the client-side life cycle, notify events, and communicate with native DOM elements.</a>

<a href="page.aspx" onclick="doClick()">All Web.UI controls have the ability to command AJAX postbacks on their own or through the ASP.NET AJAX’s UpdatePanel control. (See Chapter 4.) For example, the TreeView and Grid controls implement their own built-in lightweight callback mechanisms for things such as load on demand or paging.</a>

<a href="page.aspx" onclick="doClick()">Similar to the ASP.NET AJAX UpdatePanel, the CallBack component can optionally wrap controls to update, and it can either bypass the standard page life cycle and execute server-side logic more quickly or maintain the latest state of all ASP.NET controls contained in the page through the view state. The client-side model of the CallBack component can be used from the client to execute server-side code. The CallBack control, though, is not used by any other Web.UI control internally.</a>

<a href="page.aspx" onclick="doClick()">For more information, visit http://www.componentart.com.</a>

<a href="page.aspx" onclick="doClick()">Infragistics’s NetAdvantage for ASP.NET AJAX</a>

<a href="page.aspx" onclick="doClick()">NetAdvantage for ASP.NET-the Infragistics’s flagship product for ASP.NET development-offers a full range of components ranging from a tree and menu, to a hierarchical grid, and even a charting engine. Infragistics employs a technique known as “Embedded AJAX” to build the AJAX functionality directly into their controls. By embedding the AJAX into the control itself, performance levels are achieved that would not otherwise be possible (when utilizing a separate AJAX engine or wrapper). In addition to the built-in AJAX features, Infragistics also supplies the “WARP Panel,” which can be used to give any control(s) AJAX capabilities, much in the same manner as Microsoft’s UpdatePanel.</a>

<a href="page.aspx" onclick="doClick()">Because the AJAX capabilities are built into Infragistics’ WebControls, a developer need only know how to set a property to start using AJAX. Infragistics refers to this concept as </a>

<a href="page.aspx" onclick="doClick()">“No-Touch AJAX.” Should you want to get your hands dirty, Infragistics provides a full clientside object model with API’s and even an event model that can be programmed entirely through JavaScript. NetAdvantage for ASP.NET offers interoperability with Microsoft’s ASP.NET AJAX Extensions-enabling you to use these two powerful toolsets side-by-side. Though the current level of integration with ASP.NET AJAX is not as deep as we’ve seen with ComponentArt’s Web.UI, Infragistics manages to provide much of the same functionality through their own framework.</a>

<a href="page.aspx" onclick="doClick()">For more information, visit http://www.infragistics.com/ajax.</a>

<a href="page.aspx" onclick="doClick()">Categorizing AJAX Frameworks</a>

<a href="page.aspx" onclick="doClick()">As you can witness yourself, each AJAX-oriented framework falls into one of the following three main categories:</a>

  • <a href="page.aspx" onclick="doClick()">RPC-style frameworks</a>
  • <a href="page.aspx" onclick="doClick()">A suite of rich controls</a>
  • <a href="page.aspx" onclick="doClick()">AJAX frameworks</a>

<a href="page.aspx" onclick="doClick()">RPC-style frameworks are ASP.NET libraries that simply provide the capability of calling back server code from the client via JavaScript. ASP.NET Script Callbacks and AjaxPro certainly have this capability.</a>

<a href="page.aspx" onclick="doClick()">Commercial products from popular vendors such as Telerik, ComponentArt, and Infragistics offer a suite of controls with AJAX capabilities. Currently, they don’t provide the same level of integration with the ASP.NET AJAX platform; however, in the short term they will be aligned at the same level and differentiate their product offerings by extending differing levels of features and capabilities, some solidly Microsoft ASP.NET AJAX compliant (Component Art) and others to a lesser degree.</a>

<a href="page.aspx" onclick="doClick()">Finally, there will be pure AJAX frameworks-that is, a code library that enables pages and applications to do AJAX. Of course, ASP.NET AJAX Extensions is the most rich and powerful option, and it’s certainly the standard to follow for the largest share of developers. However, a number of good frameworks (often, open-source frameworks) exist-such as Anthem.NET and ComfortASP.NET-that simply help you build AJAX pages quickly and effectively. They have anticipated most of the features you find today in ASP.NET AJAX Extensions.</a>


<a href="page.aspx" onclick="doClick()"> </a>

<a href="page.aspx" onclick="doClick()">ASP NET AJAX in Person</a>

<a href="page.aspx" onclick="doClick()">Architecturally speaking, the ASP.NET AJAX framework is made of two distinct elements: a client script library and a set of server controls that add AJAX capabilities to ASP.NET 2.0. The client script library is written entirely in JavaScript and therefore works with any modern browser. ASP.NET AJAX offers an end-to-end programming model that spans the client and server environment. It’s also seamless to use for most developers because it simply extends the popular and known application model of classic ASP.NET.</a>

<a href="page.aspx" onclick="doClick()">Setting Up ASP NET AJAX Extensions</a>

<a href="page.aspx" onclick="doClick()">Before we delve into the ASP.NET AJAX architecture, let’s briefly review some common issues related to installing, configuring, and running ASP.NET AJAX applications.</a>

<a href="page.aspx" onclick="doClick()">Installing ASP.NET AJAX Extensions</a>

<a href="page.aspx" onclick="doClick()">The setup phase of ASP.NET AJAX Extensions installs debug and release copies of the AJAX Script Library and any needed binaries. If you have any version of Visual Studio 2005 installed, the package also configures the Integrated Development Environment (IDE) to show a ready-made AJAX project template. (See Figure 1-6.)</a>

<a href="page.aspx" onclick="doClick()">image from book
Figure 1-6: The new AJAX project template that shows up when you create a new Web site. </a>

<a href="page.aspx" onclick="doClick()">The ASP.NET AJAX Extensions Microsoft Windows Installer (MSI) package installs a handful of files on your computer under the following folder:</a>

<a href="page.aspx" onclick="doClick()">
%DRIVE%:Program FilesMicrosoft ASP.NETASP.NET 2.0 AJAX Extensionsv1.0.61025</a>

<a href="page.aspx" onclick="doClick()">In addition, it places an assembly named System.Web.Extensions.dll in the global assembly cache (GAC). The ASP.NET AJAX assembly incorporates a bunch of JavaScript files (.js files) that form the client script library.</a>

  <a href="page.aspx" onclick="doClick()">Note </a>

<a href="page.aspx" onclick="doClick()">The official installer of ASP.NET AJAX copies the binaries in the GAC. This is still the recommended way to go. However, simply copying the System.Web.Extensions assembly in the Bin folder does suffice to deploy an ASP.NET AJAX Web site.</a>

<a href="page.aspx" onclick="doClick()">Deploying ASP.NET AJAX Applications</a>

<a href="page.aspx" onclick="doClick()">The simplest way to create an ASP.NET AJAX application is by choosing the Visual Studio 2005 project template. (See Figure 1-6.) Visual Studio adds to the project a web.config file that contains all settings required to run an ASP.NET AJAX application. In particular, the configuration file links the ASP.NET AJAX assembly to the project.</a>

<a href="page.aspx" onclick="doClick()">If your ASP.NET AJAX application consumes Web services, you should ensure that these Web services-local to the application-have correctly installed and can find all of their required resources.</a>

  <a href="page.aspx" onclick="doClick()">Important </a>

<a href="page.aspx" onclick="doClick()">Not all configuration entries created in the default web.config file are required in all cases. You might want to remove those that you don’t need. In particular, you might want to remove HTTP handlers and HTTP modules that serve calls to Web services and page methods, respectively, if your application doesn’t place remote out-of-band calls directly from JavaScript. However, when you edit the web.config file pay a lot of attention and limit yourself to commenting out parts rather than deleting them. You might inadvertently remove an important setting that breaks the whole application.</a>

<a href="page.aspx" onclick="doClick()">Core Components</a>

<a href="page.aspx" onclick="doClick()">The ASP.NET AJAX framework is made of a client and a server part. Applications use a clientside JavaScript library mostly to manage the page user interface, to call server-based components, and order partial page refreshes. Server components generate the response for the client and emit predefined client script that integrates and sometimes extends the client library. The server-side part of ASP.NET AJAX includes Web services, ad hoc controls, and the JavaScript Object Notation (JSON) infrastructure. (I discuss the JSON data interchange technology a bit later in this chapter.)</a>

<a href="page.aspx" onclick="doClick()">The Microsoft Client Library for AJAX</a>

<a href="page.aspx" onclick="doClick()">The AJAX client library is made of a set of JavaScript (*.js) files that are linked from client pages in case of need. These *.js files are downloaded on each client that consumes ASP.NET AJAX pages. These files are transparent to ASP.NET developers, as they are embedded in the ASP.NET AJAX assembly.</a>

<a href="page.aspx" onclick="doClick()">The client library provides object-oriented and cross-browser extensions to the JavaScript language such as classes, namespaces, inheritance, and data types. In addition, it defines a largely shrink-wrapped version of the .NET base class library that includes string builders, regular expressions, timers, and tracing. The key part of the ASP.NET AJAX client library is the networking layer that manages the complexity of making asynchronous calls over XMLHttpRequest. This layer allows the client page to communicate with Web services and Web pages through out-of-band calls. </a>

<a href="page.aspx" onclick="doClick()">Server-Based Components</a>

<a href="page.aspx" onclick="doClick()">ASP.NET AJAX is an extension to ASP.NET, and ASP.NET is a server-side development platform. Hence, ASP.NET AJAX sports a number of server-based components, including Web services and controls, that offer a double benefit. On one end, you can program these components from the client and update the current page without a full refresh; on the other hand, though, the programming model remains unaltered for the most part. In this way, at least limited to core functionalities, the ASP.NET AJAX learning curve might be pleasantly short.</a>

<a href="page.aspx" onclick="doClick()">Built-in Web services expose a handful of ASP.NET features to client pages, including user profiles, membership, and roles. Server controls look like classic ASP.NET server controls, except that they emit additional script code. The script code enriches the user’s experience with the control by optionally taking advantage of the facilities provided by the AJAX client library. Some key AJAX server controls you will work with are UpdatePanel, UpdateProgress, and Timer. I’ll cover them in Chapter 4.</a>

<a href="page.aspx" onclick="doClick()">The JSON Infrastructure</a>

<a href="page.aspx" onclick="doClick()">The growing use of out-of-band calls in Web applications poses a new issue-moving more and more complex data around. It’s not a mere serialization issue for which the .NET Framework and other platform-specific frameworks have a ready-made solution. The serialization involved with out-of-band calls is not just cross-platform; it also involves distinct tiers and radically different tools and languages. With out-of-band calls, you move data from a client to a server and back. But the client is a browser (if not a mobile device), and JavaScript is the native format of data. The server is a Web server hosted on a variety of hardware/software platforms and running a specific Web application framework.</a>

<a href="page.aspx" onclick="doClick()">JSON is the emerging technology for passing structured data across the Web. It is a data interchange format and is fully described at http://www.json.org. Relatively easy to read for humans and to parse and generate for machines, JSON describes data using two universal data structures-collections and array-that are supported in one way or another by most modern programming languages and class libraries.</a>

<a href="page.aspx" onclick="doClick()">JSON is a text format that is completely language independent, although it relies heavily on a number of conventions inherited from the C family of languages.</a>

<a href="page.aspx" onclick="doClick()">The JSON client infrastructure can serialize a JavaScript object to an interchange format and send it over the wire to a server-side receiver. The platform-specific receiver will parse the data stream to build a platform-specific object. Likewise, the JSON server infrastructure can take any platform-specific object and serialize to an interchange format. Back on the client, the data stream is promptly transformed in a JavaScript object. As far as the .NET Framework and ASP.NET are concerned, a bit of reflection is used to examine the internal structure of classes and create proper JavaScript wrappers. </a>

<a href="page.aspx" onclick="doClick()">Virtually all AJAX-based frameworks implement a JSON infrastructure. ASP.NET AJAX is no exception.</a>

  <a href="page.aspx" onclick="doClick()">Note </a>

<a href="page.aspx" onclick="doClick()">For a while, XML has been touted as the lingua franca of the Web because it is ideal and made-to-measure for developers and architects to package and exchange data in a totally cross-platform way. Today, you find out that JSON (a non-XML technology) is sold for the same task. Is there any difference? Both JSON and XML do the same work. XML is more complex, quirky in some respects, and general-purpose, and it is preferable to describe data to be styled using an XSLT style sheet for UI purposes. For raw data, JSON is a more lightweight format that is easier to read and parse for both humans and computers.</a>


<a href="page.aspx" onclick="doClick()"> </a>

<a href="page.aspx" onclick="doClick()">Conclusion</a>

<a href="page.aspx" onclick="doClick()">Most attentive developers have been developing around interactive Web technologies since the late 1990s. Various technologies (for example, Microsoft Remote Scripting and opensource and commercial variations) have been developed without forming a critical mass of acceptance and use. Or perhaps the mass was big enough, but everyone was waiting for the spark of a killer application. Another factor that slowed down the adoption of more advanced client techniques was the lack of cross-browser support for them.</a>

<a href="page.aspx" onclick="doClick()">Today, the situation is radically different from what it was only three or four years ago. Now about 90 percent of the available browsers support all the minimal requirements for implementing interactive Web applications, known as AJAX applications. In addition, the W3C is standardizing the XMLHttpRequest object, which is the necessary communication workhorse behind all existing platforms for AJAX. The next generation of Web applications will be based on a different mechanism: it is no longer, or not just, forms posted in a change of pages, but individual requests for data and dynamic updates to displayed pages.</a>

<a href="page.aspx" onclick="doClick()">As a server technology aimed at the creation of Web pages, ASP.NET takes advantage of the opportunity for providing this much desired functionality. Script callbacks were the first Microsoft attempt to offer an API for building AJAX-style pages. Modeled after the classic postback event, callbacks are sometimes unnecessarily heavy and inflexible.</a>

<a href="page.aspx" onclick="doClick()">An add-on to ASP.NET 2.0, Microsoft ASP.NET AJAX Extensions, shows the way ahead for AJAX applications as far as the ASP.NET platform is concerned. It integrates the AJAX lifestyle into the existing application model of ASP.NET, resulting in a familiar programming model with greatly improved and richer functionality. </a>


<a href="page.aspx" onclick="doClick()"> </a>

<a href="page.aspx" onclick="doClick()">Chapter 2 The Microsoft Client Library for AJAX</a>



Introducing Microsoft ASP. NET AJAX
Introducing Microsoft ASP.NET AJAX (Pro - Developer)
ISBN: 0735624135
EAN: 2147483647
Year: 2004
Pages: 81
Authors: Dino Esposito

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net