0% found this document useful (0 votes)
11 views

5 - Managing State

The document discusses different techniques for managing state in web applications built using .NET technology. It describes how state is not preserved inherently in web pages due to their stateless nature. It then covers various methods for preserving state including hidden fields, cookies, query strings, session state, and view state. Session state stores information on the server while view state preserves page-level state on the client.

Uploaded by

akshay patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

5 - Managing State

The document discusses different techniques for managing state in web applications built using .NET technology. It describes how state is not preserved inherently in web pages due to their stateless nature. It then covers various methods for preserving state including hidden fields, cookies, query strings, session state, and view state. Session state stores information on the server while view state preserves page-level state on the client.

Uploaded by

akshay patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

DOT NET TECHNOLOGY

Managing State

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology
State
• Web pages are stateless

• A new instance of a web page is created when it is


posted to the server

• Values of page’s variables and controls are not


preserved on client or server

• State management is a process in which the different


states of a web page and its session and control
related information is maintained

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 2
Preserving State
• The state of a web application helps us to store the
runtime changes that are made to the web
application

• Ex: select and save products in a shopping cart

• Various methods for preserving state

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 3
Preserving State
• Hidden Fields
▫ Refers to a control that is not visible when a web
application is viewed in browser
▫ Contents of the control are sent in HTTP Form
Collection control to the server

• Cookies
▫ Refers to the text files that store data (like user ID)
▫ On page request, cookie is sent along with the page
▫ Web server then retrieves the information from the
cookie
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 4
Preserving State
• Query Strings
▫ Refers to the information strings added at the end of
a URL
▫ Not secure because information is exposed through
URL

• In all above methods, state information is stored at


client end

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 5
Preserving State
• Session State
▫ Stores information specific to user session (duration
for which the user uses the website)
▫ Object of HttpSessionState class is used

• Application State
▫ Stores application data not frequently modified by
users
▫ Object of HttpApplicationState class is used

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 6
Page-Level state
• ViewState property is used to store the page-level state
of a web page

• ViewState property stores the state information of a


single user, as long as the user is working with the
page

• ViewState property allows controls to remember their


state

• ViewState information is maintained in a hidden field


and automatically sent back to server with every
postback

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 7
Page-Level state
• Ex:
ViewState[“Counter”] = 1;

• Value 1 is placed in ViewState collection


• If no item exists with name “Counter”, it will be
created automatically
• Retrieving value
Count = (Int) ViewState[“Counter”];

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 8
protected void BtnIncrement_Click(object sender, EventArgs e)
{
int Count;
if (ViewState["Counter"] == null)
{
Count = 1;
}
else
{
Count = (int) ViewState["Counter"] + 1;
}

ViewState["Counter"] = Count;

lblcount.Text = "Counter: " + Count.ToString();

}
Counter increments each time a
button is pressed. Counter value is
preserved even if the page is
reloaded, until the page is closed.
Query String
• Viewstate is tightly bound to a specific page
• If user navigates to another page, information is
lost

• Pass information using Query String


• Commonly used in search engines

• Portion of a URL after a ‘?’

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 12
Query String
• Limitations
▫ Information is limited to simple strings
▫ Information is clearly visible to anyone
▫ Cannot place large amount of information in query
string as many browsers impose a limit on length of
the URL

• Well suited to database applications


• Ex: http://localhost/newpage.aspx?ID=10&mode=full

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 13
\\QueryString_1.aspx

protected void Button1_Click(object sender, EventArgs e)


{

string url = "QueryString_2.aspx?";


url += "Item=" + ListBox1.SelectedItem.Text + "&";
url += "Mode=" + CheckBox1.Checked.ToString();

Response.Redirect(url);

}
\\QueryString_2.aspx

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "Item: " + Request.QueryString["Item"];
Label1.Text += "<br>Show Full Record: ";
Label1.Text += Request.QueryString["Mode"];
}
Query String
Cookies
• Small files created on client machine

• Stored in the form of a text file on client system or in


the memory of client browser session

• Stores site-specific information of a user (like


username, password)

• Can be created temporarily with specific expiration


times and dates

• Can be created permanent – persistent cookies


Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 19
Cookies
• Created by a server and saved on a client machine

• Client sends cookie information with a page


request

• Server reads the cookie and extracts its value

• Set Cookies using Response object


• Retrieve Cookies using Request object

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 20
Cookies
• Import : System.Net
Cookie Object Cookie Name

• Create cookie object


HttpCookie Cookie = New HttpCookie(“preferences”);

• Set a value in a Cookie


Cookie[“language”] = “English”;
Cookie Key
• Add Cookie to web response
Response.Cookies.Add(Cookie);
Cookie Object
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 21
Cookies
• Expiration of Cookies
Cookie.Expires = DateTime.Now.AddYears(1);

• Retrieving Cookies
HttpCookies Cookie = Request.Cookies[“preferences”];

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 22
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["Preferences"];

if (cookie == null)
{
lblWelcome.Text = "<b>Unknown Customer</b>";
}
else
{
lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
lblWelcome.Text += "Welcome, " + cookie["Name"];
}
}
// continue….
protected void cmdStore_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}

cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);

lblWelcome.Text = "<b>Cookie Created.</b>";


lblWelcome.Text += "New Customer: " + cookie["Name"];

}
Reload the page
Session State
• Session: A period of time in which a user interacts with a
web application
• Session state is a collection of data

• Allows to store any type of data in memory on the server

• Information is protected because it is never transmitted to


the client

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 31
Session State
• Session state is maintained by providing a unique
SessionID to the user, when the session begins

• SessionID –> a unique 120-bit identifier

• SessionID is the only piece of information that is


transmitted between the web server and the client

• Client presents the SessionID and corresponding data are


retrieved from the server

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 32
Session State Modes
• In-Process
▫ Refers to the mode in which the session state memory is kept within
ASP.NET process
▫ Used with web applications hosted on a single server

• Out-of-Process (StateServer)
▫ Refers to the mode in which there is a reliability of a separate
process that manages the state of all servers

• SQL Server
▫ Refers to the mode in which there is a reliability of the data within a
web application with the help of a database

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 33
Storing objects in Session State
• Create session variables
Session[“Name”] = txtName.Text;

• Session state is global to entire application for the current


user

• Retrieving session variables


Label1.Text = Session[“Name”];

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 34
Using Session State
• We can interact with session state using
System.Web.SessionState.HttpSessionState class

• HttpSessionState Members
▫ Count
 Number of items in session collection

▫ IsCookieless
 Identifies if session is tracked with cookies
 Gets a value indicating whether the session ID is embedded in the
URL or stored in an HTTP cookie.

▫ IsNewSession
 identifies whether the session is just created

▫ Mode
 specifies how ASP.NET stores session state information

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 35
Using Session State
• HttpSessionState Members:
▫ SessionID
 Provides a string with a unique session identifier

▫ TimeOut
 Number of minutes that must elapse before the session will be
abandoned

▫ Abandon()
 Cancels the current session immediately and releases all the
memory it occupied

▫ Clear()
 Removes all session items
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 36
// Session_1.aspx

protected void Page_Load(object sender, EventArgs e)


{
Session["username"] = TextBox1.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Session_2.aspx");
}
// Session_2.aspx

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "Welcome:" + Session["username"].ToString();

Label2.Text = "Session ID: " + Session.SessionID;


Label2.Text += "<br>Number of Objects: " + Session.Count.ToString();
Label2.Text += "<br>Mode: " + Session.Mode.ToString();
Label2.Text += "<br>Is Cookieless: " + Session.IsCookieless.ToString();
Label2.Text += "<br>Is New: " + Session.IsNewSession.ToString();
Label2.Text += "<br>Session Timeout (minutes):"+Session.Timeout.ToString();

}
Configuring Session State
• Session state is configured through web.config file

• Cookieless (Using Cookieless SessionIDs)


▫ We can set the Cookieless setting to True or False
<sessionState
cookieless=“false”
/>
▫ When true, SessionID will automatically be inserted into the URL
 http://localhost:1349/WebApp2/(S(x2vesw55eepozdzmfecqa1i
1))/Session_2.aspx

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 41
Configuring Session State
• Timeout
▫ Specifies the number of minutes that ASP.NET waits,
before it abandons the session
<sessionState
timeout=“10”
/>

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 42
Configuring Session State
• Mode
▫ InProc
 Instructs information to be stored in the same process
 Best performance, but least durability
 If server restarts, state information will be lost
 Default mode
<sessionState mode=“InProc” />

▫ Off
 Disables session state management for every page in
the application

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 43
Configuring Session State
• Mode
▫ StateServer (setting up Out-of-Process State Server)
 With this setting, ASP.NET uses a separate Windows Service
for state management

 Need to specify stateConnectionString value (TCP/IP


address & port)

 Allows to host StateServer on another computer

 Start the service: Start Menu > Control Panel >


Administrative Tools > Computer Management > Services
and Applications > Services > ASP.NET State Service (start
& stop by right clicking it) OR in command prompt, write
‘net start aspnet_state’

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 44
//web.config

<sessionState
mode="StateServer"
stateConnectionString="tcpip=localhost:1349"
/>
Configuring Session State
• Mode
▫ SqlServer (Storing Session State in SQL Server)
 This setting instructs ASP.NET to use SQL server database to store
session information

 Need to specify sqlConnectionString value


<sessionState
mode=“SqlServer”
stateConnectionString = “tcpip=127.0.0.1:42424”
sqlConnectionString=“data source=“test1”; user id=sa”
/>

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 48
Application State
• Stores global objects that can be accessed by any client
• Uses System.Web.HttpApplicationState class

• Ex: Global counter that tracks how many times a given page has been
visited by various clients.

int count = 0;

if (Application["Visit"] != null)
{
count = Convert.ToInt32(Application["Visit"].ToString());
}

count = count + 1;
Application["Visit"] = count;
Label1.Text = "Total Visit = " + count.ToString();

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 49
Application State
• Items in application state never time out, they last until the application or server is
restarted.
• If two clients request a page at a same time, one request may be lost.
• Use Lock() and Unlock() to allow only one client to access the value at a time.

Application.Lock();
int count = 0;

if (Application["Visit"] != null)
{
count = Convert.ToInt32(Application["Visit"].ToString());
}

count = count + 1;
Application["Visit"] = count;
Application.UnLock();
Label1.Text = "Total Visit = " + count.ToString();

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 50
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 51
Run on two different clients

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 52
End

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology

You might also like