Application Caching: To Add An Item To The Cache by Directly Setting The Item Via Key and Value

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Caching ASP.

Net Application
An application can often increase performance by storing data in memory that is accessed
frequently and that requires significant processing time to create. For example, if your
application processes large amounts of data using complex logic and then returns the data as a
report accessed frequently by users, it is efficient to avoid re-creating the report every time that a
user requests it. Similarly, if your application includes a page that processes complex data but
that is updated only infrequently, it is inefficient for the server to re-create that page on every
request.
To help you increase application performance in these situations, ASP.NET provides caching
using two basic caching mechanisms.
1. Application caching, which allows you to cache data you generate, such as a DataSet
object
2. Page output caching, which saves the output of page processing and reuses the
output instead of re-processing the page when a user requests the page again.

1. Application caching
The application cache provides a programmatic way for you to store arbitrary data in memory
using key/value pairs. Using the application cache is like using application state. However,
unlike application state, the data in the application cache is volatile. This means it is not stored in
memory for the life of the application. The advantage of using the application cache is that
ASP.NET manages the cache and removes items when they expire or become invalidated, or
when memory runs low. You can also configure application caching to notify your application
when an item is removed.

To add an item to the cache by directly setting the item via key and value
Add items to the cache as you would add items to a dictionary by specifying the item's key and
value.
The following code example adds an item named CacheItem1 to the Cache object:
Cache["CacheItem1"] = "Cached Item 1";

To add items to the cache by using the Insert method


Call the Insert method, passing the key and value of the item to add.
The following code example adds a string under the name CacheItem2:
Cache.Insert("CacheItem2", "Cached Item 2");

To retrieve the value of a cached item


string cachedString;
cachedString = (string)Cache["CacheItem"];
if (cachedString == null)
{
cachedString = "Hello, World.";
Cache.Insert("CacheItem", cachedString);
}

2. Page Output Caching


A typical kind of caching for server applications is output caching. Output caching enables you
to store rendered HTML. The stored HTML is served in response to subsequent requests for
the same page. You can use output caching to cache a whole Web page or just the output of an
ASP.NET control.
Output caching enables you to do the following:
a) Configure ASP.NET to cache a particular output cache entry for a specific period.
b) Cache a different version of the content based on the browser type or user-language
preferences of the clients visiting your application.
c) Cache a mobile version of a page that differs from a version that is optimized for a desktop
browser.
d) Configure ASP.NET to evict a cache entries based on an external event.
The page output cache stores the contents of a processed ASP.NET page in memory. This lets
ASP.NET send a page response to a client without going through the page processing life cycle
again. Page output caching is especially useful for pages that do not change often but that require
significant processing to create.
For example, if you are creating a high-traffic Web page to display data that is not frequently
updated, page output caching can dramatically increase the performance of that page. Page
caching can be configured individually for each page, or you can create cache profiles in the
Web.config file, which allow you to define caching settings once and then use those settings with
multiple pages.
Page output caching provides two models for page caching: full-page caching and partial-page
caching.
a) Full-page caching persists the complete contents of a page and uses the cached page
content to fulfill client requests.
b) Partial-page caching persists specified portions of a page and lets other portions of the
page be created dynamically

A. Full Page Caching : Set the Cacheability of an ASP.NET Page


Declaratively
Instead of executing a page each time the page is requested, you can cache the output of the page
and send the cached copy to satisfy browser requests.

I.

To set a page's cacheability declaratively

a) Include an @ OutputCache directive in the page and define Duration and VaryByParam
attributes.
b) Include a Location attribute in the @ OutputCache directive and define its value as one of
the following values in the OutputCacheLocation enumeration: Any, Client, Downstream,
Server, ServerAndClient, or None.

To enable output caching for a page, include the following page directive in the page:
Syntax
<%@ OutputCache Duration="60" VaryByParam="*" Location="Client" %>

Varying Cache Contents by Parameter


The OutputCache directive has a second attribute that indicates how a page should be cached
when a request for a page contains parameters (either query string parameters or form field
parameters). This attribute can accept either a semicolon-delimited list of parameters or one of
the following special values:
none Indicates that different cached versions of a page should not be created when the
page is requested with different parameters.
* Indicates that different cached versions of a page should be created whenever the
page is requested with different parameters.
The VaryByParam attribute is particularly useful when you need to display different content on
a page depending on the value of a query string parameter.
By default, when you enable page output caching, the page is cached on both the server and
client. The page is cached in the server's memory, and the proper headers are sent to the
browser requesting the page to cause the browser to create a cached copy.
The Location attribute can have any one of the following values from the OutputCacheLocation
enumeration:
Any This is the default value. The page should be cached at any location, including the
server, and the browser.
Client The output of the page should be cached only on the browser.
None No page caching should be performed.
Server The page should be cached only on the server.
This directive causes the output of the page to be cached for 60 seconds.
<%@ Page Language="C#" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>
<html>
<head><title>TimeCache.aspx</title></head>
<body>
At the tone, the time will be:
<%=DateTime.Now.ToString()%>
</body>
</html>

