Chapter 3: What's New with ASP.NET?

The previous two chapters presented some important principles—the basic theories and goals of Microsoft's new .NET initiative and details of the software foundation upon which .NET is based. In this chapter, you'll get a quick overview of ASP.NET itself.

You'll learn how ASP.NET offers a new way to build Web applications with "smart" Web Forms and powerful Web Services. You'll also learn some of the infrastructure features of ASP.NET, including a powerful security model, improved deployment and update features, easier configuration, and increased scalability and availability for your ASP.NET solutions.

ASP.NET Web Forms and Web Services

ASP.NET offers a new, evolutionary approach to building Web applications on the Microsoft platform. This includes an improved, object-oriented programming model for creating Web pages, built-in support for multiple client browsers and devices, and clear separation between markup and execution code.

Improved Web Page Authoring

In the past, a Microsoft Web author was limited to standard HTML markup and client- and server-side interpreted scripting. This meant that both code and markup often were mixed on the same page, making it difficult to update and maintain solutions over time. Also, programmers had to constantly switch between server-side and client-side coding in order to create fully functional solutions. However, ASP.NET introduces solutions for these problems.

Simplified Programming Model

ASP.NET supports a complete language model including Visual Basic, C#, JScript.NET, and many other third-party languages. In addition, ASP.NET solutions are fully compiled on the server. The results are increased performance and improved reliability. Even though all Web pages are compiled, ASP.NET programmers can still use the familiar text-based coding model by simply posting ASCII text pages to the Web server and allowing the ASP.NET runtime to perform the compilation automatically, as needed.

Finally, the programming paradigm for ASP.NET Web Forms is the familiar event- driven model. This is the same paradigm used by rich-client desktop applications such as the one used to build Windows forms applications. Consequently, it is now much easier for Windows programmers to build Web applications without having to learn a whole new set of programming rules and processes.

Multiple Client Support

The ASP.NET Web Forms model also provides automatic support for multiple client browsers and devices.

In the past, Web programmers had to create pages that searched for the browser type and version that was calling the page and then include customized code that took advantage of the features of each of the many browser types currently available. Now, ASP.NET Web Forms can automatically query the browser type and then determine the best mix of server and client code to use to support the calling device.

In some cases, this means that the ASP.NET runtime will send a great deal of client-side DHTML to the calling client, to limit the number of server-side postbacks and create a rich experience for the user. In other cases, the exact same ASP.NET Web Forms will send simple HTML to the browser in order to make sure that the page will work properly.

Separating Code from Content

Another key feature of ASP.NET Web Forms is their ability to easily separate execution code from page markup. In the past, it was almost inevitable that you would need to mix HTML markup and ASP scripting in the same page. As a result, rendering the markup without first completing all the execution code was almost impossible. Updating and maintaining ASP pages also was complicated since even simple changes in execution code could break HTML markup as well.

By default, ASP.NET Web Forms now offer a clear separation between code and markup. First, by offering a fully event-driven, object-oriented programming model, Web Forms simplify the creation of source code documents that separate code and markup. Also, ASP.NET supports code-behind format for Web pages. Code-behind capability allows you to place all execution code in an entirely different physical file. Listings 3.1 and 3.2 show an example of the code-behind format.

Listing 3.1 CODEBEHIND.ASPX—ASP.NET Web Form with HTML Markup and No Execution Code

%@ Page Description="Code-Behind style" Inherits="CBPage" Src="CBPage.vb" %>
<html>
<body>
<h2 id="header" runat="server" />
<hr />

<form runat="server">
<asp:TextBox id="nameInput" runat="server"/>
<asp:Button id="submit" OnClick="submit_click" runat="server"/>
</form>
<asp:Label id="postBack" runat="server" />
</body>

</html>

Listing 3.2 CBPAGE.VB—An Example of 'Code-Behind' for a Markup Page

Option Strict Off

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class CBPage : Inherits Page

  Public nameInput As TextBox
  Public header As HtmlGenericControl
  Public submit As Button
  Public postBack as Label


sub Page_Load(sender as Object, e As EventArgs)

  if Page.IsPostBack=false then
   submit.Text="Click me"
   header.innerHtml="In-Page Coding Style Web Form"
  end if
  
