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
hEAD>
<% = Datetime.now%>
ID = "grdtitles" DataSourceID = "SqlDataSource1" Runat = "server" /> ID = "SqlDataSource1" EnableCaching = "True" Sqlcachedependency = "pubs: titles" SelectCommand = "SELECT * from Titles" CONNECTIONSTRING = "<% $ connectionstrings: mysqlserver%>" Runat = "server" /> form> body> html> 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 Finally, you can 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: DisplayTITLANT.ASPX (C #) <% @ Page language = "c #"%> <% @ Import namespace = "system.data.sqlclient"%> Void Page_Load () { INT count = 0; IF (cache ["title"]! = null) { Count = (int) cache ["titlecount"]; } Else { String connectionString = ConfigurationSettings.Connectionstrings [ "mysqlserver"]. consNectionstring; SqlConnection Con = New SqlConnection (Connectionstring); SQLCommand cmd = new SQLCommand ("Select Count (*) from Titles", Con); C.Open (); Count = (int) cmd.executescalar (); C. close (); Cache.insert ("Titlecount", Count, New Sqlcachedependence ("Pubs", "Titles")); } LBltitlecount.text = count.toString (); } script>
hEAD>
form>
body>
html>
Listing 6: DisplayTITLANT.ASPX (Visual Basic .NET)
<% @ Page language = "vb"%> <% @ import namespace = "system.data.sqlclient"%>
SUB Page_Load ()
Dim count as integer = 0
IF not cache ("titlecount") is nothing then
Count = Convert.Toint32 (Cache ("TitleCount"))
Else
DIM Connectionstring as string = _
ConfigurationSettings.Connectionstrings (_
"mysqlserver"). Connectionstring
DIM Con As New SqlConnection (Connectionstring)
DIM CMD AS New_
SQLCommand ("Select Count (*) from Titles", CON)
Con.open ()
Count = Convert.Toint32 (cmd.executescalar ())
Con. close ()
Cache.insert ("Titlecount", Count, _
New Sqlcachedependency ("Pubs", "Titles")))
END IF
Lbltitlecount.text = count.toString ()
End Sub
script>
hEAD>
form>
body>
html>
Back to top
Use Post-Cache Substitution
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.
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 substection control into the cache of the cache (see Figure 3). Figure 3: Display the username using the Substitution control
Listing 7: Postcachesubstitude.aspx (C #)
<% @ Page language = "c #"%>
<% @ Outputcache duration = "6000" VarybyParam = "none"%>
Static String DisplayUserName (httpcontext context)
{
IF (! context.Request.isauthenticated)
Return "anonymous";
Else
Return context.user.Identity.name;
}
script>
hEAD>
Welcome MethodName = "displayusername" runat = "server" />! This page is cached because time <% = DATETIME.NOW.TOSTRING ("T")%> There is no change. p> form> body> html> Listing 7: Postcachesubstitude.aspx (Visual Basic .NET) <% @ Page language = "vb"%> <% @ Outputcache duration = "6000" VarybyParam = "none"%> Shared function displayusername (Byval Context As httpcontext) As string If not context.request.isauthenticated then Return "Anonymous" Else Return context.user.Identity.name END IF END FUNCTION script>
hEAD>
Welcome MethodName = "DisplayUsername" Runat = "server" />! This page is cached because time <% = DATETIME.NOW.TOSTRING ("T")%> There is no change. p> form> body> html> 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. 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. Back to top in conclusion 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. 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. 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. 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. Reference • ASP.NET Unleashed • A First Look At ASP.NET V. 2.0 • ASP.NET 2.0 REVEALED About the Author 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.