Storing Session State in a SQL Server Database, Page 3
Running the sample Web forms
To test your web forms, set Page1.aspx as the start page and run the Web site. You should see something as shown in Figure 4.
Select a few products by clicking the "Add to cart" button. This will add some rows in the DataTable. Recollect that you are storing your DataSet in a session variable. Then, navigate to Page2.aspx by clicking the "Show my cart" hyperlink. Figure 5 shows Page2.aspx with the previously selected products.
Figure 5: Sample run of Page2.aspx
As you can see, Page2.aspx correctly displays the items you selected on the previous page. This indicates that your session variable was indeed stored in the SQL server database and retrieved on the second page. Also, note that you used the same syntax of storing and retrieving values in the session irrespective of the storage mode.
Disadvantages of Storing the Session State in SQL Server
Though storing the session state in SQL server makes your Web site more scalable and reliable, it has some disadvantages of its own:
- Performance: In terms of performance, a SQL Server-based session store is possibly the slowest option. Because your session variables are stored in a physical database, it takes more time to get them in and out of the database. This affects the performance of your Web site.
- Cost: Because you are storing your data in a SQL Server database, you need to have a SQL Server license. This can add to overall cost of your Web site.
- Serializable data: This method requires that all the data stored in session variables must be serializable. This may force you to mark your own classes as [Serializable] if you want to store them in a session.
ASP.NET 2.0 allows you to store the session state to a SQL Server database. The ASPNET_REGSQL.EXE tool configures the SQL Server to support this feature. Further, the <sessionState> tag configures your Web site to support this mode. Storing a session state in SQL server is a more scalable, secure, and reliable option. However, its performance will be slower as compared to the other storage options.
Download the Code
You can download the code that accompanies the article here.
About the Author
Bipin Joshi is the founder and owner of BinaryIntellect Consulting, www.binaryintellect.com, where he conducts professional training programs on .NET technologies. He is the author of the Developer's Guide to ASP.NET 2.0 and co-author of three WROX press books on .NET 1.x. He writes regularly for www.dotnetbips.com and www.binaryintellect.net, the community Web sites he founded. He also writes about life and Yoga at www.bipinjoshi.com and www.binaryintellect.info. He is a Microsoft MVP, member of ASPInsiders, MCAD, and MCT. When away from computers, he spends time in practicing, studying, and teaching Yoga.
Page 3 of 3