end sub

sub submit_click(sender as object, e as EventArgs)

  postBack.Text="Welcome back, " & nameInput.Text

end sub


end Class

You can see in Listing 3.1 the page declaration has the Inherits and Src attributes that link the execution code file (CBPAGE.VB) to the markup page (CODEBEHIND.ASPX). Modifying either the code or the markup without breaking the page is now much safer and easier.

ASP.NET Server Controls

Much of the power of the new ASP.NET Web Forms model comes from the use of the new server-side controls, or Web Controls. Web Controls offer a number of important features that make building ASP.NET Web Forms much easier. For example, Web Controls allow programmers to build Web Forms using XML-type markup in the page that ASP.NET will interpret at runtime in order to generate customized code based on the device calling to request the document.

Also, Web Controls automatically support custom rendering, view state, and postback. This makes the controls much more powerful and easier to work with. Finally, ASP.NET supports a number of high-level 'templated' controls. These controls allow programmers to use XML-like markup to determine the look and feel of the control at runtime, instead of locking down look and feel at design time.

Declarative Programming

Another instance of the power of ASP.NET Web Forms, declarative programming, handles much of the work that used to require extensive scripting. For example, in the past Web programmers needed to create libraries of client- and server-side script that could perform user-input validation at runtime. If the solution needed to support a wide range of browser types and versions, this could be a difficult scripting task.

Now, with ASP.NET Web Forms, programmers can use a simple XML-markup tag called a validation control that handles all aspects of input validation without adding any client- or server-side code at design time. Listing 3.3 shows an example of using an input validation control in an ASP.NET Web Form.

Listing 3.3 VALIDATE.ASPX—An Example of Declarative Input Validation

<%@ page description="validation example" %>
<html>
<body>
<h2>Input Validation Example</h2>
<hr />

<form runat="server">
Enter a string:
<asp:Textbox id="inputBox" runat="server" />
<asp:RequiredFieldValidator id="inputBoxVal"
controltovalidate="inputBox" runat="server">
Error: This is a required field</asp:RequiredFieldValidator>
<br />
<asp:Button id="submit" Text="Submit" runat="server" />
</form>
</body>

</html>

Figure 3.1 shows the error display when users attempt to press the submit button without entering a value in the input box.

Figure 3.1
The results of posting an empty field in an input validation form.

Support for ViewState and Postback

The ability of server controls to handle viewstate management and automatic postback services without any programmer intervention is yet another example of ASP.NET's power. In classic ASP coding, programmers needed to handle issues such as complex rendering, restoring input values on refresh, and posting the input back upon the same page to perform validation. This added a great deal of work and potential for errors when building user-friendly input forms.

In contrast, ASP.NET Web Forms builds all this intelligence into the server controls themselves. Programmers no longer need to know the details of the HTTP request headers in order to build easy-to-use input forms. Listing 3.4 shows an example that takes advantage of the viewstate and postback features of ASP.NET Web Forms.

Listing 3.4 POSTBACK.ASPX—An Example That Shows postback and viewstate Features of ASP.NET

<%@ page description="postback example" %>
<script language="vb" runat="server">
sub myButton_click(sender as object, args as EventArgs)
myLabel.Text=myTextBox.Text
end sub
</script>
<html>
<body>
<h2>PostBack Example</h2>
<hr />

<form runat="server">
Enter a string: <asp:TextBox id="myTextBox" runat="server" />
<asp:Button id="myButton" Text="Submit"
OnClick="myButton_click" runat="server" />
</form>
You entered: <asp:Label id="myLabel" runat="server" />
</body>

</html>

You should notice that the code block in Listing 3.4 does not address the HTTP request object at all. That is because the state of the input control is maintained after posting back to the server. Also notice that the HTML form control does not contain an action or method attribute. This is also handled by the ASP.NET Web Forms. Finally, after entering a string and pressing the submit button, the contents of the input box are retained (see Figure 3.2).

Figure 3.2
Running the POSTBACK.ASPX page in a browser.

Templated Controls

Finally, ASP.NET Web Forms offers a set of high-level controls that allow you to define your own look and feel for the display. You use a set of templates that define the display at design time, and let ASP.NET render the display at runtime. Listing 3.5 shows an example of a templated DataList control in an ASP.NET Web Form.

Listing 3.5 TEMPLATES.ASPX—An Example of the Templated DataLis Control

<form runat=server>
<asp:DataList id="DataList1" runat="server"
OnItemCommand="DataList_ItemCommand">
<HeaderTemplate>
Items
<hr />
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton id="button1" runat="server"
Text="Details" CommandName="select" />
<%# DataBinder.Eval(Container.DataItem, "StringValue") %>
</ItemTemplate>
<SelectedItemTemplate>
Item:
<%# Container.DataItem("StringValue") %><br>
Order Date:
<%# DataBinder.Eval(Container.DataItem, "DateTimeValue", "{0:d}") %><br>
Quantity:
<%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:N1}") %><br>
</SelectedItemTemplate>
<FooterTemplate>
<hr />
</FooterTemplate>
</asp:DataList>

</form>

You can see in Listing 3.5 that the DataList control has four different templates defined. One template defines the display of the list header and one defines the list footer. There is also a template that defines the display of each item in the list as well as a special template to define the item that has been selected by the user. Figure 3.3 shows how this looks when loaded in a browser.

Figure 3.3
Testing the templated DataList control.

ASP.NET Web Services

Possibly the most innovative aspect of ASP.NET is the ability to build SOAP-based (Simple Object Access Protocol) Web remote procedure invocations called Web Services. The Web Service feature of ASP.NET lets programmers publish components via the Internet, enabling others to call into those components directly using the SOAP open standard for communicating between machines. This feature brings a powerful distributed computing model to Web applications.

Easy Programming Model

While the SOAP interface is powerful, it also involves a complex mix of XML, protocol stacks, and message handling at the sockets level. However, ASP.NET allows programmers to create these powerful components without having to deal with XML or sockets at all. All you need to do is build a special ASMX text template that contains a class and set of methods that you wish to expose to the Internet and then post this document in your ASP.NET Web.

Listing 3.6 shows an example of a simple Web Service built using ASP.NET.

Listing 3.6 WEBSERVICE.ASMX—A Simple ASP.NET Web Service

<%@ webservice class="wsBasic" language="vb" %>
imports System
imports System.Web.Services

public class wsBasic : Inherits WebService
<WebMethod()>public function DoMath(ByVal Value1 as double, _
ByVal Value2 as double) as double
return(Value1*value2)
end function

end class

After placing this ASMX document in a public Web, users can execute the DoMath method with nothing more than a simple anchor tag in an HTML document:

<a href="wsbasic.asmx/DoMath?value1=12&value2=12>DoMath</a>

Support for Multiple Protocols

ASP.NET Web Services also support multiple protocols when communicating with the remote server that is publishing Web methods. For example, ASP.NET supports HTTP-get (anchor tags), HTTP-post (HTML forms), and SOAP (XML messaging). In addition, ASP.NET allows programmers to define their own custom protocol format. This capability makes it possible for ASP.NET to support new, more powerful communications protocols as they become available in the future.

ASP.NET Infrastructure

Along with an improved programming experience, ASP.NET also offers a number of infrastructure innovations that make ASP.NET more secure, easier to configure and deploy, and more scalable and reliable.

The following sections summarize just a few of the more important improvements in the ASP.NET infrastructure.

Powerful Security Model

ASP.NET now supports three different authentication schemes—Windows, Forms-Base, and Passport authentication. This means that you can integrate existing powerful security models into your application with a minimum of coding. Even better, in most cases, you can control the scheme using just a configuration setting, without having to change your code at all.

In addition to the authentication systems, ASP.NET also supports both URL- and access control list- (ACL-) based authorization services. This allows programmers to determine if authenticated users have the proper rights to perform the requested task or view the requested document. The built-in authorization scheme supports both user- and role-based security, too.

Improved Deployment and Update

In the past, deploying and updating most classic ASP solutions could involve gaining access to the registry on the remote server, stopping the Internet Information Server service, and possibly even rebooting the server itself. Now, with ASP.NET, deployment and update is extremely easy and reliable.

Deploying an ASP.NET solution requires only the ability to copy both pages and compiled components to a target Web root. This can be done with a simple DOS xcopy command, an FTP script, or even just dragging and dropping files from one machine to another.

Even better, there is no need to make entries in the Web server's registry and no need to run regsvr.exe against any compiled components. Instead, updating compiled components on a Web server is as simple as copying the new DLL over the old one. There is no need to restart Internet Information Server or reboot the server. As soon as the new DLL appears on the server, it is available to users of the public Web.

Easier Configuration

One of the main reasons that deployment and update of ASP.NET solutions is so easy is that most of the important information about the Web application is now kept in an XML-based configuration file. In fact, the ASP.NET runtime itself uses an XML configuration file to control most of its runtime behavior. As a result, programmers and Web administrators can quickly and easily update the settings of both Web servers and Web applications using simple text-based tools instead of special registry editors and metabase tools.

Listing 3.7 shows an example configuration file.

Listing 3.7 SAMPLE_WEB.CONFIG—A Sample Web Configuration File

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<appSettings>
<add key="PubsDSN"
     value="server=myServer;database=pubs;userid=sa;password=''" />
<add key="dialogLevel" value="expertMode" />
<add key="defaultBackgroundColor" value="white" />
<add key="defaultFontColor" value="black" />
</appSettings>
<system.web>
<customErrors mode="On" defaultredirect="ErrorGeneric.aspx">
<error statuscode="404" redirect="err404.aspx"/>
</customErrors>
<sessionState 
mode="inproc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20" 
    />
</system.web>

</configuration>

Increased Scalability and Availability

Lastly, ASP.NET has a number of improvements that help increase overall scalability and availability of your Web solutions, including improvements in session state, new data caching options, and the power to automatically restart services when memory gets low.

Improved Session State

ASP.NET allows you to configure session state management to use one of three supplied providers. You can use the default session state manager that saves all state information in memory on the local machine. This is the same scheme used in classic ASP.

However, you can also use the new "shared session state" manager. This allows you to indicate a server in a Web farm that will hold all the session state data for the entire Web farm. Now session state can be used in a load-balanced server cluster without any trouble at all. Finally, you can use the SQL state manager that allows you to store all session data in a special SQL Server database.

Most important, all these settings are transparent to your programs. You do all this work in the configuration files, not in your code. This means you can change the session-management scheme at any time in the life of your application without needing to change code in any way.

Data and Output Caching

ASP.NET also provides two different caching systems you can use in your ASP.NET solutions. First, you can use output caching for pages that you wish to keep in memory for a fixed time frame. All you need to do is add an output caching directive to the pages you wish to keep in memory. For example, the following code snippet will instruct ASP.NET to keep the page in memory for one hour.

<%@ OutputCache Duration="600">

When ASP.NET loads the page for the first time, it will keep the page in memory, and all subsequent requests for that page will be served from memory instead of executing the code.

You can also employ a new data caching service for your solutions. This allows you to place any object or collection into a special memory location and then recall it at any time. The data caching service is especially handy for database lists that do not change very often but are displayed frequently in an application such as a list of menu options.

Automatic Restarts

ASP.NET supports settings that control just how the runtime will behave in stressful situations, such as low memory or a high number of page requests.

This is handled using the <processmodel> element of the configuration files. For example, the following code snippet shows how to control the runtime behavior of ASP.NET.

<processModel enable="true"
requestLimit="200000"
requestQueueLimit="500"
memoryLimit="40"
/>

This entry tells the runtime that it should restart processes every 200,000 page requests, whenever the page queue grows past 500, or when the available free memory falls below 40MB.

The capacity for automatic restarts makes it much easier to build robust Web solutions that will perform a level of "self-healing" in stressful situations.

Summary

ASP.NET offers a number of important improvements over classic ASP. These improvements include programming changes, such as new, powerful Web Forms and Web Services that offer event-driven object-oriented programming, declarative smart controls, and separation between code and markup. In addition, improvements to the ASP.NET runtime infrastructure are powerful security services, improved deployment and updated features, easier configuration, and increased availability and reliability.