Cache feature in ASP.NET 2.0

xiaoxiao2021-03-05  24

Release Date: 11/2/2004

| Update Date: 11/2/2004

Stephen walther

Microsoft Corporation

Applicable to:

Microsoft ASP.NET 2.0

Microsoft ASP.NET FRMEWORK

Microsoft SQL Server

Microsoft Visual Studio .NET

Summary: In this article, Stephen Walther will focus on the new cache function 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 some links to English sites.)

This page

Easy data cache uses SQL Cache Invalidation to use Post-Cache Substitude Conclusion

For web applications driven by the database, improve their performance, the best way is to use caches. 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 to change the way 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 processing database data, one of the following three DataSource controls is usually used:

SqlDataSource - Represents SQL data sources, such as Microsoft SQL Server or Oracle Database. •

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 (see Figure 1). The page in Listing 1 describes how to bind the DropDownList control to the SqlDataSource control.

Figure 1: Search data using the SqlDataSource control

Listing 1: DisplayTitles.aspx

Display Titles </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><ask: DropDownList</p> <p>ID = "DropDownList1"</p> <p>DataSourceID = "SqlDataSource1"</p> <p>DataTextField = "Title"</p> <p>Runat = "server" /></p> <p><asp: sqldatasource</p> <p>ID = "SqlDataSource1"</p> <p>Connectionstring = "Server = localhost; database = pubs"</p> <p>SelectCommand = "SELECT TIM TIM TIM"</p> <p>Runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>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.</p> <p>Use the DataSource control to cache data</p> <p>With the DataSource control, not only make it easier to connect to the database, but also make the 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.</p> <p>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.</p> <p><asp: sqldatasource</p> <p>ID = "SqlDataSource1"</p> <p>EnableCaching = "True"</p> <p>Cachedure = "600"</p> <p>Connectionstring = "Server = localhost; database = pubs"</p> <p>SelectCommand = "SELECT TIM TIM TIM"</p> <p>Runat = "server" /></p> <p>If the value of the EnableCaching property is true, SqlDataSource will automatically cache the data retrieved through SELECTCOMMAND. 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.</p> <p>For example, the following SQLDataSourceControl is configured to use a variable expiration strategy, the expiration time is 10 minutes.</p> <p><asp: sqldatasource</p> <p>ID = "SqlDataSource1"</p> <p>EnableCaching = "True"</p> <p>CacheexpirationPolicy = "sliding"</p> <p>Cachedure = "600"</p> <p>Connectionstring = "Server = localhost; database = pubs"</p> <p>SelectCommand = "SELECT TIM TIM TIM"</p> <p>Runat = "server" /></p> <p>Since the value of the CacheExpirationPolicy property is set to sligned, the value of the cacheduration property is set to 600, so, as long as you continue to access within 10 minutes, the data indicated by this SqlDataSource will remain in memory.</p> <p>Back to top</p> <p>Use SQL Cache Invalidation</p> <p>SQL Cache INVALIDATION is one of the new features of ASP.NET 2.0 Framework. 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.</p> <p>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).</p> <p>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.</p> <p>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.</p> <p>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. Configure SQL Cache Invalidation</p> <p>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.</p> <p>You can configure SQL Server as follows: Use the ASPNET_REGSQL command line tool, or use the SqlCachedependencyAdmin class.</p> <p>Enable SQL Cache Invalidation with ASPNET_REQSQL</p> <p>Using 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.</p> <p>To support SQL Cache Invalidation when using the PUBS database, you need to perform the following command.</p> <p>ASPNET_REGSQL-E-D Pubs -ed</p> <p>The -e option allows the ASPNET_REGSQL tool to use integrated security settings 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.</p> <p>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.</p> <p>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.</p> <p>ASPNET_REGSQL-E-D Pubs -t Titles -Et</p> <p>-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.</p> <p>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.</p> <p>Finally, you want to get a list of tables for SQL Cache Invalidation in a particular database, you can use the following command.</p> <p>ASPNET_REGSQL-E-D Pubs -LT</p> <p>This method will select a list of tables from the ASPNET_SQLCACHETABLESFORCHANGENOTIFICATION. In addition, you can retrieve this information by performing queries directly in the database table.</p> <p>Use the SqlcachedependencyAdmin class</p> <p>The ASPNET_REGSQL tool configures Microsoft SQL Server using the SqlCachedependencyAdmin class in the background. If you prefer, you can use this type directly from the ASP.NET page.</p> <p>The SQLCachedependencyAdmin class has five important methods:</p> <p>•</p> <p>Disablenotifications - Disable SQL Cache Invalidation for specific databases.</p> <p>•</p> <p>DisableTableForNotifications - Disable SQL Cache Invalidation for specific tables in the database.</p> <p>•</p> <p>Enablenotifications - Enables SQL Cache Invalidation for a specific database.</p> <p>•</p> <p>EnableTableForNotifications - Enables SQL Cache Invalidation to specific tables in the database.</p> <p>•</p> <p>GetTablesenableDforNotifications - Returns a list of all tables that enable SQL Cache Invalidation.</p> <p>For example, using the ASP.NET page in Listing 2, you can configure SQL Cache Invalidation for any table in the PUBS database (see Figure 2).</p> <p>Figure 2: Enable SQL Cache Invalid from the ASP.NET page</p> <p>Listing 2: Enablesci.aspx (C #)</p> <p><% @ Page language = "c #"%></p> <p><% @ Import namespace = "system.web.caching"%></p> <p><script runat = "server"></p> <p>Const string connectionstring = "server = localhost; database = pubs";</p> <p>Void Page_Load ()</p> <p>{</p> <p>IF (! ispostback)</p> <p>{</p> <p>Sqlcachedependencyadmin.enablenotifications</p> <p>Connectionstring);</p> <p>SqlDataSource1.selectParameters.Add ("Connectionstring",</p> <p>Connectionstring);</p> <p>}</p> <p>}</p> <p>Void EnableTable (Object S, Eventargs E)</p> <p>{</p> <p>Try</p> <p>{</p> <p>Sqlcachedependencyadmin.enableetablefornotifications</p> <p>Connectionstring, TXTTABLENAME.TEXT);</p> <p>}</p> <p>Catch (Exception EX)</p> <p>{</p> <p>LBLERRORMESSAGE.TEXT = EX.MESSAGE;</p> <p>}</p> <p>TXTTABLENAME.TEXT = "";</p> <p>}</p> <p></ script></p> <p><html></p> <p><head runat = "server"></p> <p><title> Enable SQL Cache Invalidation </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><H1> SQL Cache Invalidation </ h1></p> <p>The following table has enabled SQL Cache Invalidation:</p> <p><p></p> <p><asp: gridview id = "grdtables"</p> <p>DataSourceId = "SqlDataSource1" Cellpadding = "10"</p> <p>Showheader = "false" runat = "server" /></p> <p></ p></p> <p><ask: ObjectDataSource</p> <p>ID = "SqlDataSource1"</p> <p>TypeName = "system.web.caching.sqlcachedependencyadmin" selectmethod = "gettablesenabledfornotifications"</p> <p>Runat = "server" /></p> <p><p></p> <p><asp: label id = "lblerrorMessage" enableviewState = "false"</p> <p>Forecolor = "red" runat = "server" /></p> <p></ p></p> <p><asp: textbox id = "txttablename" runat = "server" /></p> <p><asp: button text = "enable table" onclick = "enabletable"</p> <p>Runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Listing 2: Enablesci.aspx (Visual Basic .NET)</p> <p><% @ Page language = "vb"%></p> <p><% @ Import namespace = "system.web.caching"%></p> <p><script runat = "server"></p> <p>Const connectionString as string = "server = localhost; database = pubs"</p> <p>SUB Page_Load ()</p> <p>IF not ispostback.</p> <p>Sqlcachedependencyadmin.enablenotifications (_</p> <p>CONNECTIONSTRING)</p> <p>SqlDataSource1.SelectParameters.Add ("Connectionstring", _</p> <p>CONNECTIONSTRING)</p> <p>END IF</p> <p>End Sub</p> <p>Sub Enabletable (Byval S as Object, ByVal E as Eventargs)</p> <p>Try</p> <p>Sqlcachedependencyadmin.enableetablefornotifications (_</p> <p>Connectionstring, TXTTABLENAME.TEXT)</p> <p>Catch exception</p> <p>LBLERRORMESSAGE.TEXT = EX.MESSAGE</p> <p>END TRY</p> <p>TXTTABLENAME.TEXT = ""</p> <p>End Sub</p> <p></ script></p> <p><html></p> <p><head id = "Head1" runat = "server"></p> <p><title> configuresci </ title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><H1> SQL Cache Invalidation </ h1></p> <p>The following table has enabled SQL Cache Invalidation:</p> <p><p></p> <p><ask: gridview id = "grdtables" DataSourceId = "sqldatasource1" cellpadding = "10" showheader = "false" runat = "server" /></p> <p></ p></p> <p><ask: ObjectDataSource</p> <p>ID = "SqlDataSource1"</p> <p>TypeName = "system.web.caching.sqlcachedependencyadmin"</p> <p>SelectMethod = "gettablesenabledfornotifications"</p> <p>Runat = "server" /></p> <p><p></p> <p><asp: label id = "lblerrorMessage" enableviewState = "false"</p> <p>Forecolor = "red" runat = "server" /></p> <p></ p></p> <p><asp: textbox id = "txttablename" runat = "server" /></p> <p><ask: button id = "button1" text = "enable table"</p> <p>OnClick = "enabletable" runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>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.</p> <p>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.</p> <p>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.</p> <p>SQL Cache Invalidation Web Configuration Settings</p> <p>Before using SQL Cache Invalidation in the ASP.NET application, 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.</p> <p>The web configuration file in Listing 3 contains configuration information necessary to polling the PUBS database.</p> <p>Listing 3: Web.config</p> <p><Configuration></p> <p><Connectionstrings></p> <p><add name = "mysqlserver" Connectionstring = "Server = localhost; database = pubs" /></p> <p></ connectionstrings></p> <p><system.Web></p> <p><caching></p> <p><sqlcachedependency enabled = "true"></p> <p><databases></p> <p><add</p> <p>Name = "PUBS"</p> <p>Connectionstringname = "mysqlserver"</p> <p>PollTime = "60000" /></p> <p></ databases></p> <p></ sqlcachedependency></p> <p></ caching></p> <p></system.web></p> <p></ configure></p> <p>The web configuration file in Listing 3 contains two parts. <ConnectionstringsTringsTringsTringsTRingsTRingsTrings The part is used to create a database connection string to connect to a PUBS database called MySQLServer.</p> <p>The Caching section is used to configure SQL Cache Invalidation polling. In the <Databases> 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).</p> <p>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.</p> <p>Use SQL Cache Invalidation in the page output cache</p> <p>Now, we have completed all configuration steps for SQL Cache Invalidation, which can be used 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.</p> <p>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.</p> <p>Listing 4: OutputCachetitles.aspx</p> <p><% @ OutputCache Sqldependency = "Pubs: Titles"</p> <p>Duration = "6000" VarybyParam = "None"%></p> <p><html></p> <p><head runat = "server"></p> <p><title> Output Cache Titles </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><% = Datetime.now%></p> <p><ask: GridView</p> <p>ID = "grdtitles"</p> <p>DataSourceID = "SqlDataSource1"</p> <p>Runat = "server" /> <ask: SQLDataSource</p> <p>ID = "SqlDataSource1"</p> <p>SelectCommand = "SELECT * from Titles"</p> <p>CONNECTIONSTRING = "<% $ connectionstrings: mysqlserver%>"</p> <p>Runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>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.</p> <p>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.</p> <p>Use SQL Cache Invalidation in the DataSource control</p> <p>In addition to using SQL Cache Invalidation in the Page Output Cache, you can also 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.</p> <p>For example, the page in the list 5 uses SQL Cache Invalidation in the SqlDataSource control.</p> <p>Listing 5: SqlDataSourceCaching.aspx</p> <p><html></p> <p><head id = "Head1" runat = "server"></p> <p><title> SqlDataSource Caching </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><% = Datetime.now%></p> <p><ask: GridView</p> <p>ID = "grdtitles"</p> <p>DataSourceID = "SqlDataSource1"</p> <p>Runat = "server" /></p> <p><asp: sqldatasource</p> <p>ID = "SqlDataSource1"</p> <p>EnableCaching = "True"</p> <p>Sqlcachedependency = "pubs: titles"</p> <p>SelectCommand = "SELECT * from Titles"</p> <p>CONNECTIONSTRING = "<% $ connectionstrings: mysqlserver%>"</p> <p>Runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>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. Use SQL Cache Invalidation in the Cache object</p> <p>Finally, you can use SQL Cache Invalidation in the Cache object. This option allows you to maximize the programming of SQL Cache Invalidation.</p> <p>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.</p> <p>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.</p> <p>Listing 6: DisplayTITLANT.ASPX (C #)</p> <p><% @ Page language = "c #"%></p> <p><% @ Import namespace = "system.data.sqlclient"%></p> <p><script runat = "server"></p> <p>Void Page_Load ()</p> <p>{</p> <p>INT count = 0;</p> <p>IF (cache ["title"]! = null)</p> <p>{</p> <p>Count = (int) cache ["titlecount"];</p> <p>}</p> <p>Else</p> <p>{</p> <p>String connectionString =</p> <p>ConfigurationSettings.Connectionstrings [</p> <p>"mysqlserver"]. consNectionstring;</p> <p>SqlConnection Con = New SqlConnection (Connectionstring);</p> <p>SQLCommand cmd = new</p> <p>SQLCommand ("Select Count (*) from Titles", Con);</p> <p>C.Open ();</p> <p>Count = (int) cmd.executescalar ();</p> <p>C. close ();</p> <p>Cache.insert ("Titlecount", Count,</p> <p>New Sqlcachedependence ("Pubs", "Titles"));</p> <p>}</p> <p>LBltitlecount.text = count.toString ();</p> <p>}</p> <p></ script></p> <p><html></p> <p><head runat = "server"></p> <p><title> Display Title Count </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><asp: label id = "lbltitlecount" runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Listing 6: DisplayTITLANT.ASPX (Visual Basic .NET)</p> <p><% @ Page language = "vb"%> <% @ import namespace = "system.data.sqlclient"%></p> <p><script runat = "server"></p> <p>SUB Page_Load ()</p> <p>Dim count as integer = 0</p> <p>IF not cache ("titlecount") is nothing then</p> <p>Count = Convert.Toint32 (Cache ("TitleCount"))</p> <p>Else</p> <p>DIM Connectionstring as string = _</p> <p>ConfigurationSettings.Connectionstrings (_</p> <p>"mysqlserver"). Connectionstring</p> <p>DIM Con As New SqlConnection (Connectionstring)</p> <p>DIM CMD AS New_</p> <p>SQLCommand ("Select Count (*) from Titles", CON)</p> <p>Con.open ()</p> <p>Count = Convert.Toint32 (cmd.executescalar ())</p> <p>Con. close ()</p> <p>Cache.insert ("Titlecount", Count, _</p> <p>New Sqlcachedependency ("Pubs", "Titles")))</p> <p>END IF</p> <p>Lbltitlecount.text = count.toString ()</p> <p>End Sub</p> <p></ script></p> <p><html></p> <p><head id = "Head1" runat = "server"></p> <p><title> Display Titles Count </ Title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p><asp: label id = "lbltitlecount" runat = "server" /></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Back to top</p> <p>Use Post-Cache Substitution</p> <p>In many cases, you need a part of the cache page instead of the entire 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.</p> <p>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.</p> <p>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.</p> <p>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 substection control into the cache of the cache (see Figure 3). Figure 3: Display the username using the Substitution control</p> <p>Listing 7: Postcachesubstitude.aspx (C #)</p> <p><% @ Page language = "c #"%></p> <p><% @ Outputcache duration = "6000" VarybyParam = "none"%></p> <p><script runat = "server"></p> <p>Static String DisplayUserName (httpcontext context)</p> <p>{</p> <p>IF (! context.Request.isauthenticated)</p> <p>Return "anonymous";</p> <p>Else</p> <p>Return context.user.Identity.name;</p> <p>}</p> <p></ script></p> <p><html></p> <p><head runat = "server"></p> <p><title> post cache substitude </ title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p>Welcome <ask: Substitude</p> <p>MethodName = "displayusername" runat = "server" />!</p> <p><p></p> <p>This page is cached because time</p> <p><% = DATETIME.NOW.TOSTRING ("T")%> There is no change.</p> <p></ p></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Listing 7: Postcachesubstitude.aspx (Visual Basic .NET)</p> <p><% @ Page language = "vb"%></p> <p><% @ Outputcache duration = "6000" VarybyParam = "none"%></p> <p><script runat = "server"></p> <p>Shared function displayusername (Byval Context As httpcontext)</p> <p>As string</p> <p>If not context.request.isauthenticated then</p> <p>Return "Anonymous"</p> <p>Else</p> <p>Return context.user.Identity.name</p> <p>END IF</p> <p>END FUNCTION</p> <p></ script></p> <p><html></p> <p><head id = "Head1" runat = "server"></p> <p><title> post cache substitude </ title></p> <p></ hEAD></p> <p><body></p> <p><form id = "form1" runat = "server"></p> <p>Welcome <ask: SubstitutionID = "substitude1"</p> <p>MethodName = "DisplayUsername"</p> <p>Runat = "server" />!</p> <p><p></p> <p>This page is cached because time</p> <p><% = DATETIME.NOW.TOSTRING ("T")%> There is no change.</p> <p></ p></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Substitution controls have a very important property: the methodname property. The methodname property is used to represent the method called back dynamic content. The method called by the Substitution control must be a static method (method in Visual Basic .NET). In addition, the method must also have a parameter representing the current httpContext.</p> <p>In ASP.NET 2.0 Framework, the ADROTATOR control has been modified to support post-cache substitution. If an ADROTATOR control is added to the page using the OutputCache instruction, the Adrotator control will automatically exclude from the cache policy that contains the page.</p> <p>Back to top</p> <p>in conclusion</p> <p>Cache has a great impact on the performance of the web application driven by the database. Fortunately, ASP.NET 2.0 Framework provides a number of new important enhancements that allow you to easily use cache functions in your application.</p> <p>The properties included in the new DataSource control make it very easy to cache database data in memory. By using the DataSource control, you can retrieve and cache database data without writing any code.</p> <p>The new SQL Cache Invalidation support automatically reloads database data in the cache when changing data in the underlying database. This feature provides you with all the performance advantages of cache, without having to worry about the problem of expiration.</p> <p>Finally, use the new Substitution control, you can mix dynamic content more easily in the cached page. The Substitution control provides a separate space for your diverse to insert dynamic content in the cached page.</p> <p>Reference</p> <p>•</p> <p>ASP.NET Unleashed</p> <p>•</p> <p>A First Look At ASP.NET V. 2.0</p> <p>•</p> <p>ASP.NET 2.0 REVEALED</p> <p>About the Author</p> <p>Stephen Walther wrote a bestseller ASP.NET Unleashed for ASP.NET. In addition, he is an architecture designer and major developer of ASP.NET Community Starter Kit (ASP.NET sample application developed by Microsoft). He also provides ASP.NET training for US companies, including NASA and Microsoft.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-35438.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="35438" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.054</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '7CvcvDaSCqSmNIFihsn71B9SM6Gfe_2BZc4l5A_2B3A4iSD3Y_2BdJz_2FpFBhUFbqV_2BD5x_2F_2B_2BAQ_2FFxHS6KFpaZNrEUFtw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>