1 March 2014

Difference Between Session and Caching

Session vs Caching
 
Session and Caching both are state-management techniques and for both data is saved onto the server. In other words you can put your data or store your data onto the server and for some amount of time, but the question is what is the difference between them.
 
Before starting on the differences between session and caching I want to explain to you there are following three 3 types of caching in ASP.NET:
  1. Output Caching
  2. Fragmentation Caching
  3. Data Caching
 
Session vs Caching
1. The first main difference between session and caching is: a session is per-user based but caching is not per-user based, So what does that mean? Session data is stored at the user level but caching data is stored at the application level and shared by all the users. It means that it is simply session data that will be different for the various users for all the various users, session memory will be allocated differently on the server but for the caching only one memory will be allocated on the server and if one user modifies the data of the cache for all, the user data will be modified.
 
Example
 
Use the following procedure to create a sample showing programmatically what the main difference is between them:
  1. First open the Visual Studio and create a new ASP.NET project with the C# language.
  2. Now add one ASP.NET page I named "Session.aspx".
  3. Now I am creating here a login page by using 2 Text Boxes and 1 Button control inside the table as you can see in the following:

    Login Form

    The code of this login page is as in the following (inside the body tag):
    1. <form id="form1" runat="server">  
    2.         <div>  
    3.             <h2 style="margin-left: 40px"><strong> Login Form</strong></h2>  
    4.             <table>  
    5.                 <tr>  
    6.                     <td>  
    7.                         UserName: </td>  
    8.                     <td>  
    9.                         <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>  
    10.                     </td>  
    11.                 </tr>  
    12.                 <tr>  
    13.                     <td>  
    14.                         Password:  
    15.                     </td>  
    16.                     <td>  
    17.                         <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>  
    18.                     </td>  
    19.                 </tr>  
    20.                 <tr>  
    21.                     <td colspan="2">  
    22.                         <center><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></center>  
    23.                     </td>  
    24.                 </tr>  
    25.             </table>  
    26.         </div>  
    27.     </form>  
  4. Now on the code behind of this page ("Session.aspx") write the following code in the click event of the submit button.

    Submit button event code

    The code above shows that we have 2 session keys UName and Pwd and I am providing the user name textbox's (txtUser's) value to the session which the key is UName and TextBox of the password's (txtPwd's) value to session of which the key is Pwd.

    Look at the code above after creating both of the session keys I am redirecting to another page called "AfterSessionRedirect.aspx".
  5. So now I am creating another page named "AfterSessionRedirect.aspx" and taking two lables where I will show the saved value on the session. I have created "AfterSessionRedirect.aspx" as follows:

    SessionRedirect

    The code of this aspx page is as folows:
    1. <div>  
    2.   
    3.      User Name:  
    4.      <asp:Label ID="lblUsr" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>  
    5.      <br />  
    6.   
    7.      Password:  
    8.      <asp:Label ID="lblPwd" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>  
    9.   
    10. </div>  
  6. Now on the code behind of that page I am writing code that will display the user name and password in the label. So on the load time of the page I am writing the following code:
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.         if (Session["UName"] != null && Session["Pwd"] != null)  
    4.         {  
    5.                 lblUsr.Text = Session["UName"].ToString();  
    6.                 lblPwd.Text = Session["Pwd"].ToString();  
    7.         }  
    8.         else  
    9.         {  
    10.                 lblUsr.Text = "Session of UName key is not set";  
    11.                 lblPwd.Text = "Session of Pwd key is not set";  
    12.         }  
    13. }  
  7. Now run the Session.aspx page; you will see output such as the following:

    When Session.aspx page loads:

    run the Session

    After entering username and password as in the following:

    Login form with username and password

    After clicking "Submit" the session variable will be stored on the server and displayed on the next page as in the following:

    next page
