Chapter
10
Building Web Applications with ASP.NET
If you’ve never created a Web application before because you
didn’t have time to climb the learning curve, ASP.NET could be your big chance.
This chapter shows you how to utilize everything you learned in the previous
chapter about building Windows Forms applications (plus a few extra twists) in
building ASP.NET Web Form Applications. It also demonstrates how to reuse the
business objects created in the previous chapter by taking you step-by-step
through the process of creating an ASP.NET Web Application.
Microsoft made a mistake a number of years ago
underestimating the tremendous impact the Internet would have on our world.
After realizing the error of its ways, Microsoft responded by creating Active
Server Pages (ASP)—a platform for creating, deploying, and running Web
applications. Although ASP contained some interesting technologies, it
definitely fell in the category of a “knee jerk” reaction. ASP allowed you to
get the job done, but not in the most efficient way.
In contrast, Active Server Pages.NET (ASP.NET) is a vast
improvement over ASP. Rather than using scripting languages to write
server-side code that is interpreted at run time, ASP.NET allows you to use
fully object-oriented languages such as C# and Visual Basic .NET to create code
that can be compiled and cached on the server for faster performance. ASP.NET
also provides a more robust event-driven model allowing events to be raised on
the client and handled on the server. In addition, Microsoft has done a great
job making the Windows Forms and Web Application architecture and design tools
similar enough so a developer can move from one to the other without incurring
a huge learning curve.
ASP.NET actually encompasses two different technologies—Web
Forms and Web Services. This chapter focuses on Web Forms. To learn about Web
Services, see Chapter 12, “XML Web Services”.

For information on using ASP.NET with Visual FoxPro 7, check out
the white paper by Cathi Gero (this book’s technical editor!) at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfoxgen7/html/usingaspnetwithvfp7.asp
What is a Web Application?
A typical Web application is comprised of Web pages,
configuration files, code files containing business object classes, images, and
references to external .NET assemblies. In this walk-through, you will see how
each element is used in an ASP.NET Web application.
A Web application starts the first time a user requests a
page from the server (for example, by entering the URL of the Web site). The
application continues to run until the Web server (the physical machine) is
restarted, IIS is restarted, or if any of the application’s configuration files
are edited.

There are a number of configuration settings where you specify
different conditions for starting a new process in your Web
application—percentage of memory used, number of unprocessed requests waiting in
the request queue, and so on. Adjusting these settings can help make your Web
applications more available and more stable. For more information, see the
“Machine.config” and “Web.config” sections later in this chapter.
What is a Session?
By default, the Web is a stateless environment. If you
send multiple requests from your Web browser to a particular Web site, you
automatically disconnect and reconnect between each request. A series of
successive requests coming from a single browser is known as a session.
The first request sent from a client browser to a Web application begins a
session for that client. By default (you can change this setting), if the
client is idle for longer than 20 minutes, the session is automatically ended
by the server.
Based on this disconnected model, your Web applications need
some way to keep track of all the user sessions. ASP.NET steps in the gap and
keeps track of each user session automatically. It does this by generating a
unique Session ID when a client sends its first request to your Web site. This
Session ID is passed back to the client by means of a cookie or modified URL.
For more information on sessions, check out the “The Session Object” section
later in this chapter.
Creating a Web Application
As in Chapter 9, “Building .NET Windows Forms
Applications”, you will learn about creating ASP.NET Web applications by
example. In this chapter you will recreate the Windows Forms application from
chapter 9 as a Web Forms application.
To create a new Web Application:
1. From
the Visual Studio .NET Start Page,
click the New Project
button.
2. In
the New Project
dialog’s Project Types pane,
select Visual C# to
create a C# Web application or Visual
Basic .NET to create a VB .NET Web application. In the Templates pane on the
right, select ASP.NET Web
Application.
3. Notice
that the Name text box is
disabled and contains the text “WebApplication1” and (if you’re creating the
Web Application on your local machine) the Location
text box contains the text “http://localhost/WebApplication1”. To change the
name of the Web application, you must change the name of the directory in the Location text box. This
is different from a Windows Forms application where you can change the name of
the application and the directory independently. In this example, change the
last part of the directory name from “WebApplication1” to
“MyFirstWebApplication”. As you type this in, notice that it automatically
changes the Name of the
application to “MyFirstWebApplication” (Figure 1).

