introduce what is asp.net ajax architecture of asp.net ajax goal of asp.net ajax scenarios asp.net...
TRANSCRIPT
IntroduceWhat is ASP.NET AJAX Architecture of ASP.NET AJAXGoal of ASP.NET AJAXScenariosASP.NET AJAX ExtensionsMicrosoft AJAX LibraryASP.NET AJAX ToolKit
What is ASP.NET AJAXName of Microsoft’s AJAX solution, and it refers to a set of client and server technologies that focus on improving web development with Visual Studio
A framework for quickly creating efficient and interactive web applications
Architecture of ASP.NET AJAX
Two major componentsMicrosoft AJAX Library (client)ASP.NET 2.0 AJAX Extensions (server)
Microsoft AJAX Library
Browsers (IE, Firefox, Safari, others)Browsers (IE, Firefox, Safari, others)
Browser CompatibilityBrowser Compatibility
Asynchronous CommunicationsAsynchronous Communications
Script Core LibraryScript Core Library
Base Class LibraryBase Class Library
XHTML/CSSXHTML/CSS Server ScriptsServer Scripts
Client Server
ASP.NET 2.0
PageFramework andServer Controls
PageFramework andServer Controls
ApplicationServices
ApplicationServices
ASP.NET 2.0 AJAX Extensions
AJAXServer Controls
AJAXServer Controls
AsynchronousCommunications
AsynchronousCommunications
ApplicationServices Bridge
ApplicationServices Bridge
ASPXASPX ASMXASMX
Goal of ASP.NET AJAX
Cross-platform, browser-indepedentIncreased productivity, less time to marketHighly extensibleEnhance existing pages using powerful AJAX controls Can be used with PHP, ColdFusion, etc.
Scenarios to develop web application with ASP.NET AJAX
Server-centric Ajax Web Development
Enrich applications without lots of Javascript code required
Enable you to keep core UI/Application logic on server (VB/C#)
Client-centric Ajax Web Development
Leverage full power of script/DHTML
Provide richer and more interactive user experience
ASP.NET AJAX provides a great Ajax framework for both server and client centric Ajax development scenarios
Server-Centric Programming Model
ASP.NETASP.NET
Application Services
Application Services
Page Framework,
Server Controls
Page Framework,
Server Controls
Microsoft Ajax LibraryMicrosoft Ajax Library
Client Application
Services
Client Application
Services
Component/UIFramework,
Controls
Component/UIFramework,
Controls
BrowserBrowser
PresentationPresentation(HTML/CSS)(HTML/CSS)
PresentationPresentation(HTML/CSS)(HTML/CSS)
ASP.NET ApplicationASP.NET Application
PagesPagesPagesPages
UI BehaviorUI Behavior(Managed(Managed
Code)Code)
UI BehaviorUI Behavior(Managed(Managed
Code)Code)
Input Data
Updated UI + Behavior
Initial Rendering
(UI + Behavior)
Page Request
Client-Centric Programming Model
BrowserBrowser
PresentationPresentation(HTML/CSS)(HTML/CSS)
PresentationPresentation(HTML/CSS)(HTML/CSS)
ServiceServiceProxiesProxies
ServiceServiceProxiesProxies
UI BehaviorUI Behavior(Script)(Script)
UI BehaviorUI Behavior(Script)(Script)
ASP.NETASP.NET
Application Services
Application Services
Page Framework,
Server Controls
Page Framework,
Server Controls
ASP.NET ApplicationASP.NET Application
PagesPagesPagesPages
WebWebServicesServices
WebWebServicesServices
Microsoft Ajax LibraryMicrosoft Ajax Library
Client Application
Services
Client Application
Services
Component/UIFramework,
Controls
Component/UIFramework,
Controls
Initial Rendering
(UI + Behavior)
Data
Data
Page Request
ASP.NET AJAX Extensions
Browser-agnostic but not platform-agnosticSupport programming easily
ScriptManager, UpdatePanel, and othersFamiliar drag-and-drop design paradigm
Built-in Web services provide bridge to key ASP.NET 2.0 application servicesASMX extensions enable Web services to be called through JavaScript proxies
Architecture
ASP.NET 2.0
Page Framework & Server Controls
Page Framework & Server Controls
ApplicationServices
ApplicationServices
ASP.NET AJAX Extensions
ServerControls
ServerControls
ASPXASPX ASMXASMX
Application ServicesBridge
Application ServicesBridge
AsynchronousCommunications
AsynchronousCommunications
Server Asynchronous Communications Layer
Http Handler
Web ServiceWeb Service Page MethodsPage Methods Profile ServicesProfile Services Authentication Service
Authentication Service
Xml Serialization JSON Serialization
Server Asynchronous Communications Layer
Server Controls
UpdatePanelUpdatePanel
Update-Progress
Update-Progress
TimerTimer
DragOverlay-Extender
DragOverlay-ExtenderScriptManagerScriptManager
ScriptManager-Proxy
ScriptManager-Proxy ProfileServiceProfileService
ScriptManagement
Partial-Page Rendering Futures CTP
ScriptManager
Starting point for ASP.NET AJAX pagesWhat does ScriptManager do?
Downloads JavaScript files to clientEnables partial-page rendering using UpdatePanelProvides access to Web services via client-side proxiesManages callback timeouts, provides error handling options and infrastructure, and more
Every page requires one ScriptManager!
ScriptManager Schema
<asp:ScriptManager ID="ScriptManager1" Runat="server" EnablePartialRendering="true|false" EnablePageMethods="true|false" AsyncPostBackTimeout="seconds" AsyncPostBackErrorMessage="message" AllowCustomErrorsRedirect="true|false" OnAsyncPostBackError="handler" EnableScriptGlobalization="true|false" EnableScriptLocalization="true|false" ScriptMode="Auto|Inherit|Debug|Release" ScriptPath="path"> <Scripts> <!-- Declare script references here --> </Scripts> <Services> <!-- Declare Web service references here --> </Services></asp:ScriptManager>
Script References
<asp:ScriptManager ID="ScriptManager1" Runat="server"> <Scripts> <asp:ScriptReference Name="PreviewScript.js" Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference Name="PreviewDragDrop.js" Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference Path="~/Scripts/UIMap.js" /> </Scripts></asp:ScriptManager>
"Path" references load script files
"Name" references load script resources
Service References
<asp:ScriptManager ID="ScriptManager1" Runat="server"> <Services> <asp:ServiceReference Path="WebServiceDemo.asmx " /> </Services></asp:ScriptManager>
ScriptManagerProxy
"Proxy" for ScriptManager controls declared in master pagesLets content pages declare script and service references
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" Runat="server"> <Scripts> <!-- Declare additional script references here --> </Scripts> <Services> <!-- Declare additional service references here --> </Services></asp:ScriptManagerProxy>
UpdatePanel
Partial-page rendering in a boxClean round trips to server and updatesRequires no knowledge of JavaScript or AJAX
Leverages PageRequestManager classEnablePartialRendering="true"
Supports explicitly defined triggersPostbacks from controls in UpdatePanel are converted into async callbacks
UpdatePanel Schema
<asp:ScriptManager ID="ScriptManager1" Runat="server" EnablePartialRendering="true" /> . . .<asp:UpdatePanel ID="UpdatePanel1" Runat="server" UpdateMode="Always|Conditional" ChildrenAsTriggers="true|false"> <Triggers> <!-- Define triggers (if any) here --> </Triggers> <ContentTemplate> <!-- Define content here --> </ContentTemplate></asp:UpdatePanel>
Triggers
AsyncPostBackTriggerConverts postbacks into async callbacksTypically used to trigger updates when controls outside an UpdatePanel post backIf ChildrenAsTriggers="false", can be used to specify which controls inside UpdatePanel should call back rather than post back
PostBackTriggerLets controls inside UpdatePanel post backTypically used to allow certain controls to post back when ChildrenAsTriggers="true"
Triggers Example
<asp:UpdatePanel ID="UpdatePanel1" Runat="server" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" /> <asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="TreeNodeExpanded" /> <asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="TreeNodeCollapsed" /> <asp:PostBackTrigger ControlID="Button2" /> </Triggers> <ContentTemplate> ... </ContentTemplate></asp:UpdatePanel>
Periodic Updates
Combine UpdatePanel with Timer control to perform periodic updatesUse Timer control Tick events as triggers
<asp:Timer ID="Timer1" Runat="server" Interval="5000" OnTick="OnTimerTick" /> ...<asp:UpdatePanel UpdateMode="Conditional" ...> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" /> </Triggers> ...</asp:UpdatePanel>
UpdateProgress
Companion to UpdatePanel controlsDisplays custom template-driven UI for:
Indicating that an async update is in progressCanceling an async update that is in progress
Automatically displayed when update begins or "DisplayAfter" interval elapses
UpdateProgress Schema
<asp:UpdateProgress ID="UpdateProgress1" Runat="server" DisplayAfter="milliseconds" DynamicLayout="true|false" AssociatedUpdatePanelID="UpdatePanelID"> <ProgressTemplate> <!-- Declare UpdateProgress UI here --> </ProgressTemplate></asp:UpdateProgress>
UpdateProgress Example
<asp:UpdateProgress DisplayAfter="500" ...> <ProgressTemplate> <asp:Image ID="ProgressImage" Runat="server" ImageUrl="~/Images/SpinningClock.gif" /> </ProgressTemplate></asp:UpdateProgress>
Animated GIF
Display after ½ second
Canceling an Update
<asp:UpdateProgress DisplayAfter="500" ...> <ProgressTemplate> <b>Working...</b> <asp:Button ID="CancelButton" Runat="server" Text="Cancel" OnClientClick="cancelUpdate(); return false" /> </ProgressTemplate></asp:UpdateProgress>
<script type="text/javascript">function cancelUpdate(){ var obj = Sys.WebForms.PageRequestManager.getInstance(); if (obj.get_isInAsyncPostBack()) obj.abortPostBack();}</script>
ASP.NET AJAX Web Services
ASP.NET AJAX supports ASMX Web methods as endpoints for asynchronous AJAX callbacks
Efficient on the wire (no SOAP or XML)Efficient on the server (no page lifecycle)
ScriptService attribute on server indicates Web service is callable from scriptJavaScript proxy on client enables JavaScript clients to call Web methods
Script-Callable Web Service[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]public class WebServiceDemo : System.Web.Services.WebService { [WebMethod] public string HelloWorld(string message) { return (message + " : " + DateTime.Now.ToLongTimeString()); } }
Declaring a Service Reference<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services> <asp:ServiceReference Path="~/WebServiceDemo.asmx" /> </Services></asp:ScriptManager>
<script src="WebServiceDemo.asmx/js" type="text/javascript"></script>
<script src="WebServiceDemo.asmx/js" type="text/javascript"></script>
Consuming a Web Service
function GetResult(){
var content = $get('location').value; WebServiceDemo.HelloWorld(content, OnSuccess, OnFailure); } function OnSuccess(result, context, methodName){
$get('result').innerHTML = result;}
Handling Errors
function GetResult() { var content = $get('location').value; WebServiceDemo.HelloWorld(content, OnSuccess, OnFailure); } function OnSuccess(result, context, methodName) { $get('result').innerHTML = result; } function OnFailure(error, context, methodName) { var errorMessage = error.get_message(); $get('result').innerHTML = errorMessage; }
Page Methods
Script-callable Web methods in pagesSimpler than Web services
Do not require service referencesDo not require dedicated ASMX files
Must be public static methodsMust be enabled via ScriptManager.-EnablePageMethods (disabled by default)Called through PageMethods proxy on client
Enabling Page Methods
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" Runat="server" />
Defining a Page Method
public partial class PageMethodDemo: System.Web.UI.Page{
... [WebMethod] public static string HelloWorld(string message) { return (message + " : " + DateTime.Now.ToLongTimeString()); }
...}
function GetResult() { var content = $get('location').value; PageMethods.HelloWorld(content, OnSuccess, OnFailure); } function OnSuccess(result, context, methodName) { $get('result').innerHTML = result; } function OnFailure(error, context, methodName) { var errorMessage = error.get_message(); $get('result').innerHTML = errorMessage; }
Calling a Page Method
Built-In Web Services
AuthenticationServiceFront end to membership serviceSys.Services.AuthenticationService proxy
Global instance of Sys.Services._AuthenticationService
ProfileServiceFront-end to profile serviceSys.Services.Profile proxy
Global instance of Sys.Services._ProfileService
Accessed through ScriptHandlerFactory
Microsoft AJAX Library
Client half of ASP.NET AJAXBrowser-agnostic and platform-agnostic
Internet Explorer, Firefox, Opera, Safari, etc.Leverage it from PHP and other platforms
Enhances JavaScript with type systemNamespaces, classes, interfaces, etc.
Packaged in *.js files downloaded to clients
Microsoft AJAX Library
Architecture
Browsers (IE, Firefox, Safari, others)
Browser CompatibilityBrowser Compatibility
Asynchronous CommunicationsAsynchronous Communications
Script Core LibraryScript Core Library
Base Class LibraryBase Class Library
XHTML/CSS Server Scripts
Client Asynchronous Communications Layer
WebRequestManager
JSONSerializer
JSONSerializer
Web ServiceProxies
Web ServiceProxies
WebRequest
Page MethodsProxies
Page MethodsProxies Profile
Proxies
ProfileProxies
AuthenticateProxies
AuthenticateProxies
XmlHttpExecutor
XmlHttp
Client Asynchronous Communications Layer
Client-Server Communication
BrowserBrowser
PresentationPresentation(HTML/CSS)(HTML/CSS)
PresentationPresentation(HTML/CSS)(HTML/CSS)
ServiceServiceProxiesProxies
ServiceServiceProxiesProxies
UI BehaviorUI Behavior(Script)(Script)
UI BehaviorUI Behavior(Script)(Script)
ASP.NET ApplicationASP.NET Application
PagesPagesPagesPages
WebWebServicesServices
WebWebServicesServices
Initial Rendering
(UI + Behavior)
Data
Data
Page RequestC
lien
t A
syn
chro
no
us
Co
mm
un
icat
ion
Clie
nt
Asy
nch
ron
ou
s C
om
mu
nic
atio
n
Ser
ver
Asy
nch
ron
ou
s C
om
mu
nic
atio
n
Ser
ver
Asy
nch
ron
ou
s C
om
mu
nic
atio
n
Global Functions
Helper functions for use anywhereUsed in JavaScript emitted by controls
Function Description
$create Creates and initializes a component
$find Retrieves the component with the specified ID
$get Retrieves the DOM element with the specified ID
$addHandler(s) Registers handlers for DOM event(s)
$removeHandler Unregisters a handler for a DOM event
$clearHandlers Unregisters handlers for DOM events
Base Type Extensions
Microsoft AJAX Library extends the following JavaScript types
Array - add, addRange, contains, insert, etc.Boolean - parseDate - format, parselocale, parseInvariant, etc.Error - argumentOutOfRange, etc.Number - format, parseLocale, parseInvariantObject - getType, getTypeNameString - format, endsWith, startWith, trim, etc.
Adding OOP to JavaScript
Object-based but not object-orientedMicrosoft AJAX Library adds OOP to JavaScript
NamespacesClasses and inheritanceInterfaces and enumerated types
prototype property forms basis for "classes"Type class provides typing and type reflection
JavaScript "Classes"
Person = function(name) { this._name = name;}
Person.prototype = { get_name: function() { return this._name; }
// Declare other class methods here}
Type Class
Adds typing and reflection to JavaScriptAdds key instance methods to all types
registerClass, registerInterfaceinitializeBase, getBaseTypegetBaseMethod, callBaseMethod, and others
Implements key "static" methodsregisterNamespaceisNamespace, isClass, isInterface, and others
Implemented in MicrosoftAjax.js
Registering Namespaces and Classes
Type.registerNamespace(‘MyNameSpace'); MyNameSpace.Person = function(name) { this._name = name;}
MyNameSpace.Person.prototype = { get_name: function() { return this._name; }}
MyNameSpace.Person.registerClass('MyNameSpace.Person');
Using MyNameSpace.Personvar p = new MyNameSpace.Person(‘A');
// Displays “A"window.alert(p.get_name());
// Displays " MyNameSpace.Person"window.alert(Object.getTypeName(p));
JavaScript Files
MicrosoftAjaxTimer.jsMicrosoftAjaxTimer.js
PreviewWebForms.jsPreviewWebForms.js
PreviewScript.jsPreviewScript.js
PreviewGlitz.jsPreviewGlitz.js
PreviewDragDrop.jsPreviewDragDrop.js
MicrosoftAjax.jsMicrosoftAjax.js
Partial-page rendering
Base Class Library(controls, XML script, etc.)
UI enhancements(animation and opacity)
Drag-and-drop
Script Core Library(run-time + framework)
Sys.UI._Timer class
InternetExplorer
Firefox
Safari
Other
MicrosoftAjax.js
String-Builder
String-Builder
Sys
WebRequest-Executor
WebRequest-Executor
Sys.Net
_ProfileService_ProfileService
Sys.Services
JavaScript-Serializer
JavaScript-Serializer
Sys.Serialization
DOMElementDOMElement
Sys.UI
_Debug_Debug
EventArgsEventArgs
ComponentComponent
_Application_Application
XMLHttp-EXecutor
XMLHttp-EXecutor
_WebRequest-Manager
_WebRequest-Manager
WebRequestWebRequest
WebService-Proxy
WebService-Proxy
WebService-Error
WebService-Error
OtherOther
ProfileGroupProfileGroup
_Authentication-Service
_Authentication-Service
DOMEventDOMEvent
BehaviorBehavior
ControlControl
PointPoint
BoundsBounds
_Timer_Timer
CultureInfoCultureInfo
OtherOther
StringBuilder
var sb = new Sys.StringBuilder();
for (var i = 1; i <= 100; i++){ sb.append(i); // Count from 1 to 100 sb.append('<br/>');}
var text = sb.toString(); // Get the results
PreviewWebForms.js
Partial-page rendering supportPageRequestManager class
Client-side counterpart to UpdatePanelManages async callbacks used for partial-page rendering and performs content updates using resultsClient-side OM enables advanced UpdatePanel customizations not possible from server side
_UpdateProgress class
PageRequestManager Methods
Provide programmatic control over client-side PageRequestManager
Method Description
get_isInAsyncPostBack Indicates whether async callback is in progress
getInstance Returns reference to current PageRequestManager instance
abortPostBack Cancel the async callback that is currently in progress
add_* Registers handlers for PageRequestManager events
remove_* Deregisters handlers for PageRequestManager events
PageRequestManager Events
PageRequestManager fires eventsHook events on client for advanced customizations
Event Description
initializeRequest Fired before async callback commences
beginRequest Fired when async callback commences
pageLoading Fired following an async callback (before content is updated)
pageLoaded Fired following a postback or callback (after content is updated)
endRequest Fired when async callback completes
PreviewScript.js
BindingBaseBindingBase
Sys.Preview Sys.Preview.UI
DataControlDataControl
Sys.Preview.Data
DataColumnDataColumn
Sys.Preview.UI.Data
ServiceMethod-Request
ServiceMethod-Request
OtherNamespaces
BindingBinding
ActionAction
InvokeMethod-Action
InvokeMethod-Action
SetProperty-Action
SetProperty-Action
ColorColor
ValidatorValidator
LabelLabel
ButtonButton
CheckBoxCheckBox
DataNavigatorDataNavigator
ItemViewItemView
ProfileProfile
TimerTimer
CounterCounter
OtherOther
TextBoxTextBox
SelectorSelector
OtherOther
ListViewListView
XSLTViewXSLTView
OtherOther
DataRowDataRow
DataTableDataTable
DataViewDataView
DataFilterDataFilter
DataSourceDataSource
OtherOther
OtherOther
Sys.Preview.UI
Classes that abstract HTML control elements
Button, Label, TextBox, Selector, etc.
Base functionality defined in Sys.UI.Control
get_visible, set_visibleget_parent, set_parentAnd so on
Control classes simplify JavaScript and facilitate browser independence
Using Control Classes
<input type="text" id="Input" /> <input type="button" id="MyButton" value="Click Me" /> <span id="Output" /> ...<script type="text/javascript">var g_textBox;var g_label;
function pageLoad() { g_textBox = new Sys.Preview.UI.TextBox($get('Input')); var button = new Sys.Preview.UI.Button($get('MyButton')); g_label = new Sys.Preview.UI.Label($get('Output')); button.initialize(); button.add_click(onClick);}
function onClick(){ g_label.set_text(g_textBox.get_text());}</script>
Sys.Preview.[UI.].Data
Contains classes that support rich client-side data bindingItemView and ListView do client-side renderingDataSource links data consumers to data service and supports 2-way data binding
DataControlDataControl
Sys.Preview.Data
DataColumnDataColumn
Sys.Preview.UI.Data
DataNavigatorDataNavigator
ItemViewItemView
ListViewListView
XSLTViewXSLTView
OtherOther
DataRowDataRow
DataTableDataTable
DataViewDataView
DataFilterDataFilter
DataSourceDataSource
OtherOther
PreviewDragDrop.js
Adds drag-drop support to BCL_DragDropManager provides core support
Global instance named DragDropManager
IDropSource and IDropTarget interfaces define signatures for drop-source and drop-target classesFloatingBehavior provides generic mechanism for floating images, DIVs, and other entities
Floating an Image
<img id="FloatMe" src="..."> ...<script type="text/javascript">function pageLoad(){ var float = new Sys.Preview.UI.FloatingBehavior ($get('FloatMe')); float.set_handle($get('FloatMe')); float.initialize();}</script>
PreviewGlitz.js
Adds UI enhancements to BCLOpacityBehavior class wraps opacityLayoutBehavior class wraps layoutAnimation and derivatives support animations
Property-Animation
Property-Animation
Interpolated-Animation
Interpolated-Animation
Discrete-Animation
Discrete-Animation
Number-Animation
Number-Animation
Length-Animation
Length-Animation
Composite-Animation
Composite-Animation
Fade-Animation
Fade-Animation
Fading In an Image
<img id="SplashImage" src="..."> ...<script type="text/javascript">function pageLoad(){ var image = new Sys.Preview.UI.Image ($get('SplashImage')); var fade = new Sys.Preview.UI.Effects.FadeAnimation(); fade.set_target(image); fade.set_effect (Sys.Preview.UI.Effects.FadeEffect.FadeIn); fade.set_duration(3); fade.set_fps(20); fade.play();}</script>