Atlas At Last

ASP.NET Atlas Powers the AJAX-Style Sites You’ve Been Waiting For

Matt Gibbs

This article is based on a prerelease version of ASP.NET "Atlas." All information contained herein is subject to change.

This article discusses:
  • Introduction to ASP.NET “Atlas”
  • Atlas architecture
  • Client and server controls
  • Atlas and Web services
This article uses the following technologies:
ASP.NET, Visual Studio 2005, Internet Explorer

Contents

What is Atlas?
The Atlas Architecture
The Client Script Core Library
Client Script Controls and Components
Server Controls
Web Services
Conclusion

In September 2005, the ASP.NET team released the first Community Technology Preview (CTP) of the new features in ASP.NET code-named "Atlas." This extension to the Microsoft® .NET Framework 2.0 enables developers to more easily create rich, interactive Web sites that take advantage of both browser and server features.

The type of rich development that Atlas enables is broadly referred to as AJAX (Asynchronous JavaScript and XML), which is a relatively new acronym for a combination of technologies that have been around for quite some time. Modern browsers include the XMLHttpRequest object that can be used from JavaScript for making calls back to the server. This allows the page to react to user input and perform out-of-band operations without requiring that the whole page be refreshed. This concept is generally simple, but AJAX libraries can greatly alleviate the arduous task of writing client-side JavaScript to communicate with the server and deal with the XML that is returned from a Web service.

The general problem that AJAX attempts to solve is rooted in the HTTP protocol itself. HTTP is the standard used by browsers to communicate with Web servers to retrieve pages and post data back from them. The protocol is stateless, which means that preserving user input between page refreshes is up to code on the server. The typical user experience has been that the entire page gets refreshed to carry the state information back to the server. The user input on the page is then restored in the HTML sent back to the browser.

ASP.NET manages this process for you by carrying a hidden view state form field. Even though only part of the page may actually be getting updated, the entire page’s HTML is transmitted and the screen blanks out momentarily. While this refresh occurs, the user is not able to interact with the page until the new view is received and rendered by the browser. AJAX improves this experience by using the XMLHttpRequest object to make calls back to the server to invoke Web services without refreshing the entire page. The portion of the page being updated is then modified directly in JavaScript based on the XML that is received. The user may not even perceive that a page update is occurring and can continue reading or interacting with the page while the out-of-band work is happening asynchronously in the background.

What is Atlas?

The Atlas features of ASP.NET are not just another AJAX script library for writing client-centric Web applications. Atlas builds on the .NET Framework 2.0 and adds support for better utilizing the capabilities of client-side JavaScript and the XMLHttpRequest object. It includes server-based features that make it easy to enrich existing ASP.NET applications, as well as a client script library that is used by the Atlas controls and services. The architecture diagram in Figure 1 shows that the Atlas architecture extends across client and server and should be viewed as a broad set of development technologies for creating richer, more responsive cross-browser Web applications.

Figure 1 ASP.NET Atlas Architecture

Figure 1** ASP.NET Atlas Architecture **

Scenarios enabled by Atlas are not limited to updating regions of the page with an asynchronous JavaScript call. You also get richer client experiences that would otherwise be impractical. For example, consider a Web application built around movie data. The application might want to allow users to search for a specific actor. Obviously it wouldn’t be practical to provide a comprehensive dropdown list of all actor names to choose from, so the application would probably break the problem down. Users might be asked to select the first letter of the actor’s name. A request to the server could then provide a list that would be somewhat more manageable, but the user experience is not great. The application could present the user with a textbox to enter in part of the actor’s name. The server would then at least have some data to use in narrowing the search. This is better, but still leaves room for improvement. With Atlas you could provide a textbox that reacts dynamically as the user types to help narrow the search without waiting for the browser to refresh the whole page. Figure 2 shows how you could use Atlas to add autocomplete behavior that provides feedback as the user types.

Figure 2 Filtering Combobox

Figure 2** Filtering Combobox **

The Atlas CTP is available as a download from atlas.asp.net. When installed, it adds an additional Web Site template for C# and Visual Basic® .NET to Microsoft Visual Web Developer™. When you create a new Web site project in Visual Web Developer (click File, then New, then Web Site), you will see a dialog like the one shown in Figure 3. The Atlas Web site includes Microsoft.Web.Atlas.dll and an updated web.config file that configures the Web application to be able to use Atlas-based ASP.NET features. In the current release, Microsoft.Web.Atlas.dll is placed in the bin directory of the application as a local assembly available throughout the application.

Figure 3 Creating an Atlas Web Site

Figure 3** Creating an Atlas Web Site **

Atlas-based applications can be easily deployed by copying the files from a development machine to a server with ASP.NET 2.0 without worrying about separately installing Atlas. The installation is at the application level instead of machine level. As subsequent CTP releases become available, they can be used on a machine with older versions of Atlas even as the features evolve and change. This provides more flexibility in migrating to newer versions than if the installation were systemwide.

The Atlas Architecture

The first thing to notice about the Atlas architecture diagram shown in Figure 1 is that it spans both client and server. ASP.NET 2.0 added some additional client features but not to the extent that Atlas does. On the right side of the architecture diagram, notice that Atlas server features are built on top of ASP.NET 2.0 and extend its capabilities. Atlas includes a new set of server controls as well as new features aimed at accessing server-based data and services from the browser.

On the left you’ll see a comprehensive client script library, which can be used independently of the server features in writing client-centric JavaScript. It is the foundation on the client that is used heavily by the new Atlas features to enable richer application development with improved client-server interactions.

In Figure 4 you can see the typical client-server interaction in a Web application. First, a page is requested by the browser and the user interacts with it. When some action from the user requires data from the server, a complete page refresh occurs to update part of the page based on their input. Unfortunately, this behavior does not allow the user to continue interacting with the page. Instead, the user must pause continuously while working with the Web application.

Figure 4 Typical Client-Server Interaction

Figure 4** Typical Client-Server Interaction **

Figure 5 shows that client-server interaction with Atlas shifts away from complete page refreshes. Instead, the initial HTML is retrieved and subsequent calls to the server get updated data in XML, JavaScript Object Notation (JSON), or snippets of HTML to update the page incrementally. The background asynchronous calls can invoke Web services or retrieve page changes without leaving users feeling that they must pause. These asynchronous calls manage updated view state information for subsequent server postbacks so that when a complete page refresh is necessary, the accurate state of the page is carried to the server.

Figure 5 Atlas Client-Server Interaction

Figure 5** Atlas Client-Server Interaction **

The Client Script Core Library

The Atlas client script library is delivered to the browser as several distinct pieces. The script core comprises the bottom layers on which the rest of the library is built. At the base is the browser compatibility layer. A key feature of Atlas is that it will run on the modern browsers that support the key elements of AJAX. In the CTP builds, this support has included Mozilla Firefox, Apple Safari, and Microsoft Internet Explorer®. The browser compatibility layer is an abstraction that allows you to write script with less worry. It hides the details of where the browser implementations differ. It also allows for Atlas support to be easily augmented as the browsers evolve and as new versions are released. The type of browser making a request automatically determines what browser-specific parts of the compatibility layer are used. The higher-level code has been written to the abstraction layer, so you don’t need to code around variations in browser implementations.

On top of the compatibility layer is the core type system. The type system allows for an object-oriented approach to JavaScript development. It gives the developer working in JavaScript the ability to create namespaces and add classes to them. It also simulates object inheritance. There is support for interfaces, delegates, and enumerations, which makes it easier to switch back and forth between developing code on the server in an object-oriented programming language like C# and writing JavaScript code on the client.

The base class library layer built on top of the type system completes the core of the client script library. The concept is borrowed from the .NET Framework and exposes some familiar types. There is an Event object that supports multicasting of events in a natural way in JavaScript. There is a StringBuilder object, too. There is also support for object serialization, including support for JSON and XML data. The base class library also includes WebRequest and WebResponse classes that provide an abstraction over the browser’s XMLHttpRequest object similar to those found in the System.Net namespace in the .NET Framework. The code in Figure 6 demonstrates creating two simple types in JavaScript using the Atlas script core. The Movie type that is created first exposes properties for the movie title and its genre as well as a toString method. The Drama type then extends the Movie type and overrides the toString method.

Figure 6 Using the Atlas Type System

Type.registerNamespace(‘AtlasSample’);

