July 30, 2008
@ 09:33 PM

ASP.NET control collections are finicky. They are the most difficult to handle when trying to modify a control collection from a scope outside of that control. The mischievous error sneaked up on me some time ago. It manifests itself with the following error:

"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."

While fiddling around for a friend I came across some interesting behavior. Perhaps it is best to just show the code and disclaim my ignorance.

Suppose I have an ASP.NET 2.0 application containing two user controls implementing an interface IReadyable.

public interface IReadyable
{
  event EventHandler Ready;
}

Each user control contains handling code to satisfy the interface, like so:

public event EventHandler Ready;

protected override void OnLoad(EventArgs e)
{
  this.OnReady(EventArgs.Empty);
}

private void OnReady(EventArgs e)
{
  if (Ready != null)
  {
    this.Ready(this, e);
  }
}

The idea is that we can use the Ready event to signal a time to swap user controls in and out of our page. Allright, now to set up the straw man. We have a page that contains a placeholder. At some point, one of our user controls is added to the control collection of the placeholder. When the OnLoad event of the control fires, the handler activates the Ready event as well.

Our application code responds to the ready event by swapping the user control for another. This causes the peculiar exception.

/// <summary>
/// This method wires up the event handlers early in the page lifecycle,
/// but not early enough to allow us to modify some control collections.
/// </summary>
protected void Page_Load(object sender, EventArgs e)
{
  base.OnInit(e);
  IReadyable readyable = (IReadyable)this.LoadControl("~/MailControl01.ascx");
  readyable.Ready += new EventHandler(readyable_Ready);
  this.placeHolder.Controls.Add((Control)readyable);
}

/// <summary>
/// This method does not work because it is invoked too late in the page lifecycle.
/// </summary>
void readyable_Ready(object sender, EventArgs e)
{
  this.placeHolder.Controls.Clear(); // <-- An exception is thrown here.
  IReadyable readyable = (IReadyable)this.LoadControl("~/MailControl02.ascx");
  readyable.Ready += new EventHandler(again_Ready);
  this.placeHolder.Controls.Add((Control)readyable);
}

/// <summary>
/// Stub for an event handler.
/// </summary>
void again_Ready(object sender, EventArgs e)
{

}

Notice the first line in the readyable_Ready method?

Now for the interesting behavior. I say interesting because the error states that control collections are unmodifyable during the Init and Load phase; however, if you swap Page_Load for an override on the page's OnInit method, and swap the user control's OnLoad override for an OnInit override, no exception occurs. Everything works just fine. I suppose there are some arcane rules I am unaware of.

Granted, in my day-to-day development, I avoid the entire issue by creating custom server controls. I make each control responsible for its own control collection and ignorant of anything outside. It seems a control can modify its own collection any time it pleases, although there are some costs to doing it late in the page lifecycle. I found this page from Microsoft helpful: http://msdn.microsoft.com/en-us/library/ms178472.aspx.

I hope this turns out helpful for someone. A full demo is attached here: ControlCollections.zip (6.21 KB)

Happy coding.


 
Categories: ASP.NET | C#

I was building a new server control for my employer when I stumbled across this unexpected error:

"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."

This proved to be a misleading error. The problem occurred because I tried to modify the Control collection outside of the new server control's own collection. This could only be done when the Parent property had been set, which is never until the Init cycle. Effectively, modifying a parent's control collection is disallowed.

The solution to my problem was ensure that all dynamically added controls were added to the custom server control's collection only.

Happy Coding!


 
Categories: ASP.NET

Download the source code for this demo here.

Introduction

The demand for high quality web interfaces is continually increasing. The movement towards Web 2.0 places an increasing emphasis in making a web application look and feel like it were a home desktop application, with all the bells and whistles attached. Users expect each page they visit to interact with them in a smooth and natural way.

Asynchronous JavaScript and XML, AJAX, is one tool that helps to create this user experience. In a typical scenario, JavaScript on the page sends and retrieves data from the web server asynchronously, updating the web page without flicker and with minimal delay. Google Inc.'s GMail is an example. Each GMail page retrieves content from GMail only a portion at a time, "on demand". The entire experience is seamless.

Microsoft recently released a framework for AJAX, and a corresponding collection of control extenders called the AJAX Control Toolkit. The toolkit contains several control extenders. An AJAX control extender adds AJAX functionality to a non-ajax web control. The extender approach can be particularly useful when there is a requirement to add similar AJAX behavior to more than one control type, such as adding behaviors to buttons, images, and panels.

This tutorial introduces the basics of creating a custom AJAX control extender. We discuss embedded resources, property decorations (attributes), and client-side Web service calls.

The Scenario

Consider a form built for a web application. The form contains several places for input. From time to time, users flood you with questions about the meaning of each element. You want to add some context sensitive help to the page to spare yourself all the most frequently asked questions, saving both time and money.

We'll create a very simple AJAX control extender that wraps a server control, such as a Button or a Label, and adds context sensitive help at the click of a mouse. Moreover, the extender will populate the help with the results of a web service call to separate the content from the functionality.

Getting Started

Below is an example of the body of a very simple page. There are three main elements. On each, we want to add context sensitive help. The fourth element, the Panel at the bottom, is a placeholder for our help content.

  <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Looking for help..."/>
    <br />
    <br />
    <asp:Image ID="Image1" runat="server" ImageUrl="~/flower.jpg" />
    <br />
    <br />
    <asp:Panel ID="Panel1" runat="server">
        This is the content of the panel.<br />
        If you would like to find help, kindly click among this text.<br />
        Good luck!
    </asp:Panel>
    <br />
    <br />
    <asp:Panel ID="HelpPanel" runat="server" />
    <br />
    <br />
  </form>

To make our control extender consumable from any website, we'll compile the extender into a separate assembly. To do this, first make sure that the extender templates are installed. Download the AJAX control toolkit from http://ajax.asp.net, extract the files into the directory of choice, and execute the .vsi installers located in the archive at AjaxControlExtender\AjaxControlExtender.vsi. Once this is installed, add the new extender project to your Visual Studio solution by right clicking on the solution and selecting Add -> New Project, or selecting File -> Add -> New Project from the menu.

Select ASP.NET AJAX Control Project from the templates.

Delete the default .cs and .js files, and create a directory, Help to hold the new control. Right click on the folder, select Add -> New Item, and select ASP.NET AJAX Extender Control from the templates. Name the control "Help", since the convention of "HelpExtender" is added by default.

We now have the basic file structure for the control.

Configuring the Namespaces

It is important to give some thought to the namespace conventions for your control. There are three namespaces of immediate concern:

  1. The namespace of your server code
  2. The namespace of your client JavaScript
  3. The default namespace of your assembly

Adjusting the namespace of server code is plain and direct. I chose KbrProductions.Web.Extensions, after the pattern set by Microsoft's System.Web.Extensions. The client namespace is adjusted in the .js file. For this project the client namespace is KbrProductions.Ajax. A simple search and replace can fix the handful of references. Finally, the default namespace of the assembly can be configured by right clicking on the project file, selecting Properties, and editing the namespace in the Application tab. This namespace is important because it influences embedded resources.

For the JavaScript file to be consumable by the website, we must include it as a resource to the project assembly. Do this by selecting the file in Solution Explorer, viewing its properties, and setting the Build Action attribute to Embedded Resource.

Now visit the HelpExtender.cs file. Edit the assembly attribute to read:

[assembly: System.Web.UI.WebResource(
    "KbrProductions.Web.Extensions.Help.HelpBehavior.js",
    "text/javascript")]

The first parameter is a resource path for the javascript file. The naming convention for the path is: [Assembly Namespace][.directory][.FileName]. Remember, the assembly namespace is the default namespace set in the project properties. For the directory, use dots (.) to separate folders instead of backslashes. Misconfiguring this line is the common cause of the following web page error:

Assembly 'Extensions, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' contains a Web resource with name 'Extensions.Help.HelpBehavior.js', but does not contain an embedded resource with name 'Extensions.Help.HelpBehavior.js'.

When in doubt, fire up ILDASM and view the contents of the control assembly. The manifest contains the proper path for the JavaScript file on a .mresource line.

The extender class includes the JavaScript file by means of a ClientScriptResource decoration. Modify the decoration as shown below, where the first string indicates the client class name, and the second string specifies the resource exactly as specified in the assembly attribute earlier in the page.

[ClientScriptResource(
    "KbrProductions.Ajax.HelpBehavior",
    "KbrProductions.Web.Extensions.Help.HelpBehavior.js")]

At this point, the namespaces of the control assembly should be configured.

Server-Side Extender Properties

Next, we'll specify the properties that will be available as attributes to our extender markup. Because we inherit from ExtenderControlBase, we already have a TargetControlID property, which we can use to specify the control we want to extend.

We also want to specify the control that will contain the contents of our help. We decorate the property with the IDReferenceProperty attribute to enable the extender to automatically resolve the specified ID into a ClientID.

/// <summary>
/// ID of the control that will contain the help content.
/// </summary>
[ExtenderControlProperty]
[DefaultValue("")]
[IDReferenceProperty(typeof(WebControl))]
[ClientPropertyName("helpPanelID")]
public string HelpPanelID
{
    get { return GetPropertyValue("HelpPanelID", ""); }
    set { SetPropertyValue("HelpPanelID", value); }
}

Next, we'll build properties to define the location of a Web service that provides the text for the context-sensitive help. We decorate this property as a UrlProperty, which provides automatic resolving of server-relative URLs, that is, any URL starting with "~/". We also decorate it with a TypeConverter to handle some Web service specific url handling.

/// <summary>
/// Path to the webservice that the extender will pull the images from.
/// </summary>
[UrlProperty()]
[ExtenderControlProperty()]
[TypeConverter(typeof(ServicePathConverter))]
[ClientPropertyName("servicePath")]
public string ServicePath
{
    get { return GetPropertyValue("ServicePath", ""); }
    set { SetPropertyValue("ServicePath", value); }
}

Next we add a required property to define which method should be called.

/// <summary>
/// The webservice method that will be called to supply help.
/// </summary>
[ExtenderControlProperty]
[RequiredProperty]
[DefaultValue("")]
[ClientPropertyName("serviceMethod")]
public string ServiceMethod
{
    get { return GetPropertyValue("ServiceMethod", ""); }
    set { SetPropertyValue("ServiceMethod", value); }
}

And, finally, we add a property to define a parameter for the Web service call. We could treat this parameter as a key to determine which piece of help to return from the service.

/// <summary>
/// Context key to pass to the service method to get help text.
/// </summary>
[ExtenderControlProperty]
[DefaultValue("")]
[ClientPropertyName("helpContextKey")]
public string HelpContextKey
{
    get { return GetPropertyValue("HelpContextKey", ""); }
    set { SetPropertyValue("HelpContextKey", value); }
}

The next step is to provide a client-side equivalent interface to these properties.

Client-Side Extender Properties

Basic handling of each property from JavaScript is made extremely simple due to the AJAX Control Toolkit. All that is required is to add variable declarations to the constructor function, and add get/set functions to the object prototype. It is important to note that the property names for the get and set functions are case sensitive and should reflect the ClientPropertyName configured in the server-side extender code. Additional utility variables can be added to the constructor function as well.

KbrProductions.Ajax.HelpBehavior = function(element) {

    KbrProductions.Ajax.HelpBehavior.initializeBase(this, [element]);

    this._helpContextKey = null; // HelpContextKey property
    this._serviceMethod = null;  // ServiceMethod property
    this._servicePath = null;    // ServicePath property
    this._helpPanelID = null;    // HelpPanelID property

    this._helpPanel = null;      // HelpPanel element
    this._clickHandler = null;   // Click Event handler for the extended control
    this._targetElement = null;  // Element of the extended control
}

KbrProductions.Ajax.HelpBehavior.prototype = {
    // ...

    // extended properties
    get_serviceMethod : function() { return this._serviceMethod; },
    set_serviceMethod : function(value) { this._serviceMethod = value; },

    get_servicePath : function() { return this._servicePath; },
    set_servicePath : function(value) { this._servicePath = value; },

    get_helpContextKey : function() { return this._helpContextKey; },
    set_helpContextKey : function(value) { this._helpContextKey = value; },

    get_helpPanelID : function() { return this._helpPanelID; },
    set_helpPanelID : function(value) { this._helpPanelID = value; }
}

Fleshing out the Client Behavior

All that remains to complete our extender is to implement the client behavior. To provide feedback to the user that a control contains help, change the mouse cursor of the extended element. The object prototype's initialize method is a good place to do this.

