-->

10 February 2020

Asp.Net Sessions

  Asp.Net CS By Example       10 February 2020

 Asp.Net Sessions 

 Session state is an important way to store temporary information across multiple page requests. However, unlike application state , which is accessible to all users, each object stored in session state is associated with a particular user’s visit to our site. Stored on the server, session state allocates each user free memory on that server for the temporary storage of objects (strings, integers, or any other kinds of objects).

 The process of reading and writing data into session state is very similar to the way we read and write data to the application state: instead of using the Application object, we use the Session object. However, the Session object doesn’t support locking and unlocking like the Application object does.

 In ASP.NET Session state store data using dictionaries or sets of name-value pairs.

C# Code
    Session["message"] = "Hello World";

 With StrMsg set, any pages in the Session can read this string:

C# Code
    string StrMsg = (string)Session["message"]; 

 Like objects stored in application state, session state objects linger on the server even after the user leaves the page that created them. However, unlike application variables, session variables disappear after a certain period of user inactivity. Since web browsers don’t notify web servers when a user leaves a web site, ASP.NET can only assume that a user has left your site after a period in which it hasn’t received any page requests from that user. By default, a user’s session will expire after 20 minutes of inactivity. We can change this timeframe simply by increasing or decreasing the Timeout property of the Session object, as follows.

C# Code
 Session.Timeout = 15;  

 We can do this anywhere in our code, but the most common place to set the Timeout property is in the Global.asax file. If we open Global.asax, we’ll see that it contains an event handler named Session_Start. This method runs before the first request from each user’s visit to our site is processed, and gives you the opportunity to initialize their session variables before the code in our web form has a chance to access them.

C# Code
 void Session_Start(Object sender, EventArgs e) 
 {
  Session.Timeout = 15;
 }

 The main application programming interface for working with Session state is the HttpSessionState class. This object is exposed by the Page.Session, Context.Session, UserControl.Session, WebService.Session, and Application.Session properties.

 This HttpSessionState class supports the following properties.

Sr.No Property Description
1) CookieMode specify whether cookieless sessions are enabled. Possible values are AutoDetect, UseCookies, UseDeviceProfile, and UseUri.
2) Count retrieve the number of items in Session state.
3) IsCookieless determine whether cookieless sessions are enabled.
4) IsNewSession determine whether a new user session was created with the current request.
5) IsReadOnly determine whether the Session state is read-only.
6) Keys retrieve a list of item names stored in Session state.
7) Mode determine the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer.
8) SessionID retrieve the unique session identifier.
9) Timeout specify the amount of time in minutes before the web server assumes that the user has left and discards the session. The maximum value is 525,600 (1 year).

 The HttpSessionState object supports the following methods:

Sr.No Methods Description
1) Abandon end a user session.
2) Clear clear all items from Session state.
3) Remove remove a particular item from Session state.

  Code: FrmSessions.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FrmSessions.aspx.cs"
    Inherits="LearnAsp.Net.ControlDemo.ApplicationState.FrmSessions" %>

<!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>Session State</title>
</head>
<body>    
    <form id="form1" runat="server">
    <div>
        <b>The page has been requested
            <asp:Label ID="lblCounter" ForeColor="Red" runat="server" />
            times!</b>
    </div>
    </form>
</body>
</html>

  Code: FrmSessions.aspx.cs
using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Web;
using  System.Web.UI;
using  System.Web.UI.WebControls;

namespace LearnAsp.Net.ControlDemo.ApplicationState
{
    public partial class FrmSessions : System.Web.UI.Page
    {
         protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["PageCounter"] != null &&
                (int)Session["PageCounter"] >= 10)
            {
                Session.Remove("PageCounter");
            }
            if (Session["PageCounter"] == null)
            {
                Session["PageCounter"] = 1;
            }
            else
            {
                Session["PageCounter"] =
                (int)Session["PageCounter"] + 1;
            }
            lblCounter.Text = Convert.ToString(Session["PageCounter"]);
        }
    }
}

  Output:
logoblog

Thanks for reading Asp.Net Sessions

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.