ASP.net 2.0 AJAX-enabled web development

Source: Internet
Author: User
Tags object functions http request net string tostring web services access
Ajax|asp.net|web
"Guided reading" in the past few months, the design patterns of highly interactive Web applications based on AJAX technology have rapidly spread. Today, highly configurable web applications, such as Google Maps and A9, are making a comprehensive use of these technologies to create a rich client user experience. In fact, the combination of AJAX technology for Web development is not the latest research results, but these technologies have been continuously updated and improved.

I have three goals in this article. First, I want to provide a high-level overview of AJAX-style applications. Second, I want to describe in detail the asynchronous callback mechanism for ASP.net 2.0. Finally, I want to look forward to future improvements to the tools and frameworks for building AJAX-style applications.

In summary, AJAX-style Web applications show the following characteristics:

• Asynchronous requests to the Web server-the browser user interface is not blocked while the user waits for a response from the Web server, and can continue to respond to user interaction.

• The latest improvements and standardization of browser-based Logic-W3C DOM, which is highly dependent on JavaScript, provides support for implementing dynamic client-side UI updates.

• XML-based Exchange-xmlhttp objects between browsers and Web servers make it possible to communicate with a Web server without overloading the page.

The biggest difference between an AJAX application and a traditional Web application is that each user interaction does not cause each HTTP request to be sent to the Web server; instead, the browser-based logic that is implemented with JavaScript holds control, The control then decides whether to make a local processing request or an asynchronous call to the server. Once the asynchronous call to the server ends, the client logic immediately updates the relevant parts of the UI appropriately. This approach has the following advantages:

• User experience is more abundant. For example, when a Google map user drags a map in one direction, the system sends an asynchronous request to the server in the background, resulting in the ability to continue dragging after the screen boundary is exceeded. Since then, when the user drags the map further, the new image is already available. This leads to a feeling of faster response.

• Since the state of the call across XMLHTTP to the server is not lost, Ajax applications can avoid the UI interface being regenerated every time.

• More logic is on the browser side, which reduces the number of requests to and from the Web server, thereby comprehensively improving the system's potential.

Despite all the advantages, AJAX-style applications still have some drawbacks. For example, the development of AJAX-style applications is difficult because of the lack of a corresponding framework (a set of UI classes similar to Windows MFC Toolkit) and the IDE (debug, visual design, and so on) support. In addition, development based on Ajax requires that one person must master at least two languages (DHTML and JavaScript). Also, the encoding of an AJAX-style application takes longer because it requires additional testing to enable it to support multiple browser versions and types. Finally, because JavaScript based source is accessible to end users, security analysis in the development process becomes very important.

Luckily, for example, Atlas,ajax. NET and the advent of tools such as Google Maps API provide better support for building AJAX-style applications in the future. Next, we'll discuss the evolution of support technologies for building AJAX-style applications and what we expect from the latest release of Toolset Atlas.

Let's first discuss the XMLHTTP object. The object was first introduced by Microsoft and later implemented on other platforms, including Mozilla and Apple's Safari browser. XMLHTTP supports asynchronous requests to the Web server, allowing clients to invoke the Web server based on JavaScript logic without overloading the entire page.

In other words, it is entirely possible to interact with the Web server in the background without causing the entire page overload.

The use of XMLHTTP objects is fairly straightforward. For simplicity's sake, let's just consider IE-specific syntax. In fact, XMLHTTP's implementation syntax on other browsers is similar to the discussion here.

request = new ActiveXObject ("Microsoft.XMLHTTP");

if (request) {request.onreadystatechange = CallbackHandler;

Request.open ("Get", URL, True);

Request.send ();

}

Function CallbackHandler () {

if (request.readystate = 4) && (Request.status =) {
br>string response = Request.responsexml;

//Update related parts of UI

}

}

In the preceding code fragment, the first step is to implement the instantiated Microsoft.XMLHTTP class. The second step is to set the properties of the XMLHTTP instance that we just created, including the address of the callback function that will be controlled when the XMLHTTP request completes. Because we are making an asynchronous call to the server (implemented by setting the third argument of the Open method to true), we need the address of the callback function. During the callback function implementation, we make additional checks to ensure that the request is completed.

You can see from the example code above that using the XMLHTTP object in an independent manner is fairly straightforward. However, it is more difficult to integrate XMLHTTP into other parts of the httppage lifecycle-for example, how do you ensure that server-side method calls can access the state of other controls on the page? To properly initialize the state of these controls, server-side callback processing needs to undergo a httppage lifecycle similar to that of the callback process. Other challenges in using the XMLHTTP object directly are that, as developers, we need to consider different browser types. Fortunately, ASP.net 2.0 provides a reusable pattern-it makes it easy to access callback functionality. Note that several controls, including Gridview,treeview, have been distributed along with ASP.net 2.0, and the callback mechanism has been comprehensively utilized.

Let's look at the server-side implementation principle first. First, a new interface ICallbackEventHandler is defined on the server side. Any ASPX page (or a control intended to support client callbacks) needs to implement this ICallbackEventHandler interface. The ICallbackEventHandler interface defines a method called RaiseCallbackEvent. This method uses a parameter of type string and returns a string.

On the client side, in order to initialize the callback function, a special JavaScript function needs to be invoked. You can get a reference to this particular JavaScript function by calling Clientscriptmanager.getcallbackeventreference. A call to GetCallbackEventReference will produce a callback reference. When calling this callback function, you only need to pass a parameter of type string. This is consistent with the RaiseCallbackEvent signature on the server side. This is all you need to do to create a callback mechanism on the client side. Other implementations of the RaiseCallbackEvent method that put the client callback function hook up to the server-side ICallbackEventHandler interface are done by the framework.

The special JavaScript function of the initialization callback mechanism mentioned earlier uses two additional parameters (__callbackparam and __callbackid) as the feedback data, which represents the string arguments passed to the caller and the ID of the control, respectively. On the server side, ASP. NET detects the existence of the other two parameters and routes the request to the appropriate control, which causes the RaiseCallbackEvent method on the target control to be invoked. To address the initialization problems of controls on the page mentioned earlier, ASP. NET runtime provides a simplified version of the Httppage lifecycle when a callback is made to a service. This cycle includes browsing for a specific phase of page initialization, observing State loading, page loading, and callback function event handling. Once the callback function event is handled by the control, the other stages of the httppage lifecycle are skipped.

To help better understand the callback mechanism for ASP.net 2.0, the release package includes a simple progress bar control that relies on callbacks to determine the status of a task determined by the server. The code for the ProgressBar control is shown in Listing 1 below. To support the client callback function, the control implements the ICallbackEventHandler interface. For demonstration purposes, the RaiseCallbackEvent method simply looks for a counter stored in the session, adds 1 to the counter each time, and returns the new value to the client. Finally, listing 2 shows the JavaScript code that is responsible for initializing the callback function. It uses this. Page.ClientScript.GetCallbackEventReference to obtain a security reference to the function that needs to initialize the callback.

List 1 ProgressBar.cs

public class ProgressBar:System.Web.UI.Control,

system.web.ui.icallbackeventhandler{

private int percentcompleted{

Get

{

If system.web.httpcontext.current.session["percentcomplete"] = = null) {

system.web.httpcontext.current.session["PercentComplete"] = 1;

}

else {

system.web.httpcontext.current.session["PercentComplete"]

= (int) system.web.httpcontext.current.session["PercentComplete"] + 1;

}

return (int) system.web.httpcontext.current.session["PercentComplete"];

}

Set

{

system.web.httpcontext.current.session["PercentComplete"] = 1;

}

}

public string RaiseCallbackEvent (string eventarguments) {

int percent = this. percentcompleted;

If (Percent > 100)

{

This. percentcompleted = 1;

return "Completed";

}

Else

{

return percent. ToString () + "%";

}

}

protected override void OnPreRender (EventArgs e) {

This. Page.ClientScript.RegisterClientScriptBlock (typeof (ProgressBar),

"ProgressBar", this. Getclientsidescript (), true);

Base. OnPreRender (e);

}

