How to Implement Caching concepts in asp.net website

By
Caching is very important concept for any web application. which is used to store the data temporarily either on a web server or on the client side (client system).In other words , Caching is a place where data is stored temporarily. This data can be stored for a specific time period on the server or client system.It is more useful when any user access the same set of data continuously.For Real Example:-Almost every user access the Search    Engine(Google,bings,Yahoo,etc.) for searching relevant information.Suppose If you open Google page on your system first time then first time Google page comes from Google Database.if you open again Google search engine then this Google page Comes from Google server cache or client system Cache memory.You already know about the cache memory concepts.Sometimes you have seen ,when your internet connection is disconnected,when you open the Google then it open without connection.What is the reason about that ,when you open Google page multiple times in your system then this page is saved in our system cache memory for a specific time period.so that it is opened without internet connection.This rules is applicable for all cache enable web applications . Cache is the best way to improve the performance of any web application.
         Accessing a database in an Asp.Net applications generally a slow and  time  consuming  process.To improve the performance of asp.net page,we can use Caching concept. which is quicker than retrieving the data from the database on each request.

Advantage of Caching:-
  • Reduce the processing Time
  • Reduce the Network Traffic
  • Improve the Performance of web application
  • Enhance the user Experience
  • Lower Data used (Internet)
  • Improve the site performance
  • Large data management
Caching in asp.net application:-
Cache is a place where data is stored for a specific time period(temporarily). An application written is ASP.NET is faster than the application written in ASP (Active server page),in terms of retrieving data from a database.In ASP caching technique we can cache data in two level variables to speed up its retrieval.
  1. Application level
  2. Session level
But in large scale web application.Data Retrieval at both levels are insufficient. In asp.net application ,there are number of classes in .NET Framework that deal the issues related to caching of data.
Suppose if you are not using caching concepts on your web application then what will be happened,suppose your application needs to query from database every two seconds that contains millions of records and your database is updated  after half an hours However , querying the database after every two seconds increase the Network Traffic every second and reduce the performance of the application.
How to solve above problem:-
When any user access the database records,then save that records in cache memory for a specific time period.If all records are saved in cache memory for a specific time periods then millions of users can access the records from cache memory not database.When database is updated after 30 minutes or one hour(a time periods) then saved the updated records also in cache memory.When we use this concepts then Network Traffic will be  reduced and web application performance also improved.
Real Life Example:- 
Many times you will have to seen,When you retrieve balance slip after withdrawing the money from ATM Machine then you find,your balance remain same as before (not deducted).What is the reason about that,Your deducted balance is saved in cache memory of the bank's server. After a specific time period when database is updated ,then you will receive balance deduction sms on your registered mobile Number.Means when database will updated then write operation performed from cache to database. Google and other top most website also use this concepts on your web applications.You already know ,why Google server is not busy,because it uses more power full caching concepts and others things also.
This single concept reduce the load and processing time on the  database server as well as improve the site performance of the web application.
There can be implemented three level of caching concepts in ASP.NET application which are given below:-
  1. Page Output Caching
  2. Fragment Caching (partial page Caching)
  3. Data Caching
  1. ) Page Output Caching :-
In this type of caching the Entire web page (HTML page) cached within memory by specifying output Cache @Directive .
In this Caching technique page output and Hypertext Transfer protocol (HTTP) response stored in an memory cache (Random Access Memory) of the computer. In ASP.NET 4.0, you can create more than one custom Output Cache provider also.
System.web.caching.OutputCacheprovider ; Class is used to create custom output cache provider which can be registered within the web.config file.This caching concept is more useful for static web page(page whose content does not change).In this caching data can be stored on different-2 location such as client side,server side or proxy side.
We can easily implement the page output caching by adding the @output cache Directive as shown below:-
<%@OutputCache Duration = "30" VaryByParam ="none" %>
We can define the location such as server side,client side or proxy side as given below:<%@OutputCache Duration = "50" Location= "Any/Client/Downstream/Server/None" VaryByParam ="none" %>

Some Important Attribute supported by the @OutputCache Directive
   Attribute                                                         Description
Cache Profile       -->  It is an optional attribute.It contains the setting of the cache to                                                      associate with a web page.                     

Duration              --> It is used to define the time duration of web page to be cached.

Location              --> It is used to define the location where the cache is created.

SqlDependency  --> It contains a string value that identifies a set of database and table 
                                 name.  

VaryByControl   --> It contains a semicolon-separated list of strings.These strings                                                         represent ID Property values of ASP.NET ,Server controls declared in                                           user control

VaryByCustom  --> It is used to define the custom strings for custom output caching.

VaryByHeader  --> It is used to define a semicolon-separated list of Http Headers.

VaryByParam   --> It is used to define the semicolon-separated lists of strings,which the                                          output cache uses to identify the cache entry.

The Locate Attribute-
The are some elements of locate attribute which are given below:-
Any                      --> It specifies that output cache can be located any where such as on the                                          client's browser,server or proxy server.
Client                   --> It specifies that the output cache is only located on the client browser.
Downstream       --> It specifies that the output cache is stored in any HTTP 1.1 cache                                                 capable devices or other proxy server or originating server.            
None                    --> It specifies,disables the output cache of the requested page.
Server                 --> It specifies that the output cache is located on the web server only.
Server and Client  --> It specifies that the output cache is stored on the web server and on                                            the client browser.

Note:- Locate attribute not support .ascx file user control.

The VaryByCustom Attribute:-
The VaryByCustom attribute is used custom strings according to the requirements of a user.
Ex. If we want to cache different types of contents for different browsers such as
  • Image for Internet Explorer
  • Text for Google chrome
  • Video for Mozilla Firefox
then we have to VaryByCustom attribute . If we want to implement a custom logic then we must override the HttpApplication. GetVaryByCustomStrings Method in our web application's Global.asax file
The VaryByParam Attribute:-
The VaryByParam attribute is used to cache different copies of a web page,when the web page is changed dynamically,based on the parameters received in the form of HTTP Post or HTTP GET.
Why we use VaryByParam attribute:-
For Example ,Suppose we want to received the student records on the basis of student Id 13 and the VaryByParam attribute set to its default value "None". In this case student Id 13 records saved in cache memory.Suppose another person want to received the records of student Id 20,In this case cache engine unable to differentiate between the two request (id 13 ,id 20) and sends the cached output student Id 13 records to the person. To overcome this problem we use the VaryByParam attribute and specify the cache engine should vary its cache data on the basis of the student Id at the top of the web page.
Meanings of below Directives:-
<%@OutputCache Duration = "30" VaryByParam ="none" %>

