Custom Server-Side Controls
During the last five years, Web usage has increased phenomenallyboth through regular Web surfing and e-commerce. Because of this, one of the most valuable assets consumers can provide for a company is their attention to the company's Web site. Naturally, companies want to create compelling, useful Web sites. Therefore Web users need sophisticated controls with which they can interact with the site.
Most browsers support standard controls such as push buttons and list boxes. However, the standard controls can take you only so far. Over the past few years, the primary way to enrich a Web page was to extend the browser. Several folks have taken a stab at thatnotably with Java applets and ActiveX controls (and we focus on ActiveX controls here).
When the user hits a page containing an ActiveX control, the browser proceeds to download a binary file representing the ActiveX control's executable code. The browser calls CoCreateInstance on the object, negotiates some interfaces, and renders the control in the browser. Java applets work in a somewhat similar fashion.
Both of these approaches have some specific advantages. The most significant advantage is that you can provide much more natural and intuitive ways for the user and Web site to talk to one another.
A great example of extending the browser is a calendar control. Imagine you are signing on to a Web site set up to handle airline ticket bookings. When it comes down to actually selecting the date for travel, clients needs to give their travel dates to the Web site. It is possible the Web site could expose a text box so that the client can type in a complete date, such as October 22, 2001. A better way would be to have standard combo boxes for selecting the month, day, and year of travel. Imagine that the users can also pull up a calendar to select their dates. Ahhh! That is much more intuitive and even more convenient. They can just point at the date they want and click to select it.
Many sites out there display a calendar for selecting dates. However, invariably, the old standby controlsusually some combo boxesare often right beside the calendar. What is going on? Why do users need both sets of controls?
Extending the Browser
The problem with extending the browser to enrich the user interface is that the browser has to support a technology to extend it. For example, if you want the browser to use an ActiveX control to interact with the site, that browser needs the infrastructure to support ActiveX controls. The browser requires a handful of COM interfaces for this. Likewise, any Web site using Java applets expects browsers to support the Java runtime.
Unfortunately, it is impossible to make sure every Web surfer out there uses the best browser available. It is difficult even to get people to agree on which browser is the best. It is also unrealistic to expect everybody to always use the very latest version of a particular browser. Most of us do not mind upgrading software every now and then, but there are many people out there who just hate it. The point is, there are diverse client browsers out there, and nobody seems to be able to enforce a standard.
It would not be so bad if the problem ended with browsers. However, during the last couple of years, numerous different devicessuch as Internet cell phones, Windows CE machines, and handheld devicesare now able to browse Web sites. Now it is even more difficult to count on a specific kind of UI on the client end. If you make Java applets or ActiveX controls integral to your Web site, you cannot reach certain clients.
ASP.NET's answer to this dilemma is to move to the server the responsibility of rendering and managing custom controls.
Server-Side Rendering
In the Web client world, HTML is the common denominator. Almost every browser understands how to parse and display HTML. If you cannot enrich the user interface by extending the browser, why not have the server generate the correct kind of HTML to give a customized appearance to the user? These controls are called Web forms controls. Microsoft provides an established framework and protocol for generating a sophisticated user interface from the server.
Web forms controls are reusable in that they are independent of the Web pages using them and can be created, modified, and maintained separately from the pages. The public fields, properties, and methods of a Web forms control can be accessed programmatically by the containing control or page. In addition, Web forms controls are hierarchical and can inherit from, contain, and extend other controls. In short, Web forms help "componentize" Web development (i.e., break apart Web user interfaces into small modularized pieces) while simultaneously making it easier to reach a much more diverse range of client devices.
Basically, a Web forms control is a component designed to work within the ASP.NET page framework. It's a DLL written in a .NET CLR language that has the proper hooks expected by the ASP.NET runtime. As ASP.NET parses a Web page, the ASP.NET runtime may encounter one of these controls. When ASP.NET does encounter a control, the ASP.NET runtime creates and initializes it. Like ActiveX controls, ASP.NET server-side custom controls expose properties, methods, and events. However, remember that these components now live on the server (and are not downloaded to the client on demand).
Control Life Cycle
A custom server-side control is much like a finite state machine. It has an established life cycle and set of states in which it can exist. For example, the control can be in a loading state, may be responding to a postback, or may be shutting down. The Control class provides the methods and properties for managing a page execution life cycle, including viewing state management, postback data handling, postback event handling, and output rendering. Implementing a server-side control means deriving from the Control class and overriding certain methods.
Knowing a page's execution life cycle is very useful for understanding how server-side controls work. As a page is loaded, the ASP.NET runtime parses the page and generates a Page class to execute. The Page class (which inherits from the Control class) instantiates and populates a tree of server control instances. Once the tree is created, the Page class begins an execution sequence that enables both ASP.NET page code and server controls to participate in the request processing and rendering of the page.
Following is a rundown of the individual control life cycle. The communication protocol for a server-side control is divided between calls to established well-known methods and various postback processing.
Responding to a page request, the ASP.NET page first calls the control's Init function. Here's where any initial setup happens.
The control now has an opportunity to set up its view state. View state information is not available during the control's Init call, so the control provides a function named LoadViewState explicitly for this purpose. A control maintains its view state in a Control.State collection. The State methods allow you to programmatically restore internal state settings between page views.
A page experiences something called a postback every once in a while. In addition to being activated as a result of a navigation request, ASP.NET pages can be activated as a result of a postback from a previously rendered instance of the same page on the client (for example, a registration form with multiple text fields that must be resubmitted and validated). Think of a postback as a chance to refresh. Controls have the opportunity to process data during a postback. That is, a control has the opportunity to process any incoming form data and update its object models and internal state appropriately. The visual and internal states of the control can automatically remain in sync. Postbacks are handled by the IPostBackDataHandler interface.
Once a page has been activated, a control wants to know when it is being loaded. Controls have the opportunity to override the OnLoad method to perform any actions common to each incoming page request (such as setting up a database query or updating a timer on a page).
A control may have to notify the client that data has changed. This is done during the postback change notification phase of the control. Controls fire appropriate change notification events during this phase in response to form and control value changes that occurred on the client between the previous and current postbacks to a page.
Controls handle client actions that cause a postback during the postback event processing phase of the control. For example, a button server control could handle a postback from the client in response to being clicked by a user and then raise an appropriate OnClick event on the server.
Controls have the opportunity to perform any last-minute update operations that must take place immediately before page/control state is saved and output rendered by overriding the control's PreRender function.
A control has the opportunity to save its view state by overriding its SaveViewState method. A control's state information is automatically transferred from the Control.State collection into a string object immediately after the SaveViewState stage of execution. To prepare for this, controls can override the SaveViewState event to modify the state collection.
Probably the most important function within a control is Render. Controls use the Render class to generate HTML output to the browser client. When it is time for an ASP.NET page to render itself, ASP.NET walks the entire list of controls instantiated on the pages, asking each one to render itself through the Render method.
Controls need a chance to clean up after a page is unloaded. Controls override the Dispose method to perform any final cleanup work.
Reasons to Use a Custom Server-Side Control
We considered a specific scenario for using a custom server-side control. However, there are several other compelling reasons for using one. In addition to making the sophisticated user interface of your Web application workable for any number of client situations, you may want to use controls to partition your application into code and content. ASP.NET's programming model lets you separate HTML from executable code. By separating the presentation part and the logical part of your application, both parts can be developed in parallel and independently.
Custom server-side controls represent a great opportunity for encapsulating reusable code. Server-side controls can be designed to be completely self-contained so that a page developer can just drop an HTML tag onto a page.
Finally, custom server-side controls simplify the application programming model. By encapsulating functionality in a custom control, page developers can use that functionality by setting control properties and responding to events. ASP.NET custom server-side controls effectively handle the issue of getting a sophisticated user interface to work in a variety of settings.