70-562 - Ajax Client Library

Filed under: , , , , by:

70-562 exam covers Ajax and I can tell that more and more developers take advantage of Ajax. However, still I notice that a lot of times Ajax for a developer means UpdatePanel, UpdateProgress, Timers + AjaxToolkit. Ajax is a lot more than that - it is also Ajax client library, without which more complex solutions wouldn't be possible. Even book Professional ASP.NET 3.5: In C# and VB (Programmer to Programmer) in chapter about Ajax doesn't mention Ajax client library. There's a lot of books about Ajax that does pretty good job describing ajax client library but a lot of developers usually get books like forementioned one rather than 5 seperate ones (ASP.NET, Ajax, WCF, Security, etc.). So this post will describe most common classes, events and properties that each developer, who uses Ajax, must know.
All ajax client classes come from System.Web.Extensions.dll. Most common are Sys.Application, Sys.WebForms.PageRequestManager, Sys.Debug, Sys.Component, Sys.UI.DomElement.
1. Sys.Application - is used mostly for its events, from which more often used are Init, Load and Unload. To utilize those events you put in javascript ie. Sys.Application.add_load(_pageLoadHandler) or Sys.Application.add_init(_pageInitHandler).
2. Sys.WebForms.PageRequestManager - this class managed every partial postback on client side, therefore it's the most often used object by developers. It offers a lot of properties, methods and events. Most common events are:
a) initializeRequest - the first event raised during the partial postback life-cycle. Mostly used to determine the HTML element that triggered the postback, cancel the current postback or abort already executed asynchronous postback.
b) beginRequest - this event is raised just before the request is sent to the server. The UpdateProgress control uses this event to displayed its output.
c) pageLoaded - raised when page being refreshed. It has access to updatepanels being deleted or updated. In this event you put animations that an update has arrived.
d) endRequest - completion of partial postback. The UpdateProgress control uses this event to displayed its output. Also any errors during postback are avaiable here.
And methods are:
a) get_isInAsyncPostBack() - this method gets a boolean value if there are any asynchronous postbacks that are still being processed (besides the current). In this way a current postback can be cancelled to wait for previous postback to finish.
b) abortPostBack() - this aborts current and other postbacks that are still being processed. Mostly used to cancel long-running operation.
But besides those methods there are arguments that are passed to events (initializeRequest, endRequest, etc.) that gives access to other methods:
a) args.get_postBackElement() - gets an element that caused the current postback
b) args.set_cancel(true) - cancels the current postback and let previous ones to finish
c) args.get_error() - to get an error if occurred during request (available in endRequest)
d) args.set_errorHandled(true) - informs that our code handled the error
e) args.get_dataItems() - gets data that was registered ScriptManager.RegisterDataItem, which is used when registered item is not part of asynchronous postback (ie. it's not inside UpdatePanel) but it should be updated as well during asynchronous postback.
3. Sys.Debug - it offers methods to help debugging a client-side code. Most common methods are:
a) trace(message) - it shows a message in debugger's output
b) traceDump(object,message) - it shows message in debugger's output plus information on an object (usually control)
c) fail (message) - it breaks into debugger so it should be used to catch developer errors.
4. Sys.Component - base class for all components and non-visual controls on the page. It is used mostly to create a component with static method Sys.Component.create or $create.
5. Sys.UI.DomElement - provides helper methods for manipulating DOM elements. Most common methods are:
a) getElementById or $get(id) - it retrieves an element with given id. It can also return a component, however to return a component $find(id) should be used.
b) setVisible(element,true/false) - makes an element visible or invisible
Examples:
1. Page with 2 buttons - btnCancel and btnRun and Label lblStatus. When user clicks btnRun a long-running operation takes place. We want to able to cancel that operation by clicking btnCancel (but only when there is a running operation) and to be able to ignore another call when user clicks again btnRun when a previous one is still running. Here is a java script that would perform those operations:

<script type="text/javascript">
var mgr=Sys.WebForms.PageRequestManager.getInstance();
var el;
var isPostBack;
mgr.add_initializeRequest(initHandler);
mgr.add_endRequest(endHandler);
function initHandler(sender,args)
{
el=args.get_postBackElement();
isPostBack=mgr.get_isInAsyncPostBack();
if (mgr.get_isInAsyncPostBack())
{
if (el.name=="btnCancel")
{
mgr.abortPostBack();
return;
}
if (el.name=="btnRun")
{
$get("lblStatus").innerText='Your request is still being processed';
args.set_cancel(true);
return;
}
}
else
{
if (el.name=="btnRun")
$get("lblStatus").innerText='Processing your request';
}
}
function endHandler(sender,args)
{
if (args.get_error()!=null)
{ 
args.set_errorHandled=true;
$get("lblStatus").innerText=args.get_error().message;
}
else
{
if (el.name=="btnRun") 
$get("lblStatus").innerText='Finished';
else
if (el.name=="btnCancel" && isPostBack )
$get("lblStatus").innerText='Your request has been cancelled';
}
}
</script>
2. This example shows how to create modal popup window with UpdateProgress panel. Also in this example you can see how to change a message in popup window (precisely in UpdateProgress template) based on the button that triggered the postback. I have seen so many times applications with generic message: Please Wait....Wouldn't it be better to show a user a little more informative message like: Retrieving list of customers or Saving user settings in the database? This simple example shows a way to do it:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MainPage" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Modal Popup Window</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<script type="text/javascript" language="javascript">
var ModalProgress = '<%= ModalProgress.ClientID %>';    
var mgr = Sys.WebForms.PageRequestManager.getInstance();
mgr.add_initializeRequest(InitRequest);
mgr.add_beginRequest(beginReqest);
mgr.add_endRequest(endReqest);
function InitRequest(sender, args) 
{
var el = args.get_postBackElement();
if (el.name == "btnOrder")
$get("lblProcessing").innerText = ' Retrieving orders...';
else
if (el.name == "btnCustomer")
$get("lblProcessing").innerText = ' Retrieving customers...';
else
$get("lblProcessing").innerText = ' Processing request...';
}
function beginReqest(sender, args) 
{
$find(ModalProgress).show();
}
function endReqest(sender, args) 
{
$find(ModalProgress).hide();
}     
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Panel ID="panelUpdateProgress" runat="server" 
CssClass="ProgressPanel">
<asp:UpdateProgress ID="UpdateProg1" DisplayAfter="0" runat="server">
<ProgressTemplate>
<div style="position: relative; top: 35%; text-align: center;">
<img src="loading.gif" style="vertical-align: middle" 
alt="Processing" />
<asp:Label ID="lblProcessing" runat="server" 
Text="Processing"></asp:Label>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender ID="ModalProgress" runat="server" 
TargetControlID="panelUpdateProgress"
BackgroundCssClass="Background" PopupControlID="panelUpdateProgress" />
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="Get Orders" ID="btnOrder"
OnClick="btnOrder_Click" Width="100px" />
<asp:Button runat="server" Text="Get Customers" ID="btnCustomer" 
OnClick="btnCustomer_Click" Width="100px" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class MainPage : System.Web.UI.Page
{
protected void btnOrder_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
}
protected void btnCustomer_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
}
}
style.css:
.Background
{
background-color:Silver;
filter: alpha(opacity=50);
opacity: 0.50;
}
.ProgressPanel
{
border-width: 1px;
border-style: solid;
background-color: #FFFFFF;
position: absolute;
width: 180px;
height: 60px;
}
Modal popup window in action:

This post will never replace a book on Ajax but I hope it has made you aware that Ajax is also a very powerful client library that allows you to create even richer Web applications and hopefully this post has encouraged you to start using it and also to thrive to be a better developer, and if you're taking an exam, to get a better score.

0 comments: