Adding Client Capabilities to Server Controls Using the ASP.NET AJAX Control Toolkit
- Adding Client-Side Behavior Using the ExtenderControlBase
- Adding Design-Time Support to Your Extender Control
- Adding Animations to Your Extender Control
- Summary
IN THE PRECEDING CHAPTER, we covered the architecture of the AJAX Control Toolkit, describing at a high level what it has to offer and the attributes, classes, and interfaces that make it all happen. The enhanced functionality you get in the toolkit, from attribute-based programming to rich animations, provides a compelling alternative to coding against the ASP.NET 2.0 AJAX Extensions and the Microsoft AJAX Library directly. In this chapter, we delve into the details of the toolkit a little further as we develop as series of extender controls that demonstrate the rich features the toolkit provides.
Adding Client-Side Behavior Using the ExtenderControlBase
The ASP.NET AJAX Control Toolkit provides many features to assist in the development of extender controls, such as the automatic creation of $create statements, the use of attributes to decorate extender control properties that should be included in the $create statement creation, built-in designer support, and many more. In this section, we revisit the ImageRotator extender we created in Chapter 5, "Adding Client Capabilities to Server Controls," and re-create it using the ASP.NET AJAX Control Toolkit. This approach enables us to compare the alternatives as we build the new extender.
The process of building an extender control using the ASP.NET AJAX Control Toolkit consists of four main steps.
- Create the template classes.
- Provide implementation for the inherited extender control class.
- Provide implementation for the Sys.UI.BehaviorBase-based JavaScript class.
- Attach the extender control to an existing server control.
Visual Studio 2008 Extender Control Library Template
The ASP.NET AJAX Control Toolkit comes with full support for Visual Studio 2008 in the form of a project template that is geared toward creating an extender control library project. The template, shown in Figure 11.1, creates a library project structure (see Figure 11.2) that contains an extender control class, a designer class, and a JavaScript behavior class. In this section, we look at the ImageRotatorExtender.cs, ImageRotatorDesigner.cs, and ImageRotatorBehavior.js files that the template generated for us as we begin to discuss creating a new and improved ImageRotator extender.
Figure 11.1 Extender control project template
Figure 11.2 Extender control project template structure
The ImageRotatorExtender class shown in Listing 11.1 serves as the basis for our ImageRotator extender control. The class inherits from ExtenderControlBase and provides a template that contains most of the required entries for us, such as the web resource registration of our associated behavior class, class attributes that associate the designer for the extender, the client script to be downloaded, and the target type for the extender. The template also creates a default property, demonstrating the use of the ExtenderControlProperty and DefaultValue attributes and the use of the GetPropertyValue method inside the property setter and getter.
Listing 11.1. ImageRotatorExtender Class
[assembly: System.Web.UI.WebResource( "ImageRotator.ImageRotatorBehavior.js","text/javascript")] namespace ImageRotator { [Designer(typeof(ImageRotatorDesigner))] [ClientScriptResource("ImageRotator.ImageRotatorBehavior", "ImageRotator.ImageRotatorBehavior.js")] [TargetControlType(typeof(Control))] public class ImageRotatorExtender : ExtenderControlBase { [ExtenderControlProperty] [DefaultValue("")] public string MyProperty { get { return GetPropertyValue("MyProperty", ""); } set { SetPropertyValue("MyProperty", value); } } } }
The ImageRotatorDesigner class shown in Listing 11.2 will be the designer class for our ImageRotator extender control. The designer class provides default designer functionality for our extender control during design time. We associate the designer with our ImageRotatorExtender class by using the Designer attribute, which is automatically added when we use the template. The ExtenderControlBaseDesigner<T> class that the ImageRotatorDesigner class inherits from makes it possible for the properties of our extender control to show up in the Properties window while the design-time focus is on the image control we are extending. This default behavior provides a more efficient way of working with extenders and the controls they are extending.
Listing 11.2. ImageRotatorDesigner Class
namespace ImageRotator { class ImageRotatorDesigner : AjaxControlToolkit.Design. ExtenderControlBaseDesigner<ImageRotatorExtender> { } }
The ImageRotatorBehavior class shown in Listing 11.3 will be the client-side behavior class for our ImageRotator extender control. The class consists of the same structure we used in Chapter 5, but now inherits from the AjaxControlToolkit.BehaviorBase class, which provides added functionality for working with client state and interacting with the asynchronous request events of the Sys.WebForms.PageRequestManager.
Listing 11.3. ImageRotatorBehavior Class
/// <reference name="MicrosoftAjaxTimer.debug.js" /> /// <reference name="MicrosoftAjaxWebForms.debug.js" /> /// <reference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit" /> Type.registerNamespace('ImageRotator'); ImageRotator.ImageRotatorBehavior = function(element) { ImageRotator.ImageRotatorBehavior.initializeBase(this, [element]); // TODO : (Step 1) Add your property variables here this._myPropertyValue = null; } ImageRotator.ImageRotatorBehavior.prototype = { initialize : function() { ImageRotator.ImageRotatorBehavior.callBaseMethod(this,'initialize'); // TODO: Add your initialization code here }, dispose : function() { // TODO: Add your cleanup code here ImageRotator.ImageRotatorBehavior.callBaseMethod(this, 'dispose'); }, // TODO: (Step 2) Add your property accessors here get_MyProperty : function() { return this._myPropertyValue; }, set_MyProperty : function(value) { this._myPropertyValue = value; } } ImageRotator.ImageRotatorBehavior.registerClass( 'ImageRotator.ImageRotatorBehavior', AjaxControlToolkit.BehaviorBase);
Inheriting from the ExtenderControlBase Class
The ASP.NET AJAX Control Toolkit comes with its own version of the System.Web.UI.ExtenderControl class, which provides additional functionality that supports the development pattern the toolkit is designed to work with. The AjaxControlToolkit.ExtenderControlBase class provides the inheritor support for serialization of property values, support for working with the toolkit-based attributes, seamless integration with control-based view state, support for working with client state, and the ability to specify an alternate script path for debugging and working with themes. The ImageRotatorExtender class in Listing 11.4 shows a much different-looking class than we saw in Chapter 5. The class no longer requires overrides for the GetScriptDescriptors and GetScriptReferences methods, it has class-level attributes, it has property-level attributes, and the property setters and getters are referencing their values through a method. So, let's go over these changes and see how we develop an extender control building on the structure the template provided for us.
The setting of the assembly-based WebResource attribute in our extender class is a pattern that all the extenders and script controls in the toolkit follow. This pattern helps centralize all the pieces for the component in one location instead of having to add an entry to the assembly when a new control is added to the toolkit. The attributes applied to the class that we cover in this section are the Designer, ClientScriptResource, RequiredScript, and TargetControlType attributes. The Designer attribute is used to specify the class that will provide design-time services to our extender. The ClientScriptResource attribute is used to include the client-side scripts for our extender and consists of the resource type and the full resource name and should refer to an embedded resource. The RequiredScriptResource attribute brings in the timer script file that is associated with the TimerScript class that we will use in our behavior class. Finally, the TargetControlType attribute is used to limit the types of controls our extender can be associated with.
The RotationInterval and ImageList properties of our class have also changed with the use of attributes and the reliance on the GetPropertyValue<T> and SetPropertyValue<T> methods to access our property data. The ExtenderControlProperty attribute is used to indicate that the property should be added to the ScriptComponentDescriptor as a property and later included in the $create statement that creates the behavior class on the client. The ClientPropertyName attribute is used to change the name of the property that is used when the property is added to the ScriptComponentDescriptor from the default value of the property name to the name provided to the attribute. The DefaultValue attribute, which comes from the System.CompnentModel namespace, is used to indicate to designers and code generators the default value of the property. The ExtenderControlBase class provides the GetPropertyValue<T> and GetPropertyValue<T> generic methods that get and set the property value directly from the control view state. By using these methods in our property setters and getters, a consumer of our extender can work with it in the designer, declaratively in the HTML editor, or in code and be assured that during a postback the values will be available.
Listing 11.4. ImageRotatorExtender Class
[assembly:System.Web.UI.WebResource("ImageRotator.ImageRotatorBehavior.js", "text/javascript")] namespace ImageRotator { [ParseChildren(true, "ImageList")] [Designer(typeof(ImageRotatorDesigner))] [ClientScriptResource("ImageRotator.ImageRotatorBehavior", "ImageRotator.ImageRotatorBehavior.js")] [RequiredScript(typeof(TimerScript))] [TargetControlType(typeof(Image))] public class ImageRotatorExtender : ExtenderControlBase { [ExtenderControlProperty] [ClientPropertyName("rotationInterval")] [DefaultValue(3), DisplayName("RotationInterval(seconds))")] [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible)] public int RotationInterval { get { return GetPropertyValue<int>("RotationInterval", 3); } set { SetPropertyValue<int>("RotationInterval", value); } } private ImageUrlList _imageList; [ExtenderControlProperty] [ClientPropertyName("imageList")] [DesignerSerializationVisibility( DesignerSerializationVisibility.Content)] [PersistenceMode(PersistenceMode.InnerDefaultProperty)] public ImageUrlList ImageList { get { if (_imageList == null) { _imageList = GetPropertyValue<ImageUrlList>( "ImageList", null); if (_imageList == null) { _imageList = new ImageUrlList(); SetPropertyValue<ImageUrlList>( "ImageList", _imageList); } } return _imageList; } } } }
Creating the AjaxControlToolkit.BehaviorBase Class
The ASP.NET AJAX Control Toolkit comes with its own version of the Sys.UI.Behavior class, which provides additional functionality and supports the development pattern the toolkit is designed to work with. The AjaxControlToolkit.BehaviorBase class provides inheritor support for working with client state and interacting with the asynchronous request events of the Sys.WebForms.PageRequestManager. The support for working with client state is provided by the get_ClientState and set_ClientState methods that can be used to work with the string-based hidden field associated with your extender. The class also provides two methods tied to the beginRequest and endRequest events of the PageRequestManager, which can be overridden to provide specific functionality in your behavior in situations where an UpdatePanel is being used.
The ImageRotatorBehavior class shown in Listing 11.5 inherits from the BehaviorBase class and provides the client-side behavior for our extender control. The structure of this class is exactly the same as in Chapter 5, with the rotationInterval property used to set the interval at which the images will be swapped out and the imageList property containing an array of the images. The one change to the class is in the use of the Sys.Timer class, which is part of the ASP.NET AJAX Control Toolkit. This class, which is contained in the Compat/Timer folder, wraps the window.setInterval call, providing a cleaner interface for this timer-specific functionality. The Sys.Timer class is just one of many that come with the toolkit that provide added functionality to the existing Microsoft AJAX Library. If you look in the Compat and Common folders in the toolkit library project, you will find classes for working with dates, drag and drop, and threading, just to name a few.
Listing 11.5. ImageRotator Behavior Class
Type.registerNamespace('ImageRotator'); ImageRotator.ImageRotatorBehavior = function(element) { ImageRotator.ImageRotatorBehavior.initializeBase(this, [element]); this._imageIndex = 0; this._imageList = new Array(); this._rotationInterval = null; this._timer = null; } ImageRotator.ImageRotatorBehavior.prototype = { initialize : function() { ImageRotator.ImageRotatorBehavior.callBaseMethod(this, 'initialize'); var element = this.get_element(); if(this._imageList) { this._imageList = Sys.Serialization.JavaScriptSerializer.deserialize( this._imageList); this._imageList[this._imageList.length] = element.src; } if(this._rotationInterval == null) this._rotationInterval = 3; if(this._timer == null) this._timer = new Sys.Timer(); this._timer.set_interval(this._rotationInterval * 1000); this._timer.add_tick(Function.createDelegate(this, this._rotateImage)); this._timer.set_enabled(true); }, dispose : function() { ImageRotator.ImageRotatorBehavior.callBaseMethod(this, 'dispose'); if (this._timer) { this._timer.dispose(); this._timer = null; } this._imageList = null; }, get_rotationInterval: function(){ return this._rotationInterval; }, set_rotationInterval: function(value){ this._rotationInterval = value; }, get_imageList: function(){ return this._imageList; }, set_imageList: function(value){ this._imageList = value; }, _rotateImage: function(){ var element = this.get_element(); if(element) { element.src = this._imageList[this._imageIndex++]; if(this._imageIndex > this._imageList.length - 1) this._imageIndex = 0; } } } ImageRotator.ImageRotatorBehavior.registerClass( 'ImageRotator.ImageRotatorBehavior', AjaxControlToolkit.BehaviorBase);
Attaching the Extender to a Control
You can attach the ImageRotator extender to an image control by using the new Extender Control Wizard (see Figure 11.3) that comes with Visual Studio 2008 and thus provide the same design-time experience we saw in Chapter 5. The wizard is available from the smart tag of the image control by selecting the Add Extender option, which opens the wizard. The wizard enables the user to select an extender control from a list and associate it with a control. In our case, we would select the ImageRotator extender to associate it with the image control. After we do that, we add values to the RotationInterval property and ImageList property using the Properties window of the image control.
Figure 11.3 Extender Control Wizard
Final Thoughts
If we compare our experience of creating extender controls using the ASP.NET AJAX Control Toolkit to using the classes provided by the ASP.NET 2.0 AJAX Extensions, we can see that our development experience is much simpler. The use of attributes to register our properties to be included in the $create statements and to register our associated script files dramatically reduces the complexity of our code compared to implementing logic in the GetScriptDescriptors and GetScriptReferences methods. This convenience alone makes it worth using the toolkit, but if we tack on the added design-time features, support for working with client state, and the numerous added JavaScript files such as the Sys.Timer class, the reasons to switch get greater. The use of the toolkit can be compared to the use of the ActiveX Template Library (ATL) that was used to create ActiveX controls in C++. The template provided a ton of base classes and Visual Studio templates that made creating them a lot easier.