initialize : function() {
    KbrProductions.Ajax.HelpBehavior.callBaseMethod(this, 'initialize');

    // Apply the CSS cursor style, "help"
    this._targetElement = this.get_element();
    this._targetElement.style.cursor = "help";

    // ...

Next, wire up an event handler in the initialize function to handle the click event of the target element. Use the Function.createDelegate method to create the handler. This ensures that multiple handlers can potentially be attached to the element without conflicting.

    // Attach an event handler to the click event of the element
    if(this._targetElement) {
        this._clickHandler = Function.createDelegate(this, this._onClick);
        $addHandler(this._targetElement, 'click', this._clickHandler);
    }

Add functionality to the dispose method to clean up the event handler. This is good practice to keep our memory clean.

dispose : function() {

    // Remove the event handler from the element if attached.
    if(this._clickHandler) {
        $removeHandler(this._targetElement, 'click', this._clickHandler);
        this._clickHandler = null;
    }

    KbrProductions.Ajax.HelpBehavior.callBaseMethod(this, 'dispose');
},

We now create the this._onClick function to handle the mouse click. We first implement a few lines to prevent any full-page postback that might occur. Parameters to the service method should be prepared as a dictionary key-value pair. We then can invoke the method using the ASP.NET AJAX Sys.Net.WebServiceProxy.invoke method. The method has seven parameters:

  1. The path to the Web service.
  2. The method to invoke.
  3. A parameter to indicate whether the call should use HTTP POST. For security reasons, this defaults to false.
  4. The parameters for the method.
  5. An event handler to be called when the service call returns successfully.
  6. An event handler to be called if the service call fails.
  7. Any JavaScript structure to pass to the event handler. This is a place holder if you want to send more than the defaults.

// click event for the extended element
_onClick : function(e) {

    // prevent post back.
    e.preventDefault();
    e.stopPropagation();

    // prepare parameters, if necessary
    var params = null;
    if (this._helpContextKey) {
        params = { 'helpContextKey' : this._helpContextKey };
    }

    // Invoke the web service
    Sys.Net.WebServiceProxy.invoke(
        this._servicePath,      // Service path
        this._serviceMethod,    // Service method
        false,                  // use POST (default false)
        params,                 // params
        Function.createDelegate(this, this._onServiceReply),  // on success
        null,                   // on failure
        null);                  // additional context
},

The last addition to the script is the this._onServiceReplay handler. The toolkit uses sender and eventArgs as parameters to the method. I think they're misnamed, because the object coming in through the sender parameter is the server reply; a string. At any rate, we fill our help panel with the contents of the reply.

// reply event for the service call
_onServiceReply : function(sender, eventArgs) {
    document.getElementById(this._helpPanelID).innerHTML = sender;
}

At this point, we completed all the code for the extender. All that remains is to reference this assembly by the website and add our extender to the page.

Using the Help Extender

Building the extender took a fair handful of code lines, but it all pays off when we start using the extender in the Web site. Add a reference to the extender project, and add the folling line to the <system.web><pages><controls> element of the Web.config file:

<add tagPrefix="kbr"
     namespace="KbrProductions.Web.Extensions"
     assembly="Extensions"/>

Note that the application will need references to the ASP.NET AJAX assembly and the AJAX Control Toolkit as well. Add a ScriptManager to the page, and extenders for the Button, Image and Panel.

<kbr:HelpExtender ID="help1" runat="server"
    TargetControlID="Button1"
    HelpContextKey="1"
    HelpPanelID="HelpPanel"
    ServiceMethod="GetHelp" />
<kbr:HelpExtender ID="help2" runat="server"
    TargetControlID="Image1"
    HelpContextKey="2"
    HelpPanelID="HelpPanel"
    ServiceMethod="GetHelp" />
<kbr:HelpExtender ID="help3" runat="server"
    TargetControlID="Panel1"
    HelpContextKey="3"
    HelpPanelID="HelpPanel"
    ServiceMethod="GetHelp" />

All that remains is to define the Web service that provides our help. We'll inject an AJAX-friendly service method right into this page. In a more practical application, the if/else if structure could be replaced with database access, file IO, or any other data retrieval. All that is required is that the method is static, takes the appropriate parameters, and returns the expected string result.

<script runat="Server" type="text/C#">
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetHelp(string helpContextKey)
{
    if (helpContextKey == "1")
        return "There is help awaiting you.";

    else if (helpContextKey == "2")
        return "Excellent clicking, friend!";

    else
        return "There is no help found for the likes of you.";
}
</script>

Running the page now shows that each control has a help cursor. When clicked, JavaScript issues an asynchronous Web service call which populates a portion of the page with context-sensitive help. The control extender is finished.

Conclusion

ASP.NET AJAX is an excellent tool to provide a richer experience to the user by taking advantage of the control extender model and asynchronous callbacks. With a little footwork, it is possible to create extenders that add complex behaviors to a variety of server controls, potentially saving considerable effort down the road. The AJAX Control Toolkit provides classes that simplify the process of creating your own extenders. Also, because the AJAX Control Toolkit is open source, you can download the existing control extenders and add behaviors to them, as well.

Happy Coding!


 
Categories: ASP.NET | AJAX