Improving Performance Through AJAX

In this lesson of the Silverlight tutorial, you will learn...
  1. How Microsoft ASP.NET AJAX is used to improve Web application performance
  2. About utilizing the ASP.NET AJAX Control Toolkit and Microsoft CodePlex to extend Microsoft development technologies
  3. To make out-of-band calls to Web Services using ASP.NET AJAX

This lesson will illustrate improving the performance of an ASP.NET application by applying Ajax techniques.

A Progression of Client-Side Technologies

Microsoft Silverlight is not a completely new idea but has evolved as a progression of Web development technologies and standards and is the next logical step in the progression.

As stated in an earlier module, as the Web became more popular, users, developers, businesses, educational institutions, and basically everyone using the Web saw the need of content being offered to go from static content to dynamic and interactive content. There is way too much data available and an inconceivable number of ways to combine that data for display purposes for Web developers and designers to ever be able to create static content representing that data. Additionally, each time the data changes, it would be a nightmare to update and maintain the data if it were all offered statically.

An additional factor that influenced the need for dynamic Web content has been the load on Web servers. When content was offered statically over the Web, most Web applications were hosted on a single Web server. As the Web grew in popularity, the number of users grew in number and the tasks that users needed to complete in an application grew in complexity. In order to bear the increased load, multiple Web servers were clustered together to form a "Web Farm" and share in the load. The introduction of Web Farms presented challenges both to existing technologies, such as classic ASP, and in the budgets of the companies offering Web content. Installing and maintaining multiple servers is much more expensive and requires more administrators to monitor and maintain the servers.

One benefit to offering content through a Web application is that, in a perfect world, any client can utilize the Web application by using any Web browser, regardless of the operating system installed on the client's computer. In essence, very little Web application processing occurs on a client's computer. However, any processing that does occur on the client's computer, such as that carried out by using JavaScript, occurs very fast because it occurs locally to the client and does not require a trip to the Web server. Furthermore, as more Web application processing occurs on the client's computer, less Web application processing needs to occur on the server. Hence, if a client's computer can be utilized more to process Web applications, the load placed on Web servers will be lighter thus requiring fewer servers, less expense, less monitoring and maintenance, and fewer administrators.

DHTML

A major challenge, of course, to performing more processing on the client's machine is that the processing that occurs must be compatible with the user's environment (operating system, browser, etc). Originally, the only method of performing processing across all platforms and browsers using a single solution was to do so by using JavaScript. JavaScript is very capable but is limited in comparison to more advance programming languages.

Dynamic HTML (DHTML) was the first popular solution to performing more client-side Web application processing through the use of HTML, the Document Object Model (DOM), Cascading Style Sheets (CSS), and JavaScript. DHTML was used to create more dynamic and interactive Web applications and was even used to create some early online games. DHTML was introduced as a joint effort by Microsoft and Netscape.

However, DHTML is build by using technologies that are interpreted by the client's browser. As such, DHTML is completely reliant upon the user's browser and platform for consistency. Not all browsers support the W3C standards in a consistent manner. A DHTML solution may not perform as intended or may not perform at all in a browser that it was not designed to function in. DHTML was a good start but, due to its reliance upon a client's browser, Web application developers do not have full control over the end result.

Plugin Technologies

Although DHTML made a valiant effort to provide interactive Web applications, it did have some shortcomings that were not entirely its fault. In addition to not being able to compensate for browser implementation inconsistencies, it was not able to deliver high quality media and animations and do so in a consistent manner. As a result, a few companies began to develop downloadable plugin extensions to the browser that would create a small consistent environment for a particular technology to operate in.

One of the first companies to develop a downloadable plugin execution environment was Sun Microsystems. Sun developed the Java Virtual Machine (JVM) and Java Runtime Environment (JRE) for hosting applications written by using the Java programming language. The Java plugin is downloaded and hosted by the user's browser. When a Java application is encountered, it is interpreted by the JVM and executed within a secure "sandbox". Since Sun created the plugin and made it available to multiple operating systems and browsers, Sun remained in charge of how the environment functioned and was no longer at the mercy of Web browser developers. As a result, Sun is able to deliver very consistent behavior through Java applications across all supported browsers and operating systems.

