Caching in ASP.Net


Hi friends among of all the .NET's good features caching is my one of the favorite. Caching is really very easy to understand it's concept is that if we need to fetch the data multiple times from sqlserver or from any file it will cause in reduction of performance as we are taking same data's multiple time from database or any file so why to take same data again and again we can just store that data in our cache object.

The scenario is somewhat like this,

If your site related to any game like cricket or football at that time lots of people are constantly watching at your site and refreshes the page just assume that there are approx 50k persons are online on your site and they refreshes the page at approx same time what happens how can you show them the data with multiple times opening database or any file that's really impossible so we can use caching at that time so just need to read data one time and store in the server's memory and giving same data to rest of the people.

Here we will see, how to cache data from file and delete them when files data will change,

To explain I have created one xml file

This is as follow,

<?xml version="1.0" standalone="yes"?>
<title>
  <artist id="10">
    <country>asdasd</country>
    <company>asd</company>
    <price>asd</price>
    <year>asdasd</year>
 </artist>
  <artist id="11">
    <country>ravi1</country>
    <company>panara</company>
    <price>jklds</price>
    <year>jkldf</year>
  </artist>
  <artist id="12">
    <country>ravi</country>
    <company>panara</company>
    <price>jklds</price>
    <year>jkldf</year>
  </artist>
</title>

Now we will see how to read this file from our code and put into cache.

Just the simple code to do this,

protected void Page_Load(object sender, EventArgs e)
{
    string str = Server.MapPath("MYXMLFile.xml");
    CacheDependency dep = new CacheDependency(str);
    if (Cache["Mydata"] == null)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(str);
        Cache.Add("Mydata", ds, dep, DateTime.Now.AddDays(100), TimeSpan.Zero, CacheItemPriority.Default, null);
    }
    GridView1.DataSource = Cache["Mydata"];
    GridView1.DataBind();
}

Here first we check if the cache is present or not if not we create the cache and bind that cache object to grid if yes then directly bind the data to grid.

We need to give following parameters,

Cache.Add(string key,object value,CacheDependency dependencies,
  DateTime    absoluteExpiration,
  TimeSpan slidingExpiration,
  CacheItemPriority priority,
  CacheItemRemovedCallback onRemoveCallback )

Where,
  • value: The object to be inserted in the cache. 
  • key: The cache key used to reference the object. 
  • dependencies: The file or cache key dependencies for the item. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains a null reference (Nothing in Visual Basic). 
  • absoluteExpiration: The time at which the inserted object expires and is removed from the cache. 
  • slidingExpiration: The interval between the time the inserted object was last accessed and when that object expires. If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed. 
  • priority: The cost of the object relative to other items stored in the cache, as expressed by the CacheItemPriority enumeration. This value is used by the cache when it evicts objects; objects with a lower cost are removed from the cache before objects with a higher cost. 
  • onRemoveCallback: A delegate that, if provided, will be called when an object is removed from the cache. You can use this to notify applications when their objects are deleted from the cache. 
Now you are ready to use caching(file caching) just download the source code debug that and see where it is going to read file and where not if you change anything in the file the cache will be cleared and again it goes to read data from file.

Finally I would like to share some code for how to insert, update and delete in xml file ,

Code to insert in my xml file,

protected void Button1_Click(object sender, EventArgs e)
{
    string str1 = Server.MapPath("MYXMLFile.xml");
    string id;
    XmlDocument doc = new XmlDocument();
    doc.Load(str1);
    using (XmlReader reader = XmlReader.Create(str1))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name == "artist")
                {
                    if (reader.HasAttributes == true)
                    {
                        id = reader.GetAttribute(0);
                        ViewState["id"] = id;
                        //Response.Write(id);
                    }
                }
            }
        }
    }
    int i = Convert.ToInt32(ViewState["id"].ToString());
    i++;
    XmlElement elem = doc.CreateElement("artist");
    elem.SetAttribute("id", i.ToString());
    elem.InnerXml = "<country>" + TextBox1.Text + "</country><company>" + TextBox2.Text + "</company><price>" + TextBox3.Text + "</price><year>" + TextBox4.Text + "</year>";
    XmlNode root = doc.DocumentElement;
    root.InsertAfter(elem, root.LastChild);
    doc.Save(Server.MapPath("MYXMLFile.xml"));
    BindData();
}

Code to update,

protected void Button2_Click(object sender, EventArgs e)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("MYXMLFile.xml"));
    XmlNodeList list = doc.SelectNodes("/title/artist[@id = " + Session["id"].ToString() + "]");
    list[0].ChildNodes[0].InnerText = TextBox1.Text;
    list[0].ChildNodes[1].InnerText = TextBox2.Text;
    list[0].ChildNodes[2].InnerText = TextBox3.Text;
    list[0].ChildNodes[3].InnerText = TextBox4.Text;
    doc.Save(Server.MapPath("MYXMLFile.xml"));      
    BindData();
}

Code to delete,

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label lblnew = (Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("Label1");
    Session["id"] = lblnew.Text;
    string path = Server.MapPath("MYXMLFile.xml");
    XmlDocument doc = new XmlDocument();
    XmlTextReader xmlReader = new XmlTextReader(path);
    doc.Load(xmlReader);
    XmlNodeList nodes = doc.SelectNodes("//artist [@id= '" + lblnew.Text + "' ]");
    foreach (XmlNode node in nodes)
    {
        node.ParentNode.RemoveChild(node);
        break;
    }
    xmlReader.Close();
    doc.Save(path);
    BindData();
}


Similar Articles