May 13, 2021 ASP.NET
A hyperbly text transfer protocol (HTTP) is a stateless protocol. W hen the client disconnects from the server, the ASP.NET engine drops the page object. This allows each Web application to scale to a large number of requests at the same time without running out of server memory.
However, there are technologies that need to store information between requests and get it back when needed. This information is called state, which is the current value of all controls and the variables currently used by the current user in the current session.
ASP.NET manage four states:
The view state is the state of the page and all its controls. It allows ASP.NET the framework to remain the same.
When a page is sent back to the client, the properties of these pages change and their controls are determined and stored within the value of a hidden input field named _VIEWSTATE. When the page is posted back again, _VIEWSTATE field is sent to the server with the HTTP request.
View state can be enabled or disabled for:
It uses a view state object, which is defined by a StateBag category defined by a set of view state items. The StateBag is a data structure that contains property value pairs and is stored as a string associated with an object.
The StateBag class has the following properties:
Property | Describe |
---|---|
Item(name) | The value of the view state with the specified name is the default property of StateBag. |
Count | The name of the item in the state collection. |
Keys | A collection of keys for all items in the collection. |
Values | A collection of values for all items in the collection. |
The StateBag class has the following methods:
Method | Describe |
---|---|
Add(name, value) | Add an item to the view state collection to update an existing item. |
Clear | Remove all items from the collection. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
Finalize | Allows resources to be freed and other cleanup operations performed. |
GetEnumerator | Returns the counter that stores the key/value pairs of the StateItem object that is repeated in the StateBag object. |
GetType | Gets the type of the current instance. |
IsItemDirty | Check the StateBag object stored to confirm that it has been modified. |
Remove(name) | Remove the development project. |
SetDirty | Sets the state of the StateBag object and the Dirty property of each StateItem object that it contains. |
SetItemDirty | Set the Dirty property for the specified StateItem object in the StateBag object. |
Tostring | Returns a string that represents the state package object. |
The following example illustrates the concept of a string that stores the state of a view.
Let's keep a counter that increments each time the page is thed back by clicking a button on the page. The label control displays the value of the counter.
The tag file code looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="statedemo._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>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>View State demo</h3>
Page Counter:
<asp:Label ID="lblCounter" runat="server" />
<asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click" />
</div>
</form>
</body>
</html>
The instance's background code file looks like this:
public partial class _Default : System.Web.UI.Page
{
public int counter
{
get
{
if (ViewState["pcounter"] != null)
{
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
lblCounter.Text = counter.ToString();
counter++;
}
}
It will produce the following results:
The control state cannot be directly modified, accessed, or disabled.
When a user connects ASP.NET the web site, a new session object is created. W hen the session state is open, the new session state is created for each new request. This session state object becomes part of the running environment and can be used through the page.
Session state is typically used to store application data, such as detailed catalogs, vendor lists, customer records, or shopping carts. It stores the user's information and their preferences, as well as the user's undefined path.
Sessions are identified and tracked by a 120-bit SessionID, passed from the client to the server and backted as a cookie or modified URL. SessionID is the only, random one in the world.
The session state object is created by the HttpSessionState class, which defines the session state item collection.
The HttpSessionState class has the following properties:
Property | Describe |
---|---|
SessionID | Unique session identifier. |
Item(name) | The value of the session state item with the specified name is the default property of the HttpSessionState class. |
Count | The number of items in the session state collection. |
TimeOut | Gets and sets the amount of time, which is allowed between requests within a few minutes before the vendor stops the session state. |
The HttpSessionState class has the following methods:
Method | Describe |
---|---|
Add(name, value) | Add a new item to the session state collection. |
Clear | Remove all items from the session state collection. |
Remove(name) | Removes the specified items from the session state collection. |
RemoveAll | Remove all keys and values from the session state collection. |
RemoveAt | Remove the item at the specified index from the session state collection. |
The session state object is a name-value pair that stores and retrieves information from the session state object. Similarly, you can use the following code:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in session dictionary objects, however, it can store all the original data types and arrays consisting of the original data types, DataSet, DataTable, HashTable, and image objects, as well as any user-defined classes that inherit the ISerializable object.
The following example illustrates the concept of storing session state. T here are two buttons on the page: a text box button that enters a string and a label button that displays the text stored from the last session. The tag file code looks like this:
<%@ 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>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 568px; height: 103px">
<tr>
<td style="width: 209px">
<asp:Label ID="lblstr" runat="server" Text="Enter a String" style="width:94px">
</asp:Label>
</td>
<td style="width: 317px">
<asp:TextBox ID="txtstr" runat="server" style="width:227px">
</asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 209px"> </td>
<td style="width: 317px"> </td>
</tr>
<tr>
<td style="width: 209px">
<asp:Button ID="btnnrm" runat="server"
Text="No action button" style="width:128px" />
</td>
<td style="width: 317px">
<asp:Button ID="btnstr" runat="server"
OnClick="btnstr_Click" Text="Submit the String" />
</td>
</tr>
<tr>
<td style="width: 209px"> </td>
<td style="width: 317px"> </td>
</tr>
<tr>
<td style="width: 209px">
<asp:Label ID="lblsession" runat="server" style="width:231px" >
</asp:Label>
</td>
<td style="width: 317px"> </td>
</tr>
<tr>
<td style="width: 209px">
<asp:Label ID="lblshstr" runat="server">
</asp:Label>
</td>
<td style="width: 317px"> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
The following should be displayed in the design view:
The background code is as follows:
public partial class _Default : System.Web.UI.Page
{
String mystr;
protected void Page_Load(object sender, EventArgs e)
{
this.lblshstr.Text = this.mystr;
this.lblsession.Text = (String)this.Session["str"];
}
protected void btnstr_Click(object sender, EventArgs e)
{
this.mystr = this.txtstr.Text;
this.Session["str"] = this.txtstr.Text;
this.lblshstr.Text = this.mystr;
this.lblsession.Text = (String)this.Session["str"];
}
}
Execute the file and see how it runs:
ASP.NET is a collection of all web pages, code, and other files for a single virtual directory on a Web server. When information is stored in the application state, it can be used by all users.
To provide the use of application state, ASP.NET create an application state object for each application from the HttpApplicationState class and store it in server memory. The object is represented by the class file global.asax.
Application state is primarily used to store counters, other statistics and tax rates, discount rates, etc. for all application data, and to store the user's path to the site.
The HttpApplicationState class has the following properties:
Property | Describe |
---|---|
Item(name) | The value of the application item with the specified name is the default property of http ApplicityState. |
Count | The number of items in the application state collection. |
The Http ApplicityState class has the following methods:
Method | Describe |
---|---|
Add(name, value) | Add a new item to the application state collection. |
Clear | Remove all items from the application state collection. |
Remove(name) | Remove the specified items from the application state collection. |
RemoveAll | Remove all objects from an Http ApplicityState collection. |
RemoveAt | Remove an Http ApplicityState object from a collection found by the index. |
Lock() | Lock the application state collection so that only the current user can access it. |
Unlock() | Unlock the application status collection so that all users can access it. |
Data for application state is typically maintained by handlers written for events:
The following snippets show the basic syntax used to store application state information:
Void Application_Start(object sender, EventArgs e)
{
Application["startMessage"] = "The application has started.";
}
Void Application_End(object sender, EventArgs e)
{
Application["endtMessage"] = "The application has ended.";
}