Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

Adding Animations to Your Extender Control

The ASP.NET AJAX Control Toolkit comes with a rich animation framework that provides support for creating cool visual effects on your pages. The animation framework consists of a set of JavaScript and .NET classes that enable you to build up animations of all types, including animations that run sequentially or in parallel, animations that fade the opacity of a control in and out, and animations that transition from one color to the next. The framework provides support for building these animations using the JavaScript API directly or using a declarative approach that consists of adding markup in the HTML editor. The following sections examine how to add animation functionality to extender controls.

Animations Using the JavaScript API

The ImageRotator extender we created earlier provided little in the area of effects as the images switched and resulted in very fast transition from one image to the next, which wouldn't catch a viewer's attention. In this section, we create a new version of the ImageRotator, called the AnimatedImageRotator, that fades in the image as it switches from one image to the next and provides this feature in addition to the existing functionality of the ImageRotator. As we cover how to add this new animation functionality, we gloss over the topics we have already covered, focusing only on implementing the animation pieces.

To add this functionality to the AnimatedImageRotator, we need to register the animation scripts with the AnimatedImageRotatorExtender class and add logic to the behavior class to call the animation when the image changes.

Registering the Animation Scripts

To register the script files so that they are downloaded to the browser, we need to add the RequiredScript attribute to the AnimatedImageRotatorExtender class, as shown in Listing 11.12. We use the RequiredScript attribute in this case to ensure that the animation.js, timer.js, and common.js script files associated with the AnimationScripts type are included with the scripts brought down to the browser for our control. This style of adding scripts associated with a type is a common practice in the toolkit and is clean way to include dependent scripts associated with a type.

Listing 11.12. AnimatedImageRotator Extender Class

...
[RequiredScript(typeof(AnimationScripts))]
...
public class AnimatedImageRotatorExtender : ExtenderControlBase
{
  ...
}

Calling Animation APIs

The ASP.NET AJAX Control Toolkit contains a JavaScript API that you can use to provide animation support on the client. In the case of our AnimatedImageRotator extender, we will use the FadeAnimation, which is part of the animation API, to provide a fade-in effect when the images on our image control change. The JavaScript code to implement this functionality will be contained in our behavior class and will integrate with the existing features of the ImageRotator.

The AnimatedImageRotator behavior class, shown in Listing 11.13, takes the ImageRotator behavior and adds a fade animation when the image changes, to fade the image into view. The constructor of the FadeAnimation takes the target of the animation, the duration of the animation, the number of steps per second, the effect, the minimum opacity, the maximum opacity, and whether to adjust for layout in Internet Explorer. In our case, the BannerImage image control will be the target of our animation, and the duration of our animation will be hard coded to 20% of the time the image is visible. To provide a clean animation, we will set the animation steps to 150, and combine that with a fade-in effect that will cause the image to transition in when the image changes. During this transition, we will start off with an opacity of 0, which will give us a full view of the image background, and then through the 150 steps work our way to a full view of the image with an opacity of 1. Table 11.1 lists some of the FadeAnimation properties and provides a little more information about what they do.

Table 11.1. Partial List of Fade Animation Class Properties

Property

Description

target

Target of the animation.

duration

Length of the animation in seconds. The default is 1.

fps

Number of steps per second. The default is 25.

effect

Determine whether to fade the element in or fade the element out. The possible values are AjaxControlToolkit.Animation.FadeEffect.FadeIn and AjaxControlToolkit.Animation.FadeEffect.FadeOut. The default value is FadeOut.

minimumOpacity

Minimum opacity to use when fading in or out. Its value can range from 0 to 1. The default value is 0.

maximumOpacity

Maximum opacity to use when fading in or out. Its value can range from 0 to 1. The default value is 1.

forceLayoutInIE

Whether we should force a layout to be created for Internet Explorer by giving it a width and setting its background color (the latter is required in case the user has ClearType enabled). The default value is true.

After we associate the animation to the element, starting, stopping, and pausing the animation is just a method call away, making it simple to manipulate the animation. In the AnimatedImageRotator, the load event of the image is used to trigger the animation to play because it will be fired each time our Sys.Timer calls the _rotateImage method. To do this, we associated the _onLoadImage event handler with the onLoad event of the image and called the play method on the animation inside the function. Now each time the load event occurs, the animation plays, transitioning the image into view. One of the side effects of working with an animation in a situation like this is a potential race condition if the duration was set too long. When working with transition-type animations like the FadAnimation, pay close attention to how you are using it to ensure the animation will work in all cases.

Listing 11.13. AnimatedImageRotator Behavior Class

...

AnimatedImageRotator.AnimatedImageRotatorBehavior = function(element) {
  ...
  this._fadeAnimation = null;
  this._timer = null;
  this._onImageLoadHandler = null;
}
AnimatedImageRotator.AnimatedImageRotatorBehavior.prototype = {
  initialize : function() {
  ...

    if(this._fadeAnimation == null)
    {
      this._fadeAnimation =
        new AjaxControlToolkit.Animation.FadeAnimation(
          element, this._rotationInterval/20, 150,
          AjaxControlToolkit.Animation.FadeEffect.FadeIn,
          0, 1, true);
    }
    if (element)
    {
      this._onImageLoadHandler = Function.createDelegate(this,
        this._onImageLoad);
      $addHandler(element, 'load', this._onImageLoadHandler);
    }
    ...
  },

  dispose : function() {
    ...
    var element = this.get_element();
    if (element) {
      if (this._onImageLoadHandler) {
        $removeHandler(element, 'load',
          this._onImageLoadHandler);
        this._onImageLoadHandler = null;
      }
    }

    ...

    if (this._fadeAnimation)
    {
      this._fadeAnimation.dispose();
      this._fadeAnimation = null;
    }

    ...
  },
  _onImageLoad: function(){
    if(this._fadeAnimation)
      this._fadeAnimation.play();
  },
  ...
}
...

Animations Using the Declarative Method

The declarative approach to animation in the toolkit provides a nice extensibility path for consumers of your extender. In our previous example, we hard coded all the animation functionality inside our extender, providing little support for developer customization. In some cases, this might be all that is needed. In other cases, however, you might need to provide a more robust solution that provides a JavaScript-free way to customize animations. In this section, we replicate the same functionality we created in the preceding section, but we provide a more extensible approach consumers of our extender can use when they are configuring it in the designer. The extender we create has just one feature: the capability to run a FadeIn animation when the onLoad event of an associated image control occurs. This new extender will be used in addition to the ImageRotator extender we created earlier, which had no animation functionality. This refined approach to adding animation support builds on the principle that many extenders can be placed on a single control to provide combined client-side capabilities. To get started, let's take a look at what the declarative syntax or our control will look like before we go into the implementation details. Just as in the preceding section, as we cover how to add this new animation functionality we gloss over the topics we have already covered, focusing only on implementing the declarative animation pieces.

Overview of Declarative Syntax

To get started, let's look at the HTML source we will be working toward being able to work with in our ImageAnimation extender. The source in Listing 11.14 contains an ImageAnimationExtender tag that contains in its body an Animations tag. As you might guess, the approach here is to add various animations that are driven by events raised by the image control we are extending. In our case, we are working with the OnLoad event and adding a Sequence animation that will call a child Fade animation. A Sequence animation is designed to run all its child animations one at a time until all have finished. So, what this source tells us is that our extender will have an animation that will be tied to the OnLoad event of the image control and will run the child Fade animation whenever the OnLoad event occurs.

Listing 11.14. AnimationImageExtender Declarative Syntax

<asp:Image ID="BannerImage" runat="server" ImageUrl="~/images/1.jpg" />
<cc3:ImageAnimationExtender ID="Banner_ImageAnimationExtender"
  runat="server" Enabled="True" TargetControlID="BannerImage">
  <Animations>
    <OnLoad>
      <Sequence>
        <FadeIn AnimationTarget="BannerImage" Duration=".3"/>
      </Sequence>
    </OnLoad>
  </Animations>
</cc3:ImageAnimationExtender>
<cc2:ImageRotatorExtender ID="Image1_ImageRotatorExtender"
  runat="server" Enabled="True" TargetControlID="Banner">
  <cc2:ImageUrl Url="~/images/2.jpg" />
  <cc2:ImageUrl Url="~/images/3.jpg" />
  <cc2:ImageUrl Url="~/images/4.jpg" />
</cc2:ImageRotatorExtender>

Providing Declarative Support in Your Extender Class

The AnimationExtenderControlBase class provides most of the functionality we need to parse the Animation tag and all its contents. This class provides internal methods that convert the XML representation of the animation into JSON format, which our behavior will then use to run the animation, and also provides the Animation property that we see in Listing 11.15. The following sections cover the steps needed to ensure the extender will work correctly.

  1. Add attributes to the class.
  2. Create a property for the event.
  3. Add attributes to the property.
Add Attributes to the Class

This type of extender has a couple of added class attribute entries of interest to us. The first is the inclusion of the RequiredScript attribute for the AnimationExtender type. The AnimationExtender class provides a lot of the client-side functionality we will be using in our extender control, and by using this type in our RequiredScripts attribute, we are guaranteed that the scripts will be present on the client for us to use. The second attribute is the System.Web.UI.Design.ToolboxItem attribute, which enables our control to show up in the toolbox of Visual Studio. It might seem strange that we have to add this because all our other extenders didn't. If we look at the attributes on the AnimationExtenderControlBase class, however, the support for viewing in the toolbox has been turned off. Therefore, we must reset this value on our control so that it will show up in the toolbox.

Create a Property for the Event

The pattern when creating extenders of this type is to add a property for each event you want to interact with. In our case, we are working with the OnLoad event, so we create a property named OnLoad (to make it easy to understand what the event is). If we were to choose other events, we would name them based on the DOM event they represent. The property accessor for these events must use the GetAnimation and SetAnimation methods to ensure proper data conversion into JSON as the data is stored and retrieved out of the extender's view state.

Add Attributes to the Event Property

The event property must have the Browsable, DefaultValue, ExtenderControlProperty, and DesignerSerializationVisibility attributes applied to it. The Browsable attribute stops the property from showing up in the Properties window and therefore excludes the property from being assigned in the Properties window. This is needed because no editor is associated with this property, and we don't want users to try to add anything into the Properties window that would corrupt the values. The DesignerSerializationVisibility attribute with a value of DesignerSerializationVisibility.Hidden is used to indicate that the property value should not be persisted by the designer because the Animation property will take care of that for us. The DefaultValue attribute indicates to the designer that the default value will be null, and the ExtenderControlProperty attribute is used to register the property with the ScriptComponentDescriptor.

Listing 11.15. ImageAnimationExtender Class

[Designer(typeof(ImageAnimationDesigner))]
[ClientScriptResource("ImageAnimation.ImageAnimationBehavior",
  "ImageAnimation.ImageAnimationBehavior.js")]
[RequiredScript(typeof(AnimationExtender))]
[ToolboxItem("System.Web.UI.Design.WebControlToolboxItem, System.Design, Version=2.0.0.0,
 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[TargetControlType(typeof(Image))]
public class ImageAnimationExtender : AnimationExtenderControlBase
{
  private Animation _onLoad;

  [DefaultValue(null)]
  [Browsable(false)]
  [ExtenderControlProperty]
  [DesignerSerializationVisibility(
     DesignerSerializationVisibility.Hidden)]
  public new Animation OnLoad
  {
    get { return GetAnimation(ref _onLoad, "OnLoad"); }
    set { SetAnimation(ref _onLoad, "OnLoad", value); }
  }
}

Adding Declarative Support to Your Behavior Class

The ImageAnimationBehavior class, shown Listing 11.16, provides all the client-side functionality for our extender with support from the animation script files associated with the AutomationExtender class. These associated scripts provide support for converting the JSON representation of the FadeIn animation that was captured on the server to an actual animation, support for associating the animation with the high-level OnLoad event, and support for playing the animation when the OnLoad event occurs.

You need to complete a few steps for each event you plan to work with:

  1. Add variables to the class.
  2. Create functions.
  3. Add handlers.
Add Variables to the Class

Each event that your behavior will work with needs a variable that references the GenericAnimationBehavior for the event and a delegate that will be called for the event that will be processed. In the ImageAnimationBehavior class, we use the _onLoad variable to store a reference to the GenericAnimationBehavior class and the _onLoadHandler variable to store a reference to the delegate that will handle the onLoad event. The guidelines established so far in the toolkit use a naming convention that includes the event name in all the variable names.

Create Functions

The behavior needs a series of functions for each event you will work with. The get_OnLoad and set_OnLoad functions in our case take care of working with the JSON-based data for the FadeIn animation and utilize the functionality provided by the GenericAnimationBehavior class to store and retrieve that data. The get_OnLoadBehavior function returns a reference to the GenericAnimationBehavior instance that was created for our FadeIn animation, providing the ability to work with the behavior that directly exposes the play, stop, and quit methods common to all animations.

Add Handlers

Handlers must be added for each event the behavior will process and should correspond to the events exposed on the extender control. In our case, we are working with the onLoad event, so we need to create the _onLoadHandler delegate and associate it with the onLoad event of the image using the $addHandler shortcut. The opposite of this must happen in the dispose of our behavior, when we use the $removeHandler shortcut to ensure proper memory cleanup.

Listing 11.16. ImageAnimationBehavior Class

Type.registerNamespace('ImageAnimation');

ImageAnimation.ImageAnimationBehavior = function(element) {
  ImageAnimation.ImageAnimationBehavior.initializeBase(this, [element]);
  this._onLoad = null;
  this._onLoadHandler = null;
}
ImageAnimation.ImageAnimationBehavior.prototype = {
  initialize : function() {
    ImageAnimation.ImageAnimationBehavior.callBaseMethod(this,
      initialize');
    var element = this.get_element();
    if (element)
    {
      this._onLoadHandler = Function.createDelegate(this,
       this.OnLoad);
      $addHandler(element, 'load', this._onLoadHandler);
    }
  },

  dispose : function() {
    ImageAnimation.ImageAnimationBehavior.callBaseMethod(this,
      'dispose');

    var element = this.get_element();
    if (element) {
      if (this._onLoadHandler) {
        $removeHandler(element, 'load', this._onLoadHandler);
        this._onLoadHandler = null;
      }
    }

    this._onLoad = null;

  },
  get_OnLoad : function() {
    return this._onLoad ? this._onLoad.get_json() : null;
  },
  set_OnLoad : function(value) {
    if (!this._onLoad) {
      this._onLoad = new
        AjaxControlToolkit.Animation.GenericAnimationBehavior(
          this.get_element());
      this._onLoad.initialize();
    }
    this._onLoad.set_json(value);
      this.raisePropertyChanged('OnLoad');
  },
  get_OnLoadBehavior : function() {
    return this._onLoad;
  },
  OnLoad : function() {
    if (this._onLoad) {
      this._onLoad.play();
    }
  }
}
ImageAnimation.ImageAnimationBehavior.registerClass(
  'ImageAnimation.ImageAnimationBehavior',
  AjaxControlToolkit.BehaviorBase);

Final Thoughts

The HTML source for our sample, shown Listing 11.14, contains a Fade animation that targets the BannerImage control and runs for a duration of .3 seconds. We could have chosen almost any type of animation as long as it occurred when the OnLoad event fired on the BannerImage image control. This flexibility provides a JavaScript-free way to set up animations of any type when a pattern such as this is used. In fact, this is exactly how the Animation extender works; and if it weren't for the way it handles the OnLoad event, we would have used it in our example.

  • + Share This
  • 🔖 Save To Your Account