Architecture guidelines for ASP.NET AJAX applications

This article was originally published in VSJ, which is now part of Developer Fusion.
AJAX is a new paradigm for developing Web applications, and is ultimately made of a set of existing software technologies; some originally developed by Microsoft, and some that are popular Web standards ratified by the W3C committee a while back.

The difference between classic Web applications and AJAX Web applications is all about the way they interact with the server. A classic Web application submits forms to receive pages; an AJAX application submits data to receive data. A classic Web application needs no code on the client and no special browser capabilities because what the server returns is ready for display. An AJAX application requires an ad hoc client infrastructure to process the data received from the server and update the page.

In short, AJAX delivers effective results in terms of user experience and opens up a whole new world of opportunities for creative developers and architects. It pushes a new approach to building Web applications with a new programming paradigm and a new set of tools; and you have to start designing applications accordingly.

Back in February 2005, Jesse James Garrett wrote the following text in an article meant to introduce the new paradigm that his company employed in recent Web applications. That article was the first to use the term AJAX:

The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities.

Giving users more

AJAX is all about the user. AJAX allows us to build applications and Web sites that are faster, more responsive and more intuitive. In AJAX pages, page flickering is reduced and expand/collapse panels, drag-and-drop, and in-place editing are common features. The page response is quicker, and when it still takes a while to download there’s timely feedback to keep the user informed, if not entertained.

The AJAX paradigm springs out from more sophisticated user requirements. In brief, users want Web applications and sites that look like desktop applications. For quite some time, Dynamic HTML and DOM manipulations made it possible to achieve desktop-like functionalities on a few particularly rich browsers. Today’s generation of browsers is powerful enough to run desktop-like Web applications. This basic fact created the conditions for a new programming paradigm to emerge.

Nowadays users require more action and more interaction from their browsers. How can you keep them happy? The first step is to understand exactly what they want. Three points sum it up:

  • The same application, only enhanced with a user interface that includes expand/collapse panels, sprites, modal windows, infotips, flying windows, maybe drag-and-drop.
  • A similar application that transmits a sense of continuity with the user. This means a limited number of full page refreshes, limited page redirects, real-time updates, mash-ups and, of course, a rich and appealing user interface.
  • A new application/site that looks like a desktop application.
Adding AJAX often requires a change in the mindset of both developers and users. AJAX breaks the Back button and the history function of the browsers. AJAX is not browser-specific, but still it doesn’t work in just any browsers. Most recent browsers – perhaps 90% of the total – support AJAX, but (for example) with Internet Explorer 5.0 and 6.0 users have to tweak (lower) security settings to enable it. Finally, AJAX may inadvertently pass the user the message that Web and desktop are going to be the same, which isn’t, and won’t ever be, true.

How do you plan a migration and/or a significant re-engineering of applications in light of AJAX? Here I focus on concepts and principles. When it gets unavoidable to discuss coding techniques and features we’ll consider the Microsoft AJAX framework that extends ASP.NET – the ASP.NET AJAX Extensions v1.0 framework, which you can freely download.

A cool user interface

Crafting a cool user interface is a hard task; leave it to professionals and employ your time otherwise. A number of good third-party libraries exist that integrate smoothly with ASP.NET AJAX Extensions. In alphabetical order, you have companies like ComponentArt, Infragistics and Telerik each offering a suite of versatile components for zero-cost enhancement of applications to AJAX. All these products run their own AJAX engine and encapsulate all surrounding logic, including scripts, into classic ASP.NET server controls. In addition, these controls can be conveniently configured through ad hoc designers in Visual Studio 2005. As a result, you keep on writing regular postback-based applications and turn them into AJAX-enabled applications just switching to a different set of server controls and without writing any JavaScript code.

When users are not ready for a new application, or there’s no budget for ambitious plans, a refreshed application that works as before, but features brand new controls, may be cheap to write and effective as far as end users are concerned. As a developer, you don’t have to struggle with a new interaction model, with a new back-end, and JavaScript. You use a different set of controls, learn about their programming interface, adjust your code-behind as appropriate, and proceed. You’re not adding AJAX explicitly; you’re just using new controls that offer an AJAX-based implementation of their specific features. Put another way, controls bring AJAX capabilities to the page and the page requires limited changes and no redesign at all. The user experience comes out significantly improved, and the user’s way of interacting with the application is preserved. Additional costs are just the costs of the licenses.

Continuous interaction

In other situations the primary goal is to provide the user with a better and smoother interaction with an application. A cool menu or treeview is not the most important thing; or at least not as important as having continuous interaction with the page, limited flickering, quick updates, no scrollbar repositioning after a postback.

In this case, pages must be modified to define regions that can be updated independently from the rest of the page. You take control of the page and orchestrate AJAX tasks. In ASP.NET AJAX Extensions, this approach is known as partial rendering. Partial rendering selectively updates fractions of the page with a lightweight postback. As a developer, you don’t need to learn any new programming paradigm. You keep on working with the traditional programming model of ASP.NET and just familiarize with a few new server controls – UpdatePanel, ScriptManager, UpdateProgress. The advantage of partial rendering is that it intercepts regular postbacks and transforms them into “out-of-band” requests operated by the XMLHttpRequest object. For users the application is still the same, but the experience is significantly better.

Getting rid of the “stop-go” model of classic Web applications, where each request takes a while to download the new page, doesn’t necessarily mean producing a cool new user interface. However, the same suites of controls mentioned earlier provide a complete interoperability with ASP.NET AJAX Extensions meaning that you can use some of them to improve the quality of the user interface and still upgrade existing pages to AJAX by defining updatable regions.

Partial rendering is a quick and effective way to convert legacy code to AJAX without restructuring pages and the whole application. Just like third-party controls, partial rendering may not work perfectly in all cases. The quest for the ideal library that contains just any controls you may need is still ongoing. Likewise, splitting existing pages into updatable regions may not be an easy task, especially when user controls, master pages, and complex page hierarchies are found. Partial rendering, with or without the help of custom controls, is a technique to be applied case-by-case and step-by-step. But it generally works.

Desktop-like Web applications

When users ask for desktop-like, rich Internet applications, you have no choice but to design a brand new application taking into careful account a new family of design patterns, service-oriented architectures and smart controls for an effective and appealing user interface. Is it ever possible to have a “desktop-like” but “Web” application? It goes without saying that a Web application is not a desktop application; and of the two attributes, the “Web” attribute is the stronger. So what users want is a Web application that behaves like a desktop application. If this is the case, technologies that are often (too often) presented as alternatives to AJAX are just out of place. I’m talking about Windows applications deployed through ClickOnce or Windows Presentation Foundation (WPF) Browser applications. They are respectively Windows and WPF applications with some characteristics that make them look like Web applications. AJAX, ClickOnce, and WPF Browser applications are alternatives if you’re looking for a smart client technology. If you’re merely looking for a cool and responsive Web application, there’s currently no alternative to AJAX. The closest you can get is through plugins such as Adobe Flash or Microsoft’s upcoming WPF/E engine.

An AJAX application will never be a desktop application. It will never gain full access to the local file system; it will never gain hardware control; it will never print under user control; it will never work through protocols other than HTTP; it will never work when no Internet connection is available. An AJAX application is a Web application deployed on a centralized server accessed using a number of possible client browsers. It has a radically different interaction model with the user. The user performs an action, the system processes the generated input, the user interface is updated – all in the same context and as part of the information flow. This interaction model is normal in Windows applications; it is totally new in Web applications. This is the big architectural point of AJAX.

The architecture of AJAX applications

AJAX applications are mostly about the client front-end that calls into a server back-end. How much logic do you need in the front-end? Will it be a thick front-end that produces all user interface refreshes on its own? Will it be a thin front-end that just grabs markup from the server and refreshes portions of the page? With partial rendering, you clearly have a thin front-end. Let’s consider a classic AJAX scheme with a service-oriented back-end and a thick front-end.

Because the front-end is represented by a client browser, JavaScript is the only language available for the calls. The server back-end is a part of the application, hosted on the same application domain and exposing data feeds, preferably JSON data feeds. Figure 1 shows the overall layout.

Figure 1
Figure 1: The high-level architecture of a pure AJAX application

How would you expose the back-end of an AJAX application? Services are the most logical and effective answer. But services are just a blanket term these days. What kind of services? In spite of the labels one can attach to the word “service” (Web, SOA, REST), in the context of AJAX, a service is just a publicly callable interface with a contract. Everything beyond this basic point is an implementation detail and can be changed at will. As in Figure 1, the service exposes data feeds, possibly in a variety of formats – primarily JSON, but also RSS, CSV, plain XML and raw text. What about SOAP?

