This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.

MSDN Magazine

Server-side Controls in Active Server Pages+
George Shepherd
Q

Ever since the PDC in July I've been hearing about Active Server Pages+ (ASP+) server-side controls. What are they, and how are they different from ActiveX® controls? Why would I ever use one?
Web Andrews

A

That's a good question. With all the new technology coming from Microsoft, it's sometimes hard to keep everything straight.
      Server-side controls are custom controls. You're probably thinking that custom controls have been around forever, right? There were VBXs in the early 90s, OLE Controls in 1994, and ActiveX controls in 1996. One main characteristic of these controls is that they reside on the client. Server-side controls are different because they live on the server. Why would you want to create controls to hang out on the server when you could simply build client-side controls?

The Problem of Extending the Browser

      Here's the problem with using client-side controls to enrich the user interface: a browser has to support the technology to extend it. For example, if you want the browser to use an ActiveX control to interact with the site, that browser must support ActiveX controls. The browser requires a handful of COM interfaces for this. Likewise, any Web site using Java-language applets expects browsers to support them.
      It's unrealistic to expect everybody to use the very latest version of a particular browser. And browsers aren't the only clients to consider; today people use WAP phones, Windows® CE-powered machines, and handheld devices. If you make Java-language applets or ActiveX controls essential to the operation of your Web site, you won't be able to reach clients that don't support them.
      In ASP+ there's an answer to this dilemmaâ€"move the responsibility of rendering to the server.

Server-side Rendering

      By definition, every browser can parse and display HTML. If you can't enrich the user interface by extending the browser, why not have the server pump out the right kind of HTML to give a customized appearance to the user? Microsoft calls these custom controls Web Form controls or server-side controls.
      Sure, you can always handcode the HTML for a rich user interface, or program it into your ASP page. What Microsoft brings to the table is an established framework and protocol for generating a rich UI from the server.
      Web Form controls are independent of the Web pages that use them and can be created, modified, and maintained separately from the pages. The public fields, properties, and methods of a Web Form control can be accessed programmatically by the containing control or page. In addition, Web Form controls are hierarchical; they can inherit from, contain, and extend other controls. In short, Web Form controls help promote component-based Web development while at the same time making it easier to reach a much wider range of client devices.
      Web Form controls are components designed to work within the upcoming ASP+ framework. They're implemented within DLLs written in a .NET common language runtime-targeted language that has the hooks expected by the ASP+ runtime. As ASP+ parses a Web page, the ASP+ runtime may encounter one of these controls. When ASP does encounter a control, the ASP+ runtime creates and initializes it. Like ActiveX controls, ASP+ server-side controls expose properties, methods, and events. However, these components, unlike ActiveX controls, live solely on the server. They are never downloaded to the client.
      Before dissecting the workings of these new server-side controls, let's take a high-level look at ASP and ASP+, because understanding the difference is important for understanding how server-side controls work.

ASP Versus ASP+

      For the past few years, ASP has evolved into a very useful means for generating HTML that is compatible with all types of browsers. The ASP execution model is pretty linear. When you set up an ASP script, the ASP runtime simply executes the script. While this works fine, it is slower than it could be and has other disadvantages associated with scripting. By contrast, ASP+ parses the ASP text and generates for execution a standard page class recognized by the .NET common language runtime. The class has an event-based execution model, and rendering the output stream (the generated HTML, for example) to the client is one phase of the Page execution.
      ASP+ defines two types of Web Form controlsâ€"pagelet controls and precompiled controls. Pagelet controls are composed of HTML text, tags, and possibly other HTML controls (buttons, text controls, and so forth). Pagelet controls are compiled on demand (as is the case with any other ASP+ page). Precompiled controls are written in a language that targets the common language runtime (CLR) and are compiled into DLLs. Right now, these languages include C#, the Managed Extensions for C++, and Microsoft® Visual Basic .NET. Other languages from other vendors are sure to follow. I'll focus on precompiled controls here.

Server-side Controls

      There are several compelling reasons to use a custom server-side control. In addition to making the rich user interface of your Web application useable in any number of client situations, you can use controls to partition your application into code and content. The programming model in ASP+ lets you separate HTML from executable code. By separating the presentation from the logic, each part may be developed independently of the other.
      Server-side controls represent a great opportunity for encapsulating reusable code, and they can be completely self-contained. That way, a page developer can drop an HTML tag onto a page.
      Finally, server-side controls simplify the application programming model. By encapsulating functionality in a custom control, page developers can use it by setting control properties and responding to events.
      The biggest part of understanding server-side controls is realizing that they exist to make it easier to manage specialized controls. Once you see the motivation behind them, the rest is mostly mechanics. To write a control, you should understand a little about ASP+, HTML, and a bit of C++ (or C#, or Visual Basic®) syntax. I'll look at the control architecture first through a C# class, then look at a similar control using Visual Basic syntax.

A Simple Control

      Under the .NET platform, code running under ASP+ must adhere to the CLR specifications. Right now, languages that target the CLR include C#, Visual Basic .NET, and the Managed Extensions to C++. Figure 1 shows a very simple control written in C#, whose job is to write a simple HTML-formatted string to a browser out on the Internet somewhere.
      While this is pretty much the simplest control you can create, it is complete and will compile into a working DLL. There are several notable aspects of the code in Figure 1, including the namespaces, the C# syntax, and the Render function. Let's take a look at each.

Namespaces
Instead of including header files as C++ does, C# uses namespaces. Namespaces organize C# programs, both internally and externally, by collecting related classes, interfaces, structures, enumerations, and delegates. The using directive tells the C# program which namespaces to use. The namespaces required by a server-side control include System, System.Web, System.Web.UI, and System.Web.UI.WebControls.
      The System namespace includes system services such as class activation and serialization. The System.Web namespace includes Web-oriented system services like HTTP management. The System.Web.UI namespace organizes services like control management and HTML cascading style sheet management. Finally, the System.Web.UI.Control namespace includes the definition of the Control class for building the control.

The Control Class
The Control class defines the properties, methods, and events common to all server controls in the ASP+ Page framework. C# supports implementation inheritance, just like C++, so control development involves deriving from a class and tweaking the virtual functions. However, with C# these functions are called overridable functions (C# includes a keyword, override, to enforce the calling of the correct version of the function). The Control class includes the necessary infrastructure to support server-side controls within the .NET platform. For this discussion, the important function to look at is called Render.

Server-side Control Rendering
The information you put into your control's Render method defines what the control will look like. Render takes a single argument of type HtmlTextWriter. HtmlTextWriter abstracts the details of streaming HTML content to the browser level. HtmlTextWriter has a host of member functions for doing this. The one that appears in Figure 1 is WriteLine, which takes a C# string and sends it to the browser. Other functions within HtmlTextWriter include methods like WriteLineNoTabs, WriteBeginTag, and WriteEndTag.

Control Lifecycle

      A server-side control is much like a finite state machine. It has an established lifecycle and set of states in which it can exist. For example, the control may be in a loading state, it may be responding to a postback, or it may be shutting down. The Control class provides the methods and properties for managing a page execution lifecycle, including view-state management, postback data handling, postback event handling, and output rendering. Implementing a server-side control involves deriving from the Control class and overriding certain methods.
      A rundown of a page's execution lifecycle is very useful in understanding how server-side controls work. As a page is loaded, the ASP+ 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 lets both ASP+ page code and server controls participate in the request processing and rendering of the page. Figure 2 shows the lifecycle of an ASP+ page and how controls fit in.

Figure 2 ASP+ Page Lifecycle
Figure 2 ASP+ Page Lifecycle

      Let's look at a rundown of an individual control's lifecycle. The communication protocol for a server-side control is divided between calls into established, well-known methods and miscellaneous postback processing.
      Responding to a page request, the ASP+ page first calls the control's Init function. Here's where any initial setup happens. Next, the control 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+ pages can be activated as a result of a postback from a previously rendered instance of the same page on the client. An example of this is a registration form with multiple text fields that must be resubmitted and validated. Think of a postback as a chance to refresh the page. 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 model and internal state appropriately. This is done so the visual and internal states of the control remain in synch automatically. Postbacks are handled by the IPostBackDataHandler interface.
      Once a page has been activated, a control needs to know when it's being loaded. Controls have the opportunity to override the OnLoad method and perform actions common to each incoming page request (for example, 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 may have 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 a user clicking it, 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 or control state is saved and before output is rendered by overriding Control's PreRender function.
      A control has the opportunity to save its view state by overriding the SaveViewState method of the Control class. 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, your control 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 comes time for an ASP+ page to render itself, ASP+ walks the entire list of controls instantiated on the pages, asking each one to render itself through the Render method.
      Finally, controls need a chance to clean up after a page is unloaded. Controls override the Dispose method to perform any final cleanup work.
      So, that's the lifecycle of a server-side control. Obviously the next question is: "How do you use one on a page?"

Using the Control on a Web Page

      The syntax for using a control on an ASP+ page is straightforward. The following code shows a very simple ASP+ page that loads a control.

  <%@ Register TagPrefix="MSDN" Namespace="MSDNSamples" %>
  
<html>
<body>
<MSDN:SimpleCtl runat="server"/>
</body>
</html>

 

      The first line in this ASP+ page declares a tag named MSDN that aliases the MSDNSamples namespace. (Go back up to the C# sample and take a look at the namespace declaration near the top.) Then the ASP+ page simply refers to the name of the control DLL. Notice the runat="server" attribute; it indicates that SimpleCtl is a server-side control. Remember that the job of ASP+ is to emit some HTML to the browser. This page first emits the html and body tags. Next comes the output of the control's Render function. The body and html tags are then closed off and the page ends.
      To test this page, just put it on a server and point to it using HTTP. The directory you're using needs to be a virtual directory under IIS. Use the Programs | Administrative Tools | Computer Management MMC snap-in to set up a virtual directory containing the ASP+ code. You can put anything you want into the output stream and it will show up in the browser. I'll look at a richer control in a future column.
      In addition to using C#, you can also write server-side controls in Visual Basic. The syntax is very similar; Figure 3 shows the same control in Visual Basic.
      Notice that the Visual Basic code imports the same namespaces as the C# program does. The Visual Basic code then defines a class that inherits from Control and overrides the Render method. This code will compile into a DLL and emit the string "What's up in Visual Basic?" when placed inside a browser as a server-side control.

Conclusion

      That's the high-level view of the new server-side control technology coming from Microsoft. Of course, I'm not implying that ActiveX controls are going away. But it does seem that they will be playing a different role for the developer. ActiveX controls are extremely useful when you can count on a certain type of client environment. ActiveX controls represent an excellent way to encapsulate UI gadgets like charts and unique controls. However, when you have no idea about what kind of client you're going to be delivering your application to, ASP+ server-side controls are usually a better option.
      In an upcoming column I'll look at a much richer control. I'll also examine the more advanced aspects of server-side controls such as managing the view state and dealing with postbacks.

George Shepherd is an Associate Director at Plural, where he helps companies use Microsoft technologies effectively. In addition, George delivers seminars with DevelopMentor and is the coauthor of Programming Visual C++ (Microsoft Press, 1998) and MFC Internals (Addison-Wesley, 1996).

From the October 2000 issue of MSDN Magazine.