Home > Articles > Programming > Windows Programming

ASP.NET Up Close

This chapter is from the book

Custom Server-Side Controls

During the last five years, Web usage has increased phenomenally—both 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 that—notably 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 controls—usually some combo boxes—are 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 devices—such as Internet cell phones, Windows CE machines, and handheld devices—are 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020