State
management techniques are used to maintain user state throughout the
application. The following are the commonly used state management techniques.
The following are the commonly used state management techniques.
View state
- Control state
- Hidden fields
- Cookies
- Query strings
- Application state
- Session state
- Profile Properties
Server Based State Management
Application
state, session state, and profile properties all store data in memory on the
server.
Session State: HTTP is a stateless
protocol, it can't hold client information on a page. If the user inserts some
information and move to the next page, that data will be lost and the user
would not be able to retrieve that information. Session provides a facility to store information on server
memory. It can support any type of object to store along with our own custom
objects. For every client, session data is stored separately, which means
session data is stored on a per client basis.
Advantages of Session:-
- It
helps maintain user state and data all over the application.
- It
is easy to implement and we can store any kind of object.
- Stores
client data separately.
- Session
is secure and transparent from the user.
Session
Mode
The following
session modes are available in ASP.NET.
- Off
- InProc
- StateServer
- SQLServer
- Custom
1 1.Off - Disables session state for the entire application.
2.InProc session : When the session state mode is set to InProc, the session state variables are stored on the web server memory inside the asp.net worker process. This is the default session state mode.
Advantages of InProc session state mode:
1. Very easy to implement.
All that is required is, to set, the session state mode=InProc in web.config
file.
2. Will perform best
because the session state memory is kept on the webserver, within the ASP.NET
worker process(w3wp.exe).
3. Suitable for web
applications hosted on a single server.
Dis-advantages of InProc session state mode:
1. Session state data is
lost, when the worker process or application pool is recycled.
2. Not suitable for web
farms and web gardens.
Note:
Web Garden - Web
application deployed on a server with multiple processors
Web Farm - Web application
deployed on multiple server .
---------------DEFAULT.ASPX---------------
-------------------DEFAULT2.ASPX CODE-----------
------------------WEB.CONFIG CODE--------
3. StateServer :When the session state mode is set to StateServer, the session state variables are stored in a process, called as asp.net state service. This process is different from the asp.net worker process. The asp.net state service can be present on a web server
Steps to follow, to configure asp.net web application to use StateServer:
1. Start the ASP.NET state
Service. To start the asp.net state service
a) Click Start > Type Run > Press
Enter
b) In the run window, type services.msc
and click OK.
c) In the services window, right click on
ASP.NET State Service and select Start.
2. In web.config set
sessionState mode="StateServer"
3. Set
stateConnectionString="tcpip=StateServer:42424"
Example:<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424"
timeout="20"></sessionState>
Advantages
of using StateServer session state mode:
1. ASP.NET
worker process independent. Survives worker process restart.
2. Can be used with web
farms and web gardens.
Dis-advantages
of using StateServer session state mode:
1. StateServer is slower
than InProc
2. Complex objects, need
to be serialized and deserialized
4.SQL SERVER:When the session state mode
is set to SQLServer, the session state
variables are stored in a SQLServer database.
Steps to follow, to configure asp.net web application to use SQLServer:
1. Create the ASPState database using aspnet_regsql.exe tool. There are several versions of t This tool. I am running .NET version 4.0, on a 64 bit operating system. So I will use the version that is present inC:\Windows\Microsoft.NET\Framework64\v4.0.30319.
a) click
Start > Type Run > Press Enter
b) Type cmd
> Press Enter
c) In the
command prompt type - cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
d) Press
Enter
e) Type -
aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
f) Press
Enter. At this point you should have ASPState Database added.
g) For help
running this tool, please refer to the following MSDN article
2. Set the Session state
mode=SQLServer and sqlConnectionString
If you want to use windows authentication
<sessionState mode="SQLServer"
sqlConnectionString="data
source=SQLServerName; integrated security=SSPI"
timeout="20"></sessionState>
If you want to
use sql serevr authentication
<sessionState mode="SQLServer"
sqlConnectionString="data
source=SQLServerName; user id=sa; password=pass"
timeout="20"></sessionState>
Note: If
you use integrated security(windows authentication), you might get an error stating
To resolve this error
a) click Start > Type
Run > Press Enter
b) Type inetmgr > Press
Enter
c) Expand IIIS and Click
on Application Pools.
d) Right click on ASP.NET
v4.0 and select Advanced settings
e) Change Process Model
> Identity to LocalSystem and Click OK
Advantages of using SQLServer session state mode:
1. SQLServer is the most
reliable option. Survives worker process recycling and SQL Server restarts.
2. Can be used with web
farms and web gardens.
3. More scalable than
State server and InProc session state modes.
Dis-advantages of using StateServer session state mode:
1. Slower than StateServer
and InProc session state modes
2. Complex objects, need
to be serialized and deserialized
2. Application state: Application state is a server side state management
technique. The date stored in application state is common for all users of that
particular ASP.NET application and can be accessed anywhere in the application.
It is also called application level state management. Data stored in the
application should be of small size. The data in application state is stored once and read several
times. Application state uses the HttpApplicationstate class to store and share the data throughout the application.
Events in Global.asax File
Some
of the Events in Global.asax file are depicted as follows; this is not a
complete list of events.
Application_Start: This event fires executes when the
application starts running
Application_End: This event ocurs on application shutdown
Application_Error: This event ocurs when unhandled error
occurs
Session_Start: This
event ocurs when new session is started.
Session_End: This event
occurs when session ends.
------------------------------------------------------------------------------------
----------------------------aspx code------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Application.Lock();
TextBox1.Text = Application["t"].ToString();
TextBox2.Text = Application["o"].ToString();
Application.UnLock();
}
protected void Button1_Click(object sender, EventArgs e)
{
Session.Abandon();
}
}
-----------------------------CODE BEHIND-------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Total Visitor"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Total Online"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Logout" />
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
------------GLOBAL asax---------------------------
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
Application.Lock();
Application["t"]=0;
Application["o"] = 0;
Application.UnLock();
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
//int t, o;
Application.Lock();
Application["t"] = int.Parse(Application["t"].ToString()) + 1;
Application["o"] = int.Parse(Application["o"].ToString()) + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
//int o;
Application.Lock();
Application["o"]= int.Parse(Application["o"].ToString()) -1;
Application.UnLock();
}
</script>
2.Client Site state: View state, control state, hidden
fields, cookies, and query strings all stores the
data on the client in various ways.
1.View State:- View state stores page-specific information,when a
page post back to the server.When a page is processed,the current state of the
page and its controls is hashed into a string and saved a s a hidden
field,such a state of the page is called view state.In any asp.net application
view state is maintained by default.
To disabled the view state on the web
page directive:-
<@page
Enableviewstate="false"%>
To disable the view state at
the coding time:-
Enableviewstate=false;
OR
Page.Eableviewstate=false;
-----------Code behind-----------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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="Label1" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="email"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
-------------axpx.cs code------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Get values from View-State
if (ViewState["Name"] != null)
{
TextBox1.Text = ViewState["Name"].ToString();
}
if(ViewState["email"]!=null)
{
TextBox2.Text = ViewState["email"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Set values in View_State
ViewState["name"] = TextBox1.Text;
ViewState["email"] = TextBox2.Text;
//Response.Redirect("defult2.aspx");
}
}
2.Hidden Fields:ASP.NET allows you to store
information in a Hidden-Field control, which renders as a standard
HTML hidden field. A hidden field
does not render visibly in the browser, but you can set its properties just as
you can with a standard control. When a page is submitted to the server, the
content of a hidden field is sent in the HTTP form collection
along with the values of other controls.
3. Cookies: Cookie is a small text file sent by web server and saved by web
browser on client machine. Cookies
are created when a user's browser loads a particular website. The website sends
information to the browser which then creates a text file. Every time the user
goes back to the same website, the browser retrieves and sends this file to the
website's server.
-The size of cookies 4kb.
-There are two types
of cookies available in .Net
- Non
Persistent / Session Cookies
- Persistent
Cookies
1.Non
Persistent / Session Cookies
Non Persistent cookies are stored in memory of the client browser
session, when browsed is closed the
non persistent cookies are lost.
2.Persistent
Cookies
Persistent Cookies have an expiration date and theses
cookies are stored in Client hard drive.
--------------------------------------Code Behind-------------------------------------
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Username"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Cookies"
onclick="Button1_Click" />
</div>
</form>
</body>
-------------------------------Default.aspx.cs Code--------------------------------------
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie ob = new HttpCookie("UserInfo");
ob["UserName"] = TextBox1.Text;
ob["Password"] = TextBox2.Text;
ob.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.Add(ob);
Response.Redirect("default2.aspx");
TextBox1.Text = "";
TextBox2.Text = "";
}
-------Second Method------------
protected void Button1_Click(object sender, EventArgs e)
{
Response.Cookies["username"].Value = TextBox1.Text;
Response.Cookies["Password"].Value = TextBox2.Text;
Response.Cookies["username"].Expires = DateTime.Now.AddDays(-1);
Response.Redirect("default2.aspx");
}
---------------------------Code Behind----------------------------------
<body>
<form id="form1" runat="server">
<div>
UserName <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
Password
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
---------------------------Default2.aspx.cs------------------------------
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie ob = Request.Cookies["UserInfo"];
if (ob != null)
{
Label1.Text = ob["Username"];
Label2.Text = ob["Password"];
}
else
{
Response.Write("Cookies has been Expired");
return;
}
}
-----Second Method---------
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
{
Label1.Text = Request.Cookies["username"].Value;
Label2.Text = Request.Cookies["password"].Value;
}
}
4. Query Strings: . A query
string is information that is appended to the end of a page URL. They can be
used to store/pass information from one page to another to even the same page.
-----------------------------CODE BEHIND------------------
<<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
First Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
last Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Send Data"
onclick="Button1_Click" />
</div>
</form>
</body>
</html>
-------------------------------BUTTON CODE------------------------
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default2.aspxfirstname="+Server.UrlEncode(TextBox1.Text)+"&lastname="+Server.UrlEncode(TextBox2.Text));
//Using String.Replace() function to replace &(ampersand) with %26
//Response.Redirect("Default2.aspx?firstname="+TextBox1.Text.Replace("&","%26")+ "&lastname="+TextBox2.Text.Replace("&","%26"));
}
-----------------------Default2.aspx Source Code---------------------
<body>
<form id="form1" runat="server">
<div>
First Name <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br /> <br />
Last Name <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
-----------------------Default2.aspx Page Load---------------------
protected void Page_Load(object sender, EventArgs e)
{
// Read the QueryString values
Label1.Text = Request.QueryString["firstname"];
Label2.Text = Request.QueryString["lastname"];
//Label1.Text = Request.QueryString[0];
//Label2.Text=Request.QueryString[1];
//Label1.Text = Request.Params[0];
//Label2.Text=Request.Params[1];
}
No comments:
Post a Comment