Another vendor that created a very popular downloadable plugin environment was Macromedia (now acquired by Adobe). Macromedia developed the Flash player plugin and the Shockwave player plugin. Flash is used to develop high quality animations and interactive movies through vector graphics. Flash was the defacto standard in animations and movies delivered over the Web prior to Silverlight. Macromedia also saw the benefit of creating and distributing a controlled execution environment to host their animations, movie, and applications so that they could deliver consistent, high quality content over the Web.

Ajax

Microsoft ASP.NET AJAX is illustrated and described in greater detail in the following section. However, ASP.NET AJAX, Microsoft's Ajax implementation in .NET, is a consolidated extension of DHTML and downloadable plugin technology. Ajax is implemented through JavaScript making out-of-band calls to the Web server separate from the page request and response stream for the purpose of updating a small portion of the page or to provide user interactivity. Ajax uses JavaScript to make calls to the Web server asynchronously so that the user gets a perceived improvement in performance by having immediate responses that do not require waiting on a postback to the server to complete.

Ajax was a vast improvement that quickly gained momentum in the industry by offering a more consistent and powerful manner of providing more powerful, interactive, and better performing user Web application experiences. When implemented through an Ajax framework, such as ASP.NET AJAX, Ajax provides more advanced features to JavaScript as well including object oriented development features, network and communications, and the ability to call Web services.

Silverlight

While Ajax offers expansive client-side Web development features, it is limited in regards to streaming media, animations, and elaborate user interfaces. Microsoft Silverlight further extends ASP.NET AJAX into another downloadable plugin execution environment that offers more features on the client and is optimized for high-end user interfaces and streaming media. In fact, Silverlight is a subset of Windows Presentation Foundation, the technology, functionality, and standards used to create the Windows Vista user interface.

ASP.NET AJAX

Through the progression of Microsoft's attempts to improve Web development and offload more processing to the client's computer, it introduced Remote Scripting (RS) in 1997. Remote Scripting instantiated an ActiveX control, the XMLHTTPRequest object, through JavaScript to initiate asynchronous calls to the Web server. Using this approach, they were able to significantly improve Web application responsiveness and performance. However, ActiveX controls are reliant upon the Microsoft Windows operating system, hence Remote Scripting and Ajax through the use of an ActiveX control was not portable to non-Microsoft operating systems. To side step this limitation, Microsoft moved forward by building Ajax support into Internet Explorer itself. Hence any operating system that supports Internet Explorer could then support Ajax. The idea and concept caught the attention of competing Web browser developers and they too integrated support for the XMLHTTPRequest object into their browsers.

On a side note, the technology behind Ajax, Remote Scripting (RS) originated with Microsoft and Microsoft states that it is an acronym that stands for "Asynchronous JavaScript and XML". This makes perfect sense since that is what the technology is doing and this is the accepted meaning by most in the industry. Additionally, it would seem that Microsoft should be able to define the acronym since they originally designed the technology. However, the developer who is credited with coining the phrase "Ajax" states that it is not an acronym. This matter is really trivial but good to be aware of.

In 2006, Microsoft released ASP.NET AJAX, the implementation of Ajax integrated into ASP.NET. ASP.NET AJAX consists of three primary components: a client-side library or framework that significantly extends what client-side JavaScript is capable of doing, server-side programming and development extensions that allow it to integrate nicely into Visual Studio, and a community-developed and supported toolkit. The ASP.NET AJAX architecture is illustrated in the following figure. A nice feature included in the AJAX client-side library is the extension of JavaScript to enable many object oriented development features by using JavaScript.

On the server-side, the AJAX extensions provide a handful of AJAX controls with the two primary controls being the ScriptManager and the UpdatePanel. Every ASP.NET Web form that needs to be AJAX-enabled must include one and only one ScriptManager control. The ScriptManager control instructs the ASP.NET engine to configure the outgoing response to the client for working with AJAX and to include the script library when sending the response. Each ASP.NET Web form that needs to be AJAX-enabled may contain one or more UpdatePanel controls. The UpdatePanel serves as a container for portions of the Web form and controls that should utilize AJAX.

Microsoft hosts a Web site with additional information, instructional information, and resources related to ASP.NET AJAX at http://www.asp.net/ajax/ as shown in the figure below.

A Simple ASP.NET AJAX Example

There are two primary methods for utilizing Ajax using Microsoft technologies: through JavaScript by instantiating the XMLHTTPRequest object and through the ASP.NET AJAX extensions. Microsoft has done a fantastic job of simplifying the process of Ajax-enabling an ASP.NET Web form by using the Visual Studio visual Web form designer. To create a new ASP.NET AJAX Web application, select the option from the New Web Site dialog box as shown in the following figure.

