Professional Documents
Culture Documents
In ASP.NET, every page you write extends the System.Web.UI.Page class, which
contains a member called Cache. You use the Cache property as you would any other
IEnumerable, which gives you methods and properties to get, set, and enumerate through
members. We will be looking at getting and setting items in the cache. In the simplest
example, you can retrieve any object from the cache like so:
Object obj = (Object)Cache["key"];
What this does is look in the Cache for an item with the key "key". If such an item exists,
the object is returned. While we don't need to cast the returned object to Object, this is
just an example of how you must cast the return to the class type you want returned. If
the item is not found, null is returned, so you will need to do some checking:
Object obj = (Object)Cache["key"];
if (obj == null) {
// Generate a new object and insert it into the cache
}
// Use your object
You can also assign object to the cache like the following code example, but using
Cache.Inset() is a much better means as you'll see later:
Cache["key"] = obj;
Now let's look at a serious example. In the example below, we will define a function that
binds data to a control, such as a ASP.NET DataGrid control. We will look at data binding
in a little more depth later. For this example, we will use a System.Data.DataSet object.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data"
%>
<script runat="server">
private string _filename = "mydata.xml";
We'll break down the above example. The first part we've already discussed, where we
get the object from the cache. If the object is null (i.e., doesn't exist in the cache), we
need to create the object. The first line after checking if our DataSet object is null loads
an XML file called a DiffGram, which is a serialized DataSet object. We'll talk about this
later. Essentially, the DataSet object (hereforth, "ds") is created from serialized XML,
which you can event type by hand. We call Server.MapPath() because the file as we know
it is virtual. ds.ReadXml needs the absolute path and filename to load it.
Server.MapPath() figures out what the absolute path of a virtual filename (such as your
web pages) and returns the absolute path.
The next statement inserts the newly created "ds" into the cache. Again, the statement is:
Cache.Insert("mydata", ds,
new CacheDependency(Server.MapPath(_filename)),
DateTime.Now.AddHours(12), NoSlidingExpiration);
1. The first parameter is the key used to identify our cache item.
2. The second parameter is the object we want to cache. In this example, we are
caching the DataSet object "ds". This can be any object, however, including
strings, numbers, controls, etc.
3. The third parameter creates a dependency on an object. If this object changes, the
cached object is marked as expired and your application will regenerate next time,
returning null as your object reference. In fact, the object is expired. You can also
pass null in this parameter to signify that you don't want any dependencies.
4. The fourth parameter is the absolute expiration period your object is valid. Here,
we use DateTime.Now (which uses "now's" time) and add 12 hours to it. This
means the object will automatically expire in 12 hours. You could also use
NoAbsoluteExpiration which means the object will never expire until the
dependent object changes. We use an absolute expiration here to make sure we
have somewhat recent data in case the CacheDependency doesn't expire the data
for some reason. (As if Microsoft software doesn't have bugs!)
5. The fifth and final parameter is a sliding expiration. This means that if the object
is access, the absolute expiration time is essentially pushed back to however many
minutes, hours, etc. you specify here. This is an object of type TimeSpan. Here,
we want our object expired after 12 hours even if the object is accessed before
then.
After all this, we can finally bind our object to a data-driven control, such as the
ASP.NET DataGrid control. While the full use of the control is out of the scope of this
tutorial, I will cover the usage in brief detail.
The DataGrid control is a data-driven control meaning that on the server, the control will
use data and will then render the HTML onto the page for the client to see in their
browser. We will define a basic DataGrid control customizing only a few parameters:
<body>
<asp:DataGrid id="myDataGrid" runat="server"
AutoGenerateColumns="true"
ShowHeader="true"
AllowPaging="true"
PageSize="25"
Font-Name="Verdana"
Font-Size="10pt">
<HeaderStyle Font-Bold="true"/>
</asp:DataGrid>
</body>
Please note: this example assumes you already have your other HTML tags setup and
that the DataGrid is the only control in the BODY, which it doesn't have to be.
Above, we define a Web server control of type DataGrid, which is a data-driven control
that renders a table on the page. By setting AutoGenerateColumns to true (which is
default anyway), we specify that the DataGrid control will automatically generate headers
and columns based on your data in the order of the columns in your DataSet. We also
setup default paging and a few items styles, while making the Header column text bold.
In the example Page_Load() event handler, we did a little data binding like so:
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
These two lines associate the DataSource property of the DataGrid with our DataSet
object "ds" and then binds the data with DataBind(). If you do not call DataBind(), you
will find that nothing is rendered on your page. The DataSource property can point at
other types of object, like ArrayList(), DataView() and many others. Consult your .NET
SDK Documentation for more details.
Scenarios
Why would you use this tutorial to build your next data-driven ASP.NET page? There are
several examples, but I will discuss one here.
Lets say that you've developed a page or site that generates a table of contents on ever
page. You also have a SQL Server storing this data because the table of contents changes
from time to time. Instead of making calls across the network to the SQL Server (even
cached data on SQL Server requires a few calls back and forth), you could use the
caching example above.
You could adapt second method above to something like the following:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data"
%>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
// If used frequently, store these strings in your Web.config
// and use ConfigurationSettings.AppSettings["key"] to get them out.
// If you do this, make sure these are constant strings!
private const string connstr = "Data Source=sqlserver1;Initial
Catalog=Web";
private const string cmdstr = "SELECT Title,URL FROM TOC";
Describing the example above, it is really nothing more than what we had before execpt
that we have no CacheDependency because we have no files to watch, and we create our
DataSet from a DataTable that is filled by a SqlDataAdapter (or OleDbDataAdapter if
you prefer). DataSets are good to store in the Cache since they are easy to use, can be
used in any data-driven control, and can be serialized at will with one call to ReadXml()
or WriteXml().
Note: another thing to mention to those that have used System.Data.OleDb classes but
not System.Data.SqlClient classes, you will notice I didn't specify a Provider in the
connection string. This is because the SqlClient classes are only interested in SQL Server
connections and, hence, already know what the Provider is.
Finally, our Repeater control would look something like the following:
<body>
<asp:Repeater id="myRepeater" runat="server" Visible="true">
<ItemTemplate>
<dd><a href="<%# DataBinder.Eval(Container, "Item.URL") %>"><%#
DataBinder.Eval(Container, "Item.Title") %></a></dd>
</ItemTemplate>
</asp:Repeater>
</body>
The expressions above evaluate your Container (your DataSet object) and find the
"Item.Title" and "Item.URL". "Item" is the name of the data item, which is the the name
of the table usually. You may remember that we called our DataTable "Item" above:
DataTable dt = new DataTable("Item");
"Title" and "URL" our the names of our fields in the table. See, even your data is
appropriately named!
Conclusions
That pretty much wraps up the tutorial of how to use caching. There are many other
examples and scenarios of how to use Caching and DataSets to cache data, but this
tutorial is long enough I think. Please keep in mind that you can cache other objects as
well, not just DataSets. I find that caching DataSets where you used infrequently
accessed data is especially helpful, however, to decrease loads on your Web server, SQL
Server (or other database server), and network.
I hope you've found this tutorial helpful and that the wheels in your head are spinning
like mad with new ways to use caching to improve your web site's performance!
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Introduction
ASP.NET has built-in cache engine that is used by ASP.NET pages to store and retrieve
objects across HTTP requests. The ASP.NET cache is private to each application and
stores objects in memory. The lifetime of the cache is equivalent to the lifetime of the
application; that is, when the application is restarted, the cache is recreated.
Value = Cache("key")
If Value <> Null Then
DisplayData(Value)
End If
• File and key dependencies allow the validity of a cache item to be based on an
external file or on another cache item. If a dependency changes, the cache item is
invalidated and removed from the cache. For an example of how you might use
this functionality, consider the following scenario: an application reads financial
information from an XML file that is periodically updated. The application
processes the data in the file and creates a graph of objects that represent that data
in a consumable format. The application caches that data and inserts a dependency
on the file from which the data was read. When the file is updated, the data is
removed from the cache and the application can reread it and reinsert the updated
copy of the data.
<html>
<script language="VB" runat="server">
dataSource = Cache("CheDataSet")
If dataSource Is Nothing
MyDataGrid.DataSource=dataSource
MyDataGrid.DataBind()
End Sub
</script>
<body>
<p>
</form>
</body>
</html>
Examples
1. When Executed for the first time
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
In this article, you will learn about concepts, advantages, types of caching and about
implementation of caching in ASP.NET applications. The code also serves as an
example of using inline coding, creating user controls, trace mechanism, etc.
What is Caching?
Why Caching?
Consider a page that has list of Employee name, contact numbers and mail-Ids of
existing employees of a company on an intranet accessible by all employees. This is
very useful information that is available throughout the company and could also be
one of the most accessed pages. The functionality of adding, updating or deleting is
usually less intensive compared to more transaction-based systems like Purchase
ordering, Voucher creation etc. Now in a normal scenario the process of querying
database for each request is not cost-effective in terms of server resources, hence is
lot better to cache or persist the data to avoid this costly loss of resources.
This is at the page level and one of the easiest means for caching pages. This
requires one to specify Duration of cache and Attribute of caching.
The above syntax specifies that the page be cached for duration of 60 seconds and
the value "none" for VaryByParam* attribute makes sure that there is a single
cached page available for this duration specified.
* VaryByParam can take various "key" parameter names in query string. Also there
are other attributes like VaryByHeader, VaryByCustom etc. Please refer to MSDN for
more on this.
2. Fragment Caching
Even though this definition refers to caching portion/s of page, it is actually caching a
user control that can be used in a base web form page. In theory, if you have used
include files in the traditional ASP model then this caching model is like caching these
include files separately. In ASP.NET more often this is done through User Controls.
Initially even though one feels a bit misleading, this is a significant technique that
can be used especially when implementing "n" instances of the controls in various
*.aspx pages. We can use the same syntax that we declared for the page level
caching as shown above, but the power of fragment caching comes from the
attribute "VaryByControl". Using this attribute one can cache a user control based on
the properties exposed.
The above syntax when declared within an *.ascx file ensures that the control is
cached for 60 seconds and the number of representations of cached control is
dependant on the property "DepartmentId" declared in the control.
Add the following into an *.ascx file. Please note the use of tag "Control" and the
cache declaration.
Add the following to an *.aspx file. Please note the way "Register" tag is used; the
declaration of control using syntax <[TagPrefix]:[TagName]>; Usage of property "
DepartMentId". Open the page in two browsers and closely watch the Base form
timing and the User control timing. Also note that the following page results in two
copies or representation of user control in the cache.
With Page level Output caching one cannot cache objects between pages within an
application. Fragment caching is great in that sense but has limitations by using user
controls as means to do. We can use the Cache object programmatically to take
advantage of caching objects and share the same between pages. Further the
availability of different overloaded methods gives a greater flexibility for our Cache
policy like Timespan, Absolute expiration etc. But one of the biggest takes is the
CacheDependancy. This means that one can create a cache and associate with it a
dependency that is either another cache key or a file.
In almost all Web applications there could be numerous master tables that act as
lookups to application specific tables. For e.g. if you take up adding a Employee,
usually one has master tables like "tblQualification" to get list of qualifications,
"tblLocations" to get list of locations etc. These tables* are usually set during the
initial application configuration phase and could be modified once a month or even
less than that. Hence it makes sense for us to use them in our Cache rather than
making calls to database on each request. But then what Cache Policy do we adopt?
We cannot hold these objects in Cache for entire application instance, because if
anybody changes data in these tables one has to also refresh the cache. It is here
that CacheDependancy can be used.
* Even though these tables are less frequently used for updates, they are extensively
used in our select statements through out the applications.
Find below the snippet that uses CacheDependancy. Here what I have done is to
provide a list view of existing employees. You need to create a Database in Sql
Server, setup some data before you can continue. The schema scripts are enclosed in
the article.
Add database connection value in Web.Config and change the value as per your
setup.
<appSettings>
<add key="conn" value="Data Source=vishnu;trusted_connection=yes;Initial
Catalog=Users"/>
</appSettings>
First I get the dataset into which I fill the user list. But before this I check for the
cache initially if it exists I directly cast it to a dataset, if not create a cache again.
daUsers.Fill(dsUsers,"tblUsers");
I create the cache with "Users" as key using Cache.Insert* and link this with a file
"Master.xml". This "Master.xml" is a XML file that contains Master data of
"tblQualifications" and "tbllocations". I have used "Server.MapPath" to get the
physical path of the file on the server. The CacheDependancy instance will make sure
that any change in this dependency file means that you need to recreate your cache
key definition. This is a great feature to use since I can recreate my cache only when
required instead of caching the data at the page level.
Cache.Insert("Users",dsUsers,new
System.Web.Caching.CacheDependency(Server.MapPath("Master.xml")) ,
DateTime.Now.AddSeconds(45),TimeSpan.Zero);
Also note how we could use trace within to add my own statements.
HttpContext.Current.Trace.Write("from Database..");
Now once you have created the above pages i.e. one that implements caching and
other that overwrites the dependency file, create two instance of browser and open
the cache implementation page and note for trace, label text; open the other
instance of browser with the page which overwrites the XML. Note the former, the
first time it fetches data from the database and the subsequent request will be from
cache till your expiration time of 45 seconds is reached or anyone overwrites or
changes the "Master.xml" file. Also give a look on Timespan parameter since you
have a concept of Sliding expiration that can also be implemented. Keep refreshing
the first page and you will see that trace indicates the cached page retrieval. Click
the overwrite XML button on the latter page that would overwrite the XML and again
refresh the former page to note that the data is retrieved from database. Though in
this example I have not shown any direct relation between the cached data and the
dependency file (like get values from dependency file and merge with cached object
etc) in terms of integrated usage, this could very easily be designed and
implemented. Dependency caching is a powerful technique that .NET supports and
should be utilized wherever applicable.
Conclusion