AtlasSample.Movie = function(title, genre) {
    var _title = title;
    var _genre = genre;
        
    this.get_title = function() {
        return _title;
    }
    this.get_genre = function() {
        return _genre;
    }
    this.toString = function() {
        return this.get_title() + " : " + this.get_genre();
    }
    AtlasSample.Movie.registerBaseMethod(this, ‘toString’);
}    
AtlasSample.Movie.registerClass(‘AtlasSample.Movie’);

AtlasSample.Drama = function(title, year) {
    AtlasSample.Drama.initializeBase(this, [title, ‘drama’]);
    
    var _year = year;
    
    this.get_year = function() {
        return _year;
    }
    this.toString = function() {        
        return AtlasSample.Drama.callBaseMethod(this, ‘toString’) +
            ‘ : ‘ + this.get_year();
    }
    AtlasSample.Drama.registerBaseMethod(this, ‘toString’);
}
AtlasSample.Drama.registerClass(‘AtlasSample.Drama’, AtlasSample.Movie);

The page that uses the Movie and Drama types is shown in Figure 7. It first references the .js file where the types are defined in an Atlas ScriptManager control. Then, in the Click handlers, the page creates instances of the Movie and Drama types and calls their toString methods. The inheritance behavior is what you would expect to see from any object-oriented programming language, but the code that is running happens to be dynamic JavaScript. Another nice aspect of the current Atlas installation is that debug versions of the client script library are included to make debugging and troubleshooting easier. Debugging JavaScript has always been cumbersome, so this may ease the pain.

Figure 7 Inheritance Demonstration

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Atlas Type System</title>
</head>
<body>
    <form id="form1" runat="server">
        <atlas:ScriptManager runat="server" ID="scriptManager">
            <Scripts>
                <atlas:ScriptReference Path="drama.js" 
                     ScriptName="Custom" />
            </Scripts>
        </atlas:ScriptManager>
        <div>
            <input id="btn1" value="Show Movie Data" type="button" 
             onclick="return Click_ShowMovie()" />
            <input id="btn2" value="Show Drama Data" type="button" 
             onclick="return Click_ShowDrama()" /> 
        </div>    
    </form>
    <script type="text/JavaScript" language="JavaScript">
        function Click_ShowMovie() {
            var aMovie = new AtlasSample.Movie(‘Ray’, ‘drama’);
            alert(aMovie.toString());
        }
        function Click_ShowDrama() {
            var aDrama = new AtlasSample.Drama(‘Ray’, ‘2005’);
            alert(aDrama.toString());        
        }
    </script>
</body>
</html>

Client Script Controls and Components

Above the layers that make up the client script core of the Atlas architecture are the component model and controls layers. This part of the script library builds on top of the script core underneath it, but is rendered to the client separately. You could choose not to include the component layer and instead just use the JavaScript type system and base class library directly when writing script, but you would not have access to the client components provided by Atlas and would not be able to use xml-script, which is a new set of declarative elements contained in the page markup that is sent to the browser. The xml-script elements are contained in a script tag that uses the new type value:

<script type="text/xml-script">

The key to enabling an additional set of elements in the markup is the use of the script tag. The browser recognizes the script element but does not have a way to handle the text/xml-script type. The Atlas script library is then able to deal with the elements contained in the script tag itself. The markup is handled by the component layer of the client script library. The xml-script is parsed on the client to create instances of components and controls. It can contain property settings for the components and controls it defines and can declare bindings between them and HTML elements elsewhere on the page. The xml-script elements can also declare Web service resources and then reference them as data sources elsewhere in the markup. The example page in Figure 8 shows the use of xml-script to declaratively establish that the movie name associated with a year is displayed as a popup element when the mouse pointer is hovered over the year.

Figure 8 Page Showcasing Pop-Up Behavior

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>Hover Example</title>
  <atlas:ScriptManager ID="ScriptManager1" runat="server" />    
</head>
<body>
  <form id="form1" runat="server">
  <div>    
  <h2>Movie of the Year</h2>
  <div id="popup2004" width="30">2004
    <span id="movieName2004" style="visibility: hidden; 
     display: none; border: solid 1px black; 
     background: cyan;">Million Dollar Baby</span>
  </div>    
  </form>
  <script type="text/xml-script">
    <page xmlns:script="https://schemas.microsoft.com/xml-script/2005" 
     xmlns:samples="samples">
      <components>
        <control id="movieName2004">
          <behaviors>
            <popupBehavior id="popupBehavior2" 
             parentElement="popup2004" 
             positioningMode="BottomLeft" />
          </behaviors>
        </control> 
        <control id="popup2004">
          <behaviors>
            <hoverBehavior hoverElement="movieName2004">
              <hover>
                <invokeMethod target="popupBehavior2" 
                 method="show" />
              </hover>
              <unhover>
                <invokeMethod target="popupBehavior2" 
                 method="hide" />
              </unhover>
            </hoverBehavior>
          </behaviors>
        </control>
      </components>
    </page>
  </script>
</body>
</html>

The page in Figure 8 contains a DIV element to display a year, and a SPAN element to display the movie name, but declares it as being hidden. In the xml-script, a popupBehavior is associated with the name and invoked by a hoverBehavior associated with the year. The code for the popupBehavior is contained in the component and control layer of the Atlas script library. The xml-script is easy to examine compared with poring over the JavaScript that would typically be included in a page, particularly when you start factoring in code to deal with multiple browser implementations. The declarative syntax like the xml-script in Figure 8 can be produced and consumed easily by development tools. And the Atlas server controls produce xml-script to enable a richer user experience when the page executes. Much of the xml-script used in an Atlas application will never exist directly in the .aspx file, nor will most developers have to code it by hand.

The variety of behaviors that are part of the Atlas CTP serve to improve the user experience. The progress behavior can provide info that an operation is pending in the background. The click, hover, and popup behaviors allow for rich user interaction. The behaviors can easily be attached to HTML elements on the page in a declarative way using xml-script. Because the behaviors themselves are implemented in JavaScript, more complex behaviors are possible, but their use across pages can be through xml-script.

Server Controls

The server controls included in the Atlas CTP make it easy to avoid the pause that accompanies a page postback. Users can continue interacting with the page while controls update their rendering in the background. Two server controls work together to make this possible. They can be added to existing pages to achieve dramatically improved results. The ScriptManager control works to modify the client postback behavior while the UpdatePanel control manages the page lifecycle on the server to achieve the change.

The ScriptManager control must be included on all pages that will use Atlas features. It coordinates what JavaScript is sent to the client. Server controls can provide JavaScript for the client and utilize the ScriptManager control for handling it. The ScriptManager control will utilize the new IScriptComponent interface that the control implements. The ScriptManager control also provides the support for the component script libraries that are associated with xml-script elements.

Setting the EnablePartialRendering property of the ScriptManager control to true results in new behavior for postbacks from the client:

<atlas:ScriptManager EnablePartialRendering="true" runat="server" />

The postback behavior is modified to allow a request to occur without interrupting the user’s experience. The view state information required to persist control information between requests is maintained for the partial rendering requests. And the HTML for the region being refreshed or modified is updated by JavaScript interacting with the browser Document Object Model (DOM). The regions on the page that should allow for partial updates are specified in the ASP.NET page using the UpdatePanel control.

The UpdatePanel control indicates to the ScriptManager control what regions on the page should be updated independently of the rest of the page. When an action in the browser causes a postback for that region of the page, the form data is posted and the page lifecycle begins to execute on the server. Because the script is initiating the postback asynchronously behind the scenes, the page is still displayed to the user. On the server, the control state is restored from view state data posted by the client. When the render phase occurs, the ScriptManager control isolates the rendering for the UpdatePanel region whose rendering is being refreshed to send back to the browser. The view state data for the page is also gathered and accompanies the HTML as part of the response. The script in the browser then replaces the HTML corresponding to the previous rendering of the UpdatePanel contents with the new HTML.

The UpdatePanel control can contain elements for Triggers and for a ContentTemplate:

<atlas:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
        ...
    </Triggers>
<ContentTemplate>
        ...
</ContentTemplate>
</atlas:UpdatePanel>

The area inside the ContentTemplate is refreshed when the ScriptManager control manages an asynchronous postback. The Triggers element can contain ControlEventTrigger and ControlValueTrigger elements. The trigger elements allow a page developer to specify specific changes that should cause the region to update. This allows controls outside of the UpdatePanel control to cause the change, without having to be contained within the UpdatePanel control directly. It also allows for using simple declarations to control the behavior of the page and the UpdatePanel control and to dictate when new data is retrieved.

