Monday, February 8, 2010

Who Benefits from AJAX?

AJAX offers benefits to both end users and developers. For end users, it reduces the “rich or reach” conflict; for developers, it helps in overcoming the constraints raised by HTTP.

Why End Users Want AJAX Applications

Users tend to view desktop applications as a sort of commitment. They install a program, usually from a disk pulled from a costly shrink-wrapped box. The program consumes hard disk space as well as a position in the program menu. The user may need to update the program periodically or perform an upgrade later on to get new features. If the program is proactive about updating itself, the user is confronted regularly with dialogs about accepting patches or downloads. In exchange for this investment of time, money, and energy, the user gets repaid by an application that is able to leverage the operating system and machine resources. It is a rich application. It has local storage capabilities, offers quick response times, and can present a compelling and intuitive graphical user interface.

More and more applications are accessible from the web browser, where the full resources of the hardware and OS are not available, but the user commitment of a desktop application is not required. Over the years, interacting with a web application has meant a predictable pattern for users. They click a link in the page and the browser flashes while the user waits until the screen is repainted (the dreaded post back). This cycle is repeated again and again. The user looks at what is presented on the page, interacts with it, and clicks somewhere. The browser produces an audible click for feedback and begins to post back to the server. The screen of the web browser flashes blank and some icon spins or flashes while the user waits for a new version of the page to be returned from the server. Many times, the new version of the page is almost exactly the same as the previous version, with only part of the page being updated. And then the cycle begins all over again. This has a sluggish feeling even when the user has a highspeed network connection.

The AJAX set of technologies has changed what users expect from web applications. JavaScript code running in the browser works to exchange data with the web server asynchronously. There is no click sound and the browser does not flash. The request to the server is nonblocking, which means the user is able to continue viewing the page and interacting with it. The script gets the updated data from the server and modifies the page dynamically using the DHTML coding methodology. The user is able to continue looking at the page while parts of it are updated in the background. AJAX is used to provide a more responsive experience, making web applications behave more like desktop installations. JavaScript is used to provide a richer experience with support for drag-and-drop, modal dialogs, and seemingly instantaneous updates to various parts of the page based on user inputs.

A big part of successfully leveraging AJAX technologies is in the perceived performance increase. Users appreciate web applications that anticipate their actions. If you also use JavaScript code in the background to pre-fetch images and data that may be needed, users can get a speedy response without the usual pause that accompanies their actions. Nobody wants to wait for data exchanges between client and server; studies have shown that a time lag between user input and subsequent UI changes can significantly reduce their productivity and give them the frustrating feeling that they are fighting the application. Users want web applications to behave like desktop installations but without the overhead associated with an installation. As more applications employ smart caching, anticipate user actions, and provide richer UI, the difference between web and desktop applications is becoming blurred. Expectations of web applications are rising. The end user has now seen that it is possible to avoid the commitment of installing a desktop application and still have a rich and responsive experience.

Why Developers Want AJAX

Often, the first question to arise when starting a new development project is what type of application it will be. Should it be a desktop application or a web application? This is a key decision because it has historically dictated a lot about the nature of the application and the development problem space. Many developers are now choosing to build web applications by default unless something about the application dictates that it must be a desktop install. If it must run offline or if it requires a user interface that is complex to achieve in HTML, targeting the web browser may be ruled out, and the choice to write a standalone application is forced.

Developers have a difficult job writing modern web applications due to the inherent worldwide-web functionality constraints imposed by the use of the Hypertext Transfer Protocol (HTTP) and the way browsers use it. HTTP is a stateless protocol. The web browser requests a page, possibly carrying some querystring or form input parameters, and the server processes the request and sends a response that includes HTML-rendered content. The server can only react to the information supplied in the current request and doesn’t know, based on the information in the request itself, details about the path the user took to get to the current view. When the response is rendered, the connection may be broken and the server won’t have any information to preserve for the next request. From the server’s perspective, it is simply listening for requests to come in from any browser anywhere and then reacting. The browser issues a request to the page and receives an HTML page in response. It uses the HTML it receives to render the user interface. The user interacts with the page, and, in response, the browser clears the screen and submits a new request to the server, carrying some information about user input or actions. Again, a complete HTML page is returned. The browser then presents the new version of HTML. Fundamentally, the HTTP protocol is stateless. The server gets a request and responds to it. The request carries limited information about the ongoing conversation that is happening between client and server.

AJAX makes this much better. AJAX breaks this pattern by updating portions of the page separately, via partial page rendering. Figure 1-1 shows a typical non-AJAX series of browser and server interactions. Each request results in a full page rendering, and, in response, the browser updates the user’s entire view.