protected override void Render (HtmlTextWriter writer) {

System.Text.StringBuilder sb = new StringBuilder ();

Sb. Append (@ "<table id=" "Progressbarcontainer" "bgcolor=" "Lightsteelblue" "

border= "0" "width=" "style=" "Display:none"; Position:absolute;

Z-index:10 "" "" ");

Sb. Append (@ "<tr> <td colspan=" "3" "style=" "padding:3px 2px 2px 10px" "" ");

Sb. Append (@ "<font face=" "Verdana, Arial, Helvetica, Sans-serif" "Size=" "2" "" ");

Sb. Append (@ "<span id=" "Progressbarlabel" ">uploading ... </span> ");

Sb. Append (@ "</font> </td> </tr> <tr> <td>");

Sb. Append (@ "<font size=" "1" "> </font> </td> <td bgcolor=" "#999999"

Width= "" 100% "" "" "";

Sb. Append (@ "<table id=" "ProgressBar" "border=" "0" "width=" "0")

Cellspacing= "" 0 "" "" "";

Sb. Append (@ "<tr> <td style=" "Background-image:url (progressbar.gif)" "" "

<font size= "1" "> </font> </td>");

Sb. Append (@ "</tr> </table> </td>");

Sb. Append (@ "<td> <font size=" "1" "> </font> </td> </tr>");

Sb. Append (@ "<tr height=" "5px" "><TD colspan=" "3" "> </td> </tr>");

Sb. Append (@ "</table>");

Writer. Write (sb.) ToString ());

Base. Render (writer);

}

private String Getclientsidescript () {

System.Reflection.Assembly DLL =

System.Reflection.Assembly.GetExecutingAssembly ();

StreamReader reader;

reader = new StreamReader (DLL. GetManifestResourceStream ("ProgressBar.txt"));

StringBuilder js = new StringBuilder (reader. ReadToEnd ());

String fp = this. Page.ClientScript.GetCallbackEventReference (This, "", "UpdateProgressBar", "");

Js. Replace ("# #InitiateCallBack # #", FP);

Reader. Close ();

Return JS. ToString ();

}

}


List 2 Progressbar.js

Implementing a progress bar control is relatively straightforward by using the client callback function provided in ASP.net 2.0, because the data passed between the control and the client is only a simple string. However, once we add other data types to it, we encounter a mismatch between JavaScript and. NET type systems. Unfortunately, the implementation of the callback function in ASP.net 2.0 does not help this very much. Any application that wants to use a variety of data types (simple types and complex types) implements its own custom pattern.

Fortunately, this restriction can be overcome by using a ajax.net open Source Library, Ajax.NET implements an agent-based approach to invoking server-side functions. Ajax. NET defines a custom attribute called Ajaxmethod. When a server-side method is decorated with Ajaxmethod, a JavaScript-based client proxy is automatically generated by HttpHandler (which is part of the Ajax.NET library). Unlike ASP.net 2.0, it supports the string type of a single parameter for use in callback implementations. Ajax. NET supports many types of integers, strings, doubles, Datetime,dataset, and so on.

Bertrand Le Roy recommends using Ajax.NET to handle the differences between JavaScript and. NET type systems. He created a server-side control called Ecmascriptobject-it recreated the JavaScript type system based on the. NET technology. The idea is to regenerate a client-side object graph with. Net. This approach is more meaningful when the conversion occurs on the server side.

Even though we have a type-safe way to invoke callback functions, we face other challenges as well. JavaScript acts as a "glue" that combines parts of an AJAX application. And, of course, the dependence on JavaScript is further increased. Unfortunately, although JavaScript is a powerful and versatile language, it does not implement object-oriented principles. This means that it can be more difficult to implement code reuse. Of course, there are some tricks you can use to make JavaScript look more like a traditional object-oriented language. Even so, it is still quite difficult to implement features such as events and proxies in managed languages.

Other difficulties include the lack of a reusable framework to further improve JavaScript development efficiency. It might be better to have a JavaScript-based UI framework that hides the difference between different execution environments. In addition, if you can create a set of classes, they can invoke the Web service in a secure way (relative to the manual encoding of the SOAP packets and use XMLHTTP to pass them), which is also pretty good.

The recent Atlas project from Microsoft has promised to focus on solving such problems. This is a great way to simplify the development of Ajax style. Atlas provides a new JavaScript framework (note that the following is a preliminary announcement based on Microsoft that may change later)-UI Development Kit. These include common controls that support features such as drag-and-drop and data binding, soap stacks that invoke Web services, browser-compatible layers that obscure browser differences, and client-side building blocks that include content such as local buffering. In addition, ASP. NET team also plans to develop other building blocks for asp.net, such as configuration management, member management, and so on, so that they can be used as Web service endpoints, enabling access to Web services directly from JavaScript-for example, easy access to personal information from the client. Finally, the Atlas project also plans to extend JavaScript syntax to include interfaces, lifecycle management, and multicast events.

<

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.