Post on 26-May-2017
1
Using AJAX inASP .NET applications
Pittsburgh .NET User GroupLou BiancanielloJorge Balderas
February 22, 2006
2/21/2006 Proprietary to Summa Technologies, © 2006. 2
Agenda
1. What is AJAX?2. AJAX .NET library3. AJAX in ASP .NET 2.04. Microsoft ATLAS5. Conclusions
2
2/21/2006 Proprietary to Summa Technologies, © 2006. 3
What is AJAX?
• Asynchronous JavaScript And XML• A conglomerate of old web technologies:
HTML and CSSJavaScript and the Document Object Model (DOM)XML and the XMLHttpRequest object
• Originated with a precursor of the XmlHttpRequestobject in Microsoft Outlook
• Term coined by AdaptivePath• Became popular with Google applications
2/21/2006 Proprietary to Summa Technologies, © 2006. 4
Traditional Web Application model
Source: AdaptivePath
3
2/21/2006 Proprietary to Summa Technologies, © 2006. 5
AJAX Web Application model
Source: AdaptivePath
2/21/2006 Proprietary to Summa Technologies, © 2006. 6
Computer Processing shifts in computer evolution
• Mainframe
• Client/Server
• Internet
• Web 2.0
4
2/21/2006 Proprietary to Summa Technologies, © 2006. 7
What is the Web 2.0?• Concept originated in conference between O’Reilly and
MediaLive• Web 2.0 by example:
MapQuest Google MapsBritannica Online WikipediaPersonal WebSites BloggingScreen Scraping Web Services, RSS
• Common trends/patterns:Content SyndicationTrust users as “co-developers”Rich user experience
• AJAX is to the UI, what Web Services are to the backend in a Service Oriented Architecture
2/21/2006 Proprietary to Summa Technologies, © 2006. 8
The XmlHttpRequest object• ActiveX object in IE• Native JavaScript object in Mozilla and other browsers• Key methods:
• Key properties:
HTTP response as a stringresponseText
HTTP response as a DOM objectresponseXML
0-4, 4 means completereadyState
reference to event handler functiononReadyStateChange
Issues POST HTTP requestsend (body)
Issues PUT/GET HTTP requests (can be asynchronous)
open(method, url)
5
2/21/2006 Proprietary to Summa Technologies, © 2006. 9
XmlHttpRequest initialization code
• ASP .NET 2.0
• ATLAS
var xmlRequest,e; try {
xmlRequest = new XMLHttpRequest(); } catch(e) {
try { xmlRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { }
}
window.XMLHttpRequest = function() {var progIDs = [ 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' ];for (var i = 0; i < progIDs.length; i++) {
try {var xmlHttp = new ActiveXObject(progIDs[i]);return xmlHttp;
}catch (ex) {}
}return null;
}
2/21/2006 Proprietary to Summa Technologies, © 2006. 10
XmlHttpRequest initialization code
• Google Suggestfunction vb(){
var C=null;try{
C=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){
try{C=new ActiveXObject("Microsoft.XMLHTTP")
}catch(sc){C=null
}}if(!C&&typeof XMLHttpRequest!="undefined"){
C=new XMLHttpRequest()}return C
}
6
2/21/2006 Proprietary to Summa Technologies, © 2006. 11
XmlHttpRequest security
• Adopts same JavaScript security policies of the browser:
Page containing the script must be accessed via http url (cannot use file protocol)The domain of the URL requested by the object must be the same as the one that serves the page containing the script
2/21/2006 Proprietary to Summa Technologies, © 2006. 12
AJAX in ASP .NET applications
• ASP .NET 1.xAJAX .NET library (by Michael Schwarz)
• ASP .NET 2.0 onlyScript call backs implemented using XmlHttpRequest objectATLAS (Microsoft) library
7
2/21/2006 Proprietary to Summa Technologies, © 2006. 13
Agenda
1. What is AJAX?2. AJAX .NET3. AJAX in ASP .NET 2.04. Microsoft ATLAS5. Conclusions
2/21/2006 Proprietary to Summa Technologies, © 2006. 14
Ajax.Net
• Library for .NET 1.x for easily incorporating AJAX into ASP .NET applications.
• Initially written by Michael Schwarz• Now being developed as an open source project
by BorgWorx.• BorgWorx version incorporates AJAX-aware
controls (e.g. sliders, drop down lists, etc.)
8
2/21/2006 Proprietary to Summa Technologies, © 2006. 15
Setup• Configure the HttpHandler for Ajax in config.web
• Requests made to the specified path (ajax/*.ashx) are handled by the Ajax.PageHandlerFactory
<configuration><system.web>
<httpHandlers><add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax" /></httpHandlers> ...
<system.web></configuration>
2/21/2006 Proprietary to Summa Technologies, © 2006. 16
Setup• Register code-behind class with Ajax.Net
• Generated javascript at runtime:
public class Index : System.Web.UI.Page{
private void Page_Load(object sender, EventArgs e){
Ajax.Utility.RegisterTypeForAjax(typeof(Index)); //...
} //...
}
<script language="javascript" src="ajax/common.ashx"> </script><script language="javascript" src="ajax/NAMESPACE.PAGECLASS,ASSEMBLYNAME.ashx"></script>
9
2/21/2006 Proprietary to Summa Technologies, © 2006. 17
Simple Server Side Example• Uses a declarative method attribute approach
• Call to function is automatically added to javascriptclient code at runtime:
[Ajax.AjaxMethod()]public int ServerSideAdd(int firstNumber, intsecondNumber){
return firstNumber + secondNumber;}
<form id="Form1" method="post" runat="server"><script language="javascript">var response = Sample.ServerSideAdd(100,99);alert(response.value);
</script></form>
2/21/2006 Proprietary to Summa Technologies, © 2006. 18
Simple Server Side Example• Client side function accepts a 3rd parameter: a
callback function to process the response:
Sample.ServerSideAdd(100,99, ServerSideAdd_CallBack);
function ServerSideAdd_CallBack(response){if (response.error != null){alert(response.error);return;
}alert(response.value);}
10
2/21/2006 Proprietary to Summa Technologies, © 2006. 19
Simple Server Side Example
• The callback function receives a response object which exposes four key properties:
The HTTP context object.Context
The raw response from the XML HTTP request.
Request
An error message, if any.Error
The return value (e.g. string, custom object or dataset) of the server-side function.
Value
2/21/2006 Proprietary to Summa Technologies, © 2006. 20
Return Types
• Ajax.Net is capable of returning:1. Integer2. String3. Double4. Boolean5. DateTime6. DataSet7. DataTable8. Primitive custom classes and arrays9. All other types have ToString() returned
11
2/21/2006 Proprietary to Summa Technologies, © 2006. 21
Lessons learned
• Issues:Will not work through a proxy.Exposes custom code to the client.
2/21/2006 Proprietary to Summa Technologies, © 2006. 22
Agenda
1. What is AJAX?2. AJAX .NET3. AJAX in ASP .NET 2.04. Microsoft ATLAS5. Conclusions
12
2/21/2006 Proprietary to Summa Technologies, © 2006. 23
Script Callbacks in ASP .NET 2.0
• Script callbacks are made using the XmlHttpRequest object at runtime
• Page class needs to implement ICallBackEventHandler interface
• Call back result must be a string• Page class now has a IsCallBack
property• Call back may be asynchronous Source: CuttingEdge
2/21/2006 Proprietary to Summa Technologies, © 2006. 24
ICallBackEventHandler interface
• ICallBackEventHandler interface methods
• ClientScriptManager class methods
void RaiseCallbackEvent(string eventArgument);string GetCallbackResult();
public string GetCallbackEventReference(Control control, string argument, string clientCallback, string context, bool useAsync);
public void RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags);
13
2/21/2006 Proprietary to Summa Technologies, © 2006. 25
Script Callback sample• Code-behind
• Adds JavaScript code below:
String callBack = Page.ClientScript.GetCallbackEventReference(this, "arg" "ClientCallback", "context", "ClientCallbackError", false);String clientFunction = "function GetChildren(arg, context){ " + callBack + "; }";Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "GetChildren", clientFunction, true);
function GetChildren(arg, context){ WebForm_DoCallback('__Page', arg, ClientCallback, context, ClientCallbackError, false); }
2/21/2006 Proprietary to Summa Technologies, © 2006. 26
Script Callback sample• .aspx/js code
• HTTP Request:
• HTTP Response:
function ClientCallback(result, context){}<asp:DropDownList ID="ParentDropDown" onchange="GetChildren(this.options[this.selectedIndex].value );” runat="server">
_VIEWSTATE /wEPDwUJMTg4MzY4MTQ4ZG…ParentDropDown Numbers__CALLBACKPARAM Numbers__EVENTVALIDATION /wEWBQLXnqCyAQLy/pvPC…
72|/wEWBQLXnqCyAQLy/pvPCwKm/p/TDAKEnuDbBgLkrqyLDiDr35gpMILoDc+MdUDLCbFNFK+DOne|Two|Three…
14
2/21/2006 Proprietary to Summa Technologies, © 2006. 27
Agenda
1. What is AJAX?2. AJAX .NET3. AJAX in ASP .NET 2.04. Microsoft ATLAS5. Conclusions
2/21/2006 Proprietary to Summa Technologies, © 2006. 28
Microsoft ATLAS Overview• Codename for a Microsoft “AJAX Framework” for ASP
.NET 2.0• More than just an AJAX library:
Client web controls (JavaScript)• Relies heavily on Object-Oriented JavaScript• Can be used using declarative XML-Script• Web Services support• Client web controls
ATLAS-enabled web server controls • UpdatePanels – partial rendering
• TimelinePreview released in PDC 2005Go-live license due in SpringFinal release Q3-Q4 2006?
15
2/21/2006 Proprietary to Summa Technologies, © 2006. 29
Getting started with ATLAS
• Download Atlas Blank Project VSIhttp://msdn.microsoft.com/asp.net/info/future/atlastemplate/
• In VS 2005 click “New Web Site” and you’ll see “ASP.NET ‘Atlas’ Web Site” under “My Templates”
• New website will contain:ScriptLibrary folder
• AtlasRuntime.js, AtlasUIDragDrop.js, etc.
Reference to Microsoft.Web.Atlas.dllATLAS web controls registered in web.config
2/21/2006 Proprietary to Summa Technologies, © 2006. 30
HelloWorld sample• Add ScriptManager control:
• Add javascript function:function buttonClick() {
var request = new Web.Net.WebRequest();request.set_url("MyAtlasHandler.ashx");request.completed.add(this.onCompleted);request.invoke();
}function onCompleted(response) {
alert(response.get_response().get_data());}
<atlas:ScriptManager ID="ScriptManager1" runat="server" />
16
2/21/2006 Proprietary to Summa Technologies, © 2006. 31
AutoComplete sample• ASPX code
• HTTP Request{"prefixText":"j","count":10}
• HTTP Response["Jaws (1975)","Jurassic Park (1993)"]
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005"><components><textBox id="txtSearch"><behaviors><autoComplete completionList="results" serviceURL="MovieWebService.asmx" serviceMethod="Search" minimumPrefixLength="1" />
</behaviors></textBox>
</components></page>
2/21/2006 Proprietary to Summa Technologies, © 2006. 32
Web Service call with complex type sample
• Add service reference
• JavaScript code
<atlas:ScriptManager runat="server" ID="scriptManager"><Services>
<atlas:ServiceReference Path="MovieWebService.asmx" /></Services>
</atlas:ScriptManager>
function OnbuttonGo_click() {
var object = new Movie();object.Name = "My favorite movie";object.Id = 123;
requestComplexService = MovieWebService.EchoMovie(object, //paramsOnComplete, //Complete eventOnTimeout //Timeout event);
return false;}
17
2/21/2006 Proprietary to Summa Technologies, © 2006. 33
Web Service call with complex type sample
• Generated proxy at runtime:
• HTTP Request{"movie":{"__serverType":"Movie","Name":"My favorite
movie","Id":123}}
• HTTP Response{"__serverType":"Movie","Id":123,"Name":"My favorite movie"}
var MovieWebService = new function() {this.path = "http://localhost:4862/AtlasDemo/MovieWebService.asmx";var cm=Web.Net.ServiceMethodRequest.createProxyMethod;cm(this,"UpdateQueue","movieIds");cm(this,"Search","PrefixText");cm(this,"EchoMovie","movie");
}var gtc = Web.Net.MethodRequest.generateTypedConstructor;var Movie = gtc("Movie");
2/21/2006 Proprietary to Summa Technologies, © 2006. 34
Drag and Drop lists sample
• Drag and Drop Movie queue
18
2/21/2006 Proprietary to Summa Technologies, © 2006. 35
Drag and Drop lists sample
• Uses DragDropList and DragDropItem behaviors
• Customized AtlasUIDragDrop.jsAdded removed and added events
<behaviors><dragDropList dataType="HTML" acceptedDataTypes="HTML"
dragMode="Move"><dropCueTemplate>
<template layoutElement="dropCueTemplate" /></dropCueTemplate>
</dragDropList></behaviors>
2/21/2006 Proprietary to Summa Technologies, © 2006. 36
Drag and Drop lists sample• Creating custom ATLAS web control:
Implement IScriptControl.RenderScript
• Generated XML-Script output
GenericScriptComponent gsc = new GenericScriptComponent(new ScriptTypeDescriptor("control", ScriptNamespace.Default));gsc.ID = this.ClientID;GenericScriptComponent draggableBehavior = new GenericScriptComponent(new ScriptTypeDescriptor("draggableListItem", ScriptNamespace.Default));draggableBehavior.AddValueProperty("handle", this.ClientID);
gsc.AddCollectionItem("behaviors", draggableBehavior);((IScriptObject)gsc).RenderScript(writer);
<control id="webPart1"><behaviors>
<draggableListItem handle="webPart1Handle" /></behaviors>
</control>
19
2/21/2006 Proprietary to Summa Technologies, © 2006. 37
UpdatePanel sample• ASPX source
• Generated JavaScript
<atlas:UpdatePanel runat="server" ID="UpdatePanel2" Mode="Always">
<ContentTemplate><asp:label runat="server" Text="Keep changing
me!" ID="Label1" BorderStyle="Solid" /></ContentTemplate>
</atlas:UpdatePanel>
Web.WebForms._PageRequest._setupAsyncPostBacks( document.getElementById('form1'), 'ScriptMgr');
2/21/2006 Proprietary to Summa Technologies, © 2006. 38
UpdatePanel sample
• HTTP Request headerdelta: true
• HTTP Response<delta><rendering>...<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTE3OTk ... IuxBS5mw==" /><span id="UpdatePanel2"><![CDATA[
<span id="Label1" style="display:inline-block;border-style:Solid;">2/7/2006 9:10:50 PM</span>
]]></span></rendering><deltaPanels>UpdatePanel2</deltaPanels></delta>
20
2/21/2006 Proprietary to Summa Technologies, © 2006. 39
Data Binding sample• ASPX source
<div id="queueDataContents"></div><div id="queueTemplate">
<div id="masterItemTemplate"><asp:Image ID="itemImage" runat="server" /><asp:Label ID="itemName" runat="server" />
</div></div><div id="masterNoDataTemplate">No data</div>
2/21/2006 Proprietary to Summa Technologies, © 2006. 40
Data Binding sample• XML Script
• HTTP Response
<itemTemplate><template layoutElement="masterItemTemplate"><image targetElement="itemImage"><bindings>
<binding dataPath="ImageUrl" property="imageURL"/></bindings>
</image><label targetElement="itemName"><bindings>
<binding dataPath="Name" property="text"/></bindings>
</label></template>
</itemTemplate>
new Web.Data.DataTable([{"Name":"The Incredibles(2004)","ImageUrl":"images/01.jpg"},...,{"Name":"Spider-Man (2002)","ImageUrl":"images/05.jpg"}],[new Web.Data.DataColumn("Name",String,null),newWeb.Data.DataColumn("ImageUrl",String,null)],["Name","ImageUrl"])
21
2/21/2006 Proprietary to Summa Technologies, © 2006. 41
Agenda
1. What is AJAX?2. AJAX .NET library3. AJAX in ASP .NET 2.04. Microsoft ATLAS5. Conclusions
2/21/2006 Proprietary to Summa Technologies, © 2006. 42
Best Practices• Use a framework!
Don’t reinvent the wheel• Always provide visual feedback to the user• Use it selectively:
Small non-critical updates• “Please rate this item”
To avoid whole page loads• E.g. add item to cart
Read only applications• Google maps
Intranet applications• Windows look-and-feel
22
2/21/2006 Proprietary to Summa Technologies, © 2006. 43
Which library should I use?• AJAX .NET?
For ASP .NET 1.x applicationsCombine with JavaScript library for visual effects
• http://script.aculo.us/• http://tool-man.org/examples/• http://prototype.conio.net/
• ATLAS?Not yetWish list:
• Rely on Web Services standards• Add [AjaxMethod] attribute approach• More and better documentation sooner
2/21/2006 Proprietary to Summa Technologies, © 2006. 44
AJAX challenges
• Back button & page bookmarks“Link to this page” approach from Google Maps
• Development challengesLack of Intellisense supportSource code fully exposed to clientAnother language, another skill setHarder to debug
• Increased web requests• Web proxy issues
23
2/21/2006 Proprietary to Summa Technologies, © 2006. 45
Questions and Answers
• Thank you for joining us!
2/21/2006 Proprietary to Summa Technologies, © 2006. 46
References• Ajax: a new approach to web applications
http://www.adaptivepath.com/publications/essays/archives/000385.php
• The XmlHttpRequest objecthttp://developer.apple.com/internet/webcontent/xmlhttpreq.html
• AJAX .NEThttp://ajax.schwarz-interactive.de/csharpsample/default.aspx
• Script CallBacks in ASP .NEThttp://msdn.microsoft.com/msdnmag/issues/04/08/CuttingEdge/
24
2/21/2006 Proprietary to Summa Technologies, © 2006. 47
References• ATLAS
http://atlas.asp.net• ATLAS quickstart tutorials
http://atlas.asp.net/quickstart/• Nikhil Kothari’s blog
http://www.nikhilk.net/• Jorge’s blog
http://yortch.blogspot.com• Web Development Helper
http://www.nikhilk.net/Project.WebDevHelper.aspx
2/21/2006 Proprietary to Summa Technologies, © 2006. 48
About Summa: What We Do
Summa helps companies modernize their business applications by:
Creating commercial-grade, custom solutions that meet current business needs.While keeping a critical eye on the future…Leveraging the existing technology resources.
Our customers continue to do business with us because we get it right the first time.
IT’S NOT ABOUT REINVENTING THE WHEEL. IT’S ABOUT ALL OF THE WHEELS
WORKING TOGETHER.
25
2/21/2006 Proprietary to Summa Technologies, © 2006. 49
About Summa: Quick Facts• Experts at implementing the right technology to solve your
business problem and leverage your existing resources:Portals - Empower managers and/or your customers to access information from multiple applications & databasesIntegration - Modernize business applications to increase their usefulness and ability to work togetherTechnical Training and Mentoring
• Founded in 1996, privately held
• 15+ years project experience building large-scale transaction processing systems
• Based in Pittsburgh, PA, subsidiary in Sao Paulo, Brazil
2/21/2006 Proprietary to Summa Technologies, © 2006. 50
Summa: Relationships & Customers• One of Top 10% of IBM WebSphere®
Partners worldwide• Our customers include:
FinancialFederal Home Loan BankFiServMellon BankPNC Bank ATM Corp.
Independent Software VendorsManagement Science Corp.CombineNetMAYA Viz (General Dynamics)
HealthcareHighmarkMulti-Modal
Manufacturing & IndustrialThyssenKrupp Materials NAUSX CorporationBayer CorporationWabtec CorporationDoyle Center for Manufacturing
Technology
Retail & DistributionRentWay CorporationSheetz WESCO Distribution
TelecommunicationsCrown Castle Intl Corporation