2. Agenda
⢠Web Apps: Whats good, whats not
⢠What is AJAX and how can AJAX help with the
bad?
⢠Creating simple AJAX applications
⢠AJAX endpoints and payloads
⢠Using third-party AJAX libraries
⢠AJAX security
⢠ASP.NET 2.0 client callbacks and Atlas
3. The Good, Bad and Ugly
(of Web Applications) Condensed Version
⢠The Good
â Centralized control of the application
â Easy deployment
⢠The Bad
â Locked into the browser sandbox
â Loose the âthick-clientâ experience
â One way to get data â the browser postback
⢠The Ugly
â Browser compatibility
4. How does AJAX help?
⢠Keep all of the good of thin client
⢠Bring the âthick-clientâ experience much closer to
the thin client
⢠Escape the standard client/server HTTP request
communications paradigm (the âpostbackâ)
5. What the heck is AJAX?
⢠Asynchronous JavaScript And XML
â No new technologies here, just a new name
⢠Takes advantage of modern uplevel browser features:
â A client side XML parser
(on Windows this is generally the Microsoft XML parser)
⢠Send data to/receive data from the server outside of the browsers standard
communications mechanism (eg the postback)
⢠Parse and enumerate XML formatted data on the client
â A rich Document Object Model (DOM)
⢠Powerful interaction points between the different elements of your
webpage, the browser and browser plugins
6. The standard web client/server
request processing model
HTTP/1.1 200 OK
Date: Fri, 04 Nov 2005 17:17:37 GMT
Server: Microsoft-IIS/6.0
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV
ONL PHY PRE PUR UNI"
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 22370
GET / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash,
application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR
2.0.50727)
Host: www.microsoft.com
Proxy-Connection: Keep-Alive
Cookie: MC1=GUID=5cd2d5ca1a1cc54183c10f4bacaa45fa&HASH=cad5&LV=20059&V=3;
A=I&I=AxUFAAAAAABuCAAAzJInmvNBZzRHm8aAr99x0A!!; msresearch=1
Browser makes a resource
request to the server
<html dir="ltr" lang="en">
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8" >
<!--TOOLBAR_EXEMPT-->
<meta http-equiv="PICS-Label" content="(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v
0 l 0))" >
<meta name="KEYWORDS" content="products; headlines; downloads; news; Web site; what's new; solutions; services;
software; contests; corporate news;" >
<meta name="DESCRIPTION" content="The entry page to Microsoft's Web site. Find software, solutions, answers,
support, and Microsoft news." >
<meta name="MS.LOCALE" content="EN-US" >
<meta name="CATEGORY" content="home page" >
<title>Microsoft Corporation</title>
<base href="http://g.msn.com/mh_mshp/98765" >
<style type="text/css" media="all">
Server processes the request
and returns a result to the
browser
HTTP Request
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
HTTP Response
8. Problems with this model
⢠To get any data requires complete round trip to the
server which is inefficient
⢠UI suffers because the entire UI must be refreshed
as part of the postback, even if it does not change
(users see the page âflashâ)
⢠User is blocked from continuing to work until the
page is returned from the postback
9. The client/server request
processing model using AJAX
GET /AjaxPresentation/AjaxWithHandler/SimpleAjax.ashx?DataRequest=true&val1=2&val2=2 HTTP/1.1
Accept: */*
Accept-Language: en-us
Referer: http://localhost/AjaxPresentation/AjaxWithHandler/SimpleAjax.aspx
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
Host: localhost
Proxy-Connection: Keep-Alive
Cookie: .ASPXANONYMOUS=AcYSqWXDsOAzMTgxM2IwZi04YzdiLTQyMWMtYjJiNi0yYWVmNDA5OGY0Njg1;
ASP.NET_SessionId=rq0avnqjfi5eer45zeq0qdj1
Server processes the
request and returns a
result to the browser
Browser makes a
resource request to
the server
HTTP Request
Using XMLHTTP object, an async
HTTP request is made to the server
JavaScript callback function
handles XMLHTTP response
HTTP Response
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Fri, 04 Nov 2005 17:33:53 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 1
4
10. AJAX Advantages
⢠Send an receive only the data you need
â Think chatty, not chunky
⢠Only update portions of the page that need to be
updated
⢠Asynchronous, so users can continue to work while
the page is updated, and more data is fetched
11. Creating Ajax applications
⢠Use JavaScript to instantiate the XML parser
//Works in Mozilla (Firefox) and Safari
var oXml = new XMLHttpRequest();
Works in Internet Explorer
var oXml = new ActiveXObject("Microsoft.XMLHTTP");
⢠Use the XML object to create a new HTTP request to
the server:
oXml.Open("GET", âEndpoint.aspxâ, true);
⢠Use the XML objects onreadystatechange property to
assign a client-side callback method
13. Side note: Debugging Client Script
via Internet Explorer
â Enable script
debugging
â Display script error
notifications
â Add the âdebuggerâ
command to your script
⢠Mozilla supports
debugging via
Venkman debugger
add-in
14. AJAX Endpoints
⢠Anything that can be accessed via HTTP can serve as
an AJAX endpoint
â Standard ASP.NET webpages (*.aspx)
â HTTP Handlers (*.ashx, or custom extenstions)
â Web Services (*.asmx)
â PHP Web Pages
⢠Think about endpoint performance
â ASPX endpoints require a complete page lifecycle to
execute on each request
â Handlers and Web Services are much more lightweight
â Both can access Session, Cache etc
15. Demo
⢠Using Handlers as AJAX endpoints
⢠Accessing Session from an Handler
16. Controlling Asynchronous
Communications
⢠Create timer based operations using JavaScripts
setInterval command
⢠Make sure you control the number of open HTTP
connections, as well as the polling interval
18. AJAX Payloads
⢠The AJAX âPayloadâ is the data returned by the
HTTP request.
⢠Since Ajax is simply a standard HTTP
request/response, the response payload can be
anything you like
⢠Examples:
â XML, HTML, Simple Types (number, string), JSON
⢠Remember that the actual HTTP payload will always
be a type of string, so objects must be serialized
19. Primary Payload Types
⢠Two primary types of payloads in AJAX:
â XML
⢠Simple, easy to read format, but you generally must use the MS
XML Parser and DOM to work with it
⢠Native to .NET â easy to create on and transport from the server
â JSON (JavaScript Object Notation)
⢠Slightly more complex
⢠Data must be massaged into JSON format
⢠Easier to work with once its on the client
⢠Either supports complex object serialization
20. Using XML Payloads
⢠Use the XML DOM to examine and manipulate XML
data on the client
â ResponseXml property automatically provides a representation
of data as parsed by the MSXML XMLDOM parser
â XMLDOM provides complete XML navigation concepts:
Document, Element, Node
â Use client side XSLT to transform or format data
â ParseError object tells you if the returned XML was badly
formed
//Works in Mozilla (Firefox) and Safari
var oXsl = new XSLTProcessor();
//Works in Internet Explorer
var oXsl = new ActiveXObject("MSXML2.DOMDocument");
21. Demo
⢠Parsing AJAX XML payloads
⢠Using XSLT with AJAX Payloads
22. JSON
⢠JSON (JavaScript Object Notation) is a lightweight
data-interchange format.
⢠It is easy for humans to read and write.
⢠It is easy for machines to parse and generate.
⢠Useful as a data-interchange because it can be
trivially parsed by JavaScript's built in eval()
procedure.
var json_data;
json_data = ""The quick brown fox."";
myObject = eval("return " + json_data);
23. Examples of JSON
⢠Object serialized to JSON example
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
⢠The same text expressed as XML:
<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
24. Other AJAX libraries
⢠Server Side Libraries
â Ajax.NET
http://ajax.schwarz-interactive.de/csharpsample/default.aspx
â PHP & ASP
http://cpaint.sourceforge.net/
⢠Client Side Libraries
â Google AJAXSLT
http://goog-ajaxslt.sourceforge.net/
â Dojo
http://dojotoolkit.org/
25. Ajax.NET
⢠Open Source AJAX implementation for .NET
(Note: while still available, the project is not longer being actively developed)
⢠Easy to use. Requires a simple method attribute (
[AjaxMethod()]) to expose server side methods as AJAX
endpoints
⢠Automatically uses JSON to transport complex objects like
DataSets
⢠Uses dynamically generated JavaScript to create client side
proxies for server side objects
⢠Supports transport of integers, strings, doubles, booleans,
DateTime, DataSets, DataTables and primitive types of custom
classes and arrays
⢠Other types supported via Custom Type converters
27. AJAX Security
⢠HTTPS is your friend
⢠Keep sensitive code or data on the server where you
can control it
⢠By default everything is sent clear text over the wire
(including client side code), and could potentially be
captured in transit and modified
⢠JavaScript has no intrinsic over-the-wire encryption
support, but you can implement your own encryption
(search Google for âAJAX encryptionâ)
28. Client Callbacks
⢠New Feature in ASP.NET 2.0
⢠Add client-side callbacks to your web pages or server
controls
⢠Executes in the context of the current page
â Allows you to access existing control state on the server
during the callback process
â Keeps you from having to pass as much data back
⢠Not as flexible in setting endpoints, and passing
arguments
29. Atlas
⢠Microsofts next generation AJAX framework
â Cross browser compatible
⢠Includes both declarative and imperative programming
models
â Code in vanilla JavaScript, or use the Atlas âtagâ
programming model
⢠Attempts to bring JavaScript to a first class language
â Uses abstraction layers to add familiar programming
constructs like Types, Enumerations, Class Inheritance
â Also uses abstraction layers to abstract cross browser
problems
⢠Includes a number of controls for common functionality