In Figure 1-2, AJAX is employed to improve the user’s experience. A request is made for the initial page rendering. After that, asynchronous requests to the server are made. An asynchronous request is a background request to send or receive data in an entirely nonvisual manner. They are asynchronous because the user interface isn’t frozen during this time, and users can continue interacting with the page while the data transfer is taking place. These calls get just an incremental update for the page instead of getting an entirely new page. JavaScript running on the client reacts to the new data and updates various portions of the page, as desired. The number of requests to the server may be no different, or in some cases there may actually be more calls to the server, but the user perception is that the application feels more responsive. They aren’t forced to pause, even if it’s only a slight pause, and wait for the server while staring at a blank browser screen.

Almost a decade ago, the Microsoft Exchange Server team created an ActiveX control called XmlHttpRequest that could be instantiated from JavaScript and used to communicate with the server. This can occur without clearing the screen to paint a whole new page. Using the XmlHttpRequest object, you could send information to the server and get data back without requiring a whole new HTML page. JavaScript code could then manipulate the HTML dynamically on the client, avoiding the annoying flash and the wait that users associate with web browsing. This functionality was not limited to Internet Explorer for long. Soon, other browsers included XmlHttpRequest objects as well. Developers could now write richer applications with reach extending across various operating systems.

The browsers also created an advanced DOM (Document Object Model) to represent the browser, the window, the page, and the HTML elements it contained. The DOM exposed events and responded to input, allowing the page to be manipulated with script. Dynamic HTML (DHTML) opened the door to writing rich interfaces hosted within the web browser. Developers started writing hundreds and even thousands of lines of JavaScript code to make rich and compelling applications that would not require any client installation and could be accessed from any browser anywhere. Web applications began to move to a whole new level of richness. Without AJAX libraries, you would be faced with writing lots and lots of JavaScript code and debugging the sometimes subtle variations in different browsers to reach this new level of richness.

What Is ASP.NET AJAX?

ASP.NET AJAX is the name of Microsoft’s AJAX solution, and it refers to a set of client and server technologies that focus on improving web development with Visual Studio. Other companies have their own AJAX solution, often taking a radically different approach, but Microsoft has sought to build upon the popular ASP.NET technology by developing a comprehensive set of script libraries as well as server programming enhancements. One piece, the Microsoft AJAX Library, is a JavaScript library that works on a variety of browsers and serves to simplify JavaScript development. It provides you with the capability to easily write JavaScript using an object-oriented programming approach similar to code-behind programming in ASP.NET. You can use the functions of the Microsoft AJAX library to interact with the DOM, dynamically update portions of the page, communicate with the web server asynchronously, and write rich animations on the page. You’ll learn about the client features in Chapters 6 and 7, but for now think of the Microsoft AJAX Library as a type system and set of class libraries that simplify writing JavaScript to enhance the user experience, manipulate the DOM, and communicate with the web server. The huge benefit in using this library is that it abstracts the tedious low-level DHTML programming into an OOP model that is much easier to work with.

The other part of the ASP.NET AJAX release is the server-side ASP.NET 2.0 AJAX Extensions. These extensions build on top of the ASP.NET classes and controls and leverage the Microsoft AJAX Library sent to the browser. They make it easy to quickly take advantage of AJAX technologies to enrich an application. Through a set of standard web services, ASP.NET AJAX is also able to leverage server-based application services such as authentication and user profile storage. The extensions both extend some of the existing ASP.NET controls by adding new behaviors and include a new set of server controls that make it easy to do asynchronous updates to a page and leverage server resources.

The client and server pieces of ASP.NET are shown in Figure 1-3. ASP.NET is built on top of the Microsoft Internet Information Services (IIS) web server. ASP.NET AJAX builds on top of that and the web services it includes. The Microsoft AJAX Library runs in the browser to manipulate the DOM, communicate asynchronously with the web server, and take advantage of ASP.NET services.

The ASP.NET Component

The original (ASP) Active Server Pages technology was released as part of Internet Information Server 3.0. It was then improved with support for transactions and access to COM objects with the release of the NT 4.0 Option Pack almost ten years ago. At the time, most websites consisted of static HTML pages. To the extent that there were any dynamic applications, they were CGI (Common Gateway Interface) or ISAPI (Internet Server API) applications typically written in C and C++. With the release of Active Server Pages (ASP), developers could use JavaScript or VBScript on the server to leverage a set of intrinsic objects provided by ASP. “Classic ASP,” as it is now called, provided a session object so that developers didn’t need to worry about the stateless nature of HTTP. It had Request and Response objects that provided for easy access to data coming from forms on the client and a way to send updated information back. The Server and Application objects were an avenue for accessing information from the web server and utilizing a common set of COM objects across the application.