When a new ASP.NET AJAX Web site is created by using Visual Studio 2008, a new page named Default.aspx is automatically created for you. The default page will include a ScriptManager control but will not contain any UpdatePanel controls.

In order to AJAX-enable an existing ASP.NET Web form, simply drag and drop a ScriptManager control onto the Web form. Adding a ScriptManager control to a Web form AJAX-enables the Web form but does define a region or portion of the Web form that should be updated by using AJAX. An entire Web form can take advantage of AJAX, however, typically, only portions of a page or controls are identified for use with AJAX. The UpdatePanel control is used to identify a portion of a Web form for use with AJAX. To identify a section of a Web form for use with AJAX, simply drag and drop an UpdatePanel control onto the Web form and then drag and drop the controls that should be AJAX enabled into the UpdatePanel. To gain more control over the placement of controls and sections of a Web form, it may be easier to add the UpdatePanel control declaratively through the Web form markup.

The markup below illustrates the sample MyFantasyPicks ASP.NET Web form with AJAX controls added. The result is that the Web form does not flicker or update when displaying the fantasy picks as the entire page is not posting back to the server.

That's all there is to it when using Visual Studio 2008 in its simplest form. However, bear in mind that once AJAX is in the picture, you can write much more elaborate client-side JavaScript to significantly improve and optimize your client-side processing. Hence, your time investments in planning your AJAX implementation may result in great returns in performance.

Code Sample: ImprovingPerformanceThroughAJAX/Demos/MyFantasyPicks/Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>My First ASP.NET Page</title>
    <link href="External.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        div.myDiv
        {
            font-weight: bold;
            font-size: 14px;
        }
    </style>

<script type="text/javascript">
<!--

function btnDisplayPicks_WSClick() {
return FantasyLeague.GetPicks(OnComplete, OnTimeOut, OnError);
return (true);
}

function OnComplete(message)
{
    document.getElementById("lblMyPicks").innerHTML = message;
}

function OnTimeOut(message)
{
    alert("a timeout encountered while getting picks");
}

function OnError(message)
{
    alert("an error encountered while getting picks");
}

// -->
</script>
</head>
<body>
    
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/FantasyLeague.asmx" />
        </Services>
    </asp:ScriptManager>
    <div class="myDiv" style="font-family: Sans-Serif;">

        <script src="Greeting.js" type="text/javascript"></script>

    </div>
    <hr />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="btnDisplayPicks" runat="server" 
    Text="Display My Fantasy Picks" OnClientClick="btnDisplayPicks_WSClick(); return false;" />
            <asp:Label ID="lblMyPicks" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <div>
    </div>
    <hr />
    <div style="text-align: center;">

        <script type="text/ecmascript">
<!--
  // Display the current date and time.
  document.write("copyright &copy; 2007 | the current date and time is " + new Date());
//-->
        </script>

    </div>
    </form>
</body>
</html>

ASP.NET AJAX Control Toolkit

Microsoft has many, many products available and many of their products are market leaders. Microsoft has their hands full innovating and creating new products and they realize that, although they employ thousands of incredibly intelligent people, they don't hold a monopoly on good ideas. In an effort to foster and nurture good ideas, Microsoft hosts an open source developer community Web site at http://www.codeplex.com/.

With the bulk of software development occurring on the Web, ASP.NET AJAX has become incredibly popular in the industry as well. Developers have introduced many great ideas for ASP.NET AJAX controls that save other developers time when they are able to reuse the controls in their applications. These ASP.NET AJAX controls have been compiled into an integrated toolkit called, not surprisingly, the ASP.NET AJAX Control Toolkit. The toolkit is available on codeplex at http://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx?ReleaseId=8513 and is shown in the figure below.

Installing the Toolkit

While you can utilize the ASP.NET AJAX Control Toolkit by using any editor and can manually reference and use the toolkit from within Visual Studio, it would be easiest if you could simply drag and drop the controls contained in the toolkit onto your ASP.NET AJAX enabled Web forms and configure the controls using the visual designer tools. The good news is that you can. However, integrating the toolkit into Visual Studio is not a straightforward process.