Figure 1. The Location text box specifies the
virtual root directory for your Web application.
4. Click
the OK button.
At this point, you may feel a
bit like Al Gore when the “Creating the Web” dialog displays. While this dialog
is displaying, VS .NET creates a new application for you using the ASP.NET Web
Application template you selected. After a few moments, a new form named
WebForm1.aspx is displayed in design mode in the Visual Studio .NET IDE (Figure
2).

Figure 2. Visual Studio .NET creates an ASP.NET
Web Application from the template you select in the New Project dialog.
As you can see this is already very similar to creating a
Windows Forms application—VS .NET created an application for you containing a
single form. Before taking a closer look at this Web form, first you’ll do a
little housekeeping and then learn a little more about what happens behind the
scenes when using VS .NET to create a Web Forms application.
Renaming the project namespace
The housekeeping involves renaming the project’s
namespace. When you create a new Web application, VS .NET automatically sets
your project’s namespace to the same name as the project—which is most likely
not what you want!
If you’re using Visual Basic .NET, before you can change the
project’s namespace, you must first close the WebForm1.aspx. To do this, you
can simply click the close button [X]
to the right of the VS .NET IDE tabs.
To change the project’s namespace, in the Solution Explorer,
right-click on the project (the second node in the Solution Explorer)
and select Properties from
the shortcut menu, which launches the Property
Pages dialog. In the left pane under the Common Properties folder,
select General (if it’s
not already selected).
If you’re using C#, in the right pane, change the Default Namespace from
“MyFirstWebApplication” to “HW.NetBook.Samples”. If you’re using VB .NET, in
the right pane, change the Root
namespace to “HW.NetBook.Samples”. When you’re done, click the OK button to save
changes.
Now you just need to change any existing references to the
old name space. Select Edit | Find
and Replace | Replace in Files from the main menu to launch the Replace in Files dialog.
In the Find What box,
enter “MyFirstWebApplication” and in the Replace
with box enter “HW.NetBook.Samples” (make sure you type the case
correctly if working with C#). Now click the Replace
All button, which launches a Replace
All warning dialog. Just click OK
to ignore the warning. After clicking OK,
a dialog appears telling you how many occurrences were replaced. If you’re
using C#, it should say, “4 occurrence(s) replaced”. If you’re using Visual
Basic .NET it should say, “2 occurrence(s) replaced”.
Understanding virtual directories
When you created the new Web application and specified
the location of the application as “http://localhost/MyFirstWebApplication”
(Figure 1), you were actually specifying a virtual
directory. In the world of IIS, a
virtual directory is a directory on the Web server that contains a Web
application. It is virtual in the sense that it does not describe the exact
physical location of a directory on the machine, but provides a higher-level
virtual name that, behind the scenes, is associated with a real
directory.
In the Location string, the “localhost” directory refers to
the home directory of the Web Server. In IIS, this is set up by default to be
c:\inetput\wwwroot, and therefore the MyFirstWebApplication virtual directory
would be physically located in the c:\inetpub\wwwroot directory (Figure 3).

Figure 3. When you create a new Web application,
VS .NET creates a virtual directory that, by default, is physically located in
the c:\inetpub\wwwroot directory.
If you look in the new MyFirstWebApplication directory from
within Windows Explorer, you’ll see that VS .NET has created a variety of files
and subfolders in your new virtual directory (Figure 4).

Figure 4. VS .NET places a variety of files in
your Web application’s virtual directory.
You’ll be taking a closer look at some of these files in the
next section, but for now, notice there is a project file in this directory
(.csproj for C# or .vbproj forVB .NET ),
but no solution file (.sln). VS .NET puts the solution file in a subfolder of
the “My Documents\Visual Studio Projects\” directory. In the example, it
creates a subfolder named “MyFirstWebApplication” and places the MyFirstWebApplication.sln
and associated .suo file in this folder. So, when you need to reopen your Web
application after restarting Visual Studio .NET, you can find your solution in
this folder.
However, this does not mean your Web application’s source
code is stored in two different places. Remember the solution is simply a
container—similar to Visual FoxPro’s project (PJX) file—with links to projects
and files. For now, all your source code is stored in your Web application’s
virtual directory.
A closer look at the Web form
Now look a little closer at “WebForm1” in your new Web
application. A Web form can be viewed in either Design mode (Figure 2) or in
HTML mode. If WebForm1 is not currently opened in the IDE, double-click on the
form in the Solution Explorer. To switch to HTML mode, either click on the HTML
tab at the bottom left of the Web Forms designer or right-click the Web form
and select View HTML Source
from the shortcut menu. As you make changes to the Web form in design mode, VS
.NET automatically changes the HTML source accordingly. On the other hand, if
you know something about HTML, you can manually edit the HTML source and your
changes will be reflected in Design mode.
If you view the HTML source of WebForm1, you will see the
following HTML.
In C#:
<%@ Page
language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="HW.NetBook.Samples.WebForm1
%>
<!DOCTYPE HTML
PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft
Visual Studio 7.0">
<meta name="vs_defaultClientScript"
content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server"
>
</form>
</body>
</HTML>
If you’re using Visual Basic .NET, the only line that’s
different is the first line at the top of the page:
<%@ Page language="vb"
Codebehind="WebForm1.aspx.vb" AutoEventWireup="false"
Inherits="HW.NetBook.Samples.WebForm1 %>
This first line of code is known as a page directive.
The “Page Language” attribute tells the compiler the language used for the code
contained in the Web page (typically “c#” or “vb”). The “CodeBehind” setting
specifies a code-behind file associated with the .aspx file—in this case
either WebForm1.aspx.cs (C#) or WebForm1.aspx.vb (VB .NET).
The code-behind file and code-behind class
An ASP.NET Web page consists of two main parts—the
visible representation stored in the .aspx file and associated code stored in a
.cs or .vb code-behind file (which gets its name from “the code file behind the
form”.) This structure lets you separate the user interface from the executable
code. When you create a Web page in Visual Studio .NET, it automatically creates
both an .aspx file and a code-behind file. It associates the two by placing the
name of the code-behind file in the .aspx page directive as seen in the
previous section.
If you look at the list of files in the Solution Explorer, by
default, you won’t see the code-behind file. To make this file visible, click
on Solution Explorer’s “Show All Files” icon button, the second button from the
right at the top of the window. When you click this button, a plus sign appears
next to the WebForm1.aspx file. If you expand the plus sign, you will see the
associated code-behind file (Figure 5).

Figure 5. If you click on the “Show All Files”
icon button in the Solution Explorer, you can see your Web form’s code-behind
file.
To view the contents of the code-behind file, double-click
the file in the Solution Explorer and VS .NET opens it in the IDE. The
code-behind file contains the following code-behind class definition.
In C# (excluding the namespace directives):
public class WebForm1 : System.Web.UI.Page
{
private void
Page_Load(object sender, System.EventArgs e)
{
// Put user code to
initialize the page here
}
}
In Visual Basic .NET:
Public Class
WebForm1
Inherits System.Web.UI.Page
[Web Form Designer
Generated Code]
Private
Sub Page_Load(ByVal sender As System.Object,ByVal e As _
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page
here
End
Sub
End Class
As you can see, VS .NET automatically added code to this
code-behind file that defines a class named WebForm1 derived from the
System.Web.UI.Page class.
Now here’s the interesting part—look back at the
WebForm1.aspx page directive:
<%@ Page language="c#"
Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="HW.NetBook.Samples.WebForm1 %>
Notice the “Inherits” attribute specifies the .aspx page
inherits from the WebForm1 class (belonging to the HW.NetBook.Samples
namespace). When you compile your Web application under Visual Studio .NET, the
.aspx file is compiled into a class derived from the code-behind class! This
means you can add methods and other members to the WebForm1 code-behind class
and they will be inherited by the class created from the .aspx file at runtime.
You will see examples of how this works later in this chapter.
Hello .NET World!
Before diving further into the details of ASP.NET Web
applications, you can get some immediate gratification by creating a simple
“Hello .NET World!” Web page.
To start, select the WebForm1.aspx file in design mode. This
involves clicking the WebForm1.aspx tab and making sure the Design tab at the bottom
left of the IDE is selected. Notice the text in the middle of the Web form (Figure
6) states the Web form is set to work in “grid layout” mode, and objects
dropped on the form are arranged using absolute coordinates. For this example,
you will change the Web form to use “flow layout”, which is more like a word
processing document (you’ll use grid layout mode later in this chapter). To
switch to flow layout, go to the Properties Window and change the pageLayout property to
“FlowLayout”. When you do this, the dotted grid lines disappear and the text in
the middle of the Web form changes accordingly.

Figure 6. By default, Web forms are set to work
in “grid layout” mode, but you can change their mode to “flow layout” to behave
more like a word processing document.
Now, drag and drop a label from the VS .NET Toolbox onto the Web form
(make sure the Web Forms
tab of the Toolbox is
selected). The label is automatically placed in the upper left-hand corner of
the form. Next, go to the Properties Window, change the (ID) property from
“Label1” to “lblHelloWorld”, and then change the Text
property to “Hello .NET World!”. This changes the visible text of the label on
the Web form accordingly.
Now change the font of the label. Click to the right of the
label control on the Web form (click at the point where your mouse pointer is
an “I-beam” rather than a quad-arrow) and you should see the Formatting toolbar
(Figure 7).

Figure 7. The Formatting toolbar allows you to
change the appearance of visual elements on your Web form.
Open the combo box that is set to “Normal” by default and select “Heading 1”
instead as shown in Figure 7. When you do this, it increases the font size and
bolds the label text.
Now you’re ready to compile and run your Web application. To
do this, click the Start
button or press F5.
When the Web application runs, you should see the text “Hello .NET World!” in
large, bold letters (Figure 8).

Figure 8. The obligatory Hello World application
provides immediate gratification for building your first Web application.
Now that you’ve gotten your first, simple Web application
under your belt, it’s time
for a quick overview of the different types of controls available to you when
creating Web Forms applications.
There are three basic types of Web controls in ASP.NET:
·
HTML controls
·
HTML server controls
·
Web Forms controls
HTML controls
HTML controls are the “classic” controls such as
<h1>, <input>, and <div>. These
controls are not processed by the Web server, but are sent directly to the
client browser for rendering. If you want the lightest-weight (but least
capable) controls for your Web forms, use HTML controls.
HTML server controls
HTML server controls are one step above regular HTML
controls regarding capability. Although the HTML for these controls looks very
similar to classic HTML controls, they have the added ability to enable
server-side processing, which includes data binding and responding to events
(discussed later in this chapter). These controls are designed to be most like
original HTML controls, so developers who are familiar with classic HTML
controls should feel very comfortable using these new ASP.NET counterparts.
Web Forms controls
Web Forms controls are the most capable of all the
ASP.NET controls. Rather than trying to imitate classic HTML controls, Web
Forms controls more closely resemble Windows forms controls. They can also
enable server-side processing, as do HTML server controls, but they are even
more powerful. For example, they can automatically detect the level of HTML
support provided by a browser and adjust their HTML output accordingly. In
addition,
they are useful in creating more complex controls such as the ad rotator and
calendar
controls. Based on their advanced capabilities, these are the controls used for
the examples
in this chapter.

To use Web Forms controls on your Web pages, make sure you have
the Web Forms tab selected in Visual Studio .NET’s Toolbox when you drag and
drop controls on your forms.
Now that you know about the different types of controls you
can use in creating Web Forms, take a closer look at what’s going on behind the
scenes with ASP.NET.
The global.asax file
Take a look at another file shown in the Solution
Explorer—the global.asax file. When you first create a new Web Application or
Web Service through Visual Studio .NET, a global.asax file is automatically
placed in the root directory of your application. At run time, the global.asax
file is automatically parsed and compiled by the CLR into a
dynamically-generated class derived from the .NET HttpApplication base class.
As its name suggests, this class represents a Web application and it’s used to
process requests from users.
If you right-click the global.asax file and select Open With from the
shortcut menu, it displays the Open
With dialog. Select “Source Code (Text) Editor” and then click
the Open button. When
the file opens, you will see an application directive similar to the
page directive found in the WebForm1.aspx file.
Here it is in C#:
<%@ Application
Codebehind="Global.asax.cs"
Inherits="HW.NetBook.Samples.Global"%>
And in Visual Basic .NET:
<%@ Application Codebehind="Global.asax.vb"
Inherits="HW.NetBook.Samples.Global"
%>
The “Codebehind” attribute specifies the name of the
associated code-behind file, and the “Inherits” attribute specifies the class
from which the global.asax file inherits—in this case
HW.NetBook.Samples.Global.
Right-click on global.asax in the Solution Explorer and
select View Code from the
shortcut menu to open the code-behind file named global.asax.cs (C#) or
global.asax.vb (VB .NET). If you look at the code contained in this code-behind
file, you’ll see it defines a class named Global derived from the
System.Web.HttpApplication class.
In C#:
public class Global : System.Web.HttpApplication
{
public Global()
{
InitializeComponent();
}
// The rest of the class
not shown for space reasons
}
In Visual Basic .NET:
Public Class Global
Inherits
System.Web.HttpApplication
#Region " Component Designer Generated Code "
Public Sub New()
MyBase.New()
'This call is
required by the Component Designer.
InitializeComponent()
'Add any
initialization after the InitializeComponent() call
End Sub
' The rest of the class
not shown for space reasons
#End Region
End Class
The first time a user requests any resource or URL
within your Web application, your Web application starts and the global.asax
file is parsed and compiled into a class derived from this Global class. The
object instantiated from this class processes requests from the user.
If you look further down in the class definition, you’ll see
application and session event handlers for the following events:
·
Application_Start
·
Session_Start
·
Application_BeginRequest
·
Application_EndRequest
·
Application_AuthenticateRequest
·
Application_Error
·
Session_End
·
Application_End
You place code in any of these empty event handler methods to
respond to the corresponding ASP.NET events. You can also add your own custom
members (such as methods, properties, fields) to this class. For example, at
Application Startup you may want to call Server.MapPath to determine the
current server path and store it in a static variable. This saves you from
making this call over and over again (and incurring a performance hit)
throughout your application. Add the following code shown in grey to your
global.asax file.
In C#:
public class
Global : System.Web.HttpApplication
{
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
}
// The rest of the class definition not shown here for space
reasons
}
In Visual Basic .NET:
Public Class Global
Inherits
System.Web.HttpApplication

#Region " Component Designer Generated Code "
Public Sub New()
MyBase.New()
'This call is
required by the Component Designer.
InitializeComponent()
'Add any
initialization after the InitializeComponent() call
End Sub
’ The rest of the class
not shown for space reasons
#End Region
Protected Sub
Application_Start(sender As [Object], e As EventArgs)

End Sub
'Application_Start
End Class
Now you can reference the static ServerPath property from
anywhere within your Web application. For example, the following code derives a
fully qualified path to a config.xml file by prepending the value stored in
Global.ServerPath to the file name.
Here’s the code in C#:
string ConfigFile = Global.ServerPath +
"\\config.xml";
And here it is in Visual Basic .NET:
Dim ConfigFile As String = Global.ServerPath +
"\config.xml"
Global objects
As a subclass of the HttpApplication base class, this
Global class exposes some important objects globally accessible throughout your
Web application. Some of these are:
·
Server
·
Application
·
Session
·
Response
·
Request
·
User
·
Site
Each of these objects is detailed in the following sections.
The Server object
The Server object is an instance of the
System.Web.HttpServerUtility class. This object has properties and methods
allowing you to get and set information regarding the machine where the Web
server is running as well as helper methods for processing Web requests.
Here is an example of accessing the MachineName property of
the Server object.
In C#:
string ServerName = Server.MachineName;
In Visual Basic .NET:
Dim ServerName As String = Server.MachineName
Notice you simply need to type the name of the Server object
followed by the property or method to access it from code. Table 1 lists
some other commonly used members of the Server object.
Table 1. Commonly used members of the Server
object
|
Member name
|
Type
|
Description
|
|
MachineName
|
Property
|
Property that stores the server’s
computer name
|
|
ScriptTimeout
|
Method
|
Gets and sets the server’s request
time-out
|
|
ClearError
|
Method
|
Clears the last error
|
|
GetLastError
|
Method
|
Returns the last error
|
|
HtmlDecode
|
Method
|
Decodes a string that has been
encoded to eliminate invalid HTML characters
|
|
HtmlEncode
|
Method
|
Encodes a string to be displayed in
a browser
|
|
MapPath
|
Method
|
Returns the physical file path of
the specified virtual directory
|
|
Transfer
|
Method
|
Transfers execution to the
specified Web page
|
|
UrlDecode
|
Method
|
Decodes a string encoded for HTTP
transmission and sent to the server in a URL
|
|
UrlEncode
|
Method
|
Encodes a string for HTTP
transmission from the server to the client via the URL
|
The Application object
The Application object is an instance of the
System.Web.HttpApplicationState class allowing you to share global data and
objects across multiple sessions in an ASP.NET application. The Application
object has a Contents dictionary collection property where you can add data and
objects at runtime that can be accessed from any user session. Although you can
specifically reference the Contents collection property to add or access items
in the collection, because it has been defined as an indexer, you simply access
the Contents collection by using the indexer syntax (For more information on
Indexers, see Chapter 5, “Object Orientation in C# and Visual Basic.
NET”).
For example, add the following code shown in grey to the
Application_Start method of the global.asax file. This code adds a new string
object named “ConnectString” to the Contents collection.
In C#:
protected void Application_Start(Object sender,
EventArgs e)
{
Global.ServerPath
= Global.ServerPath = Server.MapPath("");
}
And in Visual Basic .NET:
Sub Application_Start(ByVal sender As Object, ByVal e As
EventArgs)
Global.ServerPath = Server.MapPath("")
End Sub
To access this string, you use a similar syntax, but you must
cast the value to the appropriate type—this is because all objects stored in
the collection are stored as the Object type. For example, the following code
gets the value of the ConnectString item from the Application object.
In C#:
string Connect = (string)Application["ConnectString"];
In Visual Basic .NET:
Dim Connect As String =
CStr(Application("ConnectString"))
In a nutshell, the Application object provides an easy way to
store data and objects accessible from any user session.
Application object pitfalls
There are a few things to watch out for when using the
Application object. First of all, if you have a Web farm (a single Web site
that contains multiple Web servers) or a Web garden (a single Web server
machine with multiple processors), be aware that the Application object is
specific to a single process running on a single processor. This means sessions
running on different processors or different physical machines do not have
access to the same Application object. If you need truly global access to data
from all sessions running in a Web farm or Web garden, you can store the
information in a globally accessible database or data file, such as an XML
file.
If you allow clients to modify global data stored in the
Application object, you need to be aware of concurrency issues. Take for
example the following code making use of a Counter value in the Application
object.
In C#:
int Count = (int)Application["Counter"];
Count += 1;
Application["Counter"] = Count;
And in Visual Basic .NET:
Dim Count As Integer = CInt(Application("Counter"))
Count += 1
Application("Counter") = Count
What happens if another session increments the Application
object’s Counter value between the time this session gets the value, increments
it, and stores it back to the Application object? The first session’s increment
of the Counter would be lost. To prevent this, you call the Application
object’s Lock and Unlock methods.
In C#:
Application.Lock();
int Count = (int)Application["Counter"];
Count += 1;
Application["Counter"] = Count;
Application.UnLock();
In Visual Basic .NET:
Application.Lock()
Dim Count As Integer = CInt(Application("Counter"))
Count += 1
Application("Counter") = Count
Application.UnLock()
The call to the Application object’s Lock method causes the
Application object to lock access to any items subsequently accessed in the
Contents collection. For example, once the second line of code executes, the
“Counter” variable is locked to any other sessions, until the call to
Application.Unlock is made. Obviously, if you lock the Application object, you
want to unlock it as quickly as possible! Also beware of any “deadly embrace”
problems you may encounter when you allow a piece of code to lock more than one
variable. If Process A has the first variable locked and Process B has the
second variable locked, they could each be waiting indefinitely for the other
process to unlock the variable.
Fortunately, if you don’t unlock the Application logic after
locking it, the Web server unlocks the Application object when it finishes
processing the .aspx file.
The Session object
The Session object is an instance of the
System.Web.SessionState.HttpSessionState class. In the same way the Application
object stores information accessible from all sessions in an application, the
Session object stores session state—information accessible from all Web forms
in a single user session. The unique session ID keeps each session’s data
separate from all other session data.
The Session object also has a Contents dictionary collection
property accessible with indexer syntax. For example, the following code adds a
new string object named “ISBN” that contains an ISBN number to the Contents
collection.
In C#:
Session["ISBN"] = "0-596-00171-1";
And in Visual Basic .NET:
Session("ISBN") = "0-596-00171-1"
Here’s an example of accessing this item in C#:
string ISBN = Session["ISBN"];
And in Visual Basic .NET:
Dim ISBN As String = Session("ISBN")
The Session object is extremely useful for storing
information that needs to be passed from one page to the next in a given
session.

By default, Session state is stored in memory outside of the
ASP.NET process. This means if the server is restarted or crashes (IIS—not the
physical server), session state is not lost! For other Session state options
see the “Caching data and objects” section later in this chapter.
The Session object has a number of other useful properties
and methods. Some of the most frequently used members are listed in Table 2.
Table 2. Commonly used members of the Session
object
|
Member name
|
Type
|
Description
|
|
IsCookieless
|
Property
|
If True, specifies the session ID
is embedded in the URL. If False, indicates the session ID is stored in an
HTTP cookie.
|
|
IsNewSession
|
Property
|
Returns a boolean value indicating
if the session was created with the current request.
|
|
Mode
|
Property
|
Specifies how session state is
cached. The value of this setting is
one of the four SessionStateMode enumerations: InProc (the default), Off,
SqlServer, StateServer. For more information on session state caching, see
the “Caching Data and Objects” section later in
this chapter.
|
|
SessionID
|
Property
|
Gets the current unique session ID.
|
|
Abandon
|
Method
|
Cancels the current session.
|
|
Clear
|
Method
|
Clears all values from the session
state.
|
The Response object
The Response object is an instance of the System.Web.HttpResponse
class and is one of the most important objects in ASP.NET. This object sends
information from the Web server to
the client.
For example, the following code displays a simple “Hello .NET
World” message to the client’s browser.
In C#:
Response.Write("Hello .NET World");
And in Visual Basic .NET:
Response.Write("Hello .NET World")
The Response object can also redirect to another page. The
following example redirects the client to the Hentzenwerke web site.
In C#:
Response.Redirect("http://www.hentzenwerke.com");
And in Visual Basic .NET:
Response.Redirect("http://www.hentzenwerke.com")
Table 3 lists some other commonly used properties and
methods of the Response object.
Table 3. Commonly used members of the Response
object
|
Member name
|
Type
|
Description
|
|
Buffer
|
Property
|
Specifies whether output should be
buffered (wait until the entire Response is finished processing).
|
|
Expires
|
Property
|
Specifies the number of minutes
before a page cached in a browser expires.
|
|
IsClientConnected
|
Property
|
Returns a boolean value indicating
if the client is still connected.
|
|
Flush
|
Method
|
Sends all buffered output to the
client.
|
|
Redirect
|
Method
|
Redirects a client to the specified
URL.
|
|
|