Although Classic ASP was a big win for developers, developers soon found that developing complex applications became difficult. The lack of support for modularization meant that applications ended up with such complex interdependencies in script that developers often referred to it as “spaghetti code.” Debugging support was severely lacking, and there were no rich design tools for developing applications. Performance also suffered because ASP used a slow scripting model, and syntax errors could only be detected at runtime. ASP.NET is a big leap forward. It provides compatibility for existing applications by including the same set of intrinsic objects found in Classic ASP but moves from interpreting JavaScript and VBScript on the fly to using a compiled set of pages and modules written in C# and VB.NET. Classic ASP simply executed script in order from the top to the bottom of the page; ASP.NET is an event-driven model with a page lifecycle, making it more like writing a desktop application. Now, instead of including separate JavaScript files to represent business objects, you can create objects in any .NET language and access them directly from ASP.NET.

ASP.NET takes a set of pages that contain code and markup and generates a Page class that is then compiled and cached. For each request to the page, the class is instantiated and a complete page lifecycle is executed. A set of events are executed, some of which have been overridden by the generated Page class. Controls in the page also participate in the lifecycle, databinding to backend databases, reacting to user input, and dealing with changes to their state from the user’s previous view. To react to user actions, the developer has only to provide an event handler for the given action. For example, the button control exposes a Click event. When using it, you don’t need to write code to examine all form variables on a page to know if the button was clicked. Instead, you just provide code for an event handler override. The event handler code can then update the HTML for the page or the properties and data of other controls on the page.

The JavaScript Component

AJAX technologies take advantage of the common support for JavaScript found in modern browsers. Because there is a standard that is supported across the various browsers, you can write scripts knowing that they will run. This wasn’t always the case.

In the mid 1990’s, Netscape and Microsoft (along with others) collaborated on a standard for a scripting language that they would support in their web browsers. The standard is called EcmaScript. Microsoft’s implementation is called JScript, but the language is generally referred to as JavaScript, as it was called in Netscape. (It has nothing to do with Java, but someone must have thought the association was useful for marketing purposes.) JavaScript program snippets are sent down to the browser along with the HTML, and they run inside the user’s browser to affect how the page is processed on the client.

JavaScript is not compiled; it is interpreted. There is no static type-checking like you get in C++ and C#. You can declare a variable without needing to specify a type, and the type to which the variable refers can change at any time. This makes it easy to get started programming in JavaScript, but there’s inevitably a certain amount of danger in allowing the data type of a variable to change dynamically at runtime. In the following snippet, notice that the variable can reference any type without difficulty:

var something = 1;
something = true;
something = “a string”;

JavaScript is a dynamic language. Types can actually be extended during program execution by other code. This means that you can write code that creates types on the fly. Because there is no enforcement of type safety, your code can receive these types as parameters or return values without any problem. This provides a great degree of flexibility and coding power.

The fundamental types in JavaScript are strings, numbers, Booleans, and functions. There is also support for objects and arrays, which are collections of the fundamental types. Some additional objects are included that are considered essential for many programming tasks. This includes support for regular expressions and date and time operations.

You can use the plus operator on strings in JavaScript to concatenate them:

var theEnd = “THE END.”;
var result = “Beginning, “ + “middle, and “ + theEnd;

In this example, the result variable is now the string: “Beginning, middle, and THE END.”

JavaScript interpreters use the IEEE floating-point standard for storing numbers. Ignoring the gory details, you can assume that for most programming tasks you won’t have any trouble.

The Boolean type in JavaScript is about what you would expect it to be but maybe not exactly so. The Boolean represents whether or not an expression is true, but it uses the C-style convention using integer values 0 and 1.

Variables can exist in JavaScript without having a value, and a variable may simply be undefined, which can produce unexpected results. In this piece of JavaScript, three variables are declared, and all of these comparisons are designed to return a true value.

You can check specifically to see if a variable has been defined like this:

if( typeof(undefinedVar ) == “undefined” )
{
alert(“undefinedVar is undefined”);
}

Variables can also have a null value, which is not the same thing as being undefined, as a null value does constitute a value.

Functions are also real types in JavaScript. They can accept arguments and return values. Functions can be passed to other functions and can be created dynamically by other script code.

Here are two equivalent definitions for a function called Add that will take two variables and return the result of applying the plus operator. Notice that I didn’t state that it takes two numbers. Remember, JavaScript variables don’t have a defined type, so I could just as easily pass two strings and get them concatenated by my Add function.

Once either of these styles is used to create a function, it can be called from that scope and any nested scope to perform the addition. There is no advantage to one of these forms over the other. You can simply choose to use the syntax that you prefer.

Objects and arrays are just collections of other types. Array types do not require that the values they hold be named; instead, you can access them by index. The values held in an object are referenced by field or property names. Objects can also hold functions (which can be accessor functions to give public visibility to local variables), which lets you create data structures that represent entities in JavaScript code. Missing from this sort of object-oriented programming is a concept of type inheritance. The Microsoft AJAX Library provides a set of classes and recommended patterns for achieving inheritance in JavaScript, making it more natural for switching between JavaScript and other high-level languages. The following code example includes a definition for an Album object that holds and returns the artist and album title. An array is then used to store information about several albums.

No comments:

Post a Comment