Figure 16-1 Explanation process for caching namespaces
16.1 System.Web.Caching IntroductionThis section begins with a general overview and composition of the cache namespace, summarizing the System.Web.Caching as a whole.
16.1.1 System.Web.Caching OverviewSystem.Web.Caching is the namespace used to manage caching. Caching is the temporary storage of server-side data on the client, which facilitates user's reading. The parent space of the cache namespace is "system.web", which shows that caching is commonly used in the development of Web sites, including in B/s projects. Caching is designed primarily to take into account that network bandwidth may delay data submission and postback, if the data stored in the client, users can read data directly from the client, so that the data is extracted from the local, will not be affected by the network. The System.Web.Caching namespace provides all the action classes associated with caching, including which classes are described in detail in the next section.
16.1.2 The classes within the System.Web.Caching namespaceThe caching namespace mainly provides three kinds of operations: caching Data Objects, object cache dependencies, and database cache dependencies. It caches any object using a class cache, but when the cache changes, normal objects and database objects rely on different processing. Figure 16-2 Lists the deployment scenarios that are cached in a three-tier structure. The two dependent classes CacheDependency and SQLCache dependency primarily change the cached data that is changed, and act as a notification. When the data is not cached, use the cache class to add it. The following is a description of the caching classes used in the diagram, based on the deployment of Figure 16-2. The descriptions of these classes are shown in table 16-1. Figure 16-2 the cached deployment chart in the three-tier structure the classes in the cache namespace and their descriptions
| Class name |
Description |
| Cache |
The editing class for cached objects, which includes adding, deleting, and changing the cache |
| CacheDependency |
Base cache object dependencies, updating cached content when basic objects change |
| SqlCacheDependency |
Dependency of Database Cache objects, updating cached content when data in the database changes |
16.2 Admin Cache classes: Cache classThe cache class is used to store data objects and provides methods for editing these objects. This section focuses on the methods that are included with the cache class, and how to use these methods to implement caching of data objects.
16.2.1 Function DescriptionThe cache class belongs to the dictionary class, which stores the data that the user needs according to certain rules, such as String, array, data table, DataSet and hash table. The advantage of using the cache class is that when the cached data changes, the cache class invalidates the data and implements the cached data to be added, and then notifies the application to report the cache's timely update.
16.2.2 Syntax DefinitionThe syntax for the cache class is defined as follows: public sealed class cache:ienumerable by its definition, the cache class is a class defined by "sealed", which means that the class is sealed and cannot be inherited. The cache class also inherits the IEnumerable interface, which indicates that the data in the collection is allowed to enumerate operations. The lifecycle of the cache terminates as the activity of the application domain ends, which means that as long as the application domain is still active, the cache persists because each application domain creates a cache instance. The information for this instance is obtained by HttpContext the cache property of the object or the Cache property of the Page object. The following code shows how to add array data to the cache: ArrayList myarray = new ArrayList (); Creates an array data myarray. Add ("1. Learning Corner"); MyArray. Add ("2. Exchange Forum"); MyArray. ADD ("3. Help"); Cache.Add ("Category", myarray); Adding an array to the cache
A detailed explanation of 16.2.3 methodThe method of cache class mainly provides editing operation of cached data, such as adding, deleting and changing. The most common methods and their descriptions are shown in table 16-2. Table 16-2 The main method of cache class and its description Add
| name " |
" Ming |
| adds data to the cache object |
| Insert |
inserts a data entry into the cache that can be used to modify an existing data cache entry |
| Remove |
Remove cached data entry in cache object |
| get |
from CA Che object to get the specified data item, note that the object type is returned, type conversion |
| GetType |
is required to get the type of the data item from the cache object, and after the data type is judged, it is convenient Make the conversion |
| getenumerator |
Iterate through the cached data items in the cache object. Note that its return type is "IDictionaryEnumerator" |
Tip: To modify the cached data, you only need to assign a value to the cache again. The most notable is the Add method, which uses the following syntax: Public Object ADD ( string key, Object value, &NB sp; cachedependency dependencies, DateTime absoluteexpiration, TimeSpan slidingexpiration, cacheitempriority priority, cacheitemremovedcallback onRemoveCallback) When using the Add method, the above 7 parameters are required and represent the following meaning:-The parameter "key" represents the key value of the cached data item and must be unique. -The parameter ' value ' represents the contents of the cached data, which can be any type. -The parameter "dependencies" represents a cached dependency, meaning that the change in this item means that the cached content has expired. If there are no dependencies, you can set this value to NULL. -Parameter ' absoluteexpiration ' is a date-type data indicating when the cache expires, the cache provided by. NET 2.0 can be used after expiration and how long it can be used to see the setting of this parameter. -the type of the parameter "SlidingExpiration" represents a time interval that indicates how long the cache parameter will be deleted, and this parameter is associated with the absoluteexpiration parameter. -The parameter "priority" represents the priority value of the undo cache, the value of this parameter is taken from the enumeration variable "CacheItemPriority", and the data item with a lower priority is deleted first. This parameter is primarily used when caching exits an object. -The parameter "onRemoveCallback" represents the event that is invoked when the data object is deleted, and is generally used as a notification program. The following code shows how to apply these methods of the cache class. When using this code, you need to be aware that the ArrayList object is used in your code, so you need to add a reference to the namespace "System.Collections" and forget to add the namespace using the cache category SystEm. Web.caching ". protected void Page_Load (object sender, EventArgs e) { & nbsp; ArrayList myarray = new ArrayList (); //create array data myarray. Add ("1. Learning Corner"); myarray. Add ("2. Exchange Forum"); myarray. ADD ("3. Help"); //Adding arrays to the cache--using the Add method Cache.Add ("Category", myarray, NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero, cacheitempriority.normal, NULL); myarray[1] = "2. Exchange Corner"; //Modify array data cache.insert ("Category", myarray); //use inThe SERT method modifies the cached data string tmpstr = "This is a temporary data"; cache["tmpdata"] = TMPSTR; //Using Get method to obtain cached data Response.Write (Cache.get ("Tmpdata"). ToString () + "<br/>");/ cache["tmpdata"] = "This is a temporary string"; //re-assigning techniques for caching Response.Write (Cache.get) (" Tmpdata "). ToString () + "<br/>"); //Using the GetType method to determine the type of cached data if ( cache["Category"]. GetType (). Name = = "ArrayList") Response.Write ("type is an array"); //Using the GetEnumerator method to traverse the data in the cache IDictionaryEnumerator Mycache = Cache.getenumerator (); while (Mycache. MoveNext ()) Response.Write (Mycache. Value + "<br/>"); cache.remove ("Tmpdata")//Remove cached temporary data using the Remove method tip: When using the GetType method, If you want to determine the type, you need to use Object.GetType (). The Name property gets the names of the types. The results of the above code are as follows: This is a temporary data this is a temporary string type is an array this is a temporary string System.Collections.ArrayList which when reading data of type ArrayList, because there is no type conversion, So the object that is typed "System.Collections.ArrayList" is taken out. This book will explain how to read the details of an array in the last instance of this section.
16.2.4 Attribute DetailedThe properties of the cache class are used primarily to get some basic information about the cached data, such as the total number of cached items, cache entries at the specified location, and so on. This book mainly introduces two attributes: Count and item. Count is used to get the total number of items in the cache. The use method is as follows: Response.Write (Cache.count); Item is used to return the contents of the specified item, which is typically inherited by a class that inherits the "IEnumerable" interface, and notes that the item needs to be wrapped with "[]". Its use is as follows: Response.Write (cache["Category"). ToString ());
16.2.5 Typical application: Realize cache fast reading function of data Cache is used primarily for caching data that is used frequently and does not need to be updated regularly. This example implements a cache of directory listings. For simplicity, the contents of the list are not read from the database, but are kept in a ArrayList object. The purpose of this example is to populate the list of directories into a drop-down box, and when the cache fails, the contents of the directory list are empty. The steps in the demo are described below. Create a Web site in VS2005 named "Cachesample". Open the default generated Default.aspx page, where you add a drop-down list box and a button. Press the F7 key to switch to the page's code view. Don't forget to reference the namespace, the code is as follows: using System.Web.Caching; Using System.Collections; in the "Page_Load" event to determine whether there is a directory cache, if not, add the directory to the cache. The detailed code is as follows, where the directory list is held for 5 seconds. protected void Page_Load (object sender, EventArgs e) { if (! Page.IsPostBack) { ArrayList myarray = new ArrayList ()// Suppose ArrayList's content comes from the database myarray. Add ("Ancient History"); myarray. ADD ("contemporary literature"); myarray. Add ("popular novel"); myarray. Add ("wuxia novel"); if (cache["categorys"] = = null)   Determine if there is a cache { //If the cache does not exist, add-save time is 5 sec Cache.Add ( "Categorys", myarray, NULL, DateTime.Now.AddSeconds (5), TimeSpan.Zero, cacheitempriority.normal, NULL); } } go back to Design view, double-click the button control, and switch to the button's event code. in the double-click of the button event, you need to determine whether there is a directory cache, there are in the Drop-down box to display the contents of the table, no then empty the Drop-down box. The detailed code is as follows: protected void Button1_Click (object sender, EventArgs e) { if (cache["Categorys"]!= null)   ; //To determine if cache failure { // If it is not invalidated, remove the cached list and note the conversion of the type. Dropdownlist1.datasource = (ArrayList) cache["Categorys"]; Dropdownlist1.databind (); } Else { DropDownList1.Items.Clear (); //If it has expired, clear the list }} Press CTRL + S key to save all the code, and then press the F5 key to run the program. Within 5 seconds. If you click the button, the list of directories is displayed normally, and if more than 5 seconds are present, the cached object no longer exists, so the contents of the Drop-down list box are empty. This section focuses on the use of the cache class, which does not involve caching dependencies, that is, whether the cache changes as the actual data changes. The next section will learn about the detailed implementation of cache dependencies by learning the "CacheDependency" class.
16.3 Cache Dependency Classes: CacheDependency classThe CacheDependency class is a bridge between the cache class and the actual data. This section describes in detail how to use the CacheDependency class to implement a timely update of data caching.
16.3.1 Function DescriptionThe CacheDependency class is called a cache dependency class, and its specific meaning is that it notifies cached objects in a timely manner when the actual data of the cached object changes. For example, the cached object "Category" holds the data of an XML file, and if the XML file changes, the system updates the contents of the cached object "Category" in time through the CacheDependency class, thus ensuring that the user is always reading the most up-to-date data.
16.3.2 Syntax Definition The syntax for the CacheDependency class is defined as follows: The public class cachedependency:idisposable inherits the interface "IDisposable", which is primarily used to define methods for freeing allocated unmanaged resources. Inheriting this interface must implement method dispose to implement the release of the resource. The constructor for the CacheDependency class implements 8 overloads, the following code lists the overloaded functions, and details the parameters of each function. Knowing these functions will tell you what advantages CacheDependency can bring to the cache. //Assuming that the cached source file is the current directory Data.xml file //cache dependent file path cachedependency MYDEP = new CacheDependency ("Data.xml"); //cache dependent files can have multiple cachedependency mydep1=new cachedependency (new string []{ Data.xml "," Data1.xml "}); /Check the basis time of the cache dependency change cachedependency mydep2 = new CacheDependency ("Data.xml", DateTime.Now); /Check the basis time of multiple dependent file changes cachedependency mydep3 = new CacheDependency (new string[] {" Data.xml "," Data1.xml "}, DateTime.Now); /Check relies on multiple files, and also relies on multiple cache key values cachedependency mydep4 = new CacheDependency (new string[] {" Data.xml "," Data1.xml "}, &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp New string[] {"Category", "Category1"}); /associated dependencies, you can also rely on another file cache dependency CacheDependency mydep5 = new CacheDependency (new string[) {"Data.xml", "Data1.xml"}, new string[] {"Category", "Category1"}, MYDEP); //File and key value last modified based on time cachedependency mydep6 = new CacheDependency (new string[] {"Data . xml "," Data1.xml "}, new string[] {" Category "," Category1 "}, DateTime.Now) ; //file, another cache dependency and key value last modified based on time cachedependency mydep6 = new CacheDependency (new string [] {"Data.xml", "Data1.xml"}, new string[] {"Category", "Category1"}, Mydep,datetime.now);
16.3.3 Methods and propertiesAlthough the CacheDependency class completes important functions, its composition is relatively simple, with two attributes and one method. -Property "Haschanged": Determines whether the CacheDependency object has changed. -Property ' utclastmodified ': Returns the modified date of the last dependency-method ' Dispose ': the resources that are available to release the CacheDependency object. This method must be implemented because the cache class inherits the interface "IDispose". Because the composition of the cache class is simpler, this section does not give the demo code, the use of properties and methods will be demonstrated in the example in the next section. Note: Only the insert and add methods of the cache class can add dependencies to the cache.
16.3.4 Typical application: Get the latest data with CacheDependency This example mainly demonstrates how to use the CacheDependency class to implement timely data updates. Example, a GridView control is used to display data from an XML file, and the client can update it when the data in the XML file changes. Its implementation features are shown in Figure 16-3. Figure 16-3 The detailed steps described in the illustration of the functional implementation diagram with CacheDependency to obtain the latest data are as follows. Open VS2005, create a Web site, named "Cachedependencysample". in the site root directory, add an XML file to provide data for the control, as follows: <?xml version= "1.0" encoding= "Utf-8"?> > <bookinfo> <name> British ancient </name> <price>28.00</price> </bookinfo> <bookinfo> <name> China history </name> <price>20.00 </price> </bookinfo> </book> Open the default generated Default.aspx page, adding a GridView control and a button control. Press F7 to switch to the Code view of the form and write the code to generate the cache in the Page_Load event. Details are as follows: private Static CacheDependency MyD