SOAP is not the ideal companion to AJAX services. A SOAP-based service uses a single URL to expose all functionalities and documents them typically through a WSDL file. Behind the URL, a single handler will receive the request, examine the body and forward the call to the internal machinery.

A more AJAX-oriented service uses a distinct URL to point to a distinct method. A similar service documents a functionality through links and/or HTTP headers. Each method has a unique URL (plus optionally HTTP headers), and this is all that is required to identify the requested resource and process it. SOAP, instead, relies on WSDL metadata to define contract and types. As such, it proves not to be particularly flexible and still too much coupled to clients. SOAP requires a fixed syntax. If this syntax is extended or modified, then all clients are to be notified and adapted. An AJAX-oriented service can start supporting a new feature without the need for notifying all clients. Furthermore, distinct clients can get data in different formats – JSON, XML, RSS, CSV, plain text, and so on. This is not possible with SOAP, as SOAP is designed to live on a clear and well-defined interface.

AJAX-oriented services are based on the REST model, where REST stands for REpresentational State Transfer. A REST-ful back-end is the first key step in the building of a pure AJAX application.

A back-end for ASP.NET AJAX

The back-end provides services to the JavaScript-based front-end and exposes its data via feeds – typically JSON feeds. The contract for the service should be well-defined and exposed in REST mode, that is through URL and headers, rather than via SOAP and WSDL. In ASP.NET AJAX Extensions version 1.0, there are two ways to implement a back-end: using slightly modified ASP.NET Web services or through page methods. In the near future, with the release of .NET 3.5 (currently code-named Orcas), a third way will be added – Windows Communication Foundation (WCF) services.

Back-end services should be designed according to the REST pattern, basically meaning that each method needs to have its own URL and receives and sends data through a JSON stream. Let’s expand a bit – generally speaking, REST services are centered on two pillars. First, resources are mapped to URLs. A resource is anything the service is expected to manage; it’s a kind of business entity you expose out of your back-end. Second, operations that can be accomplished on the resource are to be HTTP verbs such as GET, POST, PUT and DELETE. Client browsers can interact with resources by invoking the specific URL through a HTTP verb. For a service meant to expose customer information, the following sample URL indicates the customer with an ID of 123:

http://server.com/customer/123
You use the GET verb to query information. To add a new customer, you might want to use the PUT verb and place the information about the new customer in the body formatted in a text stream that can either be JSON, plain XML, raw text or whatever else suits you.

So much for the abstract theory of the Representational State Transfer mode – a model for remote services that competes with SOAP-based Web services. Let’s see how it is coded in ASP.NET AJAX Extensions.

When you design a remote service for an ASP.NET AJAX Extensions, you’re not supposed to know about REST. All that you do is creating a classic ASP.NET Web service with an extra attribute – ScriptService:

[ScriptService]
public class MyDataService :
	WebService, IMyDataService
{
	[WebMethod]
	public Customer Lookup(string id)
		{
			:
		}
}
This little attribute is the trigger that enables REST support in ASP.NET AJAX remote services. Once such a service is registered with the ASP.NET AJAX script manager in a Web page, the attribute instructs the script manager to generate a JavaScript proxy class for the client to invoke the service. From the client, you run code like this:
// Attached to a client event,
// such as a button click
function getData() {
	MyDataService.Lookup(
		"123",onDataAvailable);
}
In ASP.NET AJAX, MyDataService is a singleton object that represents your proxy to the remote service. Again, where’s REST? This looks more like RPC or classic proxying for SOAP services.

If you monitor the call using a network sniffer like Fiddler, you see that the URL requested is actually the following:

http://server.com/mydataservice.asmx/
	lookup
It is requested through a POST verb and the body sends a JSON string with the 123 input data. ASP.NET AJAX Extensions does fully support the REST model, but keeps you away from it, covering this new model with a familiar programming interface.

When writing the back-end of an ASP.NET AJAX application, focus on two things:

  • Define a contract for the services
  • Implement the services as stateless ASP.NET Web services
Furthermore, you might want to move to WCF services as soon as they will be integrated in ASP.NET AJAX.

A front-end for ASP.NET AJAX

At the current stage of the technology, an AJAX front-end can only be made with JavaScript. There’s probably no technological limitation to using a more powerful engine than JavaScript on the client, but that would break the combination of factors that make it possible to run AJAX on virtually every browser available.

