My INSURER PTE LTD - Insurtech Innovation Award 2024
Chapter 23
1. • What is Caching
• When to use Caching
• Types of Caching
• Output Caching
• QueryString and Profile Caching
• Data Caching
• Simple, Dataset and DataSource Caching
• Cache Dependencies
• File / Item / DataBase Dependencies
2. Caching is the process of storing frequently used data,
usually data that is costly to generate, for reuse.
Typically this data is stored in memory since retrieving
data from memory is much more efficient than retrieving
the data from other locations, such as a database or a file.
When you store information in a cache the lifetime of that
information is at the discretion of the server. If the cache
becomes full or other applications consume a large
amount of memory, data will be selectively evicted from the
cache, ensuring that the application continues to perform
well.
3. A good caching strategy identifies the most frequently
used pieces of data that are the most time-consuming to
create and stores them. If you store too much
information, you risk filling up the cache with relatively
unimportant data and forcing out the content you really
want to keep.
Cache data (or web pages) that are expensive: The
results of a database query or contents of a file.
Cache data (or web pages) that are used frequently: The
list of product categories instead of product detail pages.
4. ASP.NET really has two types of caching.
Output caching: It stores a copy of the final rendered
HTML page that is sent to the client. The next client that
submits a request for this page doesn’t actually run the
page. Instead, the final HTML output is sent automatically.
Data caching: This is carried out manually in your code.
To use data caching, you store important pieces of
information that are time-consuming to reconstruct (such
as a DataSet retrieved from a database) in the cache.
Other pages can check for the existence of this
information and use it, thereby bypassing the steps
ordinarily required to retrieve it.
5. With output caching, the final rendered HTML of the page
is cached. When the same page is requested again, the
control objects are not created, the page life cycle doesn’t
start, and none of your code executes. Instead, the
cached HTML is served.
You can cache an ASP.NET page in two ways.
Insert the OutputCache directive at the top of your .aspx
file, just below the Page directive
<%@ OutputCache Duration="20" VaryByParam="None" %>
Cache the page exclusively on the client side
<%@ OutputCache Duration="20" VaryByParam="None"
Location="Client" %>
6. When you request the page with additional query string
information, ASP.NET will examine the query string. If the
string matches a previous request and a cached copy of
that page exists, it will be reused. Otherwise, a new copy
of the page will be created and cached separately.
You can set the VaryByParam attribute to * to indicate that
the page uses the query string and to instruct ASP.NET to
cache separate copies of the page for different query
string arguments:
<%@ OutputCache Duration="20" VaryByParam="*" %>
Or
<%@ OutputCache Duration="20“
VaryByParam="ProductID;CurrencyType" %>
7. ASP.NET includes a feature called cache profiles that
makes it easy to apply the same caching settings to a
group of pages.
With cache profiles, you define a group of caching settings
in the web.config file, associate a name with these
settings, and then apply these settings to multiple pages
using the name.
That way, you have the freedom to modify all the linked
pages at once simply by changing the caching profile in
the web.config file.
8. To define a cache profile, you use the <add> tag in the
<outputCacheProfiles> section, as follows.
<configuration>
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="ProductItemCacheProfile" duration="60" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
...
</system.web>
</configuration>
You can now use this profile in a page through the CacheProfile
attribute:
<%@ OutputCache CacheProfile="ProductItemCacheProfile"
VaryByParam="None" %>
9. The basic principle of data caching is that you add items
that are expensive to create to a built-in collection object
called Cache.
Cache is a property of the Page class, and it returns an
instance of the System.Web.Caching.Cache class.
You can insert an object into the cache in several ways.
1. Cache["KeyName"] = objectToCache;
2. Cache.Insert(key, item, dependencies, absoluteExpira
tion, slidingExpiration);
10.
11. Absolute expirations are best when you know the
information in a given item can be considered
valid only for a specific amount of time (such as a stock
chart or a weather report).
Sliding expiration, on the other hand, is more useful
when you know that a cached item will always remain
valid (such as with historical data or a product catalog)
but should still be allowed to expire if it isn’t being
used.
12. You cannot set both a sliding expiration and an
absolute expiration policy at the same time. If you want
to use an absolute expiration, set the slidingExpiration
parameter to TimeSpan.Zero
Cache.Insert("MyItem", obj, null,
DateTime.Now.AddMinutes(60), TimeSpan.Zero);
To set a sliding expiration policy, set the
absoluteExpiration parameter to DateTime.MaxValue
Cache.Insert("MyItem", obj, null,
DateTime.MaxValue, TimeSpan.FromMinutes(10));
13. private DataSet RetrieveData()
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].Connection
String;
string SQLSelect = "SELECT * FROM Customers";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(SQLSelect, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
adapter.Fill(ds, "Customers");
}
finally
{
con.Close();
}
return ds;
}
14. private DataSet GetDataSet()
{
DataSet ds = (DataSet)Cache["Customers"];
// Contact the database if necessary.
if (ds == null)
{
ds = RetrieveData();
Cache.Insert("Customers", ds, null, DateTime.MaxValue,
TimeSpan.FromMinutes(2));
lblCacheStatus.Text = "Created and added to cache.";
}
else
{
lblCacheStatus.Text = "Retrieved from cache.";
}
return ds;
}
15. The SqlDataSource and ObjectDataSource support built-in data caching.
Using caching with these controls is highly recommended, because they
can be more inefficient than handwritten data access code.
Caching Properties of the Data Source Controls
16. As time passes, the information in your data source may
change. If your code uses caching, you may remain
unaware of the changes and continue using out-of-date
information from the cache.
To help mitigate this problem, ASP.NET supports cache
dependencies. Cache dependencies allow you to make a
cached item dependent on another resource, so that when
that resource changes, the cached item is removed
automatically.
ASP.NET includes three types of dependencies:
• Dependencies on files or folders
• Dependencies on other cached items
• Dependencies on a database query
17. To use a cache dependency, you need to create a CacheDependency
object. You then need to supply the CacheDependency object when
you add the dependent cached item.
For example, the following code creates a CacheDependency that
Create a CacheDependency that depends on an XML file named
ProductList.xml. When the XML file is changed, the
CacheDependency will be invalidated, and the dependent cached
item will be evicted from the cache immediately.
Dim dom As XmlDocument()
dom.Load(Server.MapPath("ProductList..xml")
Cache(“prodInfo") = dom
CacheDependency prodDependency = new CacheDependency(
Server.MapPath("ProductList.xml"));
Cache.Insert("ProductInfo", prodInfo, prodDependency);
18. Cache["Key1"] = "Cache Item 1";
// Make Cache["Key2"] dependent on Cache["Key1"]
string[] dependencyKey = new string[1];
dependencyKey[0] = "Key1";
CacheDependency dependency = new CacheDependency(null,
dependencyKey);
Cache.Insert("Key2", "Cache Item 2", dependency);
19. string connectionString = WebConfigurationManager.ConnectionStrings[
"Northwind"].ConnectionString;
SqlDependency.Start(connectionString)
SqlConnection con = new SqlConnection(connectionString);
string query =
"SELECT EmployeeID, FirstName, LastName, City FROM dbo.Employees";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "Employees");
// Create the dependency.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
Cache.Insert("Employees", ds, empDependency);