November 30, 2007 12:11 AM

Create Control Extenders

Using Visual Studio 2008, ASP.NET 3.5, and AJAX
DevConnections
Rating: (0)

ControlFreak

LANGUAGES:VB.NET | C#

ASP.NETVERSIONS: 3.5

 

Create Control Extenders

Using Visual Studio 2008, ASP.NET 3.5, and AJAX

 

 

This month, you?ll learn to use some of the exciting newcontrol development features of Microsoft?s latest cutting-edge developmenttools to create your own AJAXcontrols and extenders. Let?s get started ...

 

What?s in Visual Studio 2008?

Visual Studio 2008 should be released around the time youread this article. Visual Studio 2008 includes the .NET Framework version 3.5,which includes ASP.NET version 3.5. ASP.NET 3.5 includes ASP.NET AJAX(codenamed Atlas), which was previously available as a separate downloadableadd-on to the preceding version of ASP.NET (version 2.0.)

 

If you?ve been using ASP.NET 2.0 AJAX,then you?re aware it required a significant number of additions to theweb.config file. These web.config settings are now included by default in allnew ASP.NET projects created with Visual Studio 2008, so there is no need toadd them manually. However, a ScriptManager control is still required on every Webform that wishes to utilize AJAXcapabilities.

 

You may have also heard of the ASP.NET AJAX ControlToolkit. That open source project is not included with Visual Studio 2008. Itis still a freely downloadable add-on. The Control Toolkit is not needed, used,or referenced by any of the code in this article.

 

Controls vs. Extenders

Microsoft?s ASP.NET AJAX provides the ability to easilycreate your own AJAX-compatible controls and control extenders. An ASP.NET AJAXServer Control is similar to the standard old ASP.NET Server Control, but itadds client-side features and capabilities based on Microsoft?s AJAXframework.

 

A ?Control Extender? is a non-visual control that extendsthe capabilities of another control. One thing that all control extenders havein common is a property named TargetControlID, which is intended to reference aspecific instance of the control type that it is extending. The ASP.NET AJAXServer Control Extender we?ll create in this article extends the classicASP.NET TextBox control with the ability to restrict its input to numericcharacters only. To do this, it will utilize Microsoft?s AJAXframework.

 

ASP.NET AJAX Server Controls inherit from the newScriptControl class, while ASP.NET AJAX Server Control Extenders inherit fromthe nearly identical ExtenderControl class. The ScriptControl class (whichinherits from WebControl) enables a number of AJAX-related functions. Forexample, it verifies that a ScriptManager control exists on the page. TheScriptControl class implements the IScriptControl interface.

 

In slight contrast, the ExtenderControl class inheritsfrom the Control class, and implements the IExtenderControl interface. TheIExtenderControl interface is virtually identical to the IScriptControlinterface; they both define two functions: GetScriptDescriptors andGetScriptReferences.

 

The GetScriptDescriptors method is used to supply a listof related JavaScript files. Similarly, the GetScriptReferences method is usedto supply a list of ScriptReference objects that represent each of thosescripts. Both the ScriptControl and the ExtenderControl classes use thesemethods to ensure exactly one reference to each JavaScript file is output tothe page?s HTML during the render event.

 

Because of the similarities between the ScriptControl andExtenderControl classes, the process of creating a basic AJAX Server Control isvirtually identical to the process of creating a basic AJAX Server ControlExtender. Once you?ve learned how to create one, you?ve essentially learned howto create both.

 

So, let?s put all this theory to work and create an AJAXServer Control Extender that limits textbox entry to decimal characters only.

 

Create a Control Extender

To create our numeric textbox control extender usingVisual Studio 2008, choose the ASP.NET AJAX Server Control Extender templatefrom the Web section of the Visual Studio 2008 New Project dialog box, as shownin Figure 1. We?ll name this new numeric textbox extender project with theabbreviated title NumTextExt.

 


Figure 1: Visual Studio 2008provides several new project templates, including the ASP.NET AJAX ServerControl Extender template selected here.

 

After clicking OK on the New Project dialog box, VisualStudio automatically creates a new project with two notable files in it:ExtenderControl1.vb, and ClientBehavior1.js. These files contain significantamounts of boilerplate code that you?d otherwise have to type in manually ifyou weren?t using Visual Studio 2008. The contents of ExtenderControl1.vb arelisted in Figure 2A. It shows examples of the GetScriptDescriptors andGetScriptReferences methods of the previously mentioned IScriptControl andIExtenderControl interfaces.

 

<TargetControlType(GetType(TextBox))> _

Public Class NumTextExt

 Inherits ExtenderControl

 

Protected Overrides Function GetScriptDescriptors( _

 ByVal targetControl AsSystem.Web.UI.Control) _

 As IEnumerable(OfScriptDescriptor)

 

 Dim descriptor As New _

 ScriptBehaviorDescriptor("NumTextExt.ClientBehavior1", _

                                    targetControl.ClientID)

 

 Dim descriptors As NewList(Of ScriptDescriptor)

 descriptors.Add(descriptor)

 Return descriptors

End Function

 

' Generate the script reference

Protected Overrides Function GetScriptReferences() _

 As IEnumerable(OfScriptReference)

 

 Dim scriptRef As New _

   ScriptReference("NumTextExt.ClientBehavior1.js", _

                       Me.GetType().Assembly.FullName)

 

   Dim scriptRefs As NewList(Of ScriptReference)

   scriptRefs.Add(scriptRef)

   Return scriptRefs

End Function

End Class

Figure 2A: Thisboilerplate VB code is automatically generated by Visual Studio 2008 when youchoose the new project template highlighted in Figure 1. The C# version islisted in Figure 2B.

 

It should be noted that if the ASP.NET AJAX Server Controltemplate is chosen from the Visual Studio New Project dialog box shown inFigure 1 instead of ASP.NET AJAX Server Control Extender, the initial projectoutput is nearly identical. In a server control project, line 1 of Figure 2Awould be gone because a standard server control doesn?t extend other controls. Theonly other difference in the generated boilerplate code is that a servercontrol inherits from ScriptControl instead of ExtenderControl. Everything elseis functionally identical, including the contents of the JavaScript fileincluded in the project.

 

I made only two edits to the boilerplateExtenderControl1.vb file listed in Figure 2A; one on each of the first twolines. I changed the default word ?Control? to ?TextBox? on the first line (thisspecifies that the control extender is intended to extend only TextBox controls).I also changed the name of the class on line 2 to ?NumTextExt? from its genericdefault name of ExtenderControl1 (just to be more descriptive).

 

namespace NumTextExtCS

{

    [

       TargetControlType(typeof(Control))

   ]

   public class NumTextExt: ExtenderControl

   {

       PublicExtenderControl1()

       {

           //

           // TODO: Addconstructor logic here

           //

       }

       protected overrideIEnumerable<ScriptDescriptor>

               GetScriptDescriptors(Control targetControl)

       {

           ScriptBehaviorDescriptor descriptor = new

             ScriptBehaviorDescriptor(

               "NumTextExt.ClientBehavior1",

               targetControl.ClientID);

           yield returndescriptor;

       }

 

       // Generate thescript reference

       protected overrideIEnumerable<ScriptReference>

               GetScriptReferences()

       {

         yield return new

           ScriptReference("NumTextExt.ClientBehavior1.js",

           this.GetType().Assembly.FullName);

       }

   }

}

Figure 2B: This isthe C# equivalent of the code listed in Figure 2A.

 

The rest is all boilerplate code that you may never needto edit. It simply ensures that the extender control?s related JavaScript file (ClientBehavior1.js)is properly referenced in the project as an embedded WebResource. If you wantedto include additional JavaScript files, this is where you?d do it.

 

Figure 3 shows the boilerplate JavaScript code generatedfor ClientBehavior1.js. It?s not critical that you understand every detail ofthis script, because it is mostly just wiring things up as needed to work withMicrosoft?s client-side AJAXframework. The most significant lines are commented.

 

/// <reference name="MicrosoftAjax.js"/>

 

Type.registerNamespace("NumTextExt");

 

NumTextExt.ClientBehavior1 = function(element)

{

 NumTextExt.ClientBehavior1.initializeBase(this,[element]);

}

 

NumTextExt.ClientBehavior1.prototype = {

   initialize: function(){

       NumTextExt.ClientBehavior1.callBaseMethod(this,

       'initialize');

 

       // Add custominitialization here

 

   },

 

   dispose: function() {

       //Add customdispose actions here

 

       NumTextExt.ClientBehavior1.callBaseMethod(this,

       'dispose');

   }

}

 

NumTextExt.ClientBehavior1.registerClass

    ('NumTextExt.ClientBehavior1', Sys.UI.Behavior);

 

if (typeof(Sys) !== 'undefined')

   Sys.Application.notifyScriptLoaded();

Figure 3: This isthe boilerplate ClientBehavior1.js code automatically generated by VisualStudio 2008 when the new project template highlighted in Figure 1 is chosen.

 

Line 1 is not strictly necessary. It merely lets VisualStudio know that AJAX will be used.This enables Visual Studio 2008?s greatly enhanced JavaScript IntelliSensecapabilities to spring to life when editing the text of this file.

 

You should also take note of the other two comments inthis file, which point out key locations where you?ll need to insert customJavaScript constructor and destructor code for the control extender. This isthe constructor code I?ve added under the ?Add custom initialization here?comment in Figure 3:

 

var e = this.get_element();

 

this._keyPressDelegate =

 Function.createDelegate(this,this._onKeyPressDelegate);

 

$addHandler(e,"keypress",this._keyPressDelegate);

 

The above code wires up the client-side key-press event ofthe extended TextBox control. The key-press event is wired up to this new delegatefunction, which I?ve also added to the JavaScript file:

 

_onKeyPressDelegate: function ()

{

 var keyCode =window.event.keyCode;

 

 if (keyCode != 46&& keyCode != 92 &&

    (keyCode > 57 ||keyCode < 48))

   window.event.returnValue = false;

}

 

This function simply checks which key was pressed andcancels the event if the associated character is non-numeric and is not thedecimal character (.) or the backspace key.

 

Finally ? to keep things tidy ? the event is unwired inthe destructor (under the ?Add custom dispose actions here? comment of Figure3) using this single line of JavaScript code:

 

$clearHandlers(this.get_element());

 

With these three changes, the initial boilerplate code ofFigure 3 now looks like the listing in Figure 4. The numeric textbox extenderis now complete and can be compiled successfully.

 

/// <reference name="MicrosoftAjax.js"/>

 

Type.registerNamespace("NumTextExt");

 

NumTextExt.ClientBehavior1 = function(element)

{

 NumTextExt.ClientBehavior1.initializeBase(this,[element]);

}

 

 NumTextExt.ClientBehavior1.prototype = {

 initialize: function() {

 

  NumTextExt.ClientBehavior1.callBaseMethod(this,

    'initialize');

 

  // Add custominitialization here

  var e =this.get_element();

 

  this._keyPressDelegate =

    Function.createDelegate(this,this._onKeyPressDelegate);

  $addHandler(e,"keypress",this._keyPressDelegate);

 

 },

 

 _onKeyPressDelegate:function () //Custom function

 {

     var keyCode =window.event.keyCode;

 

     if (keyCode != 46&& keyCode != 92 &&

         (keyCode > 57 || keyCode < 48))

         window.event.returnValue = false;

 },

 

 dispose: function(){       

   //Add custom disposeactions here

   $clearHandlers(this.get_element());

 

   NumTextExt.ClientBehavior1.callBaseMethod(this,

    'dispose');

 }

}

 

NumTextExt.ClientBehavior1.registerClass

    ('NumTextExt.ClientBehavior1', Sys.UI.Behavior);

 

if (typeof(Sys) !== 'undefined')

   Sys.Application.notifyScriptLoaded();

Figure 4: Theboilerplate JavaScript code of Figure 3 has been modified as shown here torestrict keyboard input to numeric characters only.

 

Testing the Extender

To try out the extender, add a new Web application to yoursolution. Then drag a ScriptManager control onto the page (as is required byany page that takes advantage of Microsoft?s client-side AJAXframework).

 

Next, drag a standard TextBox control onto the Web form?sdesigner surface. A smart tag should appear, prompting you to optionally add anextender. Click on it to add an extender. The dialog box in Figure 5 thenappears. Select the NumTextExt extender we created. This will have the effectof linking the extender to the textbox by assigning ?TextBox1? to the controlextender?s standard TargetControlID property.

 


Figure 5: Visual Studio 2008provides enhanced support for control extenders with the new extender smart tagand dialog box shown here.

 

Now set the Web application to be the solution?s startupproject (via the right-click menu of Solution Explorer) and run the solution. Ifprompted to add debugging to the web.config file, accept. The resulting browserwindow should render a textbox that allows only decimal numbers to be entered. Othercharacters are filtered out by the client-side JavaScript code defined by thecontrol extender.

 

Conclusion

One of the most notable changes in Web development sincethe release of ASP.NET version 2.0 has been the emergence of AJAX.So it only makes sense that one of the most notable new enhancements to ASP.NETcontrol creation is the addition of AJAX-related capabilities. In Visual Studio2008 and ASP.NET 3.5, these enhancements have taken the form of the new ASP.NETAJAX Server Control and ASP.NET AJAX Server Control Extender project templates,which in turn take advantage of the new ScriptControl and ExtenderControl classes.

 

Every Web control developer needs to know about theseexciting new features. With such power at your fingertips you can create new cutting-edgecontrols that exhibit all the user-friendly AJAXfeatures that modern users have come to expect.

 

The code samples inthis article were created using Beta 2 of Visual Studio 2008, so there is asmall chance that minor code changes may regrettably be necessary in order towork with the final release version.

 

Steve C. Orr is anASPInsider, MCSD, Certified ScrumMaster, Microsoft MVP in ASP.NET, and authorof the book Beginning ASP.NET 2.0 AJAX by Wrox. He?sbeen developing software solutions for leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.net or e-mail him at mailto:Steve@Orr.net.

 

 

 

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS