1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET 4 Unleased - p 142 doc

10 98 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Nội dung

ptg 1384 CHAPTER 29 Caching Application Pages and Data LISTING 29.32 DataSourceKeyDependency.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <script runat=”server”> protected void srcMovies_Selecting(object sender, ➥SqlDataSourceSelectingEventArgs e) { lblMessage.Text = “Selecting data from database”; } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>DataSource Key Dependency</title> </head> <body> <form id=”form1” runat=”server”> <div> <p> <asp:Label id=”lblMessage” EnableViewState=”false” Runat=”server” /> </p> <asp:GridView id=”grdMovies” DataSourceID=”srcMovies” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” EnableCaching=”True” CacheDuration=”Infinite” CacheKeyDependency=”MovieKey” SelectCommand=”SELECT * FROM Movies” ConnectionString=”<%$ ConnectionStrings:Movies %>” OnSelecting=”srcMovies_Selecting” Runat=”server” /> <br /><br /> From the Library of Wow! eBook ptg 1385 Using DataSource Caching 29 <a href=”AddMovieDataSourceKeyDependency.aspx”>Add Movie</a> </div> </form> </body> </html> The SqlDataSource control in Listing 29.32 includes a CacheKeyDependency property that has the value MovieKey. This property creates a dependency between the DataSource control’s cached data and an item in the cache named MovieKey. The Global.asax file in Listing 29.33 creates the initial MovieKey cache item. The value of the cache item doesn’t really matter. In Listing 29.33, the MovieKey cache item is set to the current date and time. LISTING 29.33 Global.asax <%@ Application Language=”C#” %> <script runat=”server”> void Application_Start(object sender, EventArgs e) { HttpContext context = HttpContext.Current; context.Cache.Insert( “MovieKey”, DateTime.Now, null, DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } </script> The page in Listing 29.34 contains a DetailsView control that enables you to insert a new record. The DetailsView control’s ItemInserted event is handled. When you insert a new record, the MovieKey item is reinserted into the cache, and every DataSource control that is dependent on this key reloads automatically. From the Library of Wow! eBook ptg 1386 CHAPTER 29 Caching Application Pages and Data LISTING 29.34 AddMovieDataSourceKeyDependency.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”> protected void dtlMovie_ItemInserted(object sender, ➥DetailsViewInsertedEventArgs e) { Cache.Insert(“MovieKey”, DateTime.Now); Response.Redirect(“~/DataSourceKeyDependency.aspx”); } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Add Movie Key Dependency</title> </head> <body> <form id=”form1” runat=”server”> <div> <h1>Add Movie</h1> <asp:DetailsView id=”dtlMovie” DefaultMode=”Insert” DataSourceID=”srcMovies” AutoGenerateRows=”false” AutoGenerateInsertButton=”true” OnItemInserted=”dtlMovie_ItemInserted” Runat=”server”> <Fields> <asp:BoundField DataField=”Title” HeaderText=”Title:” /> <asp:BoundField DataField=”Director” HeaderText=”Director:” /> </Fields> </asp:DetailsView> <asp:SqlDataSource id=”srcMovies” From the Library of Wow! eBook ptg 1387 Using Data Caching 29 ConnectionString=”<%$ ConnectionStrings:Movies %>” InsertCommand=”INSERT Movies (Title, Director) VALUES (@Title, @Director)” Runat=”server” /> </div> </form> </body> </html> Using Data Caching Behind the scenes, all the various caching mechanisms included in ASP.NET Framework use the Cache object. In other words, the Cache object is the fundamental mechanism for all caching in ASP.NET Framework. One instance of the Cache object is created for each ASP.NET application. Any items you add to the cache can be accessed by any other page, control, or component contained in the same application (virtual directory). In this section, you learn how to use the properties and methods of the Cache object. You learn how to add items to the cache, set cache expiration policies, and create cache item dependencies. Using the Cache Application Programming Interface The Cache object exposes the main application programming interface for caching. This object supports the following properties: . Count—Represents the number of items in the cache. . EffectivePrivateBytesLimit—Represents the size of the cache in kilobytes. The Cache object also supports the following methods: . Add—Enables you to add a new item to the cache. If the item already exists, this method fails. . Get—Enables you to return a particular item from the cache. . GetEnumerator—Enables you to iterate through all the items in the cache. . Insert—Enables you to insert a new item into the cache. If the item already exists, this method replaces it. . Remove—Enables you to remove an item from the cache. For example, the page in Listing 29.35 displays all the items currently contained in the cache (see Figure 29.13). From the Library of Wow! eBook ptg 1388 CHAPTER 29 Caching Application Pages and Data LISTING 29.35 EnumerateCache.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”> public class CacheItem { private string _key; private object _value; public string Key { get { return _key; } } public string Value { get { return _value.ToString(); } } FIGURE 29.13 Displaying the cache’s contents. From the Library of Wow! eBook ptg 1389 Using Data Caching 29 public CacheItem(string key, object value) { _key = key; _value = value; } } void Page_Load() { ArrayList items = new ArrayList(); foreach (DictionaryEntry item in Cache) items.Add(new CacheItem(item.Key.ToString(),item.Value)); grdCache.DataSource = items; grdCache.DataBind(); } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <style type=”text/css”> .grid td, .grid th { padding:5px; } </style> <title>Enumerate Cache</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:GridView id=”grdCache” CssClass=”grid” Runat=”server” /> </div> </form> </body> </html> The page in Listing 29.35 displays only items that have been added to the cache by the methods of the Cache object. For example, it does not display a list of pages that have been output cached. Output cached pages are stored in the internal cache (the secret cache maintained by the ASP.NET Framework). From the Library of Wow! eBook ptg 1390 CHAPTER 29 Caching Application Pages and Data Adding Items to the Cache You can add items to the cache by using the Insert() method. There are several over- loaded versions of the Insert() method. The maximally overloaded version of the Insert() method accepts the following parameters: . key—Enables you to specify the name of the new item. . value—Enables you to specify the value of the new item. . dependencies—Enables you to specify one or more cache dependencies, such as a file, key, or SQL dependency. . absoluteExpiration—Enables you to specify an absolute expiration time for the cached item. If you don’t need to specify a value for this property, use the static field Cache.NoAbsoluteExpiration. . slidingExpiration—Enables you to specify a sliding expiration interval for the cached item. If you don’t need to specify a value for this property, use the static field Cache.NoSlidingExpiration. . priority—Enables you to specify the priority of the cached item. Possible values are AboveNormal, BelowNormal, Default, High, Low, Normal, and NotRemovable. . onRemoveCallback—Enables you to specify a method called automatically before the item is removed from the cache. When using the cache, you need to understand that items that you add to the cache might not be there when you attempt to retrieve the item in the future. The cache supports scavenging. When memory resources become low, items are automatically evicted from the cache. Before using any item that you retrieve from the cache, you should always check whether the item is Nothing (null). If an item has been removed, you retrieve Nothing when you attempt to retrieve it from the cache in the future. You can add almost any object to the cache. For example, you can add custom components, DataSets, DataTables, ArrayLists, and Lists to the cache. You shouldn’t add items to the cache that depend on an external resource. For example, it does not make sense to add a SqlDataReader or a FileStream to the cache. When using a SqlDataReader, you need to copy the contents of the SqlDataReader into a static repre- sentation such as an ArrayList or List collection. Adding Items with an Absolute Expiration Policy When you insert items in the cache, you can specify a time when the items expire. If you want an item to remain in the cache for an extended period of time, you should always specify an expiration time for the item. The page in Listing 29.36 illustrates how you can add an item to the cache with an absolute expiration policy. The item is added to the cache for 1 hour. From the Library of Wow! eBook ptg 1391 Using Data Caching 29 LISTING 29.36 ShowAbsoluteExpiration.aspx <%@ Page Language=”C#” Trace=”true” %> <%@ Import Namespace=”System.Data” %> <%@ Import Namespace=”System.Data.SqlClient” %> <%@ Import Namespace=”System.Web.Configuration” %> <!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() { // Get movies from Cache DataTable movies = (DataTable)Cache[“Movies”]; // If movies not in cache, recreate movies if (movies == null) { movies = GetMoviesFromDB(); Cache.Insert(“Movies”, movies, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration); } grdMovies.DataSource = movies; grdMovies.DataBind(); } private DataTable GetMoviesFromDB() { Trace.Warn(“Getting movies from database”); string conString = WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString; SqlDataAdapter dad = new SqlDataAdapter(“SELECT Title,Director FROM Movies”, conString); DataTable movies = new DataTable(); dad.Fill(movies); return movies; } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <title>Show Absolute Expiration</title> </head> <body> <form id=”form1” runat=”server”> <div> From the Library of Wow! eBook ptg 1392 CHAPTER 29 Caching Application Pages and Data <asp:GridView id=”grdMovies” Runat=”server” /> </div> </form> </body> </html> The first time the page in Listing 29.36 is requested, nothing is retrieved from the cache. In that case, a new DataTable is created that represents the Movies database table. The DataTable is inserted into the cache. The next time the page is requested, the DataTable can be retrieved from the cache, and there is no need to access the database. The DataTable remains in the cache for 1 hour or until memory pressures force the DataTable to be evicted from the cache. In either case, the logic of the page dictates that the DataTable will be added back to the cache when the page is next requested. Tracing is enabled for the page in Listing 29.36 so that you can see when the Movies database table loads from the cache and when the table loads from the database. The GetMoviesFromDB() method writes a Trace message whenever it executes (see Figure 29.14). FIGURE 29.14 Adding an item to the cache with an absolute expiration policy. From the Library of Wow! eBook ptg 1393 Using Data Caching 29 Adding Items with a Sliding Expiration Policy When you specify a sliding expiration policy, items remain in the cache just as long as they continue to be requested within a specified interval of time. For example, if you specify a sliding expiration policy of 5 minutes, the item remains in the Cache just as long as no more than 5 minutes pass without the item being requested. Using a sliding expiration policy makes sense when you have too many items to add to the cache. A sliding expiration policy keeps the most requested items in memory and the remaining items are dropped from memory automatically. The page in Listing 29.37 illustrates how you can add a DataSet to the cache with a sliding expiration policy of 5 minutes. LISTING 29.37 ShowSlidingExpiration.aspx <%@ Page Language=”C#” Trace=”true” %> <%@ Import Namespace=”System.Data” %> <%@ Import Namespace=”System.Data.SqlClient” %> <%@ Import Namespace=”System.Web.Configuration” %> <!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() { // Get movies from Cache DataSet movies = (DataSet)Cache[“Movies”]; // If movies not in cache, recreate movies if (movies == null) { movies = GetMoviesFromDB(); Cache.Insert(“Movies”, movies, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); } grdMovies.DataSource = movies; grdMovies.DataBind(); } private DataSet GetMoviesFromDB() { Trace.Warn(“Getting movies from database”); string conString = WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString; SqlDataAdapter dad = From the Library of Wow! eBook . ptg 13 84 CHAPTER 29 Caching Application Pages and Data LISTING 29.32 DataSourceKeyDependency.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC -/ /W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>. Library of Wow! eBook ptg 1388 CHAPTER 29 Caching Application Pages and Data LISTING 29.35 EnumerateCache.aspx <%@ Page Language=”C#” %> <!DOCTYPE html PUBLIC -/ /W3C//DTD XHTML 1.0. dependent on this key reloads automatically. From the Library of Wow! eBook ptg 1386 CHAPTER 29 Caching Application Pages and Data LISTING 29. 34 AddMovieDataSourceKeyDependency.aspx <%@ Page

Ngày đăng: 06/07/2014, 18:20

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN