After you complete these configuration steps, Session state information is stored in the ASP.NET State Server automatically.. However, by default, Session state information is stored in
Trang 1CHAPTER 28 Maintaining Application State
WARNING
Don’t use the web configuration file in Listing 28.16 without modifying the values of
both the decryptionKey and validationKey attributes Those values must be secret
You can use the GenerateKeys.aspx page discussed in Chapter 27, “Using ASP.NET
Membership,” to generate new values for these attributes
After you complete these configuration steps, Session state information is stored in the
ASP.NET State Server automatically You don’t need to modify any of your application
code when you switch to out-of-process Session state
Configuring SQL Server Session State
If you want to store Session state in the most reliable way possible, you can store Session
state in a Microsoft SQL Server database Because you can set up failover SQL Server
clus-ters, Session state stored in SQL Server should survive just about anything, including a
major nuclear war
You must complete the following two steps to enable SQL Server Session state:
1 Configure your database to support SQL Server Session state
2 Configure your application to use SQL Server Session state
You can use the aspnet_regsql tool to add the necessary tables and stored procedures to
your database to support SQL Server Session state The aspnet_regsql tool is located in
the following path:
\WINDOWS\Microsoft.NET\Framework\[version]\aspnet_regsql.exe
NOTE
If you open the Visual Studio Command Prompt, you don’t need to navigate to the
Microsoft.NET folder to use the aspnet_regsql tool
Executing the following command enables SQL Server Session state for a database server
named YourServer
aspnet_regsql -C “Data Source=YourServer;Integrated Security=True” -ssadd
When you execute this command, a new database is created on your database server
named ASPState The ASPState database contains all the stored procedures used by Session
state However, by default, Session state information is stored in the TempDB database
When your database server restarts, the TempDB database is cleared automatically
If you want to use SQL Server Session state with a failover cluster of SQL Servers, you can’t
store Session state in the TempDB database Also, if you want Session state to survive
database restarts, you can’t store the state information in the TempDB database
Trang 2If you execute the following command, Session state is stored in the ASPState database
instead of the TempDB database:
aspnet_regsql -C “Data Source=YourServer;Integrated Security=True” -ssadd -sstype p
This command includes a -sstype p switch The p stands for persistent Session state
stored in the ASPState database is called persistent Session state because it survives
data-base server restarts
Finally, you can store Session state in a custom database The following command stores
Session state in a database named MySessionDB:
aspnet_regsql -C “Data Source=YourServer;Integrated Security=True”
➥-ssadd -sstype c -d MySessionDB
Executing this command creates a new database named MySessionDB that contains both
the tables and stored procedures for storing Session state The -sstype switch has the
value c for custom The command also includes a -d switch that enables you to specify
the name of the new database
If you want to remove the Session state tables and stored procedures from a server, you
can execute the following command:
aspnet_regsql -C “Data Source=YourServer;Integrated Security=True” -ssremove
Executing this command removes the ASPState database It does not remove a custom
Session state database You must remove a custom database manually
After you configure your database server to support Session state, you must configure
your ASP.NET application to connect to your database You can use the web configuration
file in Listing 28.17 to connect to a database named YourServer
LISTING 28.17 Web.Config
<?xml version=”1.0”?>
<configuration>
<system.web>
<sessionState
mode=”SQLServer”
sqlConnectionString=”Data Source=YourServer;Integrated Security=True”
sqlCommandTimeout=”30” />
<machineKey
decryption=”AES”
validation=”SHA1”
decryptionKey=”306C1FA852AB3B0115150DD8BA30821CDFD125538A0C606DACA
➥53DBB3C3E0AD2”
validationKey=”61A8E04A146AFFAB81B6AD19654F99EA7370807F18F5002725D
Trang 3CHAPTER 28 Maintaining Application State
➥AB98B8EFD19C711337E26948E26D1D174B159973EA0BE8CC9CAA6AAF513BF84E44
➥B2247792265” />
</system.web>
</configuration>
The sessionState element includes three attributes The mode attribute is set to the value
SQLServer to enable SQL Server Session state The second attribute, sqlConnectionString,
contains the connection string to the Session state database Finally, the
sqlCommandTimeout specifies the maximum amount of time in seconds before a command
that retrieves or stores Session state times out
The configuration file in Listing 28.17 includes a machineKey element If your Session state
database is located on a different machine than your ASP.NET application, you are required
to include a machineKey element that contains explicit encryption and validation keys
WARNING
Don’t use the web configuration file in Listing 28.16 or 28.17 without modifying the
val-ues of both the decryptionKey and validationKey attributes Those values must be
secret You can use the GenerateKeys.aspx page discussed in Chapter 27 to
gener-ate new values for these attributes
If you select the option to store Session state in a custom database when executing the
aspnet_regsql tool, you need to specify the name of the custom database in your
config-uration file You can use the web configconfig-uration file in Listing 28.18
LISTING 28.18 Web.config
<?xml version=”1.0”?>
<configuration>
<system.web>
<sessionState
mode=”SQLServer”
sqlConnectionString=”Data Source=YourServer;
Integrated Security=True;database=MySessionDB”
sqlCommandTimeout=”30”
allowCustomSqlDatabase=”true”/>
<machineKey
decryption=”AES”
validation=”SHA1”
decryptionKey=”306C1FA852AB3B0115150DD8BA30821CDFD125538A0C606DACA
Trang 4➥53DBB3C3E0AD2”
validationKey=”61A8E04A146AFFAB81B6AD19654F99EA7370807F18F5002725D
➥AB98B8EFD19C711337E26948E26D1D174B159973EA0BE8CC9CAA6AAF513BF84E44
➥B2247792265” />
</system.web>
</configuration>
The sessionState element in the configuration file in Listing 28.18 includes an
allowCustomSqlDatabase attribute Furthermore, the sqlConnectionString attribute
contains the name of the custom database
Enabling SQL Server session state has no effect on how you write your application code
You can initially build your application using in-process Session state and, when you
have the need, you can switch to SQL Server Session state
NOTE
ASP.NET 4 introduced a new option to compress session state for the out-of-process
providers (SQL Server and State Server) You can enable compression when using
these providers by setting the compressionEnabled option to true
<sessionState
mode=”SqlServer”
sqlConnectionString=”data source=dbserver;Initial Catalog=aspnetstate”
allowCustomSqlDatabase=”true”
compressionEnabled=”true”
/>
This compresses the session state before storing it, which can substantially improve
performance
Using Profiles
The ASP.NET Framework provides you with an alternative to using cookies or Session
state to store user information: the Profile object The Profile object provides you with
a strongly typed, persistent form of session state
You create a Profile by defining a list of Profile properties in your application root web
configuration file The ASP.NET Framework dynamically compiles a class that contains
these properties in the background For example, the web configuration file in Listing
28.19 defines a Profile that contains three properties: firstName, lastName, and
numberOfVisits
Trang 5CHAPTER 28 Maintaining Application State
LISTING 28.19 Web.Config
<?xml version=”1.0”?>
<configuration>
<system.web>
<profile>
<properties>
<add name=”firstName” />
<add name=”lastName” />
<add name=”numberOfVisits” type=”Int32” defaultValue=”0” />
</properties>
</profile>
</system.web>
</configuration>
When you define a Profile property, you can use any of the following attributes:
name—Enables you to specify the name of the property
type—Enables you to specify the type of the property The type can be any custom
type, including a custom component that you define in the App_Code folder (The
default type is string.)
defaultValue—Enables you to specify a default value for the property
readOnly—Enables you to create a read-only property (The default value is false.)
serializeAs—Enables you to specify how a property is persisted into a static
repre-sentation Possible values are Binary, ProviderSpecific, String, and Xml (The
default value is ProviderSpecific.)
allowAnonymous—Enables you to allow anonymous users to read and set the
prop-erty (The default value is false.)
provider—Enables you to associate the property with a particular Profile provider
customProviderData—Enables you to pass custom data to a Profile provider
After you define a Profile in the web configuration file, you can use the Profile object
to modify the Profile properties For example, the page in Listing 28.20 enables you to
modify the firstName and lastName properties with a form Furthermore, the page
auto-matically updates the numberOfVisits property each time the page is requested (see
Figure 28.7)
Trang 6LISTING 28.20 ShowProfile.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
void Page_PreRender()
{
lblFirstname.Text = Profile.firstName;
lblLastName.Text = Profile.lastName;
Profile.numberOfVisits++;
lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Profile.firstName = txtNewFirstName.Text;
Profile.lastName = txtNewLastName.Text;
}
</script>
FIGURE 28.7 Displaying Profile information
Trang 7CHAPTER 28 Maintaining Application State
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show Profile</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
First Name:
<asp:Label
id=”lblFirstname”
Runat=”server” />
<br /><br />
Last Name:
<asp:Label
id=”lblLastName”
Runat=”server” />
<br /><br />
Number of Visits:
<asp:Label
id=”lblNumberOfVisits”
Runat=”server” />
<hr />
<asp:Label
id=”lblNewFirstName”
Text=”New First Name:”
AssociatedControlID=”txtNewFirstName”
Runat=”server” />
<asp:TextBox
id=”txtNewFirstName”
Runat=”server” />
<br /><br />
<asp:Label
id=”lblNewLastName”
Text=”New Last Name:”
AssociatedControlID=”txtNewLastName”
Runat=”server” />
<asp:TextBox
id=”txtNewLastName”
Runat=”server” />
<br /><br />
<asp:Button
id=”btnUpdate”
Text=”Update Profile”
Trang 8OnClick=”btnUpdate_Click”
Runat=”server” />
</div>
</form>
</body>
</html>
Profile properties are exposed as strongly typed properties The numberOfVisits property,
for example, is exposed as an integer property because you defined it as an integer
property
It is important to understand that Profile properties are persistent If you set a Profile
property for a user, and that user does not return to your website for 500 years, the
prop-erty retains its value Unlike Session state, when you assign a value to a Profile property,
the value does not evaporate after a user leaves your website
The Profile object uses the Provider model The default Profile provider is the
SqlProfileProvider By default, this provider stores the Profile data in a Microsoft SQL
Server 2008 Express database named ASPNETDB.mdf, located in your application’s App_Data
folder If the database does not exist, it is created automatically the first time that you use
the Profile object
By default, you cannot store Profile information for an anonymous user The ASP.NET
Framework uses your authenticated identity to associate Profile information with you
You can use the Profile object with any of the standard types of authentication
supported by ASP.NET Framework, including both Forms and Windows authentication
(Windows authentication is enabled by default.)
NOTE
Later in this section, you learn how to store Profile information for anonymous users
Creating Profile Groups
If you need to define a lot of Profile properties, you can make the properties more
manageable by organizing the properties into groups For example, the web configuration
file in Listing 28.21 defines two groups named Preferences and ContactInfo
LISTING 28.21 Web.Config
<?xml version=”1.0”?>
<configuration>
<system.web>
<profile>
Trang 9<properties>
<group name=”Preferences”>
<add name=”BackColor” defaultValue=”lightblue”/>
<add name=”Font” defaultValue=”Arial”/>
</group>
<group name=”ContactInfo”>
<add name=”Email” defaultValue=”Your Email”/>
<add name=”Phone” defaultValue=”Your Phone”/>
</group>
</properties>
</profile>
</system.web>
</configuration>
The page in Listing 28.22 illustrates how you can set and read properties in different
groups
LISTING 28.22 ShowProfileGroups.aspx
<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.Drawing” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<script runat=”server”>
void Page_Load()
{
// Display Contact Info
lblEmail.Text = Profile.ContactInfo.Email;
lblPhone.Text = Profile.ContactInfo.Phone;
// Apply Preferences
Style pageStyle = new Style();
pageStyle.BackColor = ColorTranslator.FromHtml(Profile.Preferences
➥BackColor);
pageStyle.Font.Name = Profile.Preferences.Font;
Header.StyleSheet.CreateStyleRule(pageStyle, null, “html”);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Untitled Page</title>
</head>
<body>
CHAPTER 28 Maintaining Application State
Trang 10<form id=”form1” runat=”server”>
<div>
Email:
<asp:Label
id=”lblEmail”
Runat=”server” />
<br /><br />
Phone:
<asp:Label
id=”lblPhone”
Runat=”server” />
</div>
</form>
</body>
</html>
Supporting Anonymous Users
By default, anonymous users cannot modify Profile properties The problem is that
ASP.NET Framework has no method of associating Profile data with a particular user
unless the user is authenticated
If you want to enable anonymous users to modify Profile properties, you must enable a
feature of ASP.NET Framework called Anonymous Identification When Anonymous
Identification is enabled, a unique identifier (a GUID) is assigned to anonymous users and
stored in a persistent browser cookie
NOTE
You can enable cookieless anonymous identifiers Cookieless anonymous identifiers
work just like cookieless sessions: The anonymous identifier is added to the page URL
instead of a cookie You enable cookieless anonymous identifiers by setting the
cookie-less attribute of the anonymousIdentification element in the web configuration file
to the value UseURI or AutoDetect
Furthermore, you must mark all Profile properties that you want anonymous users to
modify with the allowAnonymous attribute For example, the web configuration file in
Listing 28.23 enables Anonymous Identification and defines a Profile property that can
be modified by anonymous users