Σχόλια 0

Το κείμενο του εγγράφου

Overview of AJAXAJAX has definitely been the hot buzzword in the Web application world for the last few years. AJAXis an acronym for Asynchronous JavaScript and XML and, in Web application development, it signi-fies the capability to build applications that make use of theXMLHttpRequestobject.The creation and inclusion of theXMLHttpRequestobject in JavaScript and the fact that most upper-level browsers support it led to the creation of the AJAX model. AJAX applications, although theyhave been around for a few years, gained popularity after Google released a number of notable,AJAX-enabled applications such as Google Maps and Google Suggest. These applications demon-strated to the world the real value of AJAX, and every developer that saw these applications in actionimmediately went out to do research in how these applications were built.AJAX is now an out-of-the-box feature of ASP.NET 3.5, and every ASP.NET application that youbuild is AJAX-enabled by default. This means that you don’t have to create a separate AJAXproject for your Web applications as the standard projects in Visual Studio for Web applica-tion development will already be enabled to use ASP.NET AJAX. This is one of the main newfeatures of ASP.NET 3.5 because of the power that AJAX brings to your applications. The AJAXcapability has become so popular since the release of ASP.NET 3.5 that most ASP.NET applica-tions built today make use of at least some features provided by this technology.Why AJAX Applications Are NeededWeb applications were in a rather stagnant state for many years. The first “Web” applicationswere nothing more than text and some images, all represented in basic HTML tags. However, thiswasn’t what people wanted; they wanted more

—

