BUY THIS BOOK
Add to Cart

Print Book $34.99


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint this content?


Programming Atlas
Programming Atlas

By Christian Wenz
Price: $34.99 USD
£24.99 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Atlas, Ajax, and ASP.NET
This book is about Atlas, the code name for a collection of new Microsoft technologies that enable web developers, particularly ASP.NET 2.0 developers, to create web sites with pages that use Ajax more easily. Ajax-style pages provide a richer interface to users, they are more responsive, because the page can react immediately to users, and they can interact more or less immediately with the server. Atlas also includes tools for creating mashups: web applications that combine content from multiple sites, typically using the APIs provided by third-party web services. We'll be exploring all of these capabilities and more throughout the book; this chapter tells you how to get started with Atlas, paints a broad picture of the technologies involved, and explains how Atlas works from an architectural point of view.
Atlas builds on near-standard browser technologies, including Asynchronous JavaScript and XML. Ajax has itself generated quite a lot of buzz lately (see the "Preface" for some thoughts about that), since it can bring the functionality and UI of web applications closer to that of desktop applications.
The main idea behind Ajax is to enable web pages to make HTTP requests in the background, or asynchronously, without reloading an entire page (or, in ASP.NET terms, without a roundtrip or a postback). Ajax also provides the means to build a more responsive UI by drawing on the power of JavaScript, the Document Object Model (DOM), and CSS, all of which most browsers support. JavaScript, for example, is used to display the information returned by an HTTP request, without a full page refresh. Google Suggest (http://www.google.com/webhp?complete=1&hl=en) shows how an Ajax-enabled page can suggest words as a user enters text (also known as autocompletion). Another Ajax-style application is the Microsoft Virtual Earth site (http://www.virtualearth.com
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Atlas and Ajax
Atlas builds on near-standard browser technologies, including Asynchronous JavaScript and XML. Ajax has itself generated quite a lot of buzz lately (see the "Preface" for some thoughts about that), since it can bring the functionality and UI of web applications closer to that of desktop applications.
The main idea behind Ajax is to enable web pages to make HTTP requests in the background, or asynchronously, without reloading an entire page (or, in ASP.NET terms, without a roundtrip or a postback). Ajax also provides the means to build a more responsive UI by drawing on the power of JavaScript, the Document Object Model (DOM), and CSS, all of which most browsers support. JavaScript, for example, is used to display the information returned by an HTTP request, without a full page refresh. Google Suggest (http://www.google.com/webhp?complete=1&hl=en) shows how an Ajax-enabled page can suggest words as a user enters text (also known as autocompletion). Another Ajax-style application is the Microsoft Virtual Earth site (http://www.virtualearth.com), which you'll explore in Chapter 12.
One goal of Atlas is to help you create these types of Ajax-enabled applications by programming the browser (client). To work with the client side of Ajax and Atlas, you need a good knowledge of the core Ajax technologies. You need to know JavaScript and the DOM, and you need to know about the XMLHttpRequest object, which handles the requests from the client to the server. (Additional knowledge of XML and XSLT is a plus, but is not mandatory; we don't use them much in this book.)
While Chapter 2 covers the essentials of JavaScript, you'll learn about other Ajax technologies in greater detail in Chapter 3. To follow the example in this chapter (see "A First Atlas Example: Hello User") all you need is a basic understanding of the Ajax technologies, and we'll provide that as we go.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Atlas and ASP.NET
Although Atlas provides a host of benefits to the client script programmer who is creating Ajax applications, Atlas is not just about writing JavaScript and making asynchronous calls to the server. Since Atlas was created by the ASP.NET team, it's no surprise that a prominent Atlas feature is a server framework that is integrated with (and requires) ASP.NET 2.0.
As with ASP.NET itself, one of the goals of Atlas is to deliver functionality—in this case, the benefits of Ajax—without requiring mastery of the technologies that make it work. Atlas can manage Ajax functionality for you in much the way that ASP.NET manages HTTP functionality such as postbacks, state management, and the client script required to make ASP.NET all "just work."
In addition, on the server side, Atlas works as part of ASP.NET, and can take advantage of ASP.NET features. Atlas controls can interact with ASP.NET controls and components and with the page life cycle. You can link Atlas to ASP.NET 2.0 features like sessions and profiles, so you can take advantage of these types of capabilities on the client. Also, with Atlas and ASP.NET, you can reach beyond the page to special web services, and to web services and third-party APIs that are outside the domain and can't be directly accessed from the client.
Key elements of the Atlas server framework include:
Atlas server controls
Provide server-based controls that resemble ASP.NET 2.0 server controls, but work with the Atlas client framework to deliver their functionality. Two controls in particular are fundamental to Atlas applications: ScriptManager, which will be discussed later in this chapter (see "The ScriptManager Control"), and UpdatePanel, which is discussed in Chapter 1.
Atlas ASP.NET services
Provide certain ASP.NET 2.0 services that are directly available to Atlas client scripts, including profiles, personalization, membership, and culture-specific services. You can expect the number of ASP.NET services available to Atlas applications to grow with future releases of Atlas.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Atlas and Future Development
While the burst of creativity that Ajax has inspired among web developers seems to have energized the work of the ASP.NET team and stimulated a host of innovations, from the client framework to xml-script to the UpdatePanel control, Microsoft has not yet indicated when or how Atlas might be packaged for final release. Currently, the ASP.NET team is releasing periodic preview versions of Atlas and interacting with the community, and that's the technology that is described in this book. For the March preview release, the ASP.NET team included a go-live license, which is permission to release applications that contain Atlas bits. The go-live license is not a guarantee that Atlas is frozen, or even that it won't change, but it does mean that Microsoft is OK with your creating live applications with the technologies you will read about here.
The goal of this book is to give you an insider's view of how Atlas and ASP.NET integrate with Ajax and to provide a through grounding in Microsoft's overall approach to enriching web UI. Even though Atlas will undoubtedly change by the time it is officially released, the concepts and the overall Atlas technology that you read about here will almost certainly remain essentially the same. What you learn about Atlas in this book will serve you well even if details change, as they likely will.
Ultimately, Atlas will take its rightful place as a key component of the next release of ASP.NET and will be fully supported with designers, IntelliSense, and debugging tools in a future release of Visual Studio.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Atlas Prerequisites and Installation
The best way to begin to understand the power of Atlas is to use it. All you need to develop Atlas applications is a JavaScript-enabled browser on the client and an ASP.NET 2.0-enabled web server. A text editor is sufficient to create Atlas applications. However, especially when applications get more complex, an IDE with additional features like IntelliSense, code completion, project management, debugging, and WYSIWYG functionality can be real 5imesavers. In the world of ASP.NET 2.0, the most widely-used editor comes from Microsoft in the form of Visual Studio 2005.
The good news is that, although the full versions of Visual Studio 2005 are usually your best bet, the web-centric Express edition of Visual Studio 2005—Microsoft Visual Web Developer 2005 Express Edition—also fully supports Atlas.
For the sake of simplicity, we will refer to Visual Web Developer as VWD throughout the rest of this book. By VWD we mean both the Express edition and the full version of Visual Studio 2005. The web development component of VS 2005 is also called Visual Web Developer (you can see it during installation of Visual Studio), so VWD is the most generic term for creating ASP.NET 2.0 applications with a Microsoft IDE.
If you do not already have an IDE, install either Visual Studio 2005 or Visual Web Developer Express Edition. For the latter, go to http://msdn.microsoft.com/vstudio/express/vwd/download, where you will find a web installer that not only downloads and installs VWD (see Figure 1-1 for the installer), but also takes care of installing the .NET Framework 2.0, if it is not already installed on your system. Follow the instructions at the site.
If for some reason the web installer does not work on your machine (e.g., it cannot connect to the outside from within a corporate environment, or your Internet connection is slow), you can find ISO and IMG images of a CD containing Visual Web Developer and all prerequisites (http://msdn.microsoft.com/vstudio/express/support/install)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Atlas Structure and Architecture
Now it is time to use Atlas. Create a new ASP.NET web site using the Atlas template. If you have a look at Solution Explorer, you will see a regular ASP.NET web site. However, there are several different file types in the web site, as shown in Figure 1-9:
Figure 1-9: The web site project the Atlas template creates
  • A server-side assembly (Microsoft.Web.Atlas.dll) in the Bin directory.
  • Several client-side JavaScript files. They will also be created by the server-side assembly, but via Start → (All) Programs → Microsoft ASP.NET Atlas → Atlas → Atlas → Atlas Assembly and Script Library, you can have a look at the JavaScript code Atlas will be using.
  • A Web.config file preconfigured with the settings required for Atlas to work.
Atlas consists of both a server and a client part. It is possible to use only the server components of Atlas, or to use only the client components of Atlas. There is one exception: every Atlas application will need the ScriptManager server control, which will be covered later in this chapter. Usually, you will want to use both the server and client components of Atlas, of course.
The roles these directories and files play in an Atlas project will become clearer when we take a closer look at how Ajax applications that use XMLHttpRequest really work.
Figure 1-10 shows the basic structure of Atlas. Whereas standard web pages consist of only two parts—one request and one response—Ajax-enabled web pages can continuously exchange data with the server. Atlas helps on both ends of the wire. Client script libraries in the ScriptLibrary directory facilitate communication between browser and web server and make client coding easier. The server assembly Microsoft.Web.Atlas.dll takes care of accepting and handling
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A First Atlas Example: Hello User
To test whether your setup of Atlas has been successful and to see the framework in action, let's end this chapter by creating a tiny sample application. The sample page accepts a username, sends it to the web server (in the background, using XMLHttpRequest), and receives it back with some extra text. The new version of the name is then shown to the user. This sample just shows you how easy it can be to set up an application using the features of Atlas. A more detailed description of the inner workings and the usage of Atlas can be found in the chapters following; however, the description of this example is not as exhaustive as the information about the other samples in this book.
After creating a new web site using the Atlas template, create a new web service (using the web service file template) in the root directory of the web site and call it WebService.asmx. In the web service .asmx file, implement a simple web method that accepts one string parameter, by pasting the code shown in Example 1-1 into the file.
Example 1-1. The web service
WebService.asmx

<%@ WebService Language="C#" Class="WebService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://hauser-wenz.de/atlas/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService  : System.Web.Services.WebService {
    [WebMethod]
    public string sayHello(string name) {
    return "Hello " + name + ", says the server!";
    }
}
Now call this web service in your web browser, but append /js to the URL. As you will see from the resulting data, this URL actually returns JavaScript code. In fact, this code implements a kind of JavaScript proxy, something that will be covered in more detail in Chapter 10. Most important, the code produces a variable named WebService that provides a reference to the web service. Figure 1-11 shows the JavaScript that displays.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The ScriptManager Control
After this first working example, here is some more background information about how this example worked, and how the other Atlas examples throughout the book work.
The central element of an Atlas-powered ASP.NET page is the ScriptManager, <atlas:ScriptManager>. This control takes care of loading the required JavaScript libraries of Atlas, depending on which browser is used.
If you look at the resulting source code in the browser, you will see that Atlas changed very little—only the <atlas:ScriptManager> element has been replaced with this code (the undecipherable data in the URL will be a bit different on your system):
<script
src="/Atlas/WebResource.axd?d=EiZ5MhryFS7wRPgWKwT3L2TYwCkaaO5mtAO5KyVbAcNmREm0baC0S
_edhhqj_Y6ZuRY56z97Nu5lD2Fw5ITB3mHpybsGTsINHdsdQ_BVGi7cUBG1EWW_cWGx-I8vZeWK0
&amp;t=632781806040000000" type="text/javascript"></script>
<script
src="/Atlas/WebResource.axd?d=EiZ5MhryFS7wRPgWKwT3L2TYwCkaaO5mtAO5KyVbAcNmREm0baC0S
_edhhqj_Y6ZuRY56z97Nu5lD2Fw5ITB3g4TEhGZLS-_Daibixpp8tw1&amp;t=632781806040000000"
type="text/javascript"></script>
<script src="atlasglob.axd" type="text/javascript"></script>
The first <script> tag is used only in non-IE browsers to add a compatibility layer; the second one loads the Atlas core library. The third <script> element contains some client-specific culture information.
When building the web application in debug mode, the JavaScript code created by WebResource.axd is nicely formatted and some errors are caught. This is convenient for developing purposes, however not required when the web site is deployed.
This ScriptManager element must be present on all pages that use Atlas features. It can also be used to load additional JavaScript libraries, either those that come with Atlas, or your own scripts:
<atlas:ScriptManager ID="ScriptManager1" runat="server">
  <Scripts>
    <atlas:ScriptReference Path="MyScript.js" />
  </Scripts>
</atlas:ScriptManager>
If you are using ASP.NET 2.0 master pages and most of your pages use the Atlas framework, you may consider putting the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter introduced Atlas, explained its relationship to Ajax and ASP.NET 2.0, and guided you through its installation and the installation of other software you need for this book, including the AdventureWorks database. You also created your first working Atlas example and learned about the ScriptManager control, one of two key server controls that ship with Atlas. In the next chapter, you'll have a look at the JavaScript you need to work with Atlas.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
For Further Reading
http://atlas.asp.net/docs/Server/Microsoft.Web.UI/ScriptManager/Declarative Syntax.aspx
Documentation on the ScriptManager control
http://msdn.microsoft.com/msdnmag/issues/06/07/AtlasAtLast/default.aspx
A quick overview of Atlas by an ASP.NET team development manager
http://weblogs.asp.net/atlas
The blog for official Atlas announcements
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: JavaScript
The ability to embed scripts in web pages is key to making them more interactive. Scripts can be used to respond to events, such as the loading of a web page or the click of a button by a user, and are the means for dealing with data sent to and from the server via HTTP requests and responses.
For most web developers, JavaScript is the script language of choice, since it is the only language supported by all major browsers. Although an Ajax framework like Atlas makes it easy to use the technology without having to know too much about its details, a sound knowledge of JavaScript is, in my view, absolutely mandatory to make the most of Atlas (but Atlas can even help developers not familiar with JavaScript at all, thanks to the framework approach). Since Atlas is a framework, without the ability to use JavaScript, you are limited to the functionality exposed by the Atlas controls. Some client scenarios actually require more work in Atlas than when using custom JavaScript. Therefore, the best strategy for a modern Ajax-enabled web site is to use the best of both worlds: the Atlas framework extended with your JavaScript code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The JavaScript Language
The JavaScript language is loosely based on C, so programmers coming from a C/C++, C#, or Java background can usually learn the syntax in a short amount of time. There are some aspects of JavaScript that make it quite accessible. It is not strongly typed, for example—the programmer doesn't assign data types; instead, JavaScript assigns data types at runtime. In addition, JavaScript supports object-oriented programming to some extent, but does not rely on it, unlike languages such as C# or Java.
JavaScript can be embedded in web pages in three ways: in scripts, in event handlers, and in URLs. The syntax used in each case is different.
Embedding a script in a web page
Scripts are typically embedded in an HTML page using the HTML <script> element. You can also use the src attribute of the <script> element to point to the URL of an external script file to load.
The major browsers—including Internet Explorer, Firefox, and Safari/Konqueror—all assume that JavaScript is the default language whenever they encounter a <script> tag on a web page. However, to satisfy W3C standards and the needs of less-used or older browsers (including outdated versions), it's always best to specify the language using the following syntax:
<script language="JavaScript" type="text/javascript">
  ...
</script>
Using a script to handle an event
JavaScript code can be used as the value of an event handler attribute of an HTML tag, e.g., <input type="button" onclick="doSomething( );" />.
Using JavaScript in a URL
JavaScript can appear in a URL that uses the special javascript: pseudoprotocol, making it, for instance, easy to use JavaScript in hyperlinks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented Programming (OOP)
JavaScript is a so-called object-based language, but not an object-oriented one. There are aspects of JavaScript that are OOP-like, but support for 33onventional OOP techniques is limited. For instance, visibility of class members (public, private, protected, etc.) can be implemented only in a limited way. Nevertheless, it is possible to create classes in JavaScript and even to provide rudimentary support for class inheritance.
A class in JavaScript is implemented by creating a function. The code within this function is the class constructor and getter and setter methods for the class properties, which are also defined in the constructor. All class properties and methods are defined within the class code. The this keyword provides access to the properties of the current class, making it possible to set properties and define methods.
Example 2-9 shows a simple class that implements a book. Note that access to the class's properties is via explicit getter and setter methods instead of the more familiar dot notation (such as book.title).
Example 2-9. Using JavaScript's OOP features
JavaScript-class.htm

<!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>
  <title>JavaScript</title>
</head>
<body>
  <script language="JavaScript" type="text/javascript">
  function Book(isbn, author, title) {
    var _isbn = isbn;
    var _author = author;
    var _title = title;

    this.get_isbn = function() {
      return _isbn;
    }
    this.set_isbn = function(value) {
      _isbn = value;
    }
    this.get_author = function() {
      return _author;
    }
    this.set_author = function(value) {
      _author = value;
    }
    this.get_title = function() {
      return _title;
    }
    this.set_title = function(value) {
      _title = value;
    }

    
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Page Elements
Although recent browsers support the W3C DOM as a means of accessing elements within the current HTML page (see the section "DOM Methods" later in this chapter for more information), there are easier ways to work with data on a page. Two of them are covered in this section.
JavaScript's document object grants access to all elements on the current page. document is a representation of the DOM that is accessible to JavaScript. To make the access as convenient as possible, there are several subproperties that allow direct access to special page elements. Here are some examples, listed alphabetically:
document.embeds
An array containing all embedded media (via <embed>) on the current page
document.forms
An array containing all <form> elements on the page
document.frames
An array containing all frames on the current page
document.images
An array containing all images on the current page
document.links
An array containing all hyperlinks on the current page
The most commonly used property is document.forms, which lets you access all <form> elements on the current page, such as text boxes and buttons. Admittedly, there is usually only a single form on a page. However, the document.forms[0] property (the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
DOM Methods
In most scenarios that involve interacting with elements on an HTML page, using the special JavaScript document.forms object and its friends or using document.getElementById() with the innerHTML property suffices. Yet there are some cases where access to the DOM itself is required. Appendix B contains a complete list of supported methods for accessing the DOM. Here are some of the most important ones:
getElementsByTagName( name )
Returns an array with all elements of the given element name in the page
createElement( name )
Creates a new DOM node with the given element name
createAttribute( name )
Creates a new attribute for the node with the given attribute name
createTextNode( text )
Creates a new text DOM node (text within an element) with the given text
appendChild( node )
Appends the node as a child of the current element
Example 2-13 shows how to use some of these methods to recreate the preceding example, but this time by dynamically creating a new <span> element and a text node. In this example, the appendChild() method comes into play: first, the text child is added to the <span> element, and then the <span> element is added to the paragraph.
Example 2-13. Using DOM with JavaScript
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, you learned the essentials of what JavaScript offers for client-side programming. In the following chapters, you will be introduced to additional JavaScript features. However, this chapter has introduced you to all the fundamental concepts that are required to understand the rest of the book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
For Further Reading
http://www.nikhilk.net/Project.ScriptSharp.aspx
Script# is a very interesting side project by Nikhil Kothari that uses C# for client scripting; a compiler generates JavaScript instead of MSIL
JavaScript: The Definitive Guide by David Flanagan (O'Reilly)
A complete programmer's guide and reference manual for the JavaScript language
JavaScript Pocket Reference by David Flanagan (O'Reilly)
A concise but thorough overview of the language
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Ajax
Ajax is the set of technologies on which Atlas is built. And although Atlas does its best to hide the technical details of Ajax, to understand what is possible with Atlas and to create advanced applications that extend the framework for your own needs, you must have a detailed knowledge of Ajax.
The term "Ajax" was coined by Jesse James Garrett in early 2005 in his essay "A New Approach to Web Applications" (http://www.adaptivepath.com/publications/essays/archives/000385.php). However, only the term is new, not the technology itself. Although XML can be part of an Ajax application (but doesn't have to be!), and some CSS may also be in the mix, the foundation of any Ajax-powered application is JavaScript.
In this chapter, we'll cover the three most important JavaScript technologies used to deliver Ajax behaviors to web apps. They are:
XMLHttpRequest
The JavaScript object that takes care of making (asynchronous) HTTP calls
XMLDocument
The JavaScript object used to parse and access XML data
JavaScript Object Notation (JSON)
An alternate data format that can be used instead of XML to exchange data between client and server without the burden of XML parsing
In this chapter, you'll create web pages that involve both client script in the browser and web server backend processing.s Therefore, the examples in this chapter and the rest of the book will involve working with ASP.NET and with .aspx pages.
The foundation of Ajax is the XMLHttpRequest object, which enables you to make HTTP requests (and get responses), without performing a full page postback and refresh.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The XMLHttpRequest Object
The foundation of Ajax is the XMLHttpRequest object, which enables you to make HTTP requests (and get responses), without performing a full page postback and refresh.
A significant portion of the web browser market does support XMLHttpRequest and therefore is Ajax-compatible. According to a study conducted by Net Applications (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The XMLDocument Object
The responseXML property of the XMLHttpRequest object expects the return value of the remote call to be in the form of an XMLDocument object. This requires the server code to return well-formed XML data so that the client script can parse it. However, it is easy to access this XML data; you have full DOM support for doing so.
JavaScript supports a set of DOM features to access specific nodes in the XML file or to navigate the tree structure of the XML document. Appendix B contains a complete list of methods and properties of the XMLDocument object. The following example shows how to use quite a lot of them.
Imagine that the return data of the server request is the following XML data:
<book title="Programming Atlas" author="Christian Wenz">
  <chapters>
    <chapter number="1" title="Introduction" />
    <chapter number="2" title="JavaScript" />
    <chapter number="3" title="Ajax" />
  </chapters>
</book>
It is important that when XML is returned, the Content-type HTTP header of the response is explicitly set to "text/xml". If this header is omitted, some browsers (most notably, Mozilla and derivatives) refuse to parse the return data, and the responseXML object is set to null. The following C# code in an ASP.NET page shows how to set the content type appropriately:
void Page_Load()
{
   if (Request.QueryString["sendData"] != null &&
       Request.QueryString["sendData"] == "ok")
   {
    string xml = "<book title=\"Programming Atlas\"
    author=\"Christian Wenz\"><chapters><chapter number=\"1\" title=\"Introduction\"
/><chapter number=\"2\" title=\"JavaScript\" /><chapter number=\"3\" title=\"Ajax\"
/></chapters></book>";
    Response.ContentType = "text/xml";    Response.Write(xml);
    Response.End();
  }
}
In the client JavaScript for this example, some of the XML data is extracted and then printed out, such as the attributes of the root node and the information about the various chapters of the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JSON
A third major technology often used for Ajax applications is JavaScript Object Notation (JSON, http://www.json.org). With JSON, JavaScript objects or data can be persisted (serialized) in a short and easily understandable way, without requiring a lot of JavaScript code to either write or read the data. JSON makes use of an often-overlooked feature of JavaScript, or to be exact of the ECMAScript language specification, also known as ECMA-262.
JSON is used internally by current versions of Atlas and generally can be used to exchange complex data with a server. This allows JavaScript to understand it, also the sometimes cumbersome XML parsing with JavaScript can be avoided. The following code uses JSON to define a book object.
{"book": {
  "title": "Programming Atlas",
  "author": "Christian Wenz",
  "chapters": {
    "chapter": [
      {"number": "1", "title": "Introduction"},
      {"number": "2", "title": "JavaScript"},
      {"number": "3", "title": "Ajax"}
    ]
  }
}}
This is the same data that you saw defined using XML in Chapter 2. The object with the book property contains title, author, and chapters properties. The chapters property contains several chapter subelements, each with a number and a title property. This can be best visualized when looking at it as XML data. You will remember it as the exact same XML that was used in the previous section, "The XMLDocument Object," as shown in this code:
<book title="Programming Atlas" author="Christian Wenz">
  <chapters>
    <chapter number="1" title="Introduction" />
    <chapter number="2" title="JavaScript" />
    <chapter number="3" title="Ajax" />
  </chapters>
</book>
The main benefit of JSON is that JavaScript can evaluate the JSON notation without your having to write any code to parse it, as demonstrated in Example 3-3.
Example 3-3. Using JSON to easily create objects
json.html

<!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>
  <title>JSON</title>
</head>
<body>

  <script language="JavaScript" type="text/javascript">
    var json = '{"book": { "title": "Programming Atlas", "author": "Christian Wenz",
"chapters": {"chapter": [ {"number": "1", "title": "Introduction"}, {"number": "2",
"title": "JavaScript"}, {"number": "3", "title": "Ajax"} ]} }}';
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
This chapter covered three of the technologies that make Ajax work. Of special importance is the XMLHttpRequest object. You also learned how to process complex data returned by the server using JavaScript and either XML or JSON.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
For Further Reading
http://www.adaptivepath.com/publications/essays/archives/000385.php
The article that started it all
http://www.json.org
Unofficial homepage for JSON
Ajax Hacks by Bruce W. Perry (O'Reilly)
Tips and tricks for Ajax apps
Head Rush Ajax by Brett McLaughlin, Elisabeth Freeman (O'Reilly)
A fast-paced introduction to Ajax
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Controls
In Chapters 2 and 3, you learned the basics of JavaScript and key Ajax technologies, especially asynchronous calls, that support it. As you saw, Ajax itself is no big deal. The effects that Atlas lets you create are possible without Atlas. Everything you do with Atlas creates HTML, CSS, and JavaScript on the client side, which is also possible with any other server-side technology.
The real value of Atlas is that it greatly facilitates development of Ajax-powered applications. Although you can create applications without it, Atlas can make their implementation go faster. Also, with Atlas, your need to master browser-agnostic JavaScript is not a top priority, though, as is always the case, having such skills will give you a much better understanding of how Atlas works its magic.
This chapter covers client-side controls that ship with Atlas and mimic the behavior of ASP.NET web controls. This not only allows for consistent development on both the server and the client, but also supports convenient features like data binding, which you'll explore in Chapter 5.
Atlas implements its client controls in the Sys.UI namespace. Sys.UI is the client-side equivalent of the similarly named and well-known Web.UI namespace in ASP.NET.
In older Atlas releases, the client-side namespace was named Web.UI, as well.
Sys.UI contains a large number of Atlas HTML controls and web controls. The functionality of Atlas controls is similar but not identical to ASP.NET server controls. Atlas controls provide a consistent, browser-independent model that enables JavaScript code to access and change client controls properties, something that with non-Atlas controls would require quite a bit of JavaScript knowledge as well as some workarounds for browser inconsistencies.
Table 4-1 lists controls provided by Atlas. The table lists the HTML elements that the Atlas control works with and the equivalent DOM object or method that you would use in JavaScript.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing Atlas Client Controls
Atlas implements its client controls in the Sys.UI namespace. Sys.UI is the client-side equivalent of the similarly named and well-known Web.UI namespace in ASP.NET.
In older Atlas releases, the client-side namespace was named Web.UI, as well.
Sys.UI contains a large number of Atlas HTML controls and web controls. The functionality of Atlas controls is similar but not identical to ASP.NET server controls. Atlas controls provide a consistent, browser-independent model that enables JavaScript code to access and change client controls properties, something that with non-Atlas controls would require quite a bit of JavaScript knowledge as well as some workarounds for browser inconsistencies.
Table 4-1 lists controls provided by Atlas. The table lists the HTML elements that the Atlas control works with and the equivalent DOM object or method that you would use in JavaScript.
Table 4-1: Atlas controls
Atlas control
Description
HTML element
JavaScript equivalent
Sys.UI.Window
Implements JavaScript pop-up windows
N/A
window.alert(), window.confirm(), window.prompt()
Sys.UI.Label
Implements a span or label element
<span>, <label>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Atlas Controls
There are two concepts the Atlas framework uses with the controls in Sys.UI. Some of these controls provide JavaScript access to standard JavaScript methods. The others provide JavaScript access to HTML elements on the current page. Both ways are demonstrated in this section.
One example of the first method is implemented by Sys.UI.Window. This implements a client-side message box. The JavaScript language supports three types of modal message boxes:
window.alert()
Message box with an OK button
window.confirm()
Message box with OK/Cancel or Yes/No buttons
window.prompt()
Message box with an input field and an OK button
Inside the Atlas Sys.UI.Window class, the functionality for calling window.alert() or window.confirm() is encapsulated in the messageBox() method. The default behavior is to present a window.alert() box. This corresponds to the message box style Sys.UI.MessageBoxStyle.OK. The alternative is to use the Sys.UI.MessageBoxStyle.OKCancel style, which uses window.confirm() under the covers.
But what about the window.prompt() window? For consistency with Visual Basic, this is implemented via the inputBox() method instead of the messageBox() method.
The following example implements all three variants of client modal window. Three client-side buttons are in place for calling the Atlas functionality:
<input type="button" value="MessageBoxOK" onclick="MessageBoxOKClick();" />
<input type="button" value="MessageBoxOKCancel" onclick="MessageBoxOKCancelClick();"
/>
<input type="button" value="InputBox" onclick="InputBoxClick();" />
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Handling Control Events
Atlas provides its client controls with an event handling mechanism. The mechanism works a bit differently than you might expect, but it's still intuitive.
The first and most important step is to call the initialize() method of the element whose events you want to handle. This enables all the mechanisms that are internally used to capture events. Then setting up events is a two-step process.
  1. Write an event handling function that is called when the event occurs.
  2. Link the event handling function to the element using < element >.< event name >.add(< method name >).