Title: Creating Rich Client Web Applications with AJAX
1Creating Rich Client Web Applications with AJAX
- Jason Beres
- jasonb_at_infragistics.com
2Agenda
- 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
3The 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
4How 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)
5What 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
6The standard web client/server request processing
model
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-Connectio
n Keep-Alive Cookie MC1GUID5cd2d5ca1a1cc54183c
10f4bacaa45faHASHcad5LV20059V3
AIIAxUFAAAAAABuCAAAzJInmvNBZzRHm8aAr99x0A!!
msresearch1
HTTP/1.1 200 OK Date Fri, 04 Nov 2005 171737
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 charsetutf-8 Content-Length
22370 lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.0 Transitional//EN" gt lthtml dir"ltr"
lang"en"gt ltheadgt ltMETA http-equiv"Content-Type"
content"text/html charsetutf-8"
gt lt!--TOOLBAR_EXEMPT--gt ltmeta http-equiv"PICS-Lab
el" content"(PICS-1.1 quothttp//www.rsac.org/r
atingsv01.htmlquot l gen true r (n 0 s 0 v 0 l
0))" gt ltmeta name"KEYWORDS" content"products
headlines downloads news Web site what's new
solutions services software contests
corporate news" gt ltmeta name"DESCRIPTION"
content"The entry page to Microsoft's Web site.
Find software, solutions, answers, support, and
Microsoft news." gt ltmeta name"MS.LOCALE"
content"EN-US" gt ltmeta name"CATEGORY"
content"home page" gt lttitlegtMicrosoft
Corporationlt/titlegt ltbase href"http//g.msn.com/m
h_mshp/98765" gt ltstyle type"text/css"
media"all"gt
Browser makes a resource request to the server
Server processes the request and returns a result
to the browser
7Demo
- A simple HTML postback example
8Problems 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
9The client/server request processing model using
AJAX
GET /AjaxPresentation/AjaxWithHandler/SimpleAjax.a
shx?DataRequesttrueval12val22
HTTP/1.1 Accept / Accept-Language
en-us Referer http//localhost/AjaxPresentation/A
jaxWithHandler/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
.ASPXANONYMOUSAcYSqWXDsOAzMTgxM2IwZi04YzdiLTQyMWM
tYjJiNi0yYWVmNDA5OGY0Njg1 ASP.NET_SessionIdrq0av
nqjfi5eer45zeq0qdj1
Browser makes a resource request tothe server
HTTP/1.1 200 OK Server Microsoft-IIS/5.1 Date
Fri, 04 Nov 2005 173353 GMT X-Powered-By
ASP.NET X-AspNet-Version 1.1.4322 Cache-Control
private Content-Type text/html
charsetutf-8 Content-Length 1 4
Server processes the request and returns a
result to the browser
10AJAX 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
11Creating Ajax applications
- Use JavaScript to instantiate the XML
parser - Use the XML object to create a new HTTP request
to the server - Use the XML objects onreadystatechange property
to assign a client-side callback method
//Works in Mozilla (Firefox) and Safari var oXml
new XMLHttpRequest() Works in Internet
Explorer var oXml new ActiveXObject("Microsoft.X
MLHTTP")
oXml.Open("GET", Endpoint.aspx, true)
12Demo
13Side 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
14AJAX 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
15Demo
- Using Handlers as AJAX endpoints
- Accessing Session from an Handler
16Controlling 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
17Demo
- Adding AJAX Asynchronous polling
18AJAX 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
19Primary 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
20Using 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.DOMD
ocument")
21Demo
- Parsing AJAX XML payloads
- Using XSLT with AJAX Payloads
22JSON
- 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)
23Examples of JSON
- Object serialized to JSON example
- The same text expressed as XML
"menu" "id" "file", "value" "File",
"popup" "menuitem" "value"
"New", "onclick" "CreateNewDoc()",
"value" "Open", "onclick" "OpenDoc()",
"value" "Close", "onclick" "CloseDoc()"
ltmenu id"file" value"File"gt ltpopupgt ltmenuitem
value"New" onclick"CreateNewDoc()" /gt
ltmenuitem value"Open" onclick"OpenDoc()" /gt
ltmenuitem value"Close" onclick"CloseDoc()" /gt
lt/popupgt lt/menugt
24Other AJAX libraries
- Server Side Libraries
- Ajax.NEThttp//ajax.schwarz-interactive.de/csharp
sample/default.aspx - PHP ASPhttp//cpaint.sourceforge.net/
- Client Side Libraries
- Google AJAXSLThttp//goog-ajaxslt.sourceforge.net
/ - Dojohttp//dojotoolkit.org/
25Ajax.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
26Demo
27AJAX 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)
28Client 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
29Demo
- ASP.NET 2.0 Client callbacks
30Atlas
- 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
31Declarative Atlas
ltpage xmlnsscript"http//schemas.microsoft.com/
xml-script/2005" xmlnswiki"wiki"gt
ltcomponentsgt ltlabel
targetElement"loadingMsg1"gt
ltbindingsgt ltbinding
dataContext"documentsSource1" dataPath"isReady"
property"visible" transform"Invert"/gt
lt/bindingsgt lt/labelgt
lttextBox targetElement"lt navCategoryID.Client
ID gt" /gt lttextBox targetElement"lt
navDefaultDocumentTitle.ClientID gt"/gt
lttextBox targetElement"recurseSubfolders1"/gt
ltdataSource id"documentsSource1
" serviceURL"lt ResolveUrl("/WebServices/Docume
ntWebService.asmx") gt"gt
ltbindingsgt ltbinding
dataContext"lt navCategoryID.ClientID gt"
dataPath"text" property"selectParameters"
propertyKey"categoryID"/gt
ltbinding dataContext"lt navDefaultDocumentTitle.
ClientID gt" dataPath"text" property"selectParam
eters
propertyKey"defaultDocumentTitle"/gt
ltbinding dataContext"recurseSubfolders1"
dataPath"text" property"selectParameters"
propertyKey"strRecurseSubfolders"/gt
lt/bindingsgt lt/dataSourcegt
32Final thoughts
- AJAX is not a magic bullet use where
appropriate - Too much HTTP chatter can be just as bad
- AJAX throws a wrench in some existing browser
features - Bookmarking
- The Back button
- AJAX is potentially a big gun, be careful
33Resources
- Fiddler HTTP Sniffer
- www.fiddlertool.com/fiddler/
- DOM Reference
- msdn.microsoft.com/library/default.asp?url/librar
y/en-us/xmlsdk/html/d051f7c5-e882-42e8-a5b6-d1ce67
af275c.asp - Ajax.NET
- http//ajax.schwarz-interactive.de/csharpsample/de
fault.aspx - Atlas
- atlas.asp.net
- JSON (JavaScript Object Notation)
- www.json.org
34Questions?
- jasonb_at_infragistics.com