Library tutorials & articles
.NET Data Caching
- Introduction
- Applications, Sessions and Cookies
- Using Data Caching
- Inserting an Item into the Cache
- A Real-World Example
Applications, Sessions and Cookies
While classic ASP does not have the rich data caching API found in the .NET Framework, it does give us the ability to maintain state and to cache data with the help of session, application and even cookie objects. For starters cookies, which are stored on the Web visitor's computer (disk) don't hold a lot of data. They have a 4k limit and can contain only string information. Additionally, a user may have their browser configured not to accept cookies. For more information on using cookies in classic ASP, see the Cookies FAQs on ASPFAQs.com.
Session variables can also be used to cache information in classic ASP, although, as with the cookie approach each session variable is specific to a particular user, and to tie a session variable to a particular user the user's browser must accept cookies. The advantages of using session variable's over cookies is that you can store objects, such as an array, or Dictionary object. Since session variables are stored on the Web server's memory, storing large objects in a user's session on a site with many simultaneous users can lead to reduced memory on the Web server. For more information on session variables see the Session Variables FAQs on ASPFAQs.com.
Most often application variables were the means one would use to cache information in classic ASP. Since a given application variable is "global" to the entire Web application, application variables are primarily candidates for caching information that is global across all Web pages on the site. That is, imagine that you ran an eCommerce Web site and that on every page you wanted to list the top 10 selling products. Rather than do a database access on every page, you could cache the results in an application variable. This is an excellent example of when an application variable would be a good use for caching. If you need to cache more user-specific information, such as the 10 most recently purchased items for the user who's visiting the site, you'd likely want to employ the session object or cookies to do this. (For more information on caching database values in an application variable be sure to read : A Real-World Example of Caching Data in the Application Object.)
You can use application variables for caching in ASP.NET much like you did in classic ASP. However, since ASP.NET Web pages can utilize the .NET data cache APIs there's really no reason to ever resort to using application variables for caching in an ASP.NET Web application. In fact, caching data through the data cache API as opposed to through application variables in an ASP.NET Web application has its advantages, including: items in the data cache will be evicted from memory if memory becomes scarce; when adding items to the data cache you can specify how long they should persist in the cache in terms of an absolute or slidign time; and many other advantages, which we will examine in this article.
So to sum up the use of Application, Session and or Cookie objects for caching in a classic ASP page:
- Use cookies for small non-critical data.
- Use Sessions on a user-to-user basis as in an eCommerce site
- And use Application variables for site-wide information that doesn't require constant revision.
While this article will focus on .NET data caching in detail, a good general article on .NET caching basics can be found here at Caching with ASP.NET.
Related articles
Related discussion
-
Profile Class does not work after Translation
by converter2009 (1 replies)
-
what is the SQL Server Provider
by hayperaktib (1 replies)
-
Very Urgent regarding deleting the images from a folder
by Nanosteps (6 replies)
-
Java Script, File uploading on ftp server using java script code
by h_c_a_andersen (2 replies)
-
sharepoint calendar web part with events from sql table
by converter2009 (2 replies)
Related podcasts
-
StackOverflow uses ASP.NET MVC - Jeff Atwood and his technical team
Scott chats with Jeff Atwood of CodingHorror.com and most recently, StackOverflow.com. Jeff and Joel Spolsky and their technical team have created a new class of application using ASP.NET MVC. What works, what doesn't, and how did it all go down?
Events coming up
-
Mar
15
DevWeek 2010
London, United Kingdom
DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.
To Access the Pages Cache from class code c#
Cache ce = new Cache();
ce = System.Web.HttpRuntime.Cache; Lol
So , Does That mean this is a Genuine Microsoft Bug??
ystem.Web.UI.Page {
No matter What If I Use this Syntax[ Colorede red] to acess the Cache Object I get an Exception...
internal class EnvUtil
internal EnvUtil()
{
}
internal string ResetClientID
{
get
{
string sResetClientId="";
try
{
if (Cache["ResetClientDoc"] == null) {
TextReader xt=new StreamReader(Server.MapPath(@"../../Content/EnvReport/ResetClientID.xml"));
sResetClientId=xt.ReadToEnd();
xt.Close();
CacheDependency dep = new CacheDependency(Server.MapPath(@"../../Content/EnvReport/ResetClientID.xml"), DateTime.Now);
Cache.Insert("ResetClientDoc", sResetClientId, dep);
}
else
{
sResetClientId=(string) Cache["ResetClientDoc"];
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return sResetClientId;
}
}
}
}
Output
?ex.Message
"Cache is not available"
Just because the Cache cannot be inherited, doesn't mean you can't access it when you are inheriting the Page class -
public class MyClass : System.Web.UI.Page {
public Object SomeMethod() {
return Cache["SomeObject"];
}
}
is fine. As it's sealed, what you can't do is this:
public class MyClass : Cache {
// override or add some methods here
}
I stumbled into this problem. The comment is correct The Cache class is a sealed class, which means it cannot be inherited. Since you are inheriting the Page class in your X testClass the Cache object will not be available. One way to solve the problem is to pass the Cache object of the Page to the Method that need to process the Cache information as shown in the Sample code..
<%@ import Namespace="Env" %>
<%@ import Namespace="System.Xml" %>
<%@ Page Language="C#" Inherits ="Env.ServerProcess" %>
<%
XmlDocument xDoc = new XmlDocument();
xDoc=ProcessRequest(Request.InputStream,this.Cache);
Response.ContentType="text/xml";
Response.Write (xDoc.OuterXml);
%>
public class ServerProcess : System.Web.UI.Page
{
public XmlDocument ProcessRequest(Stream PageRequestStream,Cache MyCache)
{
string sResetClientId="";
XmlDocument xdoc =new XmlDocument();
try{
if (MyCache ["ResetClientDoc"] == null){
TextReader xt=new StreamReader(Server.MapPath(@"Content/ResetClientID.xml"));
sResetClientId=xt.ReadToEnd();
xt.Close();
MyCache dep = new CacheDependency(Server.MapPath(@"Content/ResetClientID.xml"), DateTime.Now);
MyCache.Insert("ResetClientDoc", sResetClientId, dep);}
Else
{
sResetClientId=(string) MyCache ["ResetClientDoc"];
}
}
catch (Exception e){
System.Diagnostics.Debug.WriteLine( e.Message.ToString())
}
xdoc.LoadXml(sResetClientId);
return xdoc;
}
Hi Charlie,
You can use .NET remoting when you need to keep your cache across processes. The process is discussed here Using Remoting Singleton Caching.
Hope this helps.
-DM
As for caching across processes, you'll need to use .NET remoting. The process is discussed here The process is discussed here Using Remoting Singleton Caching.
Hope this helps.
-DM
Yes I have tried that as well. IMHO: The thing is that you are trying to access a cache object from a class. But the documentation says that the Cache object cannot be inherited. therefore I would expect it to throw a "Cache is not available" exception. Now this is a real bugger specially when you want to cache data across process/pages. This is precisely what I'm trying to do right now and I have yet to find a solution. Help anyone?
How would one use the .NET cache object to keep caches accurate across processes?
--Charlie
On what line does the error occur?
// test.cs
//
namespace xtest {
using System;
using System.Web;
using System.Web.Caching;
public class xtest {
public static Cache srvCache = new Cache();
public xtest() {}
public static string getCache(string key){
try {
object strServer= 0;
if (srvCache["ServerString"] == null)
srvCache["ServerString"]=key;
strServer = srvCache.Get("ServerString");
return (string) strServer;
}
catch (Exception e)
{
return "error: getCache() - "+ e.Message;
}
}
}
}
When I run the below mentioned aspx. I get error:
- Object reference not set to an instance of an object.
<%@ Page Language="C#" %>
<%@ import Namespace="xtest" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) {
Response.Write(xtest.getCache("X-STAGE"));
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<!-- Insert content here -->
</form>
</body>
</html>
This thread is for discussions of .NET Data Caching.