more interactivity, a more integrated workflow,more responsiveness, and an overall richer experience.When building applications, even today, you have to make some specific decisions that really endup dictating the capabilities and reach of your application. Probably one of the more importantdecisions is the choice of building the application as a “thin” client or a “thick” client.192171c01.indd 112/15/08 1:44:51 PMCOPYRIGHTED MATERIAL2Chapter 1: Overview of AJAXA thick client application is a term used for applications that are either MFC (in the C++world) orWindows Forms applications. These types of applications also provide the container along with all thecontainer contents and workflows. A thick client application is typically a compiled executable that endusers can run in the confines of their own environment, usually without any dependencies elsewhere(for example, from an upstream server).A thin client application is the term generally used for Web applications. These types of applicationsare typically viewed in a browser, and your application can provide end user workflows as long as it iscontained within this well-known container. A thin client application is one whose processing and ren-dering are controlled at a single point (the upstream server), and the results of the view are sent downas HTML to a browser to be viewed by the client.Typically, a Web application is something that requires the end user to have Internet access in order towork with the application. On the other hand, a thick client application was once generally considered aself-contained application that worked entirely locally on the client’s machine. However, in the last fewyears, this perception has changed as thick clients have evolved into what are termed “smart clients”and now make use of the Internet to display data and to provide workflows.Web applications have historically been less rich and responsive than desktop applications. End usersdon’t necessarily understand the details of how an application works, but they know that interactingwith a Web site in the browser is distinctly different from using an application installed locally. Webapplications are accessible from just about any browser, just about anywhere, but what these browserspresent is limited by what you can do with markup and script code running in the browser.There are definitely pros and cons in working with either type of application. The thick client applica-tion style is touted as more fluid and more responsive to an end user’s actions. Thick client applicationsrequire that users perform an installation on their machine but let developers leverage the advancedmouse and graphics capabilities of the operating system that would be extremely difficult to implementin a Web browser, and also take advantage of the user’s machine for tasks such as offline storage.Conversely, the main complaint about Web applications for many years has been that every action by anend user typically takes numerous seconds and results in a jerky page refresh.Conversely, Web applications can be updated just by changing what is running on the server, and site visi-tors get the latest version of that application instantaneously. However, it is much more difficult to update adesktop application, because you would have to get users to perform yet another installation or else ensurethat the application has been coded to include a clever system for doing updates automatically.Web applications are said to use a zero-deployment model, but desktop applications use a heavydeployment and configuration model. The choice is often characterized as a tradeoff between rich andreach: Desktop applications generally offer a richer user experience than what could be offered in thebrowser, but with a Web application you are able to reach users anywhere on any OS with almost noextra effort. Furthermore, many companies have restrictive policies in place regarding what softwarecan be installed on employees’ machines, and they often don’t allow employees to have administrativeaccess that is required to install new applications, so Web applications are the only viable option inmany situations.AJAX is the first real leap of a technology to bridge this historic wall between thick and thin. AJAX,though still working through the browser, focuses on bringing richness to Web applications by allowingfor extremely interactive workflows that usually were only found in the thick client camp.92171c01.indd 212/15/08 1:44:52 PM3Chapter 1: Overview of AJAXBringing Richness to Web ApplicationsYears ago, having a Web presence was a distinguishing factor for companies. That is no longer the case.Now just having a Web presence is no longer enough. Companies are distinguishing themselves furtherthrough Web applications that react intuitively to customer actions and anticipate user input. This bookshows you how ASP.NET AJAX addresses specific Web development challenges and paves the way fortaking your Web site to another level of user experience.The fundamental set of technologies used in the AJAX model that enable the next generation of Webapplications is not entirely new. You will find that many people point to Google, Flickr, and several otherservices as prime examples of leveraging AJAX and its underlying technologies in unique ways. Theapplications have some unique features, but in reality, the underlying technologies have been aroundand in use for nearly a decade. Look at how Microsoft Exchange Server provided rich access to e-mailfrom a Web browser in the Outlook Web Access application, and the concept of ubiquitous access from abrowser while leveraging a common set of browser features for a rich user experience has been aroundfor years. In this case, users get a remarkably full-featured application with no local installation and areable to access e-mail from virtually any machine.While the AJAX acronym is nice, it doesn’t do much to explain what is actually happening. Instead ofbuilding a Web application to be just a series of page views and postbacks, developers are using JavaScriptto communicate asynchronously with the Web server and update parts of the page dynamically. Thismeans that the Web page can dynamically adapt its appearance as the user interacts with it, and it caneven post or fetch data to or from the Web server in the background. Gone are the days of the ugly post-back, which clears the user’s screen and breaks his concentration! Instead, you need to post back nowonly if you want to change to a different Web page.Even that rule can be bent. Some applications are pushing this boundary and completely changing theuser’s view, just as though they navigated to a new page, but they do so through an asynchronous postand by changing the page content without actually navigating to a new URL.The AJAX acronym refers to XML as the data format being exchanged between client and server, but inreality, applications are being built that retrieve simple pieces of text, XML, and JSON (JavaScript ObjectNotation) (which is discussed in more detail in Chapter 4). Part of the AJAX appeal is not even coveredby the acronym alone: In addition, to communicating with the server without blocking, developers areleveraging Dynamic HTML (DHTML) and Cascading Style Sheets (CSS) to create truly amazing userinterfaces. JavaScript code running on the client communicates asynchronously with the server and thenuses DHTML to dynamically modify the page, which supports rich animations, transitions, and updatesto the content while the user continues interacting with the page. In many cases, end users will some-times forget they are using a Web application!Just remember that AJAX is not a single holistic entity but instead is a novel and creative way of usinga combination of technologies such as theXMLHttpRequestobject, HTML, XHTML, CSS, DOM, XML,JSON, XSLT, and JavaScript. You might be thinking of the difficulties of piecing this all together to getthe Web applications you want to build. Be ready to be wowed, however, as the focus of this book is onshowing you how to use the built-in technologies provided by ASP.NET 3.5 to give you this power in aneasy to use manner.92171c01.indd 312/15/08 1:44:52 PM4Chapter 1: Overview of AJAXWho Benefits from AJAX?AJAX offers benefits to both end users and developers. For end users, it reduces the “rich or reach” conflict;for developers, it helps in overcoming the constraints raised by HTTP such as the dreaded page postback.Why End Users Want AJAX ApplicationsUsers tend to view desktop applications as a commitment. They install a program, usually from a diskpulled from a costly shrink-wrapped box. The program consumes hard disk space as well as a positionin the program menu. The user may need to update the program periodically or perform an upgradelater on to get new features. If the program is proactive about updating itself, the user is confrontedregularly with dialogs about accepting patches or downloads. In exchange for this investment of time,money, and energy, the user is repaid with an application that is able to leverage the operating systemand machine resources. It is a rich application. It has local storage capabilities, offers quick responsetimes, and can present a compelling and intuitive graphical user interface.More and more applications are becoming accessible from the Web browser, where the full resourcesof the hardware and OS are not available, but the user commitment of a desktop application is notrequired. Over the years, interacting with a Web application has meant a predictable pattern for users.They click a link in the page, and the browser flashes while the user waits until the page is repainted(the dreaded page postback). This cycle is repeated over and over. The user looks at what is presentedon the page, interacts with it, and clicks somewhere on the page. The browser then produces an audibleclick for feedback and begins to postback to the server. The screen of the Web browser flashes blankand some icon spins or flashes while the user waits for a new version of the page to be returned fromthe server. Many times, the new version of the page is almost exactly the same as the previous version,with only part of the page being updated. And then the cycle begins all over again. This has a sluggishfeeling even when the user has a high-speed network connection and is simply unacceptable for sometypes of applications.The AJAX set of technologies has changed what users expect from Web applications. JavaScript coderunning in the browser works to exchange data with the Web server asynchronously. There is no clicksound and the browser does not flash. The request to the server is non-blocking, which means the useris able to continue viewing the page and interacting with it. The script gets the updated data from theserver and modifies the page dynamically, using the DHTML coding methodology. The user is ableto continue looking at the page while parts of it are updated in the background. AJAX is used to pro-vide a more responsive experience, making Web applications behave more like desktop installations.JavaScript is used to provide a richer experience with support for drag-and-drop, modal dialogs, andseemingly instantaneous updates to various parts of the page based on user inputs.A big part of successfully leveraging AJAX technologies is in the perceived performance increase. Usersappreciate Web applications that anticipate their actions. If you also use JavaScript code in the backgroundto pre-fetch images and data that may be needed, users can get a speedy response without the usual pausethat accompanies their actions. Nobody wants to wait for data exchanges between client and server; studieshave shown that a time lag between user input and subsequent UI changes can significantly reduce theirproductivity and give them the frustrating feeling that they are fighting the application. Users want Webapplications to behave like desktop installations but without the overhead associated with an installation.As more applications employ smart caching, anticipate user actions, and provide richer UIs, the differencebetween Web and desktop applications is definitely becoming blurred. Expectations for Web applicationsare rising. The end user has now seen that it is possible to avoid the commitment of installing a desktopapplication and still have a rich and responsive experience.92171c01.indd 412/15/08 1:44:52 PM5Chapter 1: Overview of AJAXWhy Developers Want AJAXOften, the first question to arise when starting a new development project is what type of applicationit will be. Should it be a desktop application or a Web application? This is a key decision because it hashistorically dictated a lot about the nature of the application and the development problem space. Manydevelopers are now choosing to build Web applications by default unless something about the applica-tion dictates that it must be a desktop install. If it must run offline or if it requires a user interface thatis too complex to achieve in HTML, targeting the Web browser may be ruled out, and developers areforced to write a standalone application.Developers have a difficult job writing modern Web applications due to the inherent World Wide Webfunctionality constraints imposed by the use of the Hypertext Transfer Protocol (HTTP) and the waythat browsers use it. HTTP is a stateless protocol. The Web browser requests a page, possibly carryingsome sort of state (a querystring or form input parameters), and the Web server processes the requestand sends a response that includes HTML-rendered content. The Web server can only react to the infor-mation supplied in the current request and does not know any additional information from the requestitself, such as any details about the path the user took to get to the current view.When the response is rendered, the connection may be broken and the server will not have any infor-mation to preserve for the next request. From the server’s perspective, it is simply listening for requeststo come in from any browser anywhere and then reacting. The browser issues a request to the pageand receives an HTML page in response. It uses the HTML it receives to render the user interface. Theuser interacts with the page, and, in response, the browser clears the screen and submits a new requestto the server, carrying some information about user input or actions. Again, a complete HTML page isreturned. The browser then presents the new version of HTML. Fundamentally, the HTTP protocol isstateless. The server gets a request and responds to it. The request carries limited information about theongoing conversation that is happening between client and server. This can definitely be a problem.AJAX makes this much better. AJAX breaks this pattern by updating portions of the page separately, viapartial page rendering. Figure 1-1 shows a typical non-AJAX series of browser and server interactions(requests and responses). Each request results in full-page rendering. In response, the browser updatesthe user’s entire view with the HTML that is returned.The sequence presented here in Figure 1-1 is typical of the type of Web application that we have beenliving with for many years now. It has a request and response cycle that is abrupt and rather noticeableto the end user. Let it be said that, with the introduction of AJAX technologies, these types of applica-tions are changing quickly to the new model this technology provides.On the other hand, Figure 1-2 shows how AJAX is employed to improve the user’s experience.In this case, a request is made for the initial page rendering. From there, asynchronous requests tothe server are made. An asynchronous request is a background request to send or receive data in anentirely nonvisual manner (meaning that there won’t be any resulting page flickering). They are asyn-chronous because the user interface is not frozen during this time, and users can continue interactingwith the page while the data transfer is taking place. These calls get just an incremental update for thepage instead of getting an entirely new page.JavaScript running on the client reacts to the new data and updates various portions of the page asdesired. The number of requests to the server may be no different, or in some cases, there may actuallybe more calls to the server, but the users’ perception is that the application feels more responsive. End92171c01.indd 512/15/08 1:44:52 PM6Chapter 1: Overview of AJAXusers are not forced to pause, even if it is only a slight pause, and wait for the server while staring at ablank browser screen. This model, while chatty in some regards, provides the fluidity you are lookingfor in your Web applications.ClientASP.NET EngineWeb ServicesWeb ServerRequest/ResponseHTMLRequest/ResponseHTMLFigure 1-1AJAX applications make use of theXMLHttpRequestobject as an initiator and caller of the underlyingdata needed by the application to make the necessary changes. These requests are routed through aserialization process before being transmitted across the wire. In most cases, the output is some typeof XML (such as SOAP) or JSON (for those who want an especially a tight format). The response fromthe server is then deserialized and provided to the JavaScript on the page, which then interacts withDHTML to render the parts of the page, outside of the normal postback process.Technologies of AJAXAlmost a decade ago, the Microsoft Exchange Server team created an ActiveX control calledXMLHttpRequestthat could be instantiated from JavaScript and used to communicate with theserver. Using theXMLHttpRequestobject, you could send information to the server and get databack without clearing the screen and painting a completely new HTML page. JavaScript code couldthen manipulate the HTML dynamically on the client, avoiding the annoying flash and the wait thatusers associate with Web browsing. This functionality was not limited to Internet Explorer for long.Soon, other browsers includedXMLHttpRequestobjects as well. Developers could now write richerapplications with their reach extending across various operating systems.92171c01.indd 612/15/08 1:44:52 PM7Chapter 1: Overview of AJAXClientASP.NET EngineWeb ServicesXMLHttpRequestObjectJSON/XML SerializerDHTML RenderingWeb ServerRequest/ResponseInitial ResponseRequest/ResponseJSON/XMLFigure 1-2The browsers that can make use of this object include the following:Internet Explorer 5.0 and above (currently in version 8.0)❑❑Safari 3.1❑❑Firefox 3❑❑Opera 8+❑❑Netscape 9❑❑The browsers also created an advanced Document Object Model (DOM) to represent the browser, thewindow, the page, and the HTML elements it contained. The DOM exposed events and responded toinput, allowing the page to be manipulated with script. Dynamic HTML (DHTML) opened the doorto writing rich interfaces hosted within the Web browser. Developers started writing hundreds and eventhousands of lines of JavaScript code to make rich and compelling applications that would not requireany client installation and could be accessed from any browser anywhere. Web applications began tomove to a whole new level of richness. Without AJAX libraries, you would be faced with writing lots andlots of JavaScript code and debugging the sometimes subtle variations in different browsers to reach thisnew level of richness.92171c01.indd 712/15/08 1:44:53 PM8Chapter 1: Overview of AJAXJavaScript Libraries and AJAXDevelopers have had access to AJAX technologies for years, and many have been leveraging AJAX topush the limits of what can be done in the Web browser. But what is really making AJAX more compel-ling now are the comprehensive script libraries and integration with server technologies that make iteasier to write rich Web applications and avoid the need to become an expert on the different versionsof JavaScript. A JavaScript library is referenced within the HTML of a page by using the<script>tag:<html><head><script src=”http://www.someSite.com/someScript.js”type=”text/javascript”></script></head>...The script is downloaded and cached by the browser. Other pages within the application can reference thesame URL for script, and the browser will not even bother to go back to the server to get it. The functional-ity of that script file is available for use from within the page rendered to the browser. A script library sentto the browser and then leveraged for writing a richer UI and a more responsive application is at the heartof all AJAX libraries.The Initiator ComponentTo initiate calls to the back end server, you need JavaScript on the client to invoke theXMLHttpRequest

object, which takes charge of making these out-of-bound calls. This component works to send data backand forth asynchronously. This core capability is browser-independent and allows for requests andresponses to occur without interrupting the end user experience.The JavaScript ComponentAJAX technologies take advantage of the common support for JavaScript found in modern browsers.Because there is a standard that is supported across the various browsers, you can write scripts knowingthat they will run. This wasn’t always the case.In the mid-1990s, Netscape and Microsoft (along with others) collaborated on a standard for a scriptinglanguage that they would support in their Web browsers. The standard is called EcmaScript. Microsoft’simplementation is called JScript, but the language is generally referred to as JavaScript, as it was calledin Netscape. (It has nothing to do with Java, but someone must have thought the association was use-ful for marketing purposes.) JavaScript program snippets are sent down to the browser along with theHTML, and they run inside the user’s browser to affect how the page is processed on the client.JavaScript is not compiled; it is interpreted. There is no static type-checking as you get in C++ and C#.You can declare a variable without needing to specify a type, and the type to which the variable referscan change at any time. This makes it easy to start programming in JavaScript, but there is inevitably acertain amount of danger in allowing the data type of a variable to change dynamically at runtime. Inthe following snippet, notice that the variable can reference any type without difficulty:var something = 1;something = true;something = “a string”;92171c01.indd 812/15/08 1:44:53 PM9Chapter 1: Overview of AJAXJavaScript is a dynamic language. Types can actually be extended during program execution by othercode. This means that you can write code that creates types on the fly. Because there is no enforcementof type safety, your code can receive these types as parameters or return values without any problem.This provides a great degree of flexibility and coding power.The fundamental types in JavaScript are strings, numbers, Booleans, and functions. There is also supportfor objects and arrays, which are collections of the fundamental types. Some additional objects that areconsidered essential for many programming tasks are included in JavaScript. This includes support forregular expressions and date and time operations.You can use the plus operator on strings in JavaScript to concatenate them:var theEnd = “THE END.”;var result = “Beginning, “ + “middle, and “ + theEnd;In this example, the result variable is now the string:“Beginning, middle, and THE END”.JavaScript interpreters use the IEEE floating-point standard for storing numbers. Ignoring the gorydetails, you can assume that for most programming tasks you won’t have any trouble.The Boolean type in JavaScript is about what you would expect it to be but maybe not exactly so. TheBoolean represents whether or not an expression is true, but it uses the C-style convention using integervalues 0 and 1.Variables can exist in JavaScript without having a value, and a variable may simply be undefined, whichcan produce unexpected results. In this snippet of JavaScript, three variables are declared, and all ofthese comparisons are designed to return a true value.<script type=”text/javascript”>var one = 1;var zero = 0;var undefinedVar;if(one) {alert(“1 is true”);}if(!zero) {alert(“0 is false”);}if(!undefinedVar) {// this test tells us that “undefinedVar” either contains 0,// or is really undefined: both of which equate to falsealert(“undefinedVar is false”);}if(one != zero) {alert(“one and zero are not the same”);}</script>92171c01.indd 912/15/08 1:44:54 PM10Chapter 1: Overview of AJAXYou can check specifically to see if a variable has been defined like this:if( typeof(undefinedVar ) == “undefined” ) {alert(“undefinedVar is undefined”);}Variables can also have a null value, which is not the same thing as being undefined, because a nullvalue does constitute a value.Functions are also real types in JavaScript. They can accept arguments and return values. Functions canbe passed to other functions and can be created dynamically by other script code.Here are two equivalent definitions for a function calledAdd()that will take two variables and return theresult of applying the plus operator. Notice that this did not state that it takes two numbers. Remember,JavaScript variables do not have a defined type, so I could just as easily pass two strings and concatenatethem with myAdd()function.<script type=”text/javascript”>function Add(x, y) {return x + y;}var AddAgain = function(x, y) { return x + y; }</script>Once either of these styles is used to create a function, it can be called from that scope and any nestedscope to perform the addition. There is no advantage to one of these forms over the other. You can simplychoose to use the syntax that you prefer.<script type=”text/javascript”>var result = Add(36, 24);alert(result); //displays 60var stringResult = Add(“Hello “, “there.”);alert(stringResult); //displays “Hello there.”</script>Objects and arrays are just collections of other types. Array types do not require that the values they holdbe named. Instead, you can access them by index. The values held in an object are referenced by fieldor property names. Objects can also hold functions (which can be accessor functions to give public vis-ibility to local variables), which lets you create data structures that represent entities in JavaScript code.Missing from this sort of object-oriented programming is a concept of type inheritance. Although, thereare things like the Microsoft AJAX Library, which provides a set of classes and recommended patternsfor achieving inheritance in JavaScript, making it more natural to switch between JavaScript and otherhigh-level languages. The following code example includes a definition for an Album object that holdsand returns the artist and album title. An array is then used to store information about several albums.<script type=”text/javascript”>// define an object named Album – note that this object is typelessAlbum = function(title, artist) {var _title = title;var _artist = artist;92171c01.indd 1012/15/08 1:44:54 PM11Chapter 1: Overview of AJAXthis.get_title = function() { return _title; }this.get_artist = function() { return _artist; }}// create object instances by calling the constructorvar albumA = new Album(“Rift”, “Phish”);var albumB = new Album(“A Picture of Nectar”, “Phish”);// create an array to hold the instances (also typeless)var albumArray = new Array();albumArray[0] = albumA;albumArray[1] = albumB;// iterate over the array to show the album titlesfor(var i = 0; i < albumArray.length; i++) {alert((albumArray[i]).get_title()); // call get_title accessor}</script>The Web Services ComponentThe fundamental concept of Web services is powerful and continues to evolve and advance. The originalSimple Object Access Protocol (SOAP) standard is the use of the HTTP protocol to pass XML-formatteddata to the server from a client and receive XML-formatted results in return. This can be from within aWeb browser using theXMLHttpRequestobject or directly from a desktop application or another server.Before Web services became widely adopted, it was not uncommon for developers to programmaticallyrequest a page as an HTML document and extract the desired data from it, a technique known as screen-scraping. This causes all sorts of frustrations as sites are continually updated and the screen-scrapingclients must try to keep up by modifying their parsing code to adapt to the new HTML that the targetsite is rendering.This resulted in frustration, because sites that presented data using HTML visual pages were prone tomodifying those pages, and this would break the screen-scraping program, which expected to see thedata in the original format. Web services were created as a nonvisual way to transfer data over the Web,and they are the natural way to isolate remote method calls from the presentation layer. Now, instead ofscreen-scraping, you are able to call a Web service and have XML-formatted data returned that is easilyconsumed by a program.By passing plain-text data formatted as XML and by eliminating the visual elements, data passed inWeb services is much easier to parse than HTML. Moreover, since XML can contain an embeddedschema, code can inspect the schema and use it to determine the structure and types used in the data.You can extend the schema passed with the data being returned without worrying that consumingapplications will be broken, and therefore XML readers can be somewhat tolerant of modifications thatwould have certainly caused a screen-scraper a great deal of grief!The schema for data can be extended without requiring all consumers to be updated. Consumers caneasily get the parts of the XML document they wish to process and disregard the rest. This has pro-gressed beyond simple XML formats. Unlike previous implementations of Web services, you can nowdefine Web service contracts to be built to employ arbitrary encoding and utilize any one of a numberof wire protocols. What drives the Web service concept is the ability to access data easily from various92171c01.indd 1112/15/08 1:44:54 PM12Chapter 1: Overview of AJAXapplications in a loosely coupled way, and the new Microsoft Windows Communication Foundation(WCF) takes this concept to a completely new level, allowing the contract to specify wire protocols,deployment strategies, and logging infrastructure, along with providing support for transactions.ASP.NET AJAX provides a set of JavaScript proxy objects to access some new Web services built into ASP.NET. Profile information, membership services, and role management can be easily accessed from theclient. Developers don’t need to create their own infrastructure to support these fundamental applicationservices but can include a few lines of code to take advantage of server resources from JavaScript coderunning in the browser, thereby dramatically extending the reach of ASP.NET to include both the clientand the server. Moreover, because the JavaScript libraries are designed to be easy to use by developersalready familiar with server-side .NET programming, all of this extra functionality comes in a friendlypackage that is easy to leverage.The Dynamic HTML ComponentDynamic HTML is not a freestanding technology. It is the use of a set of technologies in a specific way.HTML is returned to the browser following a Web server request. The browser then renders the page, andthe user is able to view it. The browser also exposes the DOM that represents the structure of the HTMLbeing displayed. The DOM can be accessed from JavaScript embedded in, or referenced by, the page. Theappearance of the HTML is affected by applying Cascading Style Sheets (CSS), which control colors, fonts,position, visibility, and more. You can bind JavaScript code to events that the browser will raise whenusers perform certain actions, such as hovering over a particular element or entering text in a textbox. TheJavaScript code can update text or manipulate the CSS settings for elements within the page. It can alsocommunicate with the server to expand the dynamic nature of the page even further. The user will see adynamically changing user interface that responds to his actions in real time, which will greatly enhancehis overall experience, thereby increasing his productivity and satisfaction with the application. This onepiece of the pie is the one that changes the underlying page without the page refresh.All these pieces together, in the end, provide you the tools that you need to build state-of-the-artapplications for today’s Web world.AJAX LibrariesASP.NET AJAX is the focus of this book. ASP.NET AJAX is an AJAX library that provides you withthe tools and components that you need to tie all the varying aforementioned technologies together.Although this book is about ASP.NET AJAX in particular, there are many third-party AJAX librariesthat can be used with ASP.NET, although not all of them were specifically designed for it.Some of these AJAX libraries are mainly focused on providing JavaScript libraries for use from withinthe browser to make manipulation of the browser DOM easier. Others include some level of serverfunctionality for use within ASP.NET pages (where server controls will render on the client side).This section briefly highlights some of what these libraries offer. The ASP.NET AJAX Frameworkcan coexist with script and controls from other libraries, although given the dynamic nature of theJavaScript language, it is possible to extend types so that they conflict with each other. Mixing andmatching libraries might work just fine for many uses, but you might find conflicts in other cases. So92171c01.indd 1212/15/08 1:44:54 PM13Chapter 1: Overview of AJAXif you decide to move forward on this route, make sure that you are aware of the potential problems.Some of the available libraries include the following:Ajax.NET Professional❑❑: Michael Schwartz developed Ajax.NET Professional as a tool primarilyused to simplify the data transport mechanism that enables a client JavaScript routine to com-municate with a server program. The server code is simple to use. You merely need to registerthe control in your page and decorate some code-behind methods with attributes to designatewhich ones can be called from the client. Then you can leverage the script library to make thecalls and pass data. This is intended for developers who are well versed in DHTML, and thereare not many prebuilt visual controls. This is a lightweight solution with very little overheadin terms of bytes transferred and processing cycles needed on the client and server. The sourcecode is available, and the package is free (www.ajaxpro.info).Anthem.NET❑❑: Anthem.NET is a SourceForge project where users are able to download thesources to the project. It targets ASP.NET 1.1 and ASP.NET 2.0. It has a set of server controlsthat use their underlying JavaScript library to communicate with the server. They provide theability to access the state of controls on the page during an asynchronous callback. At the timeof writing, the Anthem.NET Web page (http://anthem-dot-net.sourceforge.net) pointsout that the Anthem.NET user needs to be an experienced ASP.NET developer to get the mostout of it. However, this is generally easier to use than Ajax.NET Professional, especially fordevelopers who are not well versed in DHTML. This project is similar to ASP.NET AJAX inmany ways but is not as comprehensive.DoJo❑❑: The DoJo toolkit can be found atwww.dojotoolkit.com. It is a client-side library forAJAX development without ties to any server technology. DoJo has a type system for JavaScriptand a function for binding script to events from JavaScript objects or DHTML elements. Oneof its strengths is rich support for dynamic script loading. You can specify dependencies andordering in the way that scripts are retrieved and processed.Prototype❑❑: The Prototype script library is available atwww.prototypejs.org. It does not targetany server technology for integration. It has a type system for scripting in a more object-orientedway, along with some shortcut syntaxes for dealing with JavaScript arrays as well as accessingand manipulating HTML elements on the page. Prototype provides networking functionalityand a method for automatically updating an HTML element with the results of an HTTP requestwhen given a URL. The Prototype library also has functions for associating script objects andmethods with DOM objects and events. The library is focused on simplifying tasks that can becumbersome and tedious. It does not provide much help for producing a richer user interface butputs forth the building blocks for an improved Web-scripting experience.❑❑ Script.aculo.us: The Script.aculo.us library can be found at the Web site of the same name,http://script.aculo.us. Their tagline is “it’s about the user interface, baby!” which accurately describestheir focus.http://script.aculo.usis built on top of the Prototype script library and picks upwhere it stops. It includes functionality for adding drag-and-drop support to an application. It has alot of effects code for fading, shrinking, moving, and otherwise animating DOM elements.http://script.aculo.usalso has a slider control and a library for manipulating lists of elements.Rico❑❑: The Rico library also builds on top of the Prototype script library. It has support foradding drag-and-drop behavior to browser DOM elements. It also has some controls to bindJavaScript objects to DOM elements for manipulating data. Rico has constructs for revealingand hiding portions of a page using an accordion style. It also has animation, sizing, and fadingeffects prebuilt for easier use. These UI helpers are available atwww.openrico.org.92171c01.indd 1312/15/08 1:44:54 PM14Chapter 1: Overview of AJAXAlthough there are many options out there for ASP.NET developers, you will find that the toolkit defined inthis book is the most integrated with ASP.NET and will be one of the more robust options in your arsenal.Creating a Simple Web Page with AJAXAlthough this book focuses on the power of using AJAX with ASP.NET 3.5 and the AJAX capabilitiesthis framework brings to AJAX development, it is also interesting to see how you could build a simpleAJAX-enabled HTML page without the use of any of the aforementioned frameworks.To show this in action, create an ASP.NET solution within Visual Studio 2008. The first step you cantake is to build the Web service that will return a value to be loaded up through the AJAX process. Thecode (in C#) of the Web service is presented here in Listing 1-1.Listing 1-1: The Web service to communicate with the AJAX-enabled Web pageusing System.Web.Services;/// <summary>/// Summary description for WebService/// </summary>[WebService(Namespace = “http://tempuri.org/“)][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]public class WebService : System.Web.Services.WebService {[WebMethod]public string HelloWorld() {return “Hello Ajax World!”;}}This is a simple C# Web service and as you can see from the single WebMethod, it only returns a stringwith no required parameters on the input. The AJAX page that you create for this example works withthis Web service, and calls the Web service using the HTTP-GET protocol. By default, ASP.NET disallowsHTTP-GET and you have to enable this capability in theweb.configfile in order for this example towork. Listing 1-2 shows the additions you need to make to this file.Listing 1-2: Changing the web.config file in order to allow HTTP-GET<system.web><webServices><protocols><add name=”HttpGet” /></protocols></webServices></system.web>Including the<add>element within the<protocols>element enables the HTTP-GET protocol so thatyour Web page will be able to make the AJAX calls to it. Finally, the HTML page that will make theAJAX call is represented here in Listing 1-3.92171c01.indd 1412/15/08 1:44:54 PM15Chapter 1: Overview of AJAXListing 1-3: The HTML page that will make the AJAX calls to the Web service<html xmlns=”http://www.w3.org/1999/xhtml”><head runat=”server”><title>Basic Ajax Page</title><script type=”text/javascript” language=”javascript”>function InitiationFunction(){var xmlHttp;

try{// Try this for non-Microsoft browsersxmlHttp = new XMLHttpRequest();}catch (e){// These are utilized for Microsoft IE browserstry{xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);}catch (e){try{xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);}catch (e){alert(“Your browser does not support AJAX!”);return false;}}}

(continued)<form><div>Statement from server:<input type=”text” name=”statement” /><br /><br /><input id=”Button1” type=”button” value=”Button”onclick=”InitiationFunction()“ /></div></form></body></html>From this bit of code, you can see that the HTML page creates an instance of theXMLHttpRequest

object. From there, a JavaScript function is assigned to theonreadystatechangeattribute. Wheneverthe state of theXMLHttpRequestinstance changes, the function is invoked. Since, for this example, youare interested only in changing the page after the page is actually loaded, you are able to specify whenthe actual function is utilized by checking thereadystateattribute of theXMLHttpRequestobject.if(xmlHttp.readyState == 4 && xmlHttp.status == 200){}In this case, thereadystateis checked to see if it equals a value of4and if the request status is equalto 200, a normal request was received. If thestatusattribute is equal to something other than200, aserver-side error most likely occurred. Areadystatevalue of4means that the page is loaded. The pos-sible values of thereadystateattribute include0,1,2,3, and4. A value of0(which is the default value)means that the object is uninitialized. A value of1means that theopen()method was called successfully,a value of2means that the request was sent but that no response was yet received, a value of3means thatthe message is being received, and a value of4(again) means that the response is fully loaded.Theopen()method called by theXMLHttpRequestobject is quite simple, as it is an HTTP-GET requestmade to the specific URL of your service.When you run this page and click the button found on the page, you are presented with results illus-trated in Figure

1-3.Figure

1-392171c01.indd 1612/15/08 1:44:55 PM17Chapter 1: Overview of AJAXThe Power of AJAXWithout the advanced use of JavaScript running in the browser, Web applications have their logic run-ning on the server. This means many page refreshes for potentially small updates to the user’s view.With AJAX, much of the logic surrounding user interactions can be moved to the client. This presentsits own set of challenges. Some examples of using AJAX include streaming large datasets, managedentirely in JavaScript, to the browser. While JavaScript is a powerful language, the debugging facilitiesand options for error handling are very limited. Putting complex application logic on the client can takea lot of time, effort, and patience. AJAX as a whole allows you to naturally migrate some parts of theapplication processing to the client, while leveraging partial page rendering to let the server actuallycontrol some aspects of the page view.Some Web sites make an application run entirely from a single page request, where JavaScript andAJAX will do a great deal of work. This presents some tough challenges. Users generally expect that theBack button will take them to the state of the application they were just viewing, but with AJAX appli-cations, this is not necessarily the case. The client may be sending some information to the server forpersistent state management (perhaps in server memory or a database), but this requires extra code andspecial attention to error handling and recovery.The richest, most maintainable applications seem to be those that balance client and server resources toprovide quick response times, easy access to server resources, and a minimum of blocking operationswhile new page views are fetched.ASP.NET AJAX itself provides a mix of client and server programming features. The Microsoft AJAXlibrary is aimed at client development. It provides a type system for an object-oriented approach toJavaScript development. It makes it easy to register code to respond to events. It provides useful functionsto simplify common tasks like finding elements on the page, attaching event handlers, and accessing theserver. The server features include functionality for managing JavaScript code to be sent to the client,declaring regions of the page to be updated asynchronously, creating timers for continuous updates, andaccessing ASP.NET services such as user profile data and authentication.SummaryThe Web has evolved over the last decade from providing a static presence to being the default choicefor developers writing applications. With Web applications, you get reach without having to deal withthe deployment and servicing issues that accompany desktop applications. But the bar continues tomove higher for Web applications as users come to expect more. AJAX technologies are driving Webapplications to rival rich desktop apps. You can use the results of asynchronous communication withthe Web server to update portions of the page without forcing the user to stop his or her work and waitfor the page to post back and be repainted. Dynamic HTML allows you to create a rich GUI with transi-tions and animations leveraging CSS for colors, fonts, positioning, and more.ASP.NET AJAX includes the Microsoft AJAX library, which makes writing browser-based JavaScripteasier and simplifies many common client programming tasks. It is easy to attach code to DOM events,write JavaScript in an object-oriented way, and access the server for persistent storage, authentication,and updated data.92171c01.indd 1712/15/08 1:44:55 PM18Chapter 1: Overview of AJAXASP.NET AJAX also includes extensions to version 2.0 of the .NET Framework that can greatly improveyour Web application. There is built-in support for returning data in the JSON format that is easily con-sumed by JavaScript in the browser.In this book, you will see how the client and server features of ASP.NET AJAX make it easier to pushthe limits of what you can do with a Web application! You learn how to update portions of a page asyn-chronously and how to manage the scripts that are used in the browser. You will find out how to usethe networking facilities, with a dive into accessing ASP.NET services such as authentication and profilestorage. You will get a closer look at the JavaScript language and how the Microsoft AJAX library buildson the language to simplify programming tasks. You will also see what ASP.NET AJAX offers for add-ing a richer UI to Web applications and look at how to debug and test Web applications.92171c01.indd 1812/15/08 1:44:55 PM