II.

To set a page's cacheability declaratively using a cache profile


1. Define a cache profile in your application's Web.config file and in the profile,
include duration and varyByParam settings.

The following <caching> configuration element defines a cache profile named


Cache30Seconds, which will cache the page on the server for 30 seconds.
<caching>

<outputCacheSettings>
<outputCacheProfiles>
<add name="Cache30Seconds" duration="30"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
2. Include an @ OutputCachedirective in each ASP.NET page that uses the
profile, and set the CacheProfile attribute to the name of the cache profile
defined in your Web.config file.
The following code specifies that the page should use the cache profile named
Cache30Seconds:
<%@ OutputCache CacheProfile="Cache30Seconds" %>
A. Full Page Caching : To set a page's cacheability programmatically
In the page's code, call the SetCacheability method on the Cache property of the Response
object.
The following code sets the Cache-Control HTTP header to Public.

Response.Cache.SetCacheability(HttpCacheability.Public);

B. Caching Portions of an ASP.NET Page


Sometimes it is impractical to cache an entire page because portions of the page might need
to change on each request. In those cases, you can cache just a portion of a page. There are
two options to do this:
a) control caching
b) post-cache substitution.

Control caching
In control caching, also known as fragment caching, you can cache parts of the page output
by creating user controls to contain the cached content and then marking the user controls as
cacheable. This allows specific content within a page to be cached, while the overall page is
recreated each time. For example, if you create a page that displays largely dynamic content,
such as stock information, but also has sections that are static, such as weekly summaries,
you can create the static sections in user controls and configure the user controls to be
cached.

Page fragment caching is implemented with user controls. You define different areas of a
page by creating separate user controls for each area of the page. Within each user control,
you can use the OutputCache directive to indicate how the output of the control is cached.
Page fragment caching is implemented with user controls. You define different areas of a page by
creating separate user controls for each area of the page. Within each user control, you can use
the OutputCache directive to indicate how the output of the control is cached.

<% @Control language="C#" %>


<% @OutputCache duration="50" varybyparam="none" %>
This user control was most recently generated at:<p>
<% string t = DateTime.Now.ToString();
Response.Write(t); %>
The Limitations of Page Fragment Caching

If we enable caching for a user control, you can no longer programmatically access the control in
its containing page.
For example, suppose you declare a cached user control like this:

<myControls:PageContents ID="ctlContents" Runat="Server"/>


Since the control is cached, you cannot programmatically set a property of the user control in a
page like this:

ctlContents.Message = "Hello!"

Post-cache substitution
Post-cache substitution is the opposite. The page is cached, but fragments within the page are
dynamic and should therefore not be cached. For example, if you create a page that is entirely
static for set periods of time such as a page of news stories, you can set the entire page to be
cached. If you added rotating ad banners to the cached page, they would not change between
page requests. However, with post-cache substitution, the page can be cached, but you can mark
specific parts as non-cacheable. In the example, you would mark your ad banners as noncacheable. They would then be dynamically created for each page request and added to the
cached page output.
To allow you to cache a page but substitute some content dynamically, you can use ASP.NET
post-cache substitution. With post-cache substitution, the entire page is output cached with
specific parts marked as exempt from caching. In the example of the ad banners, the AdRotator

control allows you to take advantage of post-cache substitution so that ads dynamically created
for each user and for each page refresh.
There are three ways to implement post-cache substitution:
a) Declaratively, using the Substitution control.
b) Programmatically, using the Substitution control API.
c) Implicitly, using the AdRotator control.
Automatic Data Removal
ASP.NET can remove data from the cache for one of these reasons:
Because memory on the server is low, a process known as scavenging.
Because the item in the cache has expired.
Because the item's dependency changes.
To help you manage cached items, ASP.NET can notify your application when items are
removed from the cache.
Scavenging
Scavenging is the process of deleting items from the cache when memory is scarce. Items are
removed when they have not been accessed in some time or when items are marked as low
priority when they are added to the cache. ASP.NET uses the CacheItemPriority object to
determine which items to scavenge first.
Expiration
In addition to scavenging, ASP.NET automatically removes items from the cache when they
expire. When adding an item to the cache, you can set it to expire as described in the following
table.

Dependencies
You can configure an item's lifetime in the cache to be dependent on other application elements
such as files or databases. When the element that a cache item depends on changes, ASP.NET
removes the item from the cache. For example, if your Web site displays a report that the
application creates from an XML file, you can place the report in the cache and configure it to
have a dependency on the XML file. When the XML file changes, ASP.NET removes the report
from the cache. When your code requests the report, the code first determines whether the report
is in the cache, and if not, your code can re-create it. Therefore, an up-to-date version of the
report is always available.
ASP.NET caching supports the dependencies described in the following table.