Sunteți pe pagina 1din 34

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

Browser submits HTTP request to server

Server responds with content; browser renders that content

Browser

Browser submits async XMLHTTP request to server; UI remains responsive; page doesn't flash

Web Server

XML-HTTP request completes; JavaScript refreshes portion of page affected by response

Time Taken During The Data Transmission Client Sitting ideal.

Client making request To JAVASCRIPT Not Server. User may continue to work.

Server Responding to JAVASCRIPT Asynchronous. JAVASCRIPT updating client.

XmlHttpRequest

Introduced in 1999 with Internet Explorer 5


ActiveX object supporting 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/

Supported 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 passed to request object by assigning 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: Pass here true/false (true if asynch else false). username: User name, if authentication required; password: Password, 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 Pass 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); } </script>

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
Controls, Components Component Model and UI Framework Base Class Library ASP.NET AJAX Server Controls

ASP.NET AJAX Server Extensions


App Services Bridge Web Services Bridge

Client Application Services


Browser Integration

ASP.NET 2.0
Script Core Browser Compatibility Page, Framework, Server controls Application Services

Client Framework & Services

Server Framework

Client
XHTML/CSS Server Scripts ASPX

Server
ASMX

Microsoft AJAX Library


Base Class Library Script Core Library Asynchronous Communications

ASP.NET AJAX Extensions


AJAX Server Controls Application Services Bridge 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

Server controls abstract Microsoft AJAX Library

Browser-agnostic but not platform-agnostic

Built-in Web services provide bridge to app services ASMX extensions and JSON serializer enable Web services to be called through JavaScript proxies

ScriptManager, UpdatePanel, and others Emit content that leverages the client-side framework Familiar drag-and-drop design paradigm

Script Management
ScriptManager ScriptManagerProxy

Partial Rendering
UpdatePanel

Extenders
AutoCompleteExtender DragOverlayExtender

Service Wrappers
ProfileScript

UpdateProgress

Timer

ScriptManager- One per page to support AJAX features ScriptManagerProxy - Use when a .master contains a ScriptManager already UpdatePanel - 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: <asp:scriptmanager id=ScMngr runat=server EnablePartialRendering="true"></ asp:scriptmanager>

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 Upside: Extremely easy to use, widely applicable Downside: Not as efficient as hand-coded AJAX

High-level abstraction of XmlHttpRequest and AJAX

Exemplifies value added by AJAX frameworks A control that causes an asynchronous postback is referred to as a trigger
<asp:ScriptManager ID="..." Runat="server" EnablePartialRendering="true" /> . . <asp:UpdatePanel ID="..." Runat="server"> <Triggers> <!-- Define triggers (if any) here --> </Triggers> <ContentTemplate> <!-- Define content here --> </ContentTemplate> </asp:UpdatePanel>

You write this:


<asp:ScriptManager ID="MyScriptManager" Runat="server" />

ScriptManager emits this:

Oblique reference to script file

<script src="/.../WebResource.axd?d=iQ15p6LHcT2T5QE..." type="text/javascript"></script>

Controlling what gets downloaded.


<asp:ScriptManager ID="..." Runat="server"> <Scripts> <asp:ScriptReference
Name="Microsoft.Web.Resources.ScriptLibrary.PreviewScript.js"

Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference


Name="Microsoft.Web.Resources.ScriptLibrary.PreviewDragDrop.js"

Assembly="Microsoft.Web.Preview" /> <asp:ScriptReference Path="~/Scripts/UIMap.js" /> </Scripts> </asp:ScriptManager>

UpdateProgress

Provides visual feedback in the browser when the content of UpdatePanel controls is updated. Associate an UpdateProgress control with an UpdatePanel control by setting the AssociatedUpdatePanelID property of

the UpdateProgress control

Timer

<asp:UpdateProgress ID="UpdateProgress1" runat="server"> <ProgressTemplate> Please wait </ProgressTemplate> </asp:UpdateProgress>

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 updatepanel control. <asp:Timer ID="Timer1" runat="server">

</asp:Timer>

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 UpdatePanel 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 UpdatePanel 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.
Raised before the request is initialized for an asynchronous postback Raised just before the asynchronous postback is sent to the server Raised after the response to the most recent asynchronous postback has been received but before any updates to the page have been made.
Raised after page regions are updated after the most recent postback Raised when request processing is finished

initializeRequest
beginRequest pageLoading

pageLoaded endRequest

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. Using Update Panel Progress Bar Binding with Update Panel Drag a Panel over the screen AutoCompleteExtender Using ASP.NET AJAX Tab Control

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <%@ Register 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 <cc1:MyExtender runat=server this._myStringPropValue = null; = 0; { this._myStringIntValue MyExtender ex1 = new MyExtender(); TargetControlID=TextBox1 } [ExtenderProperty]= Hello; ex1.MyStringProp MyStringProp=Hello MyProject.MyBehavior.prototype = { public string MyStringProp{} ex1.MyIntProp MyIntProp=23 initialize function() { }, = 23; get_MyStringProp : function(){}, ex1.TargetControlID = TextBox1; </cc1:MyExtender> 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 download 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/download.aspx

Thank you!

S-ar putea să vă placă și