FREE BOOK

Chapter 11 - Adding Client Capabilities to Server Controls Using the ASP.NET AJAX Control Toolkit

Posted by Addison Wesley Free Book | ASP.NET & Web Forms September 21, 2009
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.

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 controlbased 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 differentlooking 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 .le that is associated with the Timer Script class that we will use in our behavior class. Finally, the Target ControlType 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 GetProperty Value<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 Script ComponentDescriptor 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 Extender ControlBase class provides the GetPropertyValue<T> and GetProperty Value<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 .eld 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 speci.c 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-speci.c 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 .nd 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.

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 .les 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 .les such as the Sys.Timer class, the Adding Client-Side Behavior Using the ExtenderControlBase 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.



Figure 11.3 Extender Control Wizard

Total Pages : 7 12345

comments