In AJAX applications, the client makes a request following up a user’s action and waits online for the response to come. When the server-generated response is back – in the same context and within the same operational flow – the client processes the result and updates the user interface. It must be made clear that the browser processes the result and updates the user interface using JavaScript code. For this reason, a rich and more powerful JavaScript language would be welcome.

ASP.NET AJAX Extensions delivers a set of OOP extensions to JavaScript so that you can create object-oriented classes that support inheritance, polymorphism and to some extent also encapsulation. Implemented as JavaScript functions, these extensions can be used also when the AJAX application is being built with other development platforms such as PHP.

In addition to a more powerful programming language, you also need effective solutions to common problems that arise in Web pages during AJAX operations. Table 1 lists a few common design patterns you might want to consider.

Table 1: A selection of AJAX design patterns
Pattern Category Description
Cross-domain proxy Services Provides guidance on how to connect to Web services available remotely outside the boundaries of the current application
Display morphing, Page rearrangement User interface Related patterns that summarize the most common techniques to update the page structure and styles of DOM elements
HTTP streaming User interface Provides guidance on how to push data from the server to the client
Progress indicator, Periodic refresh Browser/Server communication Related patterns that show common ways to implement periodic refresh of the page and monitor server-side operations
Timeout, Heartbeat Browser/Server communication Related patterns that show common ways to determine whether a user is still actively working with an application and give guidance on what to do once you know it
On-demand JavaScript Performance Provides guidance on how to apply lazy-loading to JavaScript files and download them only when required
Submission throttling Performance Provides guidance on how to retain posted data on the client and submit it at fixed intervals
Predictive fetch Performance Provides guidance on how to make the browser more responsive by anticipating user actions and call the server in advance

Data binding is a hot topic in the context of a front-end for a thick AJAX client. It’s easy to handle data binding with a thin AJAX client that makes use of partial rendering. It’s much less obvious how to refresh a complex, template-based user interface with a collection of data coming from the server. You need an ad hoc client framework for this to handle it comfortably in large-scale projects. Currently, ASP.NET AJAX Extensions version 1.0 provides no facilities for this.

Conclusion

AJAX is a new paradigm for Web applications, and we’re all experimenting and learning the most effective ways to use it. There are two main types of applications, that many call AJAX Lite and AJAX Deluxe. In the first case, you have essentially a server-side Web application (i.e., a classic ASP.NET app) enhanced to add AJAX capabilities. The client is clearly a thin client that essentially receives markup and replaces it dynamically.

AJAX Deluxe applications rely on a RESTful back-end and implement rich JavaScript functions to fill out the user interface with raw data. Thick clients may not be trivial to write – strong Dynamic HTML and JavaScript skills are required – and this is just one of the most common misconceptions and overlooked aspects of AJAX development.


Dino Esposito is a Solid Quality Learning mentor, and regularly contributes to various developer magazines. He is the author of the two-volume Programming Microsoft ASP.NET 2.0 (Microsoft Press, 2005), and will be presenting a pre-conference workshop on architecting web applications with ASP.NET AJAX at Software Architect 2007 in June.


Web sites vs Web applications

A subtle difference exists between two expressions too often used interchangeably: Web sites and Web applications.

A Web site is composed of a relatively large number of distinct pages that the user navigates through. The site represents a sort of state machine where each page represents a state with a list of possible transitions. Menus, hyperlinks, and programmatic statements redirect the user from one page to the next according to the logic of the site. Any browsers visiting a Web site offer users some free services – history, refresh, and the Back/Forward buttons.

A Web application is somewhat simpler. It is a relatively small application implemented through one or just a few Web pages. There’s likely to be no menu and no site map to navigate. The logic is mostly presentation logic and it is contained in the main page. This type of application is also referred to as a micro-application. Gmail and GoogleMaps are good examples of AJAX-based Web applications. In some cases, a Web application is the front-end of a multi-tier enterprise application, and its main purpose in life is collecting input for the back-end system and displaying results to the user.

You might also like...

Comments

About the author

Dino Esposito United Kingdom

Dino Esposito is an instructor for Solid Quality Mentors, and a trainer and consultant based in Rome. He is the author of various books, including Windows Shell Programming, Instant DHTML Script...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“There are only two kinds of languages: the ones people complain about and the ones nobody uses” - Bjarne Stroustrup