You can download the control toolkit with source code included or without source code. If you plan to extend or add to the toolkit controls, be sure to download the version that includes source code. To integrate the toolkit with Visual Studio:

  1. Download the version of the toolkit that best suits your needs. The toolkit resides in a zip file
  2. Unzip the file. The typical unzip location is C:\Program Files\Microsoft ASP.NET\ASP.NET AJAX Control Toolkit.
  3. Start or open Visual Studio 2008.
  4. Open an ASP.NET Web form in Design mode.
  5. Right-click on the Toolbox and select Add Tab. Name the tab AJAX Control Toolkit.
  6. Right-click on the newly added Toolbox tab and select Choose Items....
  7. The Choose Toolbox Items dialog may take a few seconds to display as it must first scan the Global Assembly Cache, the Windows Registry, etc. From the Choose Toolbox Items dialog, select the Browse button.
  8. Navigate to the location where you unzipped the toolkit files. In the toolkit is a folder named SampleWebSite that contains a subfolder named Bin. In the Bin folder, you should find a file named AjaxControlToolkit.dll. Select this file and click Open.
  9. In the Choose Toolbox Items dialog, the toolkit controls should all be selected. Click Ok.

The AJAX Control Toolkit tab of the Toolbox should resemble the following figure.

To use one of the controls, simply drag and drop it onto an ASP.NET AJAX Web form and configure it. All of the controls in the toolkit are documented in the toolkit documentation as well as online at CodePlex.

Further Improving ASP.NET AJAX Performance

There are many little tweaks and design practices that you can follow to improve performance and streamline and optimize ASP.NET, AJAX, and all of the technologies involved. However, on the topic of ASP.NET AJAX, it is important to understand the process that occurs when a call is made to the server. When an ASP.NET page is posted back to the server, the entire page event life cycle for the page is executed and this consumes some time and resources. The goal in utilizing ASP.NET AJAX and client-side processing is to minimize calls to the server and server-side processing.

When an asynchronous call is made to the server using AJAX, the entire page is not posted back. However, when the AJAX call is received at the server, the page associated with the call is read into memory on the server, the entire page event life cycle is executed, and only the return value that relates to the AJAX call is sent back to the client. The additional processing of the entire page event life cycle consumes time and resources and causes a delay in the response making its way back to the client. This behavior can be avoided by making a call from the AJAX JavaScript to a Web service instead of making a call to the Web server hosting the page.

The Web Service

In a nutshell, a Web service is a class that contains methods that can be called over the Web. In the same manner that a method contained in a class would be called from code in an application, a method in a Web service is called over the Web. Web services are not a Microsoft technology but are an industry technology that complies with the Service Oriented Architecture (SOA) industry standard.

Web services originated from JavaScript files. A JavaScript file that is published for use on a Web site can be called from anywhere on the Web, contains functions, and returns a response. However, a JavaScript file generally resides on the client while a Web service remains on the server.

ASP.NET Web services are ready to be called from ASP.NET AJAX JavaScript when they are created using Visual Studio 2008 although a slight modification is necessary. When an ASP.NET Web service is created, open the code behind file and note the commented out attribute. Uncomment this attribute and the Web service is ready to be called.

The Web service must contain at least one method that can be called over the Web. The code snippet below shows the example Web method that returns a string.

Code Sample: ImprovingPerformanceThroughAJAX/Demos/MyFantasyPicks/App_Code/FantasyLeague.cs

