Developer
Featured Article |
Designing State Management with ASP.NET
|
 |
By Scott Mauvais, MCSE, MCSD,
MCDBA
Designing good state management has
traditionally been one of the hardest parts of building Web
applications, and, when poorly implemented, state management
has led to more sluggish (and unreliable) Web sites than any
other design mistake. Fortunately, Microsoft� ASP.NET makes
state management so easy you don't have to worry about many of
the challenges you may have faced in other development
environments. Once you understand how state management works
in ASP.NET, you will forget you are even doing it�it is that
seamless!
|
In this article, I will show you the
keys to good state management that will help you avoid the
pitfalls that can result in an underperforming site. I start
off with a quick recap of what state means and why it is more
difficult in Web development than it is in desktop,
client/server, and other development models. Next I will
explain the various types of state. Finally, I will show you
the tools that ASP.NET provides to help manage those types of
state. By the time you have read through this article you will
understand state management in ASP.NET and will be ready to
build your own state-aware applications.
Because Microsoft engineers built the
the state management engine on top of ASP.NET, the best way to
learn the ins and outs of it is to pick up a book on Microsoft
ASP.NET. One of the best ones is Microsoft
ASP.NET Step by Step by G. Andrew Duthie. His book is a
great, modular primer, so you can jump in and read just the
sections in which you are interested. Duthie covers everything
from ASP.NET programming basics to security to trace
debugging�he even has a complete chapter on state management.
To get a feel for what is in the book and to make sure it is
right for you, check out the book's table
of contents and read the Chapter
9: Creating Web Forms.
Another must-have book is Dino
Esposito's Building
Web Solutions with ASP.NET and ADO.NET. This is a great
book if you are building applications that use XML or need to
connect to a backend database. The book covers essential
topics such as efficiently using data-bound .NET controls,
advanced reporting, and building disconnected applications.
You can also review the book's table
of contents and read the chapter Advanced
Data Reporting.
|
What Is
State and Why Do I Have to Manage It? |
State management refers to the process of preserving the
values of a set of attributes over time. In geek speak, the
collection of these values is called state. For Web
applications, this means preserving user information (such as
the contents of a shopping basket) as he or she navigates from
page to page. When you add an item to your shopping basket on
one page, you expect to be able to view it on the next page,
right?
This seems like a reasonable request and would
appear to be simple enough. The problem is that HTTP is a
stateless protocol. This means that, at a protocol level, any
attributes that are set on one page are not preserved and
available to a subsequent page. In other words, each request
is completely independent and has no knowledge of the commands
that preceded it.
At first glance you might think that
this lack of built-in state management is a horrible flaw in
the very underpinnings of the Web, but it is one of the two
main reasons (along with being text-based) HTTP has been so
successful. While it certainly presents some challenges to Web
developers, a stateless protocol allows for much greater
scalability than a stateful protocol ever could. A typical
stateful protocol requires that the server dedicate resources
(memory, connections, locks, CPU cycles, and so on) for each
user for the duration of his or her session, even when the
session is idle.
Think of a typical application
developed in Microsoft Access that connects to a back-end
database; nothing fancy, just a simple form that displays some
records. As soon as I open a datasheet, the database server
fires up a connection (which typically eats up a few dozen K
of RAM), allocates a cursor for the result set, and may even
lock a screenful of rows. Furthermore, it must check
back every now and then to make sure my connection is still
active lest it tie up those resources forever. Sure,
with this stateful connection I don't have to worry about
managing the data as my user scrolls through the rows, but
this convenience comes at a pretty high price in terms of
server resources. This model supports a few hundred concurrent
users, but it never would work on an Internet scale where I
need to support tens (and even hundreds) of thousands of
concurrent users. To achieve this level of scalability, I need
a protocol that minimizes the resources used by opening a
connection, possessing the request, sending the result, and
then closing down as fast as possible. And this is exactly
what HTTP gives me.
Because HTTP is stateless, if you
want to maintain state you have to build in state management
at a higher level�in the application. Astute readers will
realize that state management, regardless of where it happens,
takes resources. Why then, is managing state at the
application layer better than managing it at the protocol
layer? Removing the responsibility for state management from
the protocol (where it would have to maintain everything) and
bumping it up to the application results in two main benefits.
First, it allows developers to decide what information is
important. For example, if I am building a simple Web store,
the only state I really need to maintain is information about
a user's order�his or her userid and a list of products in
that user's shopping cart. On the other hand, if I am working
on a medical billing site, I need to track the user's IP
address, privilege level, and all the information viewed and
edited. Second, stateless models avoid holding open
connections, which are the most expensive resource.
The
downside of moving state management from the protocol to the
application is that now you and I have to build the logic
rather than just using part of the infrastructure that ships
with the product. With ASP.NET, however, the logic is part of
the infrastructure. Alas, I'm getting ahead of myself. I
have talked a lot about state without defining the various
types of state.
|
|
How Many
States Are There? |
When Web developers talk about managing state, they mean
correlating various unrelated (at a protocol level) requests
so that a given request has access to information�the
state�contained in a previous request. There are three types
of state that you will be most interested in managing:
- View�This refers to the state between
multiple views of the same page.
- Session�A session is defined as a
particular user's interaction with an application during a
specific visit.
- Application�This is the state shared by
all users of a particular Web application
If you are a Classic ASP developer you are no doubt
familiar with the much-maligned Session and Application
objects which were (and still are) used to manage session and
application state. Their shortcomings are well documented
elsewhere, so I won't go into them here other than to mention
that they are fixed. Enough said about the past; let's look at
examples of each of these in order.
View
State. Most people forget about view state, but it is
incredibly annoying to end users when it is implemented
incorrectly. Say you entered your billing information to
complete an on-line order. When you post the page back to the
server it will (hopefully) validate the information and, if it
finds errors, send the page back to you to correct. The
problem is that, by default, the information you previously
entered will be lost unless the developer puts in the extra
effort to save the original values and include them in the new
page. As a result, you would have to reenter all your
information if the developer is not dutiful. In ASP.NET, when
a form is processed, the current state is hashed into a string
and saved along with the page as a hidden field. When the
server processes the page, it retrieves this view state string
during page initialization and includes the field values
automatically so that the developer does not have to worry
about handcoding it into the app.
Session
State. This is the state that most developers think
of first. For example, when I add Microsoft
ASP.NET Step by Step to my shopping cart, the page
processing request knows that I added Building
Web Solutions with ASP.NET and ADO.NET five minutes ago
and will therefore show both books in my basket. Initially,
maintaining session state was one of the hardest things to do
in Web development because there was no standard way to
approach it. When Microsoft shipped ASP along with IIS 3.0 it
provided the Session object that provided an easy way for
developers to maintain a user's session state. The problem was
that the Session object stored all its information in memory
on the server. This had two major drawbacks. First, it did not
work in a Web farm because the user's session state was not
shared across all machines in the farm. Second, because it was
in memory, it was vulnerable should the machine fail. The
Session object in ASP.NET provides a persistent session state
management that can be shared across all servers in a Web farm
(and all processes in a Web garden) and can survive a failure
of any server in the farm.
Application
State. Just as Classic ASP provided a session object,
it also provided an Application object that managed
application state. As with the Session object, the Application
object was stored in a single server's memory; thus it
suffered the same drawbacks as the Session object. As you
would expect, the new Application object in ASP.NET provides a
distributed framework for managing application state that is
shared across all servers (or processes) and can survive
machine failures.
|
Configuring State in ASP.NET |
In ASP.NET, you have three ways of persisting the state.
First, you can use the standard in-process approach if you
want; however, this has the same drawbacks as Classic ASP. For
reliable state management, you can either use the ASP State
Server or Microsoft SQL Server� to maintain session and
application state. The State Server is a Windows NT� service
called ASP.NET State Service that provides state management
over TCP/IP and stores state in memory but in a separate
process (or even a separate machine) from IIS. The SQL Server
mode is similar to the State Server except that the state is
stored in SQL Server and therefore persisted to
disk.
Because the State Server approach stores the
state in memory, it is vulnerable should that server fail, so
I typically don't use it. I prefer to use SQL Server, but the
trade-off is a bit of a performance hit.
The best part
of state management in ASP.NET is that it is fully
configurable in the web.config file. This means you
can start off with the state server approach in development
and move to SQL Server in production. Here is the relevant
portion of the web.config file.
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=SQLStateServer;user
id=State;password=Secret"
server="StateServer"
port="42424"
/> </configuration>
Most of this
should be pretty straightforward, but let's look at the
entries quickly.
- Mode�The mode setting supports three
options: inproc, sqlserver, and stateserver.
- Cookieless�This determines whether or
not ASP.NET uses cookies or a unique key in the URL to
identify a user. This is a really important feature in
ASP.NET, as all other session-manage approaches require
cookies that more and more people are turning off out of
privacy concerns.
- Timeout�This defines the length of a
session in minutes.
- Sqlconnectionstring�If the mode is set
to sqlserver, this defines the connection string to the
Microsoft SQL Server hosting the state database.
- Server�If the mode is stateserver, this
lists the server name (or IP) address of the server running
the ASP.NET State Service.
- Port�If the mode is stateserver, this
defines the port that the ASP.NET State Service is listening
on. If you want to change the port it is located at
HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port.
|
|
For More
Information |
Now that you have an overview of developing Web
applications with Microsoft ASP.NET, you should be ready to
dive in and start developing your own real applications. I
started off this article by describing some of the state
management problems that result from using the HTTP protocol
and showed you how its stateless nature contributes to its
scalability and ends up being one of its strongest points.
Next I walked you through the different types of state�view,
session, and application. Finally, I covered some of the
features in Microsoft ASP.NET that make state management
incredibily easy.
To see exactly how easy it is to
develop Web Applications with ASP.NET applications, you should
get a copy of Microsoft ASP.NET
Step by Step by G. Andrew Duthie and Dino Esposito's Building
Web Solutions with ASP.NET and ADO.NET. With these books
in hand, you will be ready for any Web development challenge,
from creating Web forms to advanced reporting to securing your
application.
Another book you should consider picking
up is Building
XML Web Services for the Microsoft .NET Platform by Scott
Short. This book covers everything from architecture and
protocols to the best practices you need to know to build
Web-ready, distributed-object applications.
For
additional books and information, check out the following
resources:
|
 |
 |
|
Last Updated: Tuesday, August 6, 2002 |
| |
 |
 |
|