Now I am creating same example for the caching,
  1. Create two more pages one named as Caching.aspx and another one is AfterCachingRedirect.aspx.
  2. On Caching.aspx:

    Login Form

    For creating this I have used same code that I have written in Session.aspx as in the following:
    1. <form id="form1" runat="server">  
    2.     <div>  
    3.     <div>  
    4.             <h2 style="margin-left: 40px"><strong> Login Form</strong></h2>  
    5.             <table>  
    6.                 <tr>  
    7.                     <td>  
    8.                         UserName: </td>  
    9.                     <td>  
    10.                         <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>  
    11.                     </td>  
    12.                 </tr>  
    13.                 <tr>  
    14.                     <td>  
    15.                         Password:  
    16.                     </td>  
    17.                     <td>  
    18.                         <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>  
    19.                     </td>  
    20.                 </tr>  
    21.                 <tr>  
    22.                     <td colspan="2">  
    23.                         <center><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></center>  
    24.                     </td>  
    25.                 </tr>  
    26.             </table>  
    27.         </div>  
    28.     </div>  
    29.     </form>  
  3. For the code behind of Caching.aspx write the following code in the click event of the submit button:

    Cache

    You can see I have created UName and Pwd two key of the caching and storing information on the server's cache memory.
    Code above is describes that I am saving username and password on the server's cache memory, and after storing the username and password inside the server cache page will be redirect to theAfterCahchingRedirect.aspx
  4. For the same as AfterSessionRedirect.aspx I have created AfterCachingRedirect.aspx and on this page use the following code:

    CacheRedirect

    And the following code is for creating this page(AfterCachingRedirect.aspx).
    1. <div>  
    2.      User Name:  
    3.      <asp:Label ID="lblUsr" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>  
    4.      <br />  
    5.       Password:  
    6.      <asp:Label ID="lblPwd" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>  
    7. </div>  
  5. On the code behind of the AfterCachingRedirect.aspx I have written the following code in the page load.
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.                 if (Cache["UName"] != null && Cache["Pwd"] != null)  
    4.                 {  
    5.                         lblUsr.Text = Cache["UName"].ToString();  
    6.                         lblPwd.Text = Cache["Pwd"].ToString();  
    7.                  }  
    8.                 else  
    9.                 {  
    10.                         lblUsr.Text = "Caching of UName key is not set";  
    11.                         lblPwd.Text = "Caching of Pwd key is not set";  
    12.                 }  
    13. }  
  6. After writing the code above run Caching.aspx as in the following:

    On load:

    run the Caching Page

    After providing username and password:

    username and password

    On click of the "Submit" button:

    Submit button
What you saw is session and caching working the same but the difference is as I explained, session is user level but caching is application level.

So now I am again running Session.aspx and showing you how it stores the data at the user level.
 
Now Difference

Run Session.aspx 
and provide username and password:

Login form with username and password

After clicking on "Submit":

click on Submit

URL
 
Now after coping the URL you will get the output:

 
Now Run Session.aspx and provide username and password:

username and password
 
After clicking on "Submit":

Submit

URL
Now after coping the URL you will get the output:

You can see both outputs.

1. In Session after storing the session, when you copy the URL and paste it into another browser then you can't access the URL but when you do that for caching, in other words after storing into the cache variable, it can be accessed by a different user also.
So now we can say that a session has user-level storage on the server but caching has application-level storage on the server.

2. A session has a relative or sliding expiration, in other words by default a session has an expiration time of 20 minutes, but an application that is not being used will be relatively increased, in other words if the user is not using that application for more than 20 minutes then the session will be automatically expired and if the user is not using it then the time will be relatively increased, well we can also provide a custom time of session expiration. But caching has 2 types of expiration as in the following:
  1. Absolute Expiration
  2. Relative Expiration or Sliding Expiration 
Absolute expiration means in caching the cache memory will be deleted after a fixed amount of time, the same as for cookies
Sliding expiration means in caching the cache memory will be deleted after a fixed amount of time if that memory is not in use, if it is used in that specific time then it can be relatively increased. the same as for a session.

1. How to provide Absolute Expiration in caching
  1. Cache.Insert("Uname", txtUser.Text, null, DateTime.Now.AddSeconds(20), TimeSpan.Zero);  
Here:
 
Uname: Key
txtUser.Text: Object Type value (that we want to save into the cache)
null: Dependencies; in caching there are the following 3 types of dependencies:
  1. Created cache that depends on another cache
  2. Created cache that depends on a file
  3. Created cache that depends upon a database. I have given it null because I don't want my cache to expire by changing a file or a cache or a database.
DateTime.Now.AddSeconds(20): Absolute time is given for expiration.
TimeSpan.Zero: This property disable the sliding expiration, in other words if it's set to zero then the relative time will never expand for the cache.
 
2. How to provide Sliding Expiration in caching 
  1. Cache.Insert("Uname", txtUser.Text, null, DateTime.MaxValue, TimeSpan.FromSeconds(20));  
Uname: Key
txtUser.Text: Object Type value (that we want to save into the cache)
null: Dependencies (in caching there are the following 3 types of dependencies as in the following:
  1. Created cache that depends on another cache
  2. Created cache that depends on a file
  3. Created cache that depends upon a database. I have given it null because I don't want my cache to expire by changing a file or a cache or a database.
DateTime.MaxValue: Sets the time to max so it will disable the property of the absolute expiration.
TimeSpan.FromSeconds(20)): It will set a sliding expiration time to 20 second and it will enable the property for a sliding expiration.

No comments:

Post a Comment