Cache feature in ASP.NET 2.0
Author: xcniky nature: Original Time: 2004-11-18 9:36:48 Popularity: 8 Stephen Walther Microsoft Corporation applies to: Microsoft ASP.NET 2.0 Microsoft ASP.NET Framework Microsoft SQL Server Microsoft Visual Studio .NET Abstract: STEPHEN WALTHER will focus on the new cache functionality in ASP.NET 2.0, and how to use these new features to improve the performance and scalability of the ASP.NET application. (This article contains links to English sites.) This page is more relaxed in this page Using SQL Cache Invalidation Using the Post-Cache Substitution Conclusion For web applications driven by the database, to improve their performance, the best way is Use a cache. Retrieving data from the database may be one of the slowest operations you performed on a Web site. If you can cache data in the database to memory, you do not need to access the database when you request each page, so that you can greatly improve your performance. There is only one shortcomings in the cache, that is, the data expired. If you cache content of the database table to memory, your web application will display expired, inaccurate data when the records in the underlying database table changes. For some types of data, even if the data displayed is slightly out of time, the impact will not be too large; but for data such as stock prices and bidding bidding, even if the data displayed is slightly unacceptable. Microsoft ASP.NET 1.0 Framework does not provide a perfect solution for this issue. When using ASP.NET 1.0 Framework, you have to make a trade-off between performance and data expiration. Fortunately, Microsoft ASP.NET 2.0 Framework provides a new feature called SQL Cache Invalidation, which can solve this tricky problem. In this article, you'll learn more about many new cache improvements in ASP.NET 2.0 Framework. First, you will learn how to integrate cache support in the new DataSource control. You will then learn how to configure and use SQL Cache Invalidation. Finally, you will learn about a new control introduced with ASP.NET 2.0 Framework: Substitution control, using this control to insert dynamic content to the cached page. More relaxed data cache In ASP.NET 2.0 Framework, one of the biggest changes is the way to access database data on the ASP.NET page. ASP.NET 2.0 Framework contains a new set of controls, which is collectively referred to as DataSource controls. You can use these controls to represent data sources, such as databases or XML files. In the ASP.NET 1.0 Framework, it is used to display the database data by binding the control to the DataSet or DataReader, using the control. In ASP.NET 2.0 Framework, it is usually bound to the DataSource control. With the DataSource control, you can create an ASP.NET page that displays database data without writing any code for access database.
When dealing with database data, one of the following three DataSource controls is usually used: • SqlDataSource - Represents SQL data sources, such as Microsoft SQL Server or Oracle databases. • AccessDataSource - a dedicated SqlDataSource control for Microsoft Access databases. • ObjectDataSource - Indicates a custom business object that acts as a data source. For example, suppose you want to display a list of books that retrieve from the database in the DropDownList control. The page in Listing 1 describes how to bind the DropDownList control to the SqlDataSource control. List 1: DisplayTitles.aspxID = "DropDownList1" DataSourceId = "SqlDataSource1" DataTextField = "Title" Runat = "server" /> ID = "SqlDataSource1" ConnectionString = "Server = localhost; database = Pubs" SelectCommand = "SELECT Title FROM Titles "Runat =" server "/>
Note that the SQLDataSource control in Listing 1 is used to provide a connection string, and the SQL SELECT command is used to retrieve records from the database. The DROPDOWNLIST control is bound to the SqlDataSource control via its DataSourceID property. Use the DataSource control Cache data to use the DataSource control, not only easier to connect the database, but also make cache database data easier. Simply set one or two properties on the SqlDataSource control, you can automatically cache data represented by the DataSource control in memory. For example, if you want to cache the Titles database table in memory in memory, you can declare the SqlDataSource control in the following way. ID = "SqlDataSource1" EnableCaching = "true" CacheDuration = "600" ConnectionString = "Server = localhost; database = Pubs" SelectCommand = "SELECT Title FROM Titles" Runat = "server" /> EnableCaching If the property is true, SqlDataSource The data retrieved through SELECTCOMMAND will automatically cache. With the Cachedure property, you can specify the time (in seconds) of the cache data before refreshing the data in the database. By default, SqlDataSource uses absolute expiration policies to cache data, that is, the number of seconds per specified is refreshed once from the database. In addition, you can choose to use variable expiration strategies. If you configure SqlDataSource to use a variable expiration policy, the data will not expire as long as you continue access to data. If you need to cache a large number of projects, use variable expiration policies will be very useful because this expiration policy will only reserve the most frequent projects in memory. For example, the following SQLDataSourceControl is configured to use a variable expiration strategy, the expiration time is 10 minutes. ID = "SqlDataSource1" EnableCaching = "true" CacheExpirationPolicy = "Sliding" CacheDuration = "600" ConnectionString = "Server = localhost; database = Pubs" SelectCommand = "SELECT Title FROM Titles" Runat = "server" /> Because CacheExpirationPolicy properties The value is set to sligned, the value of the cacheduration property is set to 600, so the data indicated by this SqlDataSource will remain in memory as long as it is continuously accessed within 10 minutes. Back to top Using SQL Cache Invalidation SQL Cache Invalidation is one of the new features of ASP.NET 2.0 Framework most expected. Use SQL Cache Invalidation to get all the performance advantages of cache without worrying about data expiration.
SQL Cache Invalidation automatically updates the data in the cache when you change the data in the underlying database. SQL Cache Invalidation Check the data changes by continuous polling the database in the background. Every time you have a certain time (milliseconds), ASP.NET Framework checks if there is an update in the database. If ASP.NET Framework detects any changes, remove any item added from the database from the database (ie, these items will expire). Note: Microsoft SQL Server 2005 supports a distinct SQL Cache Invalidation method. You can configure SQL Server 2005 to notify ASP.NET applications when changing in database, database tables, or database rows. This way, ASP.NET Framework does not need to check the data changes by continuously polling SQL Server 2005 databases. It should be noted that SQL Cache Invalidation can only be used in Microsoft SQL Server 7 and higher, which cannot be used for other databases such as Microsoft Access or Oracle. SQL Cache Invalidation can be used when the output of the entire page is cached, using the DataSource control or directly using the Cache object. These three situations will be described below. Configuring SQL Cache Invalidation Before using SQL Cache Invalidation in a web application, you must first perform some configuration steps. The Microsoft SQL Server must be configured to support SQL Cache Invalidation and must also add the necessary configuration information in the application's web configuration file. You can configure SQL Server as follows: Use the ASPNET_REGSQL command line tool, or use the SqlCachedependencyAdmin class. Enable SQL Cache Invalidation with ASPNET_REQSQL Use the ASPNET_REGSQL tool, you can configure SQL Cache Invalidation through the command line. The ASPNET_REGSQL tool is located in the Windows / Microsoft.Net / Framework / [Release] folder. To use this tool, you must open the Command Prompt window and browse to this folder. To support SQL Cache Invalidation when using the PUBS database, you need to perform the following command. The ASPNET_REGSQL-E-D Pubs -ed -e option enables the ASPNET_REGSQL tool to use integrated security when connecting to the database server. The -d option is used to select a PUBS database. Finally, the -ed option is used to enable SQL Cache Invalidation for the database. When this command is executed, a new database table named ASPNET_SQLCACHETABLESFORCHANGENOTIFICA will be added to the database. This table contains a list of all database tables that enable SQL Cache Invalidation. This command will also add a set of stored procedures in the database. After enabling SQL Cache Invalidation for the database, you must select a specific table to enable SQL Cache Invalid from the database. The following command will enable SQL Cache Invalidation for the Titles database table. The ASPNET_REGSQL-E-D Pubs -t title -et -t option is used to select a database table.
The -t option enables SQL Cache Invalidation for the database table. Of course, you can enable SQL Cache Invalidation for multiple tables by repeating this command for each database table. When this command is executed, a trigger will be added to the database table. As long as you modify the table, this trigger will trigger and update the ASPNET_SQLCACHETABLESFORCHANGENOTIFICATION table. Finally, you want to get a list of tables for SQL Cache Invalidation in a particular database, you can use the following command. ASPNET_REGSQL-E-D Pubs -lt This method will select a list of tables from the ASPNET_SQLCHETABLESFORCHANGENOTIFICATION. In addition, you can retrieve this information by performing queries directly in the database table. Use the SQLCachedEpendencyAdmin class ASPNET_REGSQL tool to use the SqlCachedependencyAdmin class by using the SQLCACHEPENDENCYADMIN class to configure Microsoft SQL Server. If you prefer, you can use this type directly from the ASP.NET page. The SQLCachedependencyAdmin class has five important methods: • Disablenotifications - Disable SQL Cache Invalidation for a specific database. • DisableTableForNotifications - Disables SQL Cache Invalidation for specific tables in the database. • Enablenotifications - Enables SQL Cache Invalidation for specific databases. • EnableTableForNotifications Enables SQL Cache Invalidation for specific tables in the database. • GetTablesenableDforNotifications - Returns a list of all tables that enable SQL Cache Invalidation. For example, using the ASP.NET page in Listing 2, you can configure SQL Cache Invalidation for any table in the PUBS database. Listing 2: Enablesci.aspx (c #) SQL Cache Invalidation
The following table has enabled SQL Cache Invalidation:
DataSourceID = "SqlDataSource1" cellpadding = "10" showhead = "false" runat = "server" />
ID = "sqlDataSource1" type = "system.Web.caching.sqlcachedependencyadmin" selectmethod = "gettablesenabledfornotifications" runat = "server" />
Forecolor = "red" runat = "server" />
Runat = "server" />
Listing 2: Enablesci.aspx (Visual Basic .NET)
SQL Cache Invalidation
The following table has enabled SQL Cache Invalidation:
CellPadding = "10" ShowHeader = "false" Runat = "Server" /> ID = "SqlDataSource1" TypeName = "System.Web.Caching.SqlCacheDependencyAdmin" SelectMethod = "GetTablesEnabledForNotifications" Runat = "Server" />
Forecolor = "red" runat = "server" />
OnClick = "enabletable" runat = "server" />
In Listing 2, the Connectionstring constant is used to select the database enabled SQL Cache Invalidation (if you want to enable SQL Cache Invalidation for the Pubs Database, you can change the value of this constant). In the Page_Load method, call the Enablenotifications method on the SQLCachedependencyAdmin class, which enables SQL Cache Invalidation for the database specified by the Connectionstring constant. The GridView in Listing 2 shows all database tables that currently enabled SQL Cache Invalidation. GridView is bound to the ObjectDataSource control, which calls the GetTablesNeableDforNotifications method for its SelectMethod. Finally, you can enable SQL Cache Invalidation to other tables using the pages in Listing 2. EnableTableForNotifications methods are called when you enter the name of the table in the text box and click the "Enable Table" button. SQL Cache Invalidation Web Configuration Settings Before the ASP.NET application uses SQL Cache Invalidation, the next step is to update your web configuration file. You need to configure ASP.NET Framework to poll the database of SQL Cache Invalidation. The web configuration file in Listing 3 contains configuration information necessary to polling the PUBS database. Listing 3: Web.config Connectionstring = "Server = localhost; database = pubs" /> name = "pubs" ConnectionstringName = "mysqlserver" POLLTIME = "60000" /> List of Web configuration files contains two parts. Part is used to create a database connection string to connect to a PUBS database called MySQLServer. The Caching section is used to configure SQL Cache Invalidation polling. In the sub-section, you can list one or more databases to be polled to check the data changes. In list 3, the database represented by MySQLServer is polled once per minute (every 60000 milliseconds). You can specify different polling intervals for different databases. Every time you poll the database to check the data changes, both the server must perform some operations. If you think the data in the database does not change frequently, you can increase the polling interval. Using SQL Cache Invalidation in the Page Outbox Now we have completed all configuration steps for SQL Cache Invalidation, you can use it in the ASP.NET page. One method is to use SQL Cache Invalidation in the page output cache. The page output cache allows you to cache all content displayed in the memory. By using SQL Cache Invalidation, you can automatically update the cached page when changing (only) database tables. For example, the page in Listing 4 shows the contents of the Titles database table in the GridView control.
At the top of this page, the OutputCache instruction is used to cache the page content in memory. If the Titles database table changes, the Sqldependency property will update the page. Listing 4: OutputCachetitles.aspxid = "grdtitles" DataSourceId = "sqldataasource1" runat = "server" /> id = "sqlDataSource1" selectcommand = "select * from titles" connectionString = "" Runat = "server" />
Note that the SQLDependency property references the name of the database defined in the web configuration file. Since we specified a Pubs database in a minute to check the data changes, if the database changes, the page in the list 4 will be updated within a minute. You can list multiple databases and / or multiple database tables for the SQLDependency property value. To create multiple dependencies, just separate each dependency with a semicolon. Use SQL Cache Invalidation in the DataSource control In addition to using SQL Cache Invalidation in the Page Outbox, you can use SQL Cache Invalidation directly in the DataSource control. If you want to use the same database data in multiple pages, consider using SQL Cache Invalidation in the DataSource control. SqlDataSource, AccessDataSource and ObjectDataSource controls support SQLCachedependency properties. For example, the page in the list 5 uses SQL Cache Invalidation in the SqlDataSource control. Listing 5: SqlDataSourceCaching.aspx
ID = "grdTitles" DataSourceId = "SqlDataSource1" Runat = "server" /> ID = "SqlDataSource1" EnableCaching = "true" SqlCacheDependency = "Pubs: Titles" SelectCommand = "select * from titles" ConnectionString = "" Runat = "server "/>
In Listing 5, the SqlDataSource control is declared using both of Both EnableCaching and SqlCachedependencency. The syntax used by the SQLCachedependencence property is the same as the SQLDependency property of the OutputCache instruction. You need to list the name of the database, followed by the name of the database table. Using SQL Cache Invalidation in the Cache object, you can also use SQL Cache Invalidation in the Cache object. This option allows you to maximize the programming of SQL Cache Invalidation. To use SQL Cache Invalidation in the Cache object, you will need to create an instance of a SQLCachedependency object. SQLCACHEDEPENDENCY objects can be used when inserting a new object in Cache using the INSERT method. For example, the page in Listing 6 displays the number of records in the Titles database table. The count is based on the dependency of the underlying database table. Listing 6: DisplayTITLOUNT.ASPX (C #) List 6: Displaytitlecount.aspx (Visual Basic .NET)
Back to top Using Post-Cache Substitution In many cases, you need to cache a part of the page instead of the page. For example, on your web site homepage, you may want to display a random title ad and record in the database table. If the entire page is cached, each user will see the same title ad on each requested page. To handle this problem with dynamic content and cache content, a method is to use a web user control. Because OutputCache instructions can be added to the web user control, the contents of the web user control can be cached so even if the content containing the page is not cached. But sometimes there may be a possibilities. Although you can use the web user control to add cached content on dynamic pages, but in many cases, you actually want to add dynamic content to the cached page. For example, suppose you want to cache the entire page, leaving only a small area to display the user name of the current user. In this case, it is best to use post-cache substitude. ASP.NET 2.0 Framework introduces a new control called Substitution control. You can use the Substitution control to insert dynamic content in the cached page. The page in Listing 7 uses the Substitution control to insert the username into the cache. Listing 7: Postcachesubstitude.aspx (C #)
Welcome methodname = "displayusername" runat = "server" />!
This page has cached because the time has no change.
Listing 7: Postcachesubstitude.aspx (Visual Basic .NET)
Welcome id = "substitude1" methodname = "displayusername" runat = "server" />!
This page has cached because the time has no change.