Training Programme ( Zed-Axis Technologies Pvt. Ltd. )
Introducing the
Advanced Ajax And Ajax.Net Control Toolkit for Asp.NET
By:
Praveen Kumar
Introduction Client Server Architecture AJAX(Asynchronous JavaScript and XML)
AJAX = JAVASCRIPT+HTML+DHTML+DOM+CSS+XML What is AJAX, and why do we care? The XmlHttpRequest revolution
Look up at ASP.NET AJAX and Control Toolkit
Agenda Understanding AJAX & XmlHttpRequest Understanding ASP.NET AJAX ASP.NET AJAX Architecture ASP.NET AJAX Client Life-Cycle events ASP.NET 2.0 AJAX Extensions ASP.NET AJAX Control Toolkit Anatomy of Toolkit Component
Client Server Architecture
Asynchronous JavaScript And XML = is a web development technique for creating responsive web applications by exchanging small amounts of data with the server behind the scenes
Overview of AJAX
1
Browser submits HTTP request to server
2
Server responds with content; browser renders that content
3
Browser
4
Browser submits async XMLHTTP request to server; UI remains responsive; page doesn't flash
XML-HTTP request completes; JavaScript refreshes portion of page affected by response
Web Server
Time Taken During The Data Transmission Client Sitting ideal.
Client making request To JAVASCRIPT Not Server. may continue to work.
Server Responding to JAVASCRIPT Asynchronous. JAVASCRIPT updating client.
XmlHttpRequest
Introduced in 1999 with Internet Explorer 5 – ActiveX object ing callbacks to Web server – Created for benefit of Outlook Web Access (OWA)
Later adopted by Firefox, Safari, and others – Implemented as native object rather than ActiveX – Currently being standardized by W3C
http://www.w3.org/TR/XMLHttpRequest/
ed by approx. 99% of browsers used today – Approx. 85%-95% have JavaScript enabled
Object Instantiation. function getobject(){ var reqst = false; try{ reqst = new XMLHttpRequest(); } catch(msnew){ try{ reqst = new ActiveXObject(“Msxml2.XMLHTTP”); } catch(msother){ try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } }}}
Methods :
open(); Sets up a new request to a server. send(); Send a request on server. readystate; provides current request State. responseText; The text server send back by server. responseXML; The Server generated XML response.
ReadyState :
0: The request is uninitialized (before call open()). 1: The request is set up, but not sent (before call send()). 2: The request was sent and is in process. 3: The request is in process; 4: The response is complete; you can get the server's response and use it. Call Back method is ed to request object by asg the onreadystatechange=“function()”
Open Method : The request open method takes following Args. request-type: The type of request to send (Get,Post). url: The URL to connect to. asynch: here true/false (true if asynch else false). name: name, if authentication required; : , if authentication required. For Example : – open(“GET”,”/myserver/abc.aspx?p1=” + p1,true); – open(“POST”,”/myserver/abc.aspx”,true);
Send Method : The parameter for send method is the data in case of data sent true post method – send(vname);
– Else null – send(null);
Demo Create Request <script language="javascript" type="text/javascript"> var request = false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; }}} if (!request) alert("Error initializing XMLHttpRequest!"); function getCustomerInfo() { var phone = document.getElementById("phone").value; var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone); }
Open Request function getCustomerInfo() { var phone = document.getElementById("phone").value; var url = "/local/lookupCustomer.aspx?phone=" + escape(phone); request.open("GET", url, true); }
Set Callback and Send function getCustomerInfo() { var phone = document.getElementById("phone").value; var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone); request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null);
}
When to process Request •Do processing of call back method when: •Readystate =4; •Status = 200; Example: -------------------------------------------------------------------------------------------------function updatePage() { function updatePage() { if (request.readyState == 4) { if (request.status == 200) // Do Request Processing var xmlDoc = request.responseXML; // if response in XML var txtDoc = request.responseText; // if response in Text } else if (request.status == 404) alert("Request URL does not exist"); else alert("Error: status code is " + request.status); }
if (request.readyState == 4) { if (request.status == 200) {
} } }
var xmlDoc = request.responseXML; var showElements = xmlDoc. getElementsByTagName("show"); // The very first element in XML Document for (var x=0; x<showElements.length; x++) { var title = showElements[x]. childNodes[0].value; var rating = showElements[x]. childNodes[1].value; }
Important HTTP Status Codes
200 301 302 305 400 401 403 404 408 500
(OK, Request Processed Successfully and Responded.) (Moved Permanently) (Found and Redirected to some other URL) (the request must use a proxy to access the resource requested) (Bad Request) (Unauthorized) (Forbidden) (Not Found) (Request Time Out) (Internal server Errors)
Demo Code – Asynchronous Binding of dropdown control
ASP.NET AJAX
Framework for building AJAX-enabled Web apps – Cross-platform, browser-agnostic – Increased productivity, less time to market – Highly extensible
Two major components
– Microsoft AJAX Library (client-side framework) – ASP.NET 2.0 AJAX Extensions (server-side framework)
Tightly integrated with ASP.NET 2.0 on server
Familiar UI elements such as progress indicators, tool tips, and pop-up windows. A framework that simplifies customization of server controls to include client capabilities.
ASP.NET AJAX Architecture Client Script Library
ASP.NET AJAX Server Extensions
Controls, Components Component Model and UI Framework
ASP.NET AJAX Server Controls
App Services Bridge Web Services Bridge
Base Class Library
Client Application Services
ASP.NET 2.0 Script Core
Browser Integration
Browser Compatibility
Client Framework & Services
Page, Framework, Server controls
Application Services
Server Framework
Client XHTML/CSS
Server Scripts
Microsoft AJAX Library
Server ASPX
ASP.NET AJAX Extensions
Base Class Library Script Core Library
ASMX
AJAX Server Controls
Application Services Bridge Asynchronous Communications
Asynchronous Communications
ASP.NET 2.0 Browser Compatibility Browsers (IE, Firefox, Safari, others)
Page Framework and Server Controls
Application Services
The ASP.NET AJAX Library JavaScript Framework
Object oriented framework build on JavaScript Provides automatic cross-browser compatibility layer Built-in classes for WebService calls, Type system, basic DOM operations Allows structured programming and encapsulation No more sprinkling JavaScript around your site!
ASP.NET 2.0 AJAX Extensions
Server half of ASP.NET AJAX
– Browser-agnostic but not platform-agnostic
Server controls abstract Microsoft AJAX Library
– ScriptManager, Update, and others – Emit content that leverages the client-side framework – Familiar drag-and-drop design paradigm
Built-in Web services provide bridge to app services ASMX extensions and JSON serializer enable Web services to be called through JavaScript proxies
Script Management
Partial Rendering
Extenders
Service Wrappers
ScriptManager
Update
AutoCompleteExtender
ProfileScript
ScriptManagerProxy
UpdateProgress
DragOverlayExtender
Timer
ScriptManager- One per page to AJAX features ScriptManagerProxy - Use when a .master contains a ScriptManager already Update - Allows partial-page updates Timer - Raises event at regular interval UpdateProgress - Send progress messages back to page
“ScriptManager” is mandatory to available on page Ajax features Which includes: – – – –
Include Asp.Net Ajax Client Script Library. Allow partial page rendering/updating. Include Java script proxy classes for web services. Include Java script classes to access ASP.NET authentication and profile application services.
To enable partial page update set EnablePartialRendering=“true” of “ScriptManager” control. Only one instance of the ScriptManager control can be added to the page. Syntax:
The "crown jewel" of ASP.NET AJAX Adds partial rendering to pages and controls – Automatically converts postbacks into async callbacks – Automatically updates content using callback results – Requires no knowledge of JavaScript or XmlHttpRequest
High-level abstraction of XmlHttpRequest and AJAX – Upside: Extremely easy to use, widely applicable – Downside: Not as efficient as hand-coded AJAX
Exemplifies value added by AJAX frameworks A control that causes an asynchronous postback is referred to as a trigger
. .
You write this:
ScriptManager emits this:
Oblique reference to script file
<script src="/.../WebResource.axd?d=iQ15p6LHcT2T5QE..." type="text/javascript">
Controlling what gets ed.
<Scripts>
Assembly="Microsoft.Web.Preview" / rel="nofollow">
Assembly="Microsoft.Web.Preview" / rel="nofollow">
UpdateProgress
Provides visual in the browser when the content of Update controls is updated. Associate an UpdateProgress control with an Update control by setting the AssociatedUpdateID property of
.
the UpdateProgress control
Timer
Please wait…
The Timer control performs postbacks at defined intervals.
The Timer control performs automated postbacks at defined intervals. The JavaScript component initiates the postback from the browser when the interval that is defined in the Interval property has elapsed. The Interval property is defined in milliseconds and has a default value of 60,000 milliseconds, or 60 seconds. When a postback was initiated by the Timer control, the Timer control raises the Tick event on the server. Used with update control.
Client Life-Cycle events
The two main Microsoft AJAX Library classes that raise events during the client lifecycle of a page are the Application and PageRequestManager classes.
The key event for initial requests (GET requests) and synchronous postbacks is the load event of the Application instance. When script in a load event handler runs, all scripts and components have been loaded and are available.
When partial-page rendering with Update controls is enabled, the key client events are the events of the PageRequestManager class. These events enable you to handle many common scenarios. These include the ability to cancel postbacks, to give precedence to one postback over another, and to animate Update controls when their content is refreshed.
PageRequestManager Class
The “Microsoft AJAX Library” manages partial-page updates in the Browser. Exposes properties, methods, and events that enables customize partial-page updates with client script. Use When Required to control: -
– How multiple asynchronous postbacks are processed. – Display status messages during asynchronous postbacks and opportunity to cancel the processing. – Provide custom error-message handling for partial-page updates. – Access the underlying request and response objects that are used for the asynchronous postbacks.
initializeRequest
Raised before the request is initialized for an asynchronous postback
beginRequest
Raised just before the asynchronous postback is sent to the server
pageLoading
Raised after the response to the most recent asynchronous postback has been received but before any updates to the page have been made.
pageLoaded
Raised after page regions are updated after the most recent postback
endRequest
Raised when request processing is finished
ASP.NET AJAX Control Toolkit
More ASP.NET AJAX server controls, plus SDK for control development Community-owned, community-driven, shared source Most of toolkit controls are extender controls An extender is a control which extends the functionality of another control
Toolkit Controls Overview AJAX Control Toolkit in the Toolbox
How to add it to the Toolbox – Right-click, Add Tab…, AJAX Control Toolkit – Right-click, Choose Items…, AjaxControlToolkit.dll
First time a control is added, DLL is copied into Bin folder – Optional: rename TagPrefix to "ajax"
Most of the new controls are Extenders – Set the TargetControlID on the extender control – Set the Extender properties on the target control
Demo: ConfirmButtonExtender
ASP.NET AJAX Techniques & Practices 1. 2. 3. 4. 5.
Udate Progress Bar Binding with Update Drag a over the screen AutoCompleteExtender Using ASP.NET AJAX Tab Control
<%@ Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <%@ Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>
More about Behaviors and Extenders in ASP.NET AJAX
Behaviors – Add or modify functionality to an element on the page – Written in JavaScript – Modify the HTML DOM Extenders – ASP.NET components – Associate an ASP.NET Control with a Behavior – Leverage Server-Side and Design Time
Creating A Toolkit Component
Two types of components in the Toolkit – Behavior + Extender – “ASP.NET AJAX-aware” Control (ScriptControl) Which to choose? – If required HTML shape is very specific, write a control and then attach behaviors to it – If HTML shape is simple or common, write an extender
Anatomy of a Toolkit Component The Extender The Behavior [ClientScript(“…”)] The Markup [TargetControlType(typeof(Control))] MyProject.MyBehavior = function(e) { The Code MyProject.MyBehavior.initializeBase(this, [e]); public class MyExtender : ExtenderControlBase
set_MyStringProp : function(value){}, [ExtenderProperty] Page.Add(ex1); public int MyIntProp{} get_MyIntProp : function(){}, }
set_MyIntProp : function(value){} }
Creating an Extender Project
Toolkit package has Visual Studio templates for: • Toolkit-enabled website • • •
Toolkit component project Toolkit Components VB & C# for each
Summary / Call to Action
AJAX = Asynchronous JavaScript and XML – Better, richer, and more interactive Web apps
ASP.NET AJAX = Framework for AJAX development – Microsoft AJAX Library (client-side framework) – ASP.NET 2.0 AJAX Extensions (server-side framework)
ASP.NET AJAX is… – Compact and well factored (minimal size) – Compatible with a wide range of browsers – Compatible with PHP, ColdFusion, and other platforms
ASP.NET AJAX is the future
Resources
AJAX Wikipedia entry – http://en.wikipedia.org/wiki/AJAX
ASP.NET AJAX Web sites – http://ajax.asp.net – http://ajax.asp.net/ajaxtoolkit
– www.ajaxwebwidgets.com – http://www.asp.net/AJAX – http://forums.asp.net/default.aspx?GroupID=34 – http://asp.net/AJAX/Documentation/Live/ClientReference/
Scott Guthrie's blog – http://weblogs.asp.net/scottgu/
Lecture Demos/Workshop – http://cds.fhcrc.org/.aspx
Thank you!