Multiple UpdatePanel controls can be placed on a single page with different triggers causing them to update independently. The contents of the UpdatePanel control can be scoped to the minimum necessary to respond to specific user input. Using the UpdatePanel control, an existing ASP.NET page can quickly be made to feel more responsive without significant change.

Web Services

Web applications are built around service-oriented architectures. Being able to access services from the browser is central to enabling interactive applications. Two distinct types of services are enabled by Atlas. The ScriptManager control will use automatically generated proxies for Web service references:

<atlas:ScriptManager EnablePartialRendering="true" runat="server">
    <Services>
        <atlas:ServiceReference GenerateProxy="true" 
         Path="~/nominees.aspx" Type="Custom"/>
    </Services>
</atlas:ScriptManager> 

Client-side components can then call the Web services directly from script. Web services are also bound to controls to enable richer behaviors. For example, AutoCompleteBehavior can be defined in xml-script to use a Web service to retrieve the relevant possibilities (see Figure 9).

Figure 9 AutoCompleteBehavior in xml-script

<script type="text/xml-script">
  <page xmlns:script="https://schemas.microsoft.com/xml-script/2005">
    <components>
      <textBox id="suggestTextBox">
        <behaviors>
          <autoComplete 
           completionList="completionList" serviceURL="suggest.asmx" 
           serviceMethod="GetSuggestions" minimumPrefixLength="1" 
           completionInterval="500" completionSetCount="15" />
        </behaviors>
      </textBox>
    </components>
  </page>
</script>

The behavior is attached to an element on the page and augments its behavior. When established in the .aspx markup, it is referred to as an extender. AutoCompleteBehavior can be associated with an element by using an AutoCompleteExtender control. Instead of writing the xml-script directly, the extender is associated with a control on the server. The control behavior is then extended by rendering the appropriate xml-script to get the client-side behavior. When calling Web services, the call and the return results are typically carried in XML. Atlas also supports serializing data from Web services in JSON, which eliminates some of the overhead inherent in XML. The JSON data can be deserialized directly into JavaScript objects in the browser. Atlas supports serializing more complex .NET managed types from the server into representative JavaScript objects on the browser. This simplifies the task of accessing Web services from the browser.

The idea of using Web services from the browser extends from custom Web services that are part of the application to ASP.NET application services. Atlas exposes the ability to use the Forms Authentication service directly from JavaScript:

Sys.Services.AuthenticationService.login(
    username, password, completionFunction);

The user doesn’t have to be redirected to a login page and then back to the original page; the HTML can then be dynamically altered when the user supplies login credentials. The Profile data available in .aspx pages is also available through a Web service call. It supports storing and retrieving profile data that is stored on the server through a JavaScript object.

The Web services that an application might use are not always located on the same host server. In fact, they are not all necessarily even in the same domain. The browser will block calls using the XmlHttpRequest to a domain other than where the page originated. There are some clever ways to circumvent this limitation using hidden IFrame objects to initiate child requests, but they are cumbersome at best. Atlas provides Web services bridging to enable this scenario. The client can initiate a Web service call destined for another domain. The call is sent to the originating Atlas application which then proxies the request to the target server for the user and serializes the results back to the client. Atlas is also capable of using the IFrame techniques to communicate directly with other domains.

Conclusion

Atlas provides a range of features for creating richer Web applications. The client script library simplifies the task of writing JavaScript and provides constructs for using an object-oriented approach to writing JavaScript. The Web services features allow easy access to remote and local services. Serialization of complex types makes it easy to utilize rich types from both client and server. Server controls take advantage of the client script library and allow existing and new applications to greatly reduce the busy-wait pauses common in Web applications today.

A new CTP build has been released about every other month with fixes, changes, and new features. Ultimately, Atlas will be integrated into the next release of the .NET Framework with design-time support in Visual Studio. In the near term, Microsoft has announced a limited license that allows you to deploy Atlas on live sites and start taking advantage of it in your Web applications. See atlas.asp.net for more information and to download the latest Atlas CTP.

Matt Gibbs is the Development Manager of the ASP.NET team at Microsoft. He has coauthored several books on ASP, Mobile Controls, and ASP.NET. He can be reached at mattgi@microsoft.com.