Click here to Skip to main content
15,888,610 members
Articles / Web Development / ASP.NET

ASP.NET Caching Dependencies

Rate me:
Please Sign up or sign in to vote.
4.26/5 (22 votes)
28 Jul 20066 min read 164.8K   1.8K   64  
A discussion on caching in ASP.NET 2.0
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Xml;
using System.Text;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // create the menu 
            CreateMenu(); 

           // CreateCacheItem(); 
        }
    }

    private void CreateCacheItem()
    {
        string itemA = "ItemA";

        Cache.Insert("ItemA", itemA, null, DateTime.Now.AddMinutes(60), TimeSpan.Zero,
            CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemovedCallBack)); 
    }

    private void ItemRemovedCallBack(string key, object value, CacheItemRemovedReason reason)
    {

    }

    private void CreateMenu()
    {
        string menuPath = "MyFiles/Menu.xml";
        string folderName = "MyFiles/"; 
        DataSet ds = null;

        if (Cache["Menu"] == null)
        {
            ds = new DataSet();
            ds.ReadXml(Server.MapPath(menuPath));
            // menu is created 
            Cache.Insert("Menu", ds, new System.Web.Caching.CacheDependency(Server.MapPath(folderName)),DateTime.Now.AddMinutes(60),TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default,new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemovedCallBack));
            
            DisplayCacheCreationTime("Object was not in the cache and created at:",DateTime.Now.ToLongTimeString()); 
        }

        else
        {
            // menu is created from the cache 

            DisplayCacheCreationTime("Object was in the cache",String.Empty); 
        }        
    }

    private void CacheItemRemovedCallBack(string key, object value, CacheItemRemovedReason reason)
    {
        //Response.Write("Hello world"); 
    }

    private void DisplayCacheCreationTime(string message,string timeString)
    {
        lblMessage.Text = message + " " + timeString; 
    }

    protected void Btn_RemoveCacheItem(object sender, EventArgs e)
    {

        Cache.Remove("ItemA"); 

        //Cache.Remove("Menu"); 
    }

    // this button will write xml to the Menu.xml file 
    // This method will expire the cache which is dependent on the xml file 
    protected void Button1_Click(object sender, EventArgs e)
    {
        string menuPath = "MyFiles/Menu.xml";

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(Server.MapPath(menuPath));

        XmlElement root = xDoc.DocumentElement;

        XmlElement newNode = xDoc.CreateElement("MenuItem");

        newNode.InnerText = "Services";

        root.InsertBefore(newNode, root.FirstChild);              

        // Now should the cache dependency expire or not 
        xDoc.Save(Server.MapPath(menuPath));        
    }

    // create a file in the MyFiles folder 
    protected void Button2_Click(object sender, EventArgs e)
    {
        string path = "MyFiles";

        try
        {

            string fileName = "Myfile.txt"; 
            
            FileStream fs = File.Create(Server.MapPath("MyFiles/somefile.txt"));
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("This is a new file");
            sw.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            string exception = ex.Message;
        }

    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        // create item A and item B 

        string itemA = "ItemA";
        string itemB = "ItemB";

        Cache.Insert("ItemA", itemA, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero,
            CacheItemPriority.Default, MyItemRemovedCallBack);
        Cache.Insert("ItemB", itemB, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero,
            CacheItemPriority.Default, MyItemRemovedCallBack); 
    }

    private void MyItemRemovedCallBack(string key, object value, CacheItemRemovedReason reason)
    {
        // remove the item from the cache 
        if (key == "ItemA" ) Cache.Remove("ItemB");
        else if (key.Equals == "ItemB") Cache.Remove("ItemB"); 
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions