Monday, 16 November 2015

Session Vs Application Vs ViewState Vs Cookie


Session

We know HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. So when a user use website or web application and he done some activities in the site may be he navigate some pages that time we can’t able to know the same user is done these all  things . Take a simple example We all are familiar with flipkart site, and let’s think we are one user we want to purchase a product  from flipkart, what we will do ? we simply open flipkart site then select what product we want, then make a payment.So simple, but when we order a product from flipkart it takes many steps and sometimes we are redirecting to one page to another. But the problem is Http is a stateless protocol so webserver treat each http request for a page as independent . so how can flipkart ensure that  the same user is selecting the product and make the order ? or it is another user ? session is used for solving this type of  problems. In asp.net  session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application or website.



·        If the user presses the browser back button you go back to the previous page but your session state is not reverted. So your CurrentAccount might not be what it originally was on the page.
·        ASP.NET processes can get recycled by IIS. When that happens your next request will start a new process. If you are using in process session state, the default, it will be gone :-(
·        Session can also timeout with the same result if the user isn't active for some time. This defaults to 20 minutes so a nice lunch will do it.
·        Using out of process session state requires all objects stored in session state to be serializable.
·        If the user opens a second browser window he will expect to have a second and distinct application but the session state is most likely going to be shared between to two. So changing the CurrentAccount in one browser window will do the same in the other.

1. Session state is maintained in session level.
 
 2. Session state value is available in all pages within a user session.
    - 
 3. Session state information stored in server.
    - 
 4. Session state persist the data of particular user in the server.
    This data available till user close the browser or session time
    Completes.
    -
 5. Session state used to persist the user-specific data on the server
    Side




Application

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another
Ø We can save Web Application path in Application State because the path is common for all the users.
ViewState
             View state is another approach for  saving data for a particular  user. It allows ASP.NET to repopulate form fields on each postback to the server. It is stored in a hidden field so that it isn't visible to the user. It is used to maintain the user's illusion that the page remembers what he did on it the last time
making sure that a form is not automatically cleared when the user hits the submit button. All this happens automatically, unless you turn it off, but you can actually use the ViewState for your own purposes as well. Please keep in mind though, that while cookies and sessions can be accessed from all your pages on your website, ViewState values are not carried between pages.
 Here is a simple example of using the ViewState to carry values between postbacks:

Ø View state is maintained in page level only. 
Ø View state of one page is not visible in another page.        
Ø View state information stored in client only.       
Ø View state persist the values of particular page in the client
  (browser) when post back     operation done.

Cookie

cookie is a small text file sent by web server and saved by web browser on client machine.
Cookies may be used for authentication, identification of a user session, user's preferences

1.      Size of cookies is limited to 4096 bytes.
2.      Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies.
3.      End user can stop accepting cookies by browsers, so it is recommended to check the users’ state and prompt the user to enable cookies.


Program Illustrate These Concepts:
SessionCheck.aspx

<%@ Page Language="C#" AutoEventWireup="True" CodeBehind="SessionCheck.aspx.cs" Inherits="SessionCookieExample.SessionCheck" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body>


    <form id="form1" runat="server">
    <div>
    <p>Username</p>
    <asp:TextBox ID="Username" runat="server" />
    <p>Password</p>
    <asp:TextBox ID="Password" TextMode="password"  runat="server" />
    <p></p>
    <asp:button id="LoginButton" runat="server" Text="Login" OnClick="CookieCreation" width="5%"/>
    <asp:button id="NextPage" runat="server" Text="GoNextPage" OnClick="SessionCreation" width="10%"/>
     <asp:button id="CookieBackup" runat="server" Text="LoginUsingCookie" OnClick="LoginUsingCookie" width="10%"/>     <asp:button id="Button1" runat="server" Text="click" OnClick="create_Click" width="10%"/>
    <p>
    </p>
    <asp:Label ID="showlabel" runat="server" />
    <asp:Label ID="Applcationstate" runat="server" />
    <p></p>
     <asp:Label ID="viewstatelabel" runat="server" />
     <input type="hidden"id="hide" name="Language" value="Images/error.png">
     

   
   </div>
  
    </form>
</body>
</html>



SessionCheck.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
 using System.Data;

namespace SessionCookieExample
{

    public partial class SessionCheck : System.Web.UI.Page
    {
     
       // SqlCommand cmd;
        public string ConnectionString = "Data Source=192.168.100.100;Initial Catalog=Sample;User ID=User;Password=Password";
      
        protected void Page_Load(object sender, EventArgs e)
        {
          
            Application["Message"] = "Mywebapplication";
            if (ViewState["Username"] != null)
                viewstatelabel.Text = ViewState["Username"].ToString();
            else
            {
                viewstatelabel.Text = " view state Not set yet...";
            }
            HttpCookie cookie = Request.Cookies["Preferences"];
            if (cookie == null)
            {
                showlabel.Text = "<b>Unknown Customer</b>";
            }
            else
            {
                showlabel.Text = "<b>Cookie Found.</b><br><br>";
                showlabel.Text += "Welcome, " + cookie["Name"];
            }
        }
        public void CookieCreation(object sender, EventArgs e)
        {
            int userId = 0;
           
          
         
            using (SqlConnection con = new SqlConnection(ConnectionString))
             {
                 using (SqlCommand cmd = new SqlCommand("Login"))
                 {
                     cmd.CommandType = CommandType.StoredProcedure;
                     cmd.Parameters.AddWithValue("@User", Username.Text);
                     cmd.Parameters.AddWithValue("@Pass", Password.Text);
                     cmd.Connection = con;
                     con.Open();
                     userId = Convert.ToInt32(cmd.ExecuteScalar());
                     con.Close();
                 }
                 if (userId ==-1)
                 {
                     showlabel.Text = "Incorrect UserName Or password";
                     Username.Text = "";
                     Password.Text = "";
                 }
                 else
                 {

                     // Cookie example ..................
                     HttpCookie cookie = Request.Cookies["Preferences"];
                     if (cookie == null)
                     {
                         cookie = new HttpCookie("Preferences");
                     }

                     cookie["Name"] = Username.Text;
                     cookie.Expires = DateTime.Now.AddYears(1);
                     Response.Cookies.Add(cookie);
                    showlabel.Text= "<b>Cookie Created..</b>";
                     showlabel.Text += "New Customer: " + cookie["Name"];
                     // Session example......................


                     Session["Username"] = Username.Text;
                     showlabel.Text += "..Welcome " + Session["Username"] + "..Your session is also Created";
                     Applcationstate.Text = Convert.ToString(Application["Message"]);

                     //.view state .........................
                     ViewState["Username"] = Username.Text;




                 }
               
             }

             
        }

        public void SessionCreation(object sender, EventArgs e)
        {
            Response.Redirect("Nextpage.aspx");

        }

        public void LoginUsingCookie(object sender, EventArgs e)
        {
            int userId = 0;

            HttpCookie cookie = Request.Cookies["Preferences"];
            if (cookie == null)
            {
                cookie = new HttpCookie("Preferences");
            }

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                
                using (SqlCommand cmd = new SqlCommand("Login"))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@User",cookie["Name"] );
                    cmd.Parameters.AddWithValue("@Pass", Password.Text);
                    cmd.Connection = con;
                    con.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
                if (userId == -1)
                {
                    showlabel.Text = "Incorrect UserName Or password";
                    Username.Text = "";
                    Password.Text = "";
                }
                else
                {
                    Response.Redirect("Nextpage.aspx");
                  

                }
              
              
            }
        }
    }
   
}


NextPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NextPage.aspx.cs" Inherits="SessionCookieExample.NextPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="Sessionlabel" runat="server" />
        <asp:Label ID="viewstatelabel" runat="server" />
    </div>
    </form>
</body>
</html>

NextPage.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SessionCookieExample
{
    public partial class NextPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Sessionlabel.Text = "Welcome "  + "..Using session i found your are.." + Session["Username"];
            Sessionlabel.Text += Convert.ToString(Application["Message"]);


            if (ViewState["Username"] != null)
                viewstatelabel.Text = ViewState["Username"].ToString();
            else
            {
                viewstatelabel.Text = " view state Not set yet...";
            }
        }
    }
}


Stored Procedure

USE [Sample]
GO
/****** Object:  StoredProcedure [dbo].[Login]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
          CREATE PROCEDURE [dbo].[Login]
      @User NVARCHAR(20),
      @Pass NVARCHAR(20)
AS
BEGIN
      SET NOCOUNT ON;
      DECLARE @UserId INT
    
      SELECT @UserId = id
      FROM vaidation WHERE Username =@User AND [Password] = @Pass
    
      IF @UserId IS NOT NULL
      BEGIN
           SELECT id FROM vaidation WHERE id = @UserId
              
               END
               ELSE
            BEGIN
                  SELECT -1 -- User not activated.
            END
                                    
   
END



No comments:

Post a Comment