Using Caching

Caching refers to storing information for later retrieval, rather than generating it from scratch every time it's requested. For instance, a Web page can be cached so that it's delivered more quickly when it's requested the second time.

graphics/tip_icon.gif

By caching, you can ease the load on the server because it does not have to regenerate the output for every page request. But this means that the output sent to a client might not be identical to what the client would have received if no caching were in place. You must balance your needs for current data against server load by specifying an appropriate expiration time for any cached content.


ASP.NET implements three types of caching, which are discussed in the following sections.

Output Caching

Output caching refers to caching the entire output of a page request.

You can specify the cacheability of a page or user control by using the OutputCache directive. Table 16.2 lists the attributes of this directive.

Table 16.2. Attributes of the OutputCache Directive

Attribute

Description

Duration

Specifies the time in seconds for which the page or user control should be cached.

Location

Specifies the location of the output cache for a page. The possible values are specified by the OutputCacheLocation enumeration and include Any (the default value, caching can be set at the client browser, proxy server, or Web server), Client, Downstream (the client browser or proxy server), None (no caching), and Server . This attribute is not supported when applied to the OutputCache directive in user controls because user controls must reside on the Web server to be assembled .

VaryByControl

Specifies a semicolon-separated list of controls in the user control for which to vary the output cache.

This attribute is supported only for user controls.

VaryByCustom

Specifies a string that indicates either the Browser or a custom string for which to vary the output cache. If the caching is to vary by a custom string, you should provide an overridden version of the HttpApplication.GetVaryByCustomString() method in the global.asax file to indicate how a page should be cached.

VaryByHeader

Specifies a semicolon-separated list of HTTP headers for which to vary the output cache.

This attribute is not supported when applied to the OutputCache directive in user controls.

VaryByParam

Specifies a semicolon-separated list of parameters of the Web page for which to vary the output cache. The possible values are None (caching does not depend on parameters), * (caching for each distinct set of parameters), any query string key names in a GET request, or any parameter names in a POST request.

graphics/tip_icon.gif

When an OutputCache directive is applied to an ASPX page, both the Duration and VaryByParam attributes must be specified. As opposed to this, in the case of user controls, either the VaryByParam or the VaryByControl attribute must be specified along with the Duration attribute. If the required attributes are not supplied, a compile-time error occurs.


Follow these steps to implement output caching for a Web page using the OutputCache directive:

  1. Add a new Visual C# ASP.NET Web Application ( Example16_2 ) to the solution.

  2. Place a Label control ( lblTime ) on the Web form. Switch to Code view and add this code in the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     lblTime.Text = DateTime.Now.ToLongTimeString(); } 
  3. Set the project as the startup project and run the application. The form is displayed with the current time. Refresh the page several times and note that the displayed time changes every time you refresh the page.

  4. Stop the application and switch to HTML view for the Web form. Add an OutputCache directive directly after the Page directive at the top of the file, like so:

     <%@ OutputCache Duration="15" VaryByParam="None" %> 
  5. Run the project; the form is displayed with the current time. Refresh the page several times and note that the displayed time does not change until you refresh the page more than 15 seconds after the original request.

In the previous example, note that the OutputCache directive requires the VaryByParam attribute. If the page output doesn't depend on any input parameters, you can use None as the value of this attribute; otherwise , use the name of the parameter to cause caching to be done on a per-parameter value basis.

The HttpCachePolicy class enables you to set output caching for a page programmatically. The Cache property of the HttpResponse object provides access to the HttpCachePolicy class. The HttpResponse object can be accessed through the Response property of the Page or HttpContext class, as shown in the following code segment:

 private void Page_Load(object sender, System.EventArgs e) {    lblTime.Text = DateTime.Now.ToLongTimeString();    Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));    Response.Cache.SetCacheability(HttpCacheability.Public);    Response.Cache.SetValidUntilExpires(true); } 

In this code, manipulating the HttpCachePolicy object has exactly the same effect as setting the OutputCache directive did in the previous example. This example uses three methods of the HttpCachePolicy object. The SetExpires() method specifies an expiration time for the cached version of the page; in this case, it's 15 seconds from the time the page is generated. The SetCacheability() method specifies where output can be cached through the HttpCachePolicy enumeration: NoCache for no caching at all, Private to allow caching only on the client (the default value), Public to allow caching on any proxy server as well as on the client, and Server to cache the document only on the Web server. Finally, the SetValidUntilExpires() method with its parameter set to true tells the server to ignore client-side attempts to refresh the cached content until it expires .

Caching multiple versions of a page is useful any time you have a page whose output depends on an input parameter. You can base such multiple-version caching on any HTTP header or browser attribute, but most commonly, you'll use the VaryByParam attribute to cache multiple values depending on a query string or form POST parameter.

For example, if you have a page that is accessed using a URL such as http:// ServerName /GetCountryInfo.aspx?ddlCountries=Brazil and the rendering of this page depends on the query string parameter, you can cache the different versions of that page by using the following OutputCache directive:

 <%@ OutputCache duration="20" VaryByParam="ddlCountries"%> 

Here, ddlCountries is the name of a query string parameter and the cache duration is set to 20 minutes. This type of caching involves fewer round trips to the database server. In addition, the Web server can deliver the data from the output cache without dynamically generating the page at every request. As a result, caching helps in creating scalable and high-performance Web applications.

You can also cache the output of a page on the basis of the control's value. For example, consider the following OutputCache directive:

 <%@ OutputCache duration="20" VaryByControl="ddlCountries"%> 

This directive caches the output for a page for 20 minutes based on the different values of the ddlCountries control.

Fragment Caching

Fragment caching refers to caching part of a page. You can encapsulate a portion of a page into a user control and cache that portion of the page, while still forcing the rest of the page to be dynamically generated for each request.

Fragment caching is similar to output caching, in which the output of a user control is cached. The OutputCache directive also caches user controls. Refer to Table 16.2 for information on the attributes of the OutputCache directive.

You should specify either the VaryByParam attribute or the VaryByControl attribute in the OutputCache directive of the user control. You should also specify the Duration attribute to indicate how long the user control should be cached. Any number of user controls can exist in a page, and each of these user controls maintains caching on its own.

While caching user controls, you should consider the following points:

  • Cached user controls are not programmatically accessible. An exception is thrown if you try to access them.

  • Cached user controls are not added to the control tree.

  • Cached user controls cannot perform data binding. An exception is thrown if you try to perform data binding on them.

Data Caching

ASP.NET also enables you to cache application data. In a Web application, data can be retrieved through expensive and time-consuming operations. Most of this data can change infrequently but be required often. The caching of arbitrary data is known as data caching or application data caching .

The Cache class of the System.Web.Caching namespace enables you to cache data. The following lists some important facts about the application cache:

  • The Cache class enables you to insert any object into the data cache by providing a key and the object to be cached. Later, you can retrieve the object programmatically by supplying its key. You can cache simple strings, array lists, data sets, hash tables, and even custom-created objects.

  • You can specify a fixed expiration time or a sliding expiration time for the data in the cache.

  • Data caching enables you to specify any dependencies for the cached item. For example, you could cache a connection string with instructions to re-create the cache if a particular XML file were ever changed. If you set the correct dependencies, you can ensure that users get data as up-to-date as you want.

  • You can set the priority for the cached item using the CacheItemPriority enumeration to AboveNormal , BelowNormal , Default ( Normal ), High , Low , Normal , NotRemovable . By setting the priority, you can ensure that data retrieved through an expensive operation is not removed and that data that can be easily retrieved or created is removed in case the memory is running low.

  • When the memory is running low, ASP.NET can remove data from the cache if the cached data is not used frequently or is unimportant. This operation is called scavenging . The scavenging process can save ASP.NET worker processes from being recycled whenever the memory is too scarce to hold the incoming requests .

  • You can provide a callback method that is called whenever the cached item is removed from the cache. The data item can be removed from the cache due to various options defined by the CacheItemRemoveReason enumeration, including DependencyChanged , Expired , Removed (via the Cache.Remove() method), and Underused (removed when the memory is scarce). The callback method receives notification that the cached item is removed from the cache, and depending on the cache data, this method can be used to perform any cleanup, logging, updating, or re-creating data operation.

The Cache object can be easily accessed using the Cache property of the Page object or the HttpContext object. You can insert or add items to the data cache using the Insert() or Add() method of the Cache object, respectively. The Insert() method has four overloads that provide a choice to insert items in the cache by specifying parameters such as expiration time, sliding expiration time, cache dependency, cache priority, and callback method. The Add() method adds an item to the data cache and returns a reference of the added item. The Remove() method is called to explicitly remove items from the data cache.

You can also easily insert data items into a data cache using indexers by providing a key and value, like so:

 Cache["CustomersDataSet"] = dsCustomers; 


MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net