Once the page is process from the server,the process page kept in the memory within 30 seconds after that this page removed from cache memory and again it will be process from server property.
There are some techniques to implement the page output caching in asp.net application.

     a.) Page Output caching Depends on some control values.
     b.) Page Output caching Depends on query string key value. 
     a.) Page Output caching Depends on some control values:-
    There are some steps to implement this page output caching concept in asp.net applications.
    Step 1 :-First open your visual studio -->File -->New-->website-->Select ASP.NET Empty website -->OK-->Open solution Explorer --> Add New web Form (outputcache1.aspx) -->Drag and drop Label,Text Box,Button and Gridview control on the form(outputcache1.aspx) from Toolbox as shown below:-
    form1

    Step 2 :-Now Add Database.mdf file on website-->create a student table with three column --> and insert some values as shown below:-


    database

    Note:- if you are facing problem adding database(.mdf) on site visit below url:-
    Step 3 :- Now click Source button from below page(outputcache1.aspx)-->write the following Directives as given below:-
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="outputcache1.aspx.cs" Inherits="outputcache" %>
    <%@OutputCache Duration = "30" VaryByParam ="TextBox1" %>
    <%--For cached all controls values,use below code
    <%@OutputCache Duration = "30" VaryByParam ="*" %>--%>
    

    Step 4 :-Now Double click on submit button-->write the following codes as given below:-
    
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;
    
    public partial class outputcache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = "This page is cached for ID: " + TextBox1.Text + ". The Current time is: " + DateTime.Now.ToString();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
    SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select*from student where id= +'" +TextBox1.Text + "'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
    

    Step 5 :-Now Run the application(press F5)-->and Enter student Id in Text Box --> press submit button.
    pagecaching


    Note:-This above page is saved in cache memory for 30 seconds. 

    b.) Page Output caching Depends on query string key value:-
    There are some steps to implement this page output caching concept in asp.net applications.
    Step 1 :- Add two web Form (outputcache2.aspx and outputcache2.1.aspx) on your  previous website-->Drag and drop Text Box and Button controls on outputcache2.aspx page from Toolbox as shown below:-


    form2

    Step 2 :-Now open outputcache2.1.aspx page -->Drag and drop Gridview control on the form as shown below:-

    form3

    Step 3 :- Now open outputcache2.aspx page --> Doubleclick on submit button -->Write the following codes as given below:-

    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class outputcache2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("outputcache2.1.aspx?sid=" + TextBox1.Text);
        }
    }
    

    Step 4 :- Now open outputcache2.1.aspx page --> Click source button from below -->write the following codes as given below:-


    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="outputcache2.1.aspx.cs" Inherits="Default3" %>
    <%@OutputCache Duration = "40" VaryByParam ="sid" %>
    

    Step 5 :-Now Run the application (press F5)-->and Enter student Id value in Text Box -->press Submit button-->you will see following output as shown below:-

    output

    Note :- 
    • This page is saved in cache memory for 40 seconds.
    • You can use Xml File instead of sql server database for this caching applications.
    2. ) Fragment Caching (partial page Caching):-
    When we want to implement caching on specific parts of a web page then we can use Fragment caching or partial caching.This type of caching is implemented by using WebUserControl ,that part of web page we want to provide caching.Caching will be 
    specify in the form of  WebUserControl and within WebUserControl .we will use caching by using output cache Directive @. 
    Real Example:-
    Suppose your web page (HTML page) have two types of content
    • Static content (Ex.image,border,theme,etc)
    • Dynamic content (Ex. Id,Gridview,etc)
    You will have to  seen there are many website on the internet that takes long time to open.Because they are not using caching concept on your website. If any website have two types of contents as static and dynamic then we have to cache the static part of web page. So that processing time and data usage decreased.Fragment caching is a caching technique that helps for static part of the web page.
    There are some steps to implement this concepts on website.Which are given below:-
    Step 1 :-First open your visual studio -->File -->New-->website-->Select ASP.NET Empty website -->OK-->Open solution Explorer --> Right click on project(website) -->Add New Items --> Select WebUserControl -->Click Add as shown below:

    webusercontrol

    Step 2 :-Now Drag and drop Image control on WebUserControl page from Toolbox -->copy one image from Desktop and pate it inside the website folder -->Now Go properties of Image control -->Choose ImageUrl as shown below:-



    Step 3:- Now open WebUserControl.ascx page -->Click Source button from below -->write the following codes as given below:-
    
    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
    <%@OutputCache Duration = "300" VaryByParam ="None" %>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="Label1" runat="server" 
        style="color: #800000; font-weight: 700; text-decoration: underline" 
        Text="Welcome to my website"></asp:Label>
    <p>
        &nbsp;<asp:Image ID="Image1" runat="server" Height="209px" 
            ImageUrl="~/ram.JPG" style="margin-top: 7px" Width="399px" />
    </p>
    
    
    Step 4 :-Now Add a web Form (Fragmentcaching.aspx)-->Drag and drop WebUserControl .ascx ,Text Box ,Button and Gridview controls on the web Form (Fragmentcaching.aspx) as shown below:-
    web form

    Step 5 :-Now Double click on submit button --> write the following codes as given below:-

    
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;
    public partial class Fragmentcaching : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
      SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select*from student where id= +'" + TextBox1.Text + "'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
    

    Step 6 :- Now Run the application (press F5)-->Enter Student Id Field and pres Submit button as shown below:-


    output

    Note:-
    • Now reload your page,you will see that your page image will not change,because it is saved in cache memory for a specific time period(300 seconds).  
    • You can use XML File instead of SQL Server
    3. ) Data Caching :- 
    Data Caching is very useful ,when you need to cache custom data into cache memory.Data caching is one of the most powerful feature in asp.net. Caching is implemented using two mechanisms
    1. Application caching
    2. Page out Caching
    Application caching allows you to cache data you generate,such as a Data Set or Custom reports.
    Page output caching saves the output of a web page and reuse it in future.If you want to access some data frequently then you have to place that data in cache memory.
    There are following basic type of dependency model in Data Caching.Which are given below .
    • Sql Dependency --> It allows to validate a cached item with the Sql Database.
    • Key Dependency -->It allows to manage relationship among cached items.Which depends on each other.
    • Aggregate Dependency -->It allow s to validate a cached items to multiple resources,such as External file or Sql Database.
    • Time Dependency -->It allows to define the expiration time of a particular item of database .
    • Custom Dependency -->It allows to build and use your own dependency instead of using built in dependency.
    • File Dependency -->It allows to validate a cached item with external file such as Extensible Markup Language(XML) and database.
    There are some steps to implement  the Data caching in asp.net.
    Step 1 :-First open your visual studio -->File -->New-->website-->Select ASP.NET Empty website -->OK-->Open solution Explorer --> Add New web Form (Datacaching.aspx) -->Drag and drop Label,Button and Gridview control on the page (Datacaching.aspx) from Toolbox as shown below:-

    form5

    Step 2 :- Now create a text file (myfile.txt)  or XML file in APP_Data Folder -->Write some content in file and save it.


    text file


    Step 3 :- Now Double click on Submit button --> Write the following codes as given below:-
    
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;
    using System.Web.Caching;
    public partial class profilecache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Cache["Data"] != null)
            {
                Label1.Text = "From Cache";
                DataSet ds = (DataSet)Cache["Data"];
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
            }
            else
            {
                Label1.Text = "From Database";
    SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter("select*from student", con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds;
                GridView1.DataBind();
                //--------------------------------------------------------
                Cache["Data"] = ds;
                Cache.Insert("Data", ds); 
    //Cache.Insert("Data", ds, null, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration);
       CacheDependency cd = new CacheDependency(Server.MapPath("myfile.txt"));
       Cache.Insert("Data", ds, cd, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration);
                Label2.Text = "Cache created";
            }
        }
    }
    

    Step 4 :-Now Run the Application (press F5) -->Press Submit button -->You will see First time Data comes from Sql Database as shown below.



    Step 5 :- Now Again Press Submit button-->You will see,Data comes from Cache memory as shown below-

    Note :- In Data Caching Example i have set Cache Expiry time 20 seconds.Means 20 seconds, data comes from cache memory to Gridview control.

    For More...
    1. How to implement Cookies in asp.net application
    2. How to make Custom Login and Registration page in asp.net
    3. Collections in C#
    4. File Handling Real application
    5. How to send mail from asp.net website free
    6. Constructor and destructor in C#
    7. How to make Data List control real application
    8. Web form controls
    9. Create composite custom control in .NET
    10. How to use dll file in asp.net application
    11. How to create Captcha image in asp.net application
    12. Create setup file with database
    I hope this is helpful for you
    Download Whole below attached file
                Download

    2 comments:

    1. this is good, but i need to know how can we set dictionary in the server side cache ..

      ReplyDelete

    Powered by Blogger.