What is session state?
· The heavy weight of state management, it allows information to store in one page to another.
· It supports any type of object, which includes custom data types.
· It also uses the same collection syntax as view state.
· It is also considered similar to application state. However, session stated scopes only current browser(user session) and only available to that session unlike application state which scopes the entire application.
ASP.NET provides the following session storage options:
· InProc
o actually this is the default condition, and it makes sense for most small websites. Moreover, it stores session state in memory on the web server.
o It is also a good choice for small applications. However, in a web farm scenario, though, it won't work at all to allow Session State to be shared between servers, you may use the StateServer or SQLServer.
· StateServer
o it actually stores session state in a service called the ASP.NET State Service.
o Session state is preserved even if the web application is restarted and makes available to multiple-web servers in a web farm.
· SQLServer
o Actually stores the session state in a SQL Server database(of course you need a server with SQL Server installed :->). However, it is quite slow compare to StateServer.
Steps to use the SQLServer mode
1. Using aspnet_regsql for session state
aspnet_regsql -S -U -P -d -sstype t|p|c -ssadd
2. configure web.config
3. Let's try to play around using Session
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SQlServerMode
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
Session["MySampleSession"] = DateTime.Now;
else
this.lblSessionValue.Text = string.Format ("You entered this page around: {0}",
Session["MySampleSession"]);
}
protected void btnClickMe_Click(object sender, EventArgs e)
{
this.lblButtonTimeAfterClick.Text = string.Format("You clicked the button around: {0}", DateTime.Now);
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SQlServerMode.Default" %>
<!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="lblSessionValue" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="lblButtonTimeAfterClick" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="btnClickMe" runat="server" onclick="btnClickMe_Click" Text="Just Click Me to show session value" />
</div>
</form>
</body>
</html>
Result






0 comments:
Post a Comment