using System;
using System.Collections;
using System.Linq;
using System.Web;
<cw:File xmlns:cw="http://www.webucator.com/Schemas/Courseware"><![CDATA[using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Linq;

/// <summary>
/// Summary description for FantasyLeague
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class FantasyLeague : System.Web.Services.WebService {

    public FantasyLeague () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string GetPicks() {

        // Create an XMLDocument
        XmlDocument xmlDoc = new XmlDocument();

        // Load the XML file.
        xmlDoc.Load(Server.MapPath("App_Data/FantasyPick.xml"));

        // We should have error handling
        // and more elaborate code in here
        // but this works for an example.

        // Reference the first pick element.
        XmlAttributeCollection pickElementAttributes = xmlDoc.DocumentElement.FirstChild.Attributes;
        XmlNodeList pickElementChildren = xmlDoc.DocumentElement.FirstChild.ChildNodes;

        // Display my picks.
        string myPicks =
            "<hr />" +
            "My fantasy picks for week number " +
            pickElementAttributes[0].Value +
            " are: <br /><ul>";

        // Iterate through the picks.
        for (int i = 0; i < pickElementChildren.Count; i++)
        {

            myPicks +=
              "<li>" +
              pickElementChildren[i].Attributes[0].Value +
              " playing " +
              pickElementChildren[i].Attributes[1].Value +
              "</li>";
        }

        // Close the list.
        myPicks += "</ul>";

        // Clean up.
        pickElementChildren = null;
        pickElementAttributes = null;
        xmlDoc = null;

        return myPicks;
    }   
}

When the Web service above is executed in Visual Studio with debugging enabled, a page as shown in the following figure is displayed.

The figure above shows that the page displays a single link to the GetPicks method. By clicking the GetPicks link, a second test page is displayed where an option to provide parameter values is given along with a button to invoke the method. The bottom portion of the second test page illustrates HTTP and SOAP calls to the GetPicks method. The following figure shows the second test page.

Finally, by clicking the Invoke button, a third page is displayed in a separate browser window instance that displays the response from the Web method as shown in the following figure.

The AJAX Modifications

Once the Web service is up and ready to be called by AJAX JavaScript, the Web service must be registered with ASP.NET AJAX to be called by the JavaScript in the page. To call a Web service from ASP.NET AJAX, modify the ScriptManager control to include a reference to the Web service.

The next step is to add a global script to the <head> section of the ASP.NET AJAX Web form. The script added is shown below.

Code Sample: ImprovingPerformanceThroughAJAX/Demos/MyFantasyPicks/Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>My First ASP.NET Page</title>
    <link href="External.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        div.myDiv
        {
            font-weight: bold;
            font-size: 14px;
        }
    </style>

<script type="text/javascript">
<!--

function btnDisplayPicks_WSClick() {
return FantasyLeague.GetPicks(OnComplete, OnTimeOut, OnError);
return (true);
}

function OnComplete(message)
{
    document.getElementById("lblMyPicks").innerHTML = message;
}

function OnTimeOut(message)
{
    alert("a timeout encountered while getting picks");
}

function OnError(message)
{
    alert("an error encountered while getting picks");
}

// -->
</script>
</head>
<body>
    
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/FantasyLeague.asmx" />
        </Services>
    </asp:ScriptManager>
    <div class="myDiv" style="font-family: Sans-Serif;">

        <script src="Greeting.js" type="text/javascript"></script>

    </div>
    <hr />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Button ID="btnDisplayPicks" runat="server" 
    Text="Display My Fantasy Picks" OnClientClick="btnDisplayPicks_WSClick(); return false;" />
            <asp:Label ID="lblMyPicks" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
    <div>
    </div>
    <hr />
    <div style="text-align: center;">

        <script type="text/ecmascript">
<!--
  // Display the current date and time.
  document.write("copyright &copy; 2007 | the current date and time is " + new Date());
//-->
        </script>

    </div>
    </form>
</body>
</html>

In the code example above, the first line of the btnDisplayPicks_WSClick function makes a call to the GetPicks method of the FantasyLeague Web service and returns the response. This is an asynchronous call directly to the Web method so the page immediately returns and the response is displayed when the call completes. In this example, the call is very simple so any latency is negligible. The call to the Web method accommodates for parameters (although none are passed in this example) and takes three additional parameters: the name of a method to run when the call to the Web method completes, the name of a method to run if the call to the Web method should timeout, and the name of a method to run if the call to the Web method should result in an error.

A final modification to make is to modify the button used to display the fantasy picks as shown below. Be sure to both, make a call to the JavaScript function and return a false value to avoid a postback to the server when the button is clicked.

Lab: Online Training Tool Version 3.0

In this exercise, you will create a simulated online training utility by using:

  • Visual Studio 2008
  • XHTML
  • CSS
  • XML
  • JavaScript
  • ASP.NET
  • ASP.NET AJAX

We'll create the simulated training tool to produce the same result as that produced in the previous module. However, we'll utilize ASP.NET AJAX to improve performance. The training utility will consist of a single HTML page that displays a single course with multiple topics stored in an XML file. Additionally, we'll add to the training utility to provide search capability through the use of a Web service.

Improving Performance Through AJAX Conclusion

In this lesson of the Silverlight tutorial, you

  • Enabled AJAX on an ASP.NET page to improve performance
  • Explored the ASP.NET AJAX Control Toolkit and Microsoft CodePlex
  • Further improved ASP.NET AJAX performance by making an out-of-band call to a Web Service
To continue to learn Silverlight go to the top of this page and click on the next lesson in this Silverlight Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.