ScriptControlDescriptor
Listing 17-8 presents the implementation of the replica ScriptControlDescriptor. As you can see, this class derives from the ScriptComponentDescriptor base class discussed in the previous sections. Note that the constructor of the ScriptControlDescriptor class makes use of the internal constructor of the ScriptComponentDescriptor base class. As discussed earlier, this internal constructor takes two parameters, the first containing the fully qualified name of the type of the ASP.NET AJAX control...
Listing The onComplete Private JavaScript Function
function onComplete response, eventArgs if response.get_responseAvailable var contentType if result response.get_object else if result response.get_xml result response.get_responseData var error var errorObj error true if errorObj result new Sys.Net.WebServiceError false, result.Message, result.StackTrace, result.ExceptionType var statusCode response.get_statusCode if statusCode lt 200 statusCode gt 300 errorObj result new Sys.Net.WebServiceError false timedout , methodName , ,...
IScriptControl
All ASP.NET AJAX script server controls implement an interface named IScriptControl, defined in Listing 17-3. As you can see, the IScriptControl interface exposes two methods GetScriptDescriptors The GetScriptDescriptors method of the IScriptControl interface plays the same role in a script server control that the GetScriptDescriptors method of the IExtenderControl plays in an extender server control. Recall that the GetScriptDescriptors method of the IExtenderControl interface takes a...
Using the endRequest Event
As the name suggests, the current PageRequestManager instance raises the endRequest event to mark the end of the current asynchronous page postback request. Since the _endPostBack method can be invoked for a number of reasons, the endRequest event can be raised for a number of reasons as well. In other words, your event handler for the endRequest event must not assume that everything went fine and the server response successfully arrived. It must include the necessary logic to determine why the...
scriptsLoadComplete
Recall from Listing 24-23 that the current _ScriptLoaderTask instance invokes the _completedCallback delegate after loading all the scripts. Also recall that this delegate represents the _scriptsLoadComplete method of the current PageRequestMananger instance. Listing 24-24 presents the internal implementation of the _scriptsLoadComplete method. This method first calls the scrollTo method on the window object to set the scroll position this._scrollPosition.y Next, this method invokes the...
OnLoad
As you can see from Listing 17-15, the TextBoxWatermarkExtenderControl server control overrides the OnLoad method of its base class to perform the following tasks. First, it invokes the OnLoad method of its base class to raise the Load event and consequently to invoke all the event handlers registered for the Load event of the TextBoxWatermarkExtenderControl To understand what the rest of the code in the OnLoad method does, you need to revisit Listing 17-14 as repeated in Listing 17-16. Recall...
Listing The updateControls Method
function this._updatePanelIDs new Array updatePanellDs.length this._updatePanelClientIDs new Array updatePanellDs.length this._updatePanelHasChildrenAsTriggers new Array updatePanellDs.length for var i 0 i lt updatePanellDs.length i updatePanelIDs i .charAt 0 't' this._updatePanelIDs i updatePanelIDs i .substr 1 this._updatePanelClientIDs i this._asyncPostBackTimeout asyncPostBackTimeout 1000 this._updatePanelIDs this._updatePanelClientIDs this._updatePanelHasChildrenAsTriggers...
Listing The updateControls Method of the PageRequestManager
function this._updatePanelIDs new Array updatePanellDs.length this._updatePanelClientIDs new Array updatePanellDs.length this._updatePanelHasChildrenAsTriggers new Array updatePanellDs.length for var i 0 i lt updatePanellDs.length i updatePanelIDs i .charAt 0 't' this._updatePanelIDs i updatePanelIDs i .substr 1 this._updatePanelClientIDs i this._asyncPostBackTimeout asyncPostBackTimeout 1000 this._updatePanelIDs this._updatePanelClientIDs this._updatePanelHasChildrenAsTriggers...
ICustomTypeDescriptor 1
The DataRow class implements the ICustomTypeDescriptor interface as shown in the boldfaced portion of the following code fragment null, Sys.INotifyPropertyChange, Sys.IDisposable An ASP.NET AJAX client class normally implements the ICustomTypeDescriptor to expose information that is not directly exposed through its properties, as if they were the values of its own properties. This allows the clients of the class to access this information as if they were accessing the values of class...
Listing The ICustomTypeDescriptor Interface
Sys.Preview.ICustomTypeDescriptor function Sys Preview ICustomTypeDescriptor throw Error.notImplemented function throw Error.notImplemented function throw Error.notImplemented getProperty setProperty invokeMethod As discussed earlier, you can customize the getProperty, setProperty, and invokeMethod methods of the TypeDescriptor class by having your type implement the ICustomTypeDescriptor interface. You may be wondering why and when you should have your type implement this interface to...
Listing The getResponseHeader Method 1
lt param name header lt returns if this._responseAvailable throw throw var result
ScriptDescriptor
Recall from Listings 17-1 and 17-3 that the GetScriptDescriptors method of the IExtenderControl and IScriptControl interfaces return an IEnumerable collection of the ScriptDescriptor objects. Listing 17-5 presents the implementation of the replica ScriptDescriptor abstract base class. As you can see, this class exposes two methods GetScript The subclasses of the ScriptDescriptor abstract base class must implement the GetScript abstract method to return a string that contains the client script...
Listing The JnitializeIntemal Intance Method of the PageRequestManager Client
function this._scriptManagerID scriptManagerID this._form formElement As you can see, this method takes two arguments. The first is a string that contains the value of the UniqueID property of the ScriptManager server control. The second references the form DOM element of the current page. The method assigns the following two parameters to the _scriptManagerID and _form private fields of the current PageRequestManager instance this._scriptManagerID scriptManagerID this._form formElement Next,...
The initializeRequest Event
As you can see from Figure 22-8, the current client-side PageRequestManager instance fires its initializeRequest event right after completing the instantiation and initialization of the WebRequest object that represents the current asynchronous page postback request. This enables you to do the following Perform application-specific tasks that must be performed right after the WebRequest object is instantiated and initialized. Run application-specific validation logic to determine whether the...
Listing The DialogResult and MessageBoxStyle Enumerators
Sys.Preview.UI.DialogResult function Sys Preview UI DialogResult Sys.Preview.UI.MessageBoxStyle function Sys Preview UI MessageBoxStyle The DialogResult enumerator represents the result of an ASP.NET AJAX pop-up dialog box that contains up to two buttons OK and or Cancel. The value of OK specifies that the OK button was clicked, and the value of Cancel specifies that the Cancel button was clicked. Listing 12-58 used the DialogResult enumerator to determine whether to cancel the current request....
Listing The Definition of TextBoxWatermarkBehavior
function element The TextBoxWatermarkBehavior applies a watermark to a textbox lt summary gt lt param name element type Sys.UI.DomElement domElement true gt Textbox associated with the behavior lt param gt element Properties this._watermarkText null this._watermarkCssClass null Member variables this._watermarked null this._focusHandler null this._blurHandler null this._keyPressHandler null this._propertyChangedHandler null this._oldClassName null this._clearedForSubmit null this._maxLength...
Listing A Page that Uses the WebRequest
lt Page Language C gt lt DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN lt script runat server gt void Page_Load object sender, EventArgs e if Request passwordtbx password amp amp Request usernametbx username Department Response.End throw new Exception Wrong credentials lt html lt head runat server gt lt title gt Untitled Page lt title gt lt script type text javascript language javascript gt function completedCallback sender, eventArgs alert Request timed out return alert Request...
PostBackAction
The PostBackAction ASP.NET AJAX action also derives from the Action base class As the name implies, PostBackAction encapsulates the client-side functionality that enables an ASP.NET AJAX object to post the current page back to the server. The best way to understand the significance of the PostBackAction action is to study its implementation of the performAction method, as shown in the following code listing _doPostBack this.get_target , this.get_eventArgument As you can see, the performAction...
Listing The Public Static Registration Methods of the ScriptManager Server
public static void RegisterArrayDeclaration Control control, string arrayName, arrayName, public static void RegisterArrayDeclaration Page page, string arrayName, arrayName, arrayValue public static void RegisterClientScriptBlock Control control, Type type, string key, string script, bool addScriptTags type, key, script, public static void RegisterClientScriptBlock Page page, Type type, string key, type, key, script, public static void RegisterClientScriptInclude Control control, Type type,...
Listing The onFormSubmitCompleted Method of the PageRequestManager
this._processingRequest true var delimitByLengthDelimiter ' ' sender return this._endPostBack null, sender return if this._request sender.get_webRequest this._request return var errorMessage var delta if sender.get_statusCode 200 sender return var reply sender.get_responseData var delimiterIndex, len, type, id, content var replyIndex 0 var parserErrorDetails null while replyIndex lt reply.length delimiterIndex reply.indexOf delimitByLengthDelimiter, replyIndex parserErrorDetails this._findText...
Listing The Internal Implementation of the PageLoadingEventArgs Class
this._panelsUpdating panelsUpdating this._panelsDeleting panelsDeleting this._dataItems dataItems new Object get_dataItems get_panelsDeleting get_panelsUpdating 'Sys.WebForms.PageLoadingEventArgs', Sys.EventArgs As you can see, the constructor of the PageLoadingEventArgs class takes three parameters. The first is an array that contains the list of UpdatePanel server controls on the current page to be updated. Note the emphasis on to be. As I mentioned earlier, the current PageRequestManager...
Listing The OnInit Method of the UpdatePanel Control
protected override void OnInit EventArgs e As you can see, the OnInit method calls the RegisterPanel and CreateContents methods of the UpdatePanel server control. I'll discuss these methods in the following sections. Recall that the dashed line in Figure 21-4 represents the method calls triggered by the call into the OnInit method of the UpdatePanel server control. As you saw in this section, these triggered method calls are the calls into the RegisterPanel and CreateContents methods of the...
RegisterScriptDescriptors For Extender Controls
The ScriptManager exposes a public method named RegisterScriptDescriptors that you can use from your server-side code to add ScriptDescriptor objects for your extender server control. As Listing 17-12 shows, this method begins by checking whether the ExtenderControls collection of the current ScriptManager server control contains the specified extender server control. Recall from previous sections that you must invoke the RegisterExtenderControl method on the current ScriptManager server...
Listing The createDelegate Method of the JavaScript Function Type
function Function createDelegate instance, method return function return method.apply instance, arguments The createDelegate method takes two parameters. The first parameter references the JavaScript object owning the method that the delegate represents. The second parameter references the Function object that represents the method the delegate represents. As you can see, the createDelegate method defines and returns a new JavaScript function that calls the apply method on the Function object,...
Overriding CreateChildControls OneStop Shopping for All Your Child Controls
The Control class exposes a method named CreateChildControls that you must override to create the child controls that you need in order to assemble your custom control. One important thing to keep in mind about child controls is that they're created on demand. Don't assume that they're created at a particular stage of your custom control's life cycle. They can be created at any time. In other words, the CreateChildControls method can be called at any stage of your custom control's life cycle to...
Listing The invoke Method
params, onSuccess, onFailure, userContext if onSuccess null typeof onSuccess 'undefined' onSuccess if onFailure null typeof onFailure 'undefined' onFailure this.get_defaultFailedCallback if userContext null typeof userContext 'undefined' userContext this.get_defaultUserContext onSuccess, onFailure, userContext, this.get_timeout Note that the _invoke method returns a reference to the WebRequest object that represents the request made to the Web service. Now, let's walk through the implementation...
Listing The onFormSubmit Method of the ClientSide PageRequestManager Instance
var continueSubmit true if this._onsubmit for var i 0 i lt this._onSubmitStatements.length i if this._onSubmitStatements i if form.action form._initialAction return if this._postBackSettings.async return var formBody new Sys.StringBuilder formBody.append this._scriptManagerID ' ' this._postBackSettings.panelID ' amp ' var count form.elements.length for var i 0 i lt count i var element form.elements i var name element.name if typeof name undefined name null name.length 0 continue var tagName...
Listing The OnInit Method of the PageRequestManager Class
if this._owner.EnablePartialRendering amp amp IHttpBrowserCapabilities capabilitiesl this._owner.Page.Request.Browser this._owner.SupportsPartialRendering capabilities1.W3CDomVersion gt new Version 1, 0 amp amp capabilitiesl.EcmaScriptVersion gt new Version 1, 0 amp amp capabilitiesl.SupportsCallback this._owner.Page.Error new EventHandler this.OnPageError Note that the current server-side PageRequestManager instance exposes a field named _owner that references the current ScriptManager server...
An Example of a NET Type that Supports a Method that Returns a
public class BuildTemplateMethodProvider public void BuildTemplate Control c labell.Text DateTime.Now.ToString c.Controls.Add labell Button buttonl new Button buttonl.Text Update buttonl.Click new EventHandler Buttonl_Click c.Controls.Add buttonl void Button1_Click object sender, EventArgs e label1.Text DateTime.Now.ToString public BuildTemplateMethod GetBuildTemplateMethod return new BuildTemplateMethod BuildTemplate The following code listing contains a page that uses the CustomUpdatePanel...
ScriptComponentDescriptor
Listing 17-6 presents the implementation of the replica ScriptComponentDescriptor class. I'll discuss the implementation of the methods and properties of this class in the following sections. Listing 17-6 The ScriptComponentDescriptor using System.Collections.Generic using System.Web.Script.Serialization using System.Web.UI using System.Text using System public class ScriptComponentDescriptor ScriptDescriptor private SortedList lt string, string gt _events private string _id private SortedList...
Listing The addProperty Instance Method of the TypeDescriptor Class
readonly, isDomElement, associatedAttributes for var i 4 i lt arguments.length i 2 var attribute arguments i var value arguments i 1 attribs attribute value return this._getProperties propertyName name propertyName, type propertyType, 'readonly' readonly, 'isDomElement' isDomElement, attributes attribs The boldface portion of the following code fragment from Listing 10-27 shows that the addProperty method creates an object literal with five name value pairs. The first name value pair specifies...
Listing The browser Object
Sys.Browser.InternetExplorer Sys.Browser.Firefox Sys.Browser.Safari Sys.Browser.Opera Sys.Browser.agent null Sys.Browser.hasDebuggerStatement false Sys.Browser.name navigator.appName Sys.Browser.version parseFloat navigator.appVersion if navigator.userAgent.indexOf ' MSIE ' gt -1 Sys.Browser.agent Sys.Browser.InternetExplorer Sys.Browser.version d . d 1 Sys.Browser.hasDebuggerStatement true else if navigator.userAgent.indexOf ' Firefox ' gt -1 Sys.Browser.agent Sys.Browser.Firefox...
Listing The Add Method of the UpdatePanelTriggerCollection
protected override void InsertItem int index, UpdatePanelTrigger item item.SetOwner this.Owner if this._initialized item.Initialize Note that the UpdatePanelTrigger API does not contain any reference to any server control see Listing 21-15 . This means that this API does not put a restriction on how a particular subclass of UpdatePanelTrigger is triggered. In other words, you could implement a subclass of the UpdatePanelTrigger base class that is triggered by a mechanism other than a server...
Listing The CustomUpdatePanel Server Control
public class CustomUpdatePanel UpdatePanel public string BuildTemplateMethodProviderType string.Empty value public string BuildTemplateMethodProviderMethod value protected override void OnInit EventArgs e if amp amp string typeName string assemblyName typeName.Length if assembly Assembly.GetExecutingAssembly assemblyName assemblyName.Trim .Remove 0, 1 assembly Assembly.Load assemblyName object provider assembly.CreateInstance typeName Type type provider.GetType MethodInfo methodInfo...
Listing The createPageRequestManagerServerError Method of PageRequestManager
function httpStatusCode var e Error.create displayMessage, name httpStatusCode httpStatusCode e.popStackFrame return e Listing 24-40 presents the internal implementation of the _createPageRequestManagerParserError method of the PageRequestManager class. As you can see, this method creates an error object with the following two properties message This property specifies the following error message parserErrorMessage name This property specifies the name of the exception, Sys.WebForms
Listing The BehaviorBase Class
AjaxControlToolkit.BehaviorBase function element Base behavior for all extender behaviors lt param name element type Sys.UI.DomElement domElement true gt Element the behavior is associated with lt param gt this._clientStateFieldID null this._pageRequestManager null this._partialUpdateBeginRequestHandler null this._partialUpdateEndRequestHandler null initialize dispose get_ClientStateFieldID set_ClientStateFieldID get_ClientState set_ClientState registerPartialUpdateEvents...
Listing The Execute Method of the ScriptLoaderTask Class
function Sys _ScriptLoaderTask execute var scriptLoadDelegate Function.createDelegate this, this._scriptLoadHandler if Sys.Browser.agent Sys.Browser.InternetExplorer this._scriptElement.readyState 'loaded' addHandler this._scriptElement, 'load', scriptLoadDelegate addHandler this._scriptElement, 'readystatechange', var headElement
Listing The Internal Implementation of registerInterface
Type.prototype.registerlnterface function a Listing 4-3 presented a portion of the implementation of the registerClass function. The first parameter of the registerClass method contains the fully qualified name of the class being registered, including its namespace hierarchy for example, Department.Employee. The second parameter is discussed in later sections of this chapter. The third optional parameter of registerClass contains the interfaces that the class being registered implements. The...
NotlmplementedException
When you're implementing a base class in the .NET Framework, you have two options when it comes to the implementation of a virtual method or property of your base class. You can either provide a default implementation for the method or property, or raise a .NET exception named NotImplementedException. The ASP.NET AJAX client-side script framework provides you with the same type of exception, which is called Sys.NotImplementedException and exposes a single name property. It shouldn't come as a...
callBaseMethod
To understand the role of the callBaseMethod method, consider a similar situation in an OOP language such as C . A C class exposes virtual methods to allow its subclasses to override the implementations of these methods. This is how a subclass extends the functionality of its base class. Most of the time, the subclass's implementation of a virtual method calls its base class's implementation in addition to providing its own implementation. In other words, the subclass's implementation...
Listing The getHandler Class
function Sys EventHandlerList getHandler id var evt this._getEvent id if evt evt.length 0 return null evt Array.clone evt if evt._handler evt._handler function source, args for var i 0, l evt.length i lt l i evt i source, args As you can see, getHandler first calls the _getEvent method to access the subarray of the _list with the specified index Then it defines a function that iterates through the event handlers in this subarray and invokes each enumerated event handler evt._handler function...
registerEnum
The registerEnum method enables you to register an enumeration with the ASP.NET AJAX client-side framework. Here's an example lt Page Language C gt lt DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN lt html lt head id Head1 runat server gt lt title gt Untitled Page lt title gt lt head gt lt body gt lt form id form1 runat server gt lt asp ScriptManager ID ScriptManager1 runat server gt lt script language javascript type text javascript gt alert MyNamespace.State.Statel alert...
registerClass
The ASP.NET AJAX client-side framework extends the functionality of Type to add support for a new method named registerClass. As the name implies, this method registers a specified class with the ASP.NET AJAX client-side framework. To add a new class to the ASP.NET AJAX client-side framework, you first need to implement the class. For example, the following code implements a class named Employee Employee function firstName, lastName this_firstName firstName this_lastName lastName get_firstName...
popStackFrame
The JavaScript Error type features two properties named fileName and lineNumber. Some browsers set the values of these properties to respectively specify the URL of the document and the line number in the document where the error occurred. These two properties provide great debugging information for developers. Some browsers set these properties to the URL of the document and the line number in the document where the error was created as opposed to the URL of the document and the line number in...
getRootNamespaces
As discussed earlier, in general there are two types of namespaces local and global or root . A local namespace is a namespace that belongs to another namespace. A global namespace, on the other hand, does not belong to any other namespace. The getRootNamespaces JavaScript function returns an array that contains all the namespaces registered at the global level. Here's an example lt Page Language C gt lt html lt head id Head1 runat server gt lt title gt Untitled Page lt title gt lt head gt lt...
ArgumentNullException
The .NET Framework includes an exception type named ArgumentNullException. This exception is raised when a method is invoked and one of the parameters passed into it is null. As you can see, ArgumentNullException is more specific than ArgumentException. The ASP.NET AJAX client-side framework follows this .NET pattern and introduces an exception type named Sys.ArgumentNullException, which is more specific than Sys.ArgumentException. Just like its .NET counterpart, Sys.ArgumentNullException is...
XMLHttpRequest
XMLHttpRequest is one of the main AJAX technologies that the scheduler component of an AJAX engine uses to make asynchronous requests to the server. The instantiation process of the XMLHttpRequest object is browser-dependent. Listing 1-1 encapsulates the browser-dependent nature of this instantiation process in a class named XMLHttpRequest. Listing 1-1 Instantiating XMLHttpRequest window.XMLHttpRequest function window XMLHttpRequest var proglDs 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP' for var i 0...
ParameterCountException
When you write a method in the .NET Framework that takes a specific number of parameters of specific types, you can rest assured that the Framework will not allow anyone to call your method with fewer parameters than your method expects. That's why your method does not need to check whether the required number of parameters is passed into it. JavaScript functions, on the other hand, allow their callers to call them with fewer parameters or no parameters at all. To make programming against...


