21
Inside the Microsoft AJAX Library JAX and JavaScript ( AJAX acronym: Asynchronous JavaScript and XML) ew object-oriented features odified XMLHttpRequest object for asynchronous calls to a remote URL. rich client-side JavaScript library. JAX actions include client-side data validation, advanced user interface features such ating menus, drag and drop, pop-up panels, and sophisticated input. quests to the server that bypasses the classic model of replacing the entire page. JAX platform is a rich JavaScript library. ASP.NET AJAX 1.0 and in the AJAX platform is integrated with ASP.NET 3.5

Inside the Microsoft AJAX Library - AJAX and JavaScript ( AJAX acronym: Asynchronous JavaScript and XML) - new object-oriented features - modified XMLHttpRequest

Embed Size (px)

Citation preview

Inside the Microsoft AJAX Library

- AJAX and JavaScript ( AJAX acronym: Asynchronous JavaScript and XML)- new object-oriented features

- modified XMLHttpRequest object for asynchronous calls to a remote URL.

- a rich client-side JavaScript library.

- AJAX actions include client-side data validation, advanced user interface features such as floating menus, drag and drop, pop-up panels, and sophisticated input.

-requests to the server that bypasses the classic model of replacing the entire page.

- AJAX platform is a rich JavaScript library.

-In ASP.NET AJAX 1.0 and in the AJAX platform is integrated with ASP.NET 3.5

The AJAX Architecture

A traditional Web application does everything on the server. Only occasionally does the application emit script code to run a task on the client—for example, to handle data validation.

                                                            

An AJAX application uses a client-side framework that takes care of issuing calls to the Web server. An AJAX server-side framework then takes care of the request and returns a data feed to the client. This will often be a JavaScript Object Notation (JSON) data stream, but other formats—such as XML, …can be used.

What's an AJAX Framework?

To keep AJAX alive in a Web page, a few conditions must be met. 1. First, you need JavaScript support from the browser. 2. A full-time Internet connection is also required—an AJAX application can't work offline.

A special framework is required by any serious AJAX application. Usually the framework of choice is articulated in separate client and server parts.There are two main types of script code in an AJAX page:

system-level code from the framework user-level code

The system-level code provides the engine used to send asynchronous requests to the Web server and process any responses. The user-level code updates the UI of the page, essentially using Document Object Model (DOM) scripting.

AJAX framework is part of ASP.NET AJAX Extensions.

ASP.NET AJAX Extensions

An extension to ASP.NET 2.0, ASP.NET AJAX Extensions provides AJAX capabilities to new and existing Web sites. There are two programming models for ASP.NET AJAX:

partial rendering and remote services.

In brief, partial rendering allows you to maintain an architecture similar to a classic ASP.NET 2.0 application. It just provides you with a set of new server-side tools you can use to implement flicker-free page updates.

Remote services, on the other hand, involve a service-oriented back. Server-side code must be factored out to application-specific services .

Next Figure  shows the client and server components of the ASP.NET AJAX Extensions framework:

File Location Description

MicrosoftAjax.js Client Contains functions to extend JavaScript with object-oriented constructs. It extends the prototype of built-in JavaScript objects and defines new helper classes, such as StringBuilder.

MicrosoftAjaxWebForms.js

Client Contains the JavaScript classes that form the network stack and all classes that implement the client-side partial rendering engine.

MicrosoftAjaxTimer.js

Client Represents the client-side object model for the new AJAX System.Web.UI.Timer server control. This is basically a server wrapper for a browser's timer object.

System.Web.UI.ScriptManager

System.Web.Extensions

Orchestrates the download of proper JavaScript files and client-side data, including the AJAX library, proxy classes for remote services, localized version of script files, and globalization data.

System.Web.UI.UpdatePanel

System.Web.Extensions

Defines a region of a page that can be refreshed through an AJAX postback in a flicker-free way.

System.Web.UI.UpdateProgress

System.Web.Extensions

Defines a server-side template that can be used to provide feedback to the user while a long partial rendering operation is taking place.

System.Web.UI.Timer

System.Web.Extensions

Helper server control that posts back the AJAX way when a child client timer times out.

Introducing the Microsoft AJAX Library

-AJAX Library consists of two related parts: JavaScript language extensions and a sort of base class library.

-JavaScript by itself can't be presented as an object-oriented language. There's a bit of inheritance you can get through object prototypes and there's a bit of encapsulation you obtain via closures.

- The AJAX Library is written in JavaScript, and stored in a couple of .js files. There are two main files involved : MicrosoftAjax.js and MicrosoftAjaxWebForms.js. MicrosoftAjax.js defines language extensions supported by the Microsoft AJAX Library including namespaces, interfaces, enums, and inheritance. MicrosoftAjaxWebForms.js defines the partial rendering engine and the whole network stack.

In an ASP.NET AJAX application, you don't need to reference or embed any of these two files directly. This is one of the tasks that the ScriptManager control accomplishes for you:

<asp:ScriptManager runat="server" ID="ScriptManager1" />

Placed in an ASP.NET AJAX page, the preceding code guarantees that one or both of the Microsoft AJAX Library .js files will be downloaded to the client

The source code of the Microsoft AJAX Library is located at ajax.asp.net/downloads.

Some programming tips:Defining Class According to the Microsoft AJAX Library

-In traditional JavaScript programming, you work by creating functions.-Now you can use functions as if they were objects in an object-oriented language.

-The Microsoft AJAX Library performs some tricks and makes some assumptions with the final goal of making JavaScript functions look and behave like classic objects.You create Microsoft AJAX Library classes using the prototype model. All instances of that function will end up calling the same method instance if the method is defined as part of the function's prototype.

As an example, suppose you have a Timer object:

MsdnMag.Timer = new function() { // This is a sort of constructor // for the function : this._interval = 5000; }

According to the Microsoft AJAX Library, this is the definition of a class

Through the preceding code, you define a function object that can be further instantiated in any page that links that code:

var timer = new MsdnMag.Timer();

Any code defined in the pseudo-constructor executes at this time. According to the preceding snippet, instantiating the function sets variable _interval to 5000.

What should you do to add a couple of start and stop methods to the timer object: (The prototype model specifies that you use several separate blocks of code to define a class. )

MsdnMag.Timer = new function() { this._interval = 5000; this._timerID = null; }

MsdnMag.Timer.prototype.start = function(callback) { this._timerID = window.setTimeout(callback, this._interval);

}

The equivalent in C# code is:

namespace MsdnMag { public class Timer

{ public Timer() { _interval = 5000; _timerID = null; }

protected int _interval; protected object _timerID; public void start(Delegate callback)

{ // Any code that can create a timer _timerID = CreateTimer(callback, _interval);

} }

}

The first thing you should notice is that you have no need to explicitly define _timerID and _interval as part of the Timer object in the Microsoft AJAX Library. You just assign both members a default value in the constructor. However, to mark them as members of the object, you should prefix them with the "this" keyword. If you don't, they would be considered private members of the function and not bound to the object's prototype. When, prefixed with the "this" keyword, you can invoke those members from any prototyped methods.

Example with a Closure for the same MsdnMag.Timer Class:

// MsdnMag.Timer :: closure

MsdnMag.Timer = function(interval) { var _interval = interval; var _timerID = null; var _userCallback = null;

this.CallbackInternal() { this._userCallback(); this.start(); }

this.start(callback) { _userCallback = callback; _timerID = window.setTimeout(CallbackInternal, _interval) }

this.stop() { _userCallback = null; _timerID = null; }

}

Here, the JavaScript object is written as a closure rather than as a prototyped object

The prototype model serves up a class with a sort of distributed scheme

All members attached to the prototype of the object are shared by all instances of the object. The Microsoft AJAX Library is entirely written according to the prototype model. (JavaScript supports both closures and prototypes.)

So what's the benefit of using the Microsoft AJAX Library? The library extends the JavaScript programming environment by adding a number of predefined objects that provide new language features such as namespaces, enumerated types, delegates, stronger typing, and inheritance.

The Figure on next slide shows the MsdnMag.Timer object written as a fully qualified Microsoft AJAX Library object.

(The sample timer class accepts up to three arguments in the constructor to initialize the interval of the timer and the callback to run periodically. )

// Define the namespace the following class(es) belong to Type.registerNamespace("MsdnMag");

// Class constructor:: Initializes internal members // interval :: interval of the timer in milliseconds // callback :: JS function to execute periodically // resetCallback :: JS function to execute when the timer is stopped

MsdnMag.Timer = function(interval, callback, resetCallback) { this._interval = interval;

this._timerID = null; this._userCallback = callback; this._resetCallback = resetCallback;

// Define a delegate to invoke the user-defined callback this._callback = Function.createDelegate(this, this._callbackInternal); }

// Internal wrapper for the user-defined callback function MsdnMag$Timer$_callbackInternal() { // Invoke the user-defined callback … }

// Official end-point to start the timer function MsdnMag$Timer$start() { … }

// Official end-point to stop the timer function MsdnMag$Timer$stop() { …this._resetCallback(); }

// Define the public interface of the class MsdnMag.Timer.prototype = { start : MsdnMag$Timer$start,

stop : MsdnMag$Timer$stop, _callbackInternal : MsdnMag$Timer$_callbackInternal }

// Register the class with the Microsoft AJAX Library framework MsdnMag.Timer.registerClass("MsdnMag.Timer");

What if you want to add a public read/write property to a new object? As long as you want it to be a property, and not just a public data container like a field, you need to read and write property values using ad hoc methods. The convention in use is get_XXX and set_XXX, where XXX is the name of the property. (A sample implementation for an Interval property on the MsdnMag.Timer object is shown:

function MsdnMag$Timer$get_Interval() { return this._interval; }

function MsdnMag$Timer$set_Interval(value) { …this._interval = value; }

// Define the public interface of the class MsdnMag.Timer.prototype =

{ get_Interval : MsdnMag$Timer$get_Interval, set_Interval : MsdnMag$Timer$set_Interval, start : MsdnMag$Timer$start, stop : MsdnMag$Timer$stop, _callbackInternal : MsdnMag$Timer$_callbackInternal }

Built-In Classes in the Microsoft AJAX Library

Array Extends the native Array object with new search methods.

Boolean Extends the native Boolean object with a parse method.

Date Extends the native Date object with formatting methods.

Error Extends the native Error object to make it similar to a managed exception object. Also exposes static properties to map predefined types of error.

Function Extends the native Function object with delegates and utilities to check method signatures.

Object Extends the native Object object with type information.

Number Extends the native Number object with parsing and formatting methods.

RegExp Simple wrapper around the native RegExp object.

String Extends the native String object with formatting methods.

Type Alias for Function where all OOP extensions are grouped.

Sys.UI.Control

Defines the foundation of Microsoft AJAX Library user interface controls.

Sys.UI.Point Defines a point in the page through (x,y) coordinates.

Sys.Component Defines the foundation of a Microsoft AJAX Library user interface component.

Sys._Application Internal class representing the lifecycle of the current page.

Sys.Net.NetworkRequestEventArgs

Defines the data associated with the Web request events.

Sys.Net._WebRequestManager

Internal class representing the centralized manager of Web requests used to set global parameters such as executor and timeout.

Sys.Net.WebRequest

Represents a Web request being made.

Sys.Net.XMLHttpExecutor

Represents the Web request executor that uses XMLHttpRequest.

Sys.Services._AuthenticationService

Internal wrapper class for the server-side authentication Web service.

Sys.Services._ProfileService

Internal wrapper class for the server-side user profile Web service.

Sys.Services._RoleService

Internal wrapper class for the server-side role Web service. This class is only available in ASP.NET 3.5.

Sys.Services.ProfileGroup

Used to contain the information about profile groups.

Sys.EventArgs Defines the foundation for the data object of any event.

Sys.EventHandlerList

Helper class used to gather all events associated with the execution of Web requests.

Sys.Serialization.JavaScriptSerializer

Helper class used to deserialize ad hoc data inserted in the page and consumed by the Sys.Cul tureInfo object.

Sys.StringBuilder Used to concatenate strings, the object works in much the same way as the managed StringBuilder class.

Partial Rendering Classes…

Description

Using objects:Example - to return type information:

myTimer = new MsdnMag.Timer(2000, updateUI, timerReset); alert(Object.getTypeName(myTimer));

Figure shows the effect of the alert function.

                                                            

A partial rendering request is often referred to as an AJAX postback.

An AJAX postback is like a classic ASP.NET postback, except that it is carried out by a piece of script code defined in the client-side ASP.NET AJAX library.

Once on the server, the request goes through the typical lifecycle of postback requests and raises such events as Init, Load, and PreRender.

A Look at Partial Rendering

First of all an ASP.NET AJAX page must include one instance of the ScriptManager control. This control is the real nerve center of all ASP.NET AJAX pages.

Anatomy of an AJAX PostbackTo make an ASP.NET page a partially rendered page, you must first add a script manager to the

page (instance of the ScriptManager control. This control is the real nerve center of all ASP.NET

AJAX pages) and then define independently updatable regions by wrapping them with an UpdatePanel control.

Whenever the script manager detects one or more UpdatePanel controls in the page, it emits the block of script . In that block is:1. Sys.WebForms.PageRequestManager._initialize(‘…, document.getElementById('form1')); 2. Sys.WebForms.PageRequestManager.getInstance()._updateControls( ['tUpdatePanel1','tUpdatePanel2']…);

The _initialize method is a static method on the client-side PageRequestManager object . It creates a global instance of the PageRequestManager class and initializes it. The instance of the class can be retrieved through getInstance(). The second statement registers an array of UpdatePanel controls with the client framework.

The key action happening here is inside the _initialize method. At this time a handler is registered for the submit event of the DOM form object. This means that whenever the page submits a form, the AJAX script kicks in and places the request using XMLHttpRequest instead of letting the request go through a normal browser postback.

The viewstate is uploaded to the server with the request. On the way back, an updated viewstate is downloaded accompanied with shorter markup (for the updatable regions that have been modified).The list includes the UpdatePanel control that triggered the postback any other UpdatePanel controls in the page that have the UpdateMode property set to Always, and any UpdatePanel control that is programmatically refreshed.

* from a performance point of view, an application is better off not using UpdatePane

* UpdatePanel makes it extremely easy to take all that flashing and flickering that occurs when an ASP.NET page posts back to the server and turn it into smooth, flicker-free updates. * UpdatePanel works its magic by converting postbacks into asynchronous callbacks (XML-HTTP requests) and using JavaScript on the client to refresh the part of the page encapsulated by the UpdatePanel control. The flashing and flickering goes away because the browser doesn’t repaint the page as it does during a postback.

The Partial Rendering Engine

The key object for partial rendering is PageRequestManager, in the Sys.WebForms namespace. The code that initializes the object is transparently inserted in any client page (with at least one UpdatePanel control). If you view the source of such a page, you'll find a piece of script:

Sys.WebForms.PageRequestManager._initialize( 'ScriptManager1', document.getElementById('form1'));

The _initialize method on the PageRequestManager does two main things. 1.First, it creates the unique instance of the object to serve all needs in the page lifecycle. 2. Second, it registers a script handler for the form's submit event.

In this way, you end up having a common piece of code to intercept any type of postback—- regular postbacks done via the browser, - cross-page postbacks, - postbacks commanded through the DOM.

The goal of the submit handler is stopping the browser's default action and replacing the form with an AJAX request .

1. The submit handler starts its job by composing the body of the request. It does that looping through the input fields in the form and creating a proper string.

2. Once the request is ready, the PageRequestManager first fires the client-side initializeRequest event. The event gives developers a chance to cancel the operation.

3. If the operation can proceed, the manager kills any pending operation—only one partial rendering operation can be active at a time—and fires the beginRequest event to notify that the request is going to leave.

4. Next, it calls invoke on the corresponding WebRequest object.

1.When the response is back the pageLoading event is fired.2. When the pageLoading event arrives, the response has been parsed but not yet merged with the current DOM of the page. 3. Next, the panels involved with the operation are refreshed and any other data coming from the server is processed, including data items and postback scripts. 4. Finally, the pageLoaded event is fired followed by the endRequest event.