Comments
jcl wrote: Hi,thank you for this tutorial I'm interested on the first way to intregate Spring and EJB3. I have tried it in a example project buy it doesn't run. I'm searching since many time a solution,but nothing. I have posted on Spring forum,but no one seems can help me. I appreciate if you can help me.Thank you Antonio
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..

SYS-CON.TV
Today's Top SOA Links


Creating Composite Server Controls in ASP.NET 2.0
Make new components from old

One underutilized technique for maximizing code reuse and increasing developer productivity is the creation and utilization of ASP.NET Server controls. Even when the problem domain is well known and understood, each new project has many developers starting at square one, dragging and dropping the common Visual Studio.NET controls onto a blank form and having to manually repeat the same processes that other developers in the company have had to perform in the past.

Server controls are an in-depth topic and it would take an entire book to do the subject justice. In this article I will explain the basics of how to create a type of server control called a Composite control, and to highlight some of the differences between ASP.NET 1.x and ASP.NET 2.0 server controls.

The Case for Server Controls
Most businesses have certain sets or types of information that are ubiquitous to most of the applications being developed. Addresses, phone numbers, and customer names are just a few examples of common input collections that are often duplicated each time a new application is being developed. Much of this can of course be copied and pasted from one application to another, but when changes occur, these changes must then be made in multiple applications. An example of this type of change would be to an address for a company that has recently gone international and now must start capturing the country where their customers are located. By utilizing a server control, the display and client-side logic to handle this new data can be coded once, with developers now focusing on updating the business logic.

The server control in our example creates a simple user interface (UI) for entering phone numbers. It is composed of a Label control, a TextBox control, and two validator controls: one is a RequiredFieldValidator and the other is a RegularExpressionValidator. One of the advantages of using composite controls is that you can utilize the ASP.NET controls' built-in behavior to minimize the amount of code you have to write. For example, you will be able to utilize the validator controls to perform their native functions without having to write any control-specific code.

Defining a Composite Control
One of the first things you will probably notice if you are familiar with developing server controls under the ASP.NET 1.x model is that our control inherits from System.Web.UI.WebControls.CompositeControl (see Listing 1). In previous versions of the .NET Framework, you inherited from Control and had to implement the INamingContainer interface. These steps, along with other functionality, are now taken care of by the CompositeControl base class. The CompositeControl class also has an associated control designer that ensures that child controls are displayed on the design surface.

You will also notice several attributes attached to the class definition. These help define various characteristics of our control:

  • AspNetHostingPermission: This is required to ensure that code that links to the control has the appropriate security permissions
  • DefaultProperty: Specifies the property to highlight in the property browser when the page developer selects the control on the design surface
  • ToolboxData: Used to specify the format string for the design environment created when the control is added to a page
Define Composite Control Properties
The next step in our composite control is to define the public properties that will be accessible via the property browser in Visual Studio.NET. Most of the properties are a direct pass through to properties inherent of the controls that make up our composite control example. The code snippet in Listing 2 demonstrates this pass-through technique.

One of the nice features of ASP.NET 2.0 is the ability to assign a group name to a set of validators to ensure that validation occurs only for controls in the specified group. This enables you to have multiple separately-validated forms on a single page. In our property example above, the validation group is assigned to both of our validation controls during the set operation. It doesn't matter which validator control's property we returned for the ValidationGroup get operation and our arbitrary choice was the value from the phoneRequired control.

There are also several attributes on the property worth mentioning:

  • Bindable: Indicates that the property supports data binding
  • Category: Determines which category this property will be associated with on the PropertyGrid
  • Description: Tells the developer who is using the control what the property does
Adding the Controls to the Controls Collection
The next step in the process is to add the controls that make up our composite control to the Controls collection of the base CompositeControls class. This is a fairly straightforward process and simply involves initializing our controls, setting any default properties, and then utilizing the Add method to add them to the controls collection by overriding the CreateChildControls() method (see Listing 3).

Define Style Properties
Defining and using styles under ASP.NET 1.x took a considerable amount of work. Simply exposing the Style property of the controls within the composite control didn't work as expected, and though you would see the Style settings displayed in the property grid, setting them did not translate into run-time functionality. One of the reasons for this is that the ASPX page didn't have a location to store the values of the style settings. This has been remedied in 2.0 and multiple style properties can be exposed and recorded in the ASPX page to allow styles to easily be set at design time. Our property for each style sheet resembles any of the other properties we have created. The way ASP.NET handles the Style properties can be viewed by looking at the HTML view in Visual Studio.NET.

<cc1:PhoneControl ID="PhoneControl1" runat="server" LabelText="Phone"
FormatMessage="Invalid Phone Number" RequiredMessage="Phone is Required" >
    <LabelStyle BackColor="Red" ForeColor="White" />
</cc1:PhoneControl>

In this example we have set a specific style for the Label by set-ting the LabelStyle property in the property grid. This was translated into the LableStyle element as a sub element of the phone control itself.

Creating Custom Functionality
Although creating a composite control in and of itself provides a considerable benefit in terms of code reuse and faster development, it is always nice to provide some additional functionality to enhance the control's usefulness. For our example we are going to provide the ability for our control to automatically put the phone number that is entered into a standard format. In order to accomplish this, we are going to render some JavaScript on the client that will be called when our control loses focus to provide the formatting (see Listing 4).

The call to this method to render the JavaScript occurs during the OnPreRender event. The necessary control attribute to call the JavaScript function when the textbox loses focus was rendered in our CreateChildControls() method.

One thing to note for those who have developed server controls under the 1.x paradigm is the ClientScript property of the Page object. The ClientScript property is an object of type ClientScriptManager and should be utilized instead of the Page.RegisterClientScriptBlock() method that has been deprecated. It has a few new arguments, including asking for a type in addition to the key field to assist in matching up the client script to the control, as well as the ability to have the method automatically output the script tags by setting the addScriptTags argument to true, which is shown in this example.

Override the Render Method
The last step in the control creation is to override the render method to provide the formatting for our control on the page. In this example we render the multiple controls that make up our composite control within a table to be sure the way the control gets rendered is consistent in any page that may use the control. This is also the location of where we render any Style attributes that are set at design time by the page developer (see Listing 5).

Building and Using the Control
The last step in the process is to add our created control to the toolbox so that we can add it to our page by using drag and drop. The easiest way to do this is to open the toolbox panel, right-click on add/remove items, and then browse to the bin directory containing the assembly for the server control. This will add our control to the toolbox and from there it can be added to a Web form like any of the built-in controls. After adding a control to the toolbox we can now create a Web project. With the Web project newly created, drag and drop the phone control from the toolbox to a Web form. Let's also add a validation summary control and a submit button.

Start the Web project and enter in the area code and phone number without any symbols or formatting. Notice how the number neatly formats itself when you move off of it provided it has either 7 or 10 digits. If it doesn't, formatting doesn't occur and the form won't submit due to our regular expression validator. If you have set the Required property to true, the form will prevent you from submitting a blank number as well.

Summary
This fairly simple example demonstrates how easy it is to begin creating custom server controls that can be used to provide common functionality for your applications. It demonstrates how to create a composite control, apply styles, and add custom functionality. Spending the little bit of extra time to develop a custom control can result in productivity gains for developers and ease making global changes to the front end by having a single control to maintain.

-SIDEBAR-

Changes Between Developing Server Controls Under ASP.NET 1.x and 2.0
There were several changes to the ASP.NET server control model that improve upon the server control object model and to make control development easier. The list below highlights some of the most notable changes:

  • ControlState: This is an alternative way for developers to persist control properties in the page without using ViewState. The advantage is that while ViewState can be turned off at the page level by the developer, ControlState can't, so the control developer can be assured that data that has to be persisted for proper control function can't be turned off
  • ValidationGroup: Allows a group of controls to be validated together so that the developer can enforce validation on a subset of controls on a page
  • CompositeControl: A new class that can be inherited from by control developers that eases the development and creation of composite server controls
  • Styles: Working with CSS Styles has been made easier with the ability to expose Style properties into the property grid and have those changes created and stored in the ASPX page at design time
-END SIDEBAR-
About Wes Weeks
Wes Weeks is president and CEO of AgileWise, a software development and consulting firm based in Topeka, KS. Wes has extensive experience in object-oriented technologies, enterprise application architecture, and service-oriented architecture design and development. He is currently consulting for Security Benefit, an organization named one of CIO Magazine's "Agile 100" in 2004 that has successfully employed numerous Agile methods and processes.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

You're not supposed to override the render method anymore. In ASP.NET 2.0 the proper way to render the control is to override the RenderContents Method

One underutilized technique for maximizing code reuse and increasing developer productivity is the creation and utilization of ASP.NET Server controls. Even when the problem domain is well known and understood, each new project has many developers starting at square one, dragging and dropping the common Visual Studio.NET controls onto a blank form and having to manually repeat the same processes that other developers in the company have had to perform in the past.

One underutilized technique for maximizing code reuse and increasing developer productivity is the creation and utilization of ASP.NET Server controls. Even when the problem domain is well known and understood, each new project has many developers starting at square one, dragging and dropping the common Visual Studio.NET controls onto a blank form and having to manually repeat the same processes that other developers in the company have had to perform in the past.


Your Feedback
Anonymous wrote: You're not supposed to override the render method anymore. In ASP.NET 2.0 the proper way to render the control is to override the RenderContents Method
news desk wrote: One underutilized technique for maximizing code reuse and increasing developer productivity is the creation and utilization of ASP.NET Server controls. Even when the problem domain is well known and understood, each new project has many developers starting at square one, dragging and dropping the common Visual Studio.NET controls onto a blank form and having to manually repeat the same processes that other developers in the company have had to perform in the past.
SYS-CON Australia News Desk wrote: One underutilized technique for maximizing code reuse and increasing developer productivity is the creation and utilization of ASP.NET Server controls. Even when the problem domain is well known and understood, each new project has many developers starting at square one, dragging and dropping the common Visual Studio.NET controls onto a blank form and having to manually repeat the same processes that other developers in the company have had to perform in the past.
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE