State management is the process by which ASP.Net manages state and page information over multiple pages for single or multiple web pages. HTTP does not manage the state.
NOTE: HTTP is a stateless protocol. Stateless means, whenever we visit a website, our browser communicates with the respective server depending on our requested functionality or the request. The browser communicates with the respective server using the HTTP or HTTPs protocol.
But after that response, what's next or what will happen when we visit that website again after closing our web browser?
In this case, HTTP/HTTPs doesn't remember what website or URL we visited or in other words, we can say it doesn't hold the state of a previous website that we visited before closing our browser, that is called stateless.
This reduces the load on our servers thereby enabling it to process more user requests. ASP.Net provides two types of state management techniques.
1. Client-side
2. Server-side
The client-side state management techniques available are:
View state
Control state
Hidden fields
Cookies
Query strings
View state
View state is a mechanism by which ASP.Net stores user-specific requests and response data between requests. View state is not stored on the server but is stored in the page itself. When the page is submitted to the server the view state is also submitted to the server. The web server pulls the view state from the page to reset the property values and controls when the page is being processed.
Ex:-
Where a user can edit some profile information. When processing the request the page might have to get information from the database. In this case, the data in various controls and the property values are stored in the view state. Suppose there is a problem with the submitted data and the page is returned back to the browser. We can see that the controls are populated with the data we entered and the property values are preserved. This is because the data is wrapped up into view state with your request and ASP.Net client-side state management features take care of all this work for us.
Example of view state
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["count"] != null)
{
int ObjView1 = Convert.ToInt32(ViewState["count"]) + 1;
View.Text = ObjView1.ToString();
ViewState["count"]=ObjView1.ToString();
}
else
{
ViewState["count"] = "1";
}
}
}
// Click Event
protected void Submit(object sender, EventArgs e)
{
View.Text=ViewState["count"].ToString();
}
Points to Remember
Some of the features of the view state are:
- It is page-level State Management
- Used for holding data temporarily
- Can store any type of data
- Property dependent
Control state
Control state(ControlState property) is used to save state information for custom controls that require a view state. It helps to persist state information for custom control but cannot be turned off like ViewState property. The control state cannot be modified, accessed directly, or disabled.
Points to Remember
- Some features of query strings are:
- Used for enabling the View State Property
- Defines a custom view
- View State property declaration
- Can't be modified
- Accessed directly or disabled
Hidden fields
ASP.Net provides a HiddenField control to store data on a page. It can be added on to a page like any other .Net control but is not visible on the page unless someone views the page’s source. It stores the data in its Value property.
Like a view state, it can be used to store information on a single page and it cannot transfer data between pages. But the data stored in the hidden field is not hashed or encrypted. So it cannot be used to store sensitive information.
To use hidden fields you must use HTTP POST to submit our request to the server. We cannot use HiddenField with HTTP GET.
Example:-
// Hidden Field
int newVal = Convert.ToInt32(HiddenField1.Value) + 1;
HiddenField1.Value = newVal.ToString();
Label2.Text = HiddenField1.Value;
Points to Remember
Some features of hidden fields are:
- Contains a small amount of memory
- Direct functionality access
Cookies
A set of Cookies is a small text file that is stored in the user's hard drive using the client's browser.
Cookies are small files that are created in the web browser’s memory or on the client’s hard disk. The maximum size of a cookie file is 4 KB or 8 KB.
Ex:-
int postbacks = 0;
if (Request.Cookies["number"] != null)
{
postbacks=Convert.ToInt32(Request.Cookies["number"].Value)+ 1;
}
// Generating Response
else
{
postbacks = 1;
}
Response.Cookies["number"].Value = postbacks.ToString();
Result.Text = Response.Cookies["number"].Value;
There are two types of Cookies
Persistent Cookie
Cookies having an expiration date is called a persistent cookie. This type of cookie reaches their end as their expiration dates come to an end. In this cookie, we set an expiration date. This is also called a permanent cookie.
EX:-
Response.Cookies["UserName"].Value = "Mithilesh";
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
HttpCookie Cookie1 = new HttpCookie("Session");
Cookie1.Value = DateTime.Now.ToString();
Cookie1.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(Cookie1);
Non-Persistent Cookie
Non-persistent types of cookies aren't stored in the client's hard drive permanently. It maintains user information as long as the user access or uses the services. It's simply the opposite procedure of a persistent cookie.
Ex:-
HttpCookie Cookie1 = new HttpCookie("Session");
Cookie1.Value = DateTime.Now.ToString();
Cookie1.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(Cookie1);
Points to Remember
Some features of cookies are:
- Store information temporarily
- It's just a simple small-sized text file
- Can be changed depending on requirements
- User Preferred
- Requires only a few bytes or KBs of space for creating cookies
Query strings are used for some specific purpose. These in a general case are used for holding some value from a different page and move these values to the different page. The information stored in it can be easily navigated to one page to another or to the same page as well.
Query strings are appended to the page URL and are used to store values for the requested page. They appear in the URL after a question mark “?” followed by the name of the query string parameter, an equal sign “=” and finally the value.
Ex:-
if (Request.QueryString["eid"] != null)
{
View.Text = Request.QueryString["eid"];
}
// Setting query string
int postbacks = 0;
if (Request.QueryString["eid"] != null)
{
postbacks = Convert.ToInt32(Request.QueryString["eid"]) + 1;
}
else
{
postbacks = 1;
}
Response.Redirect("default.aspx?eid=" + postbacks);
Points to Remember
Some of the features are:
- It is generally used for holding values
- Works temporarily
- Switches info from one to another page
- Increase performance
- Uses real and virtual path values for URL routing
The server-side state management techniques available are:
Application state - The information is global o the application and is available to all users regardless of the identity of the user requesting the page.
Session state - a user-specific state that is stored on the server. It is available on a user basis who is visiting your site.
Application state.
The application state is a global storage mechanism for our application for data that needs to be available for our entire application. We can use the application state to store information that must be maintained between requests. A product catalog that does not change very often can be considered for application state. You can think of an application state as a form of application-level caching of data that is hard to obtain.
Application state is stored in an instance of HttpApplicationState class available through the Page. Application property. This class represents a key-value pair where data is stored as key-value pairs. We can write into and read from the application state. Once data is added to the application state the server manages it.
The application state is a great place to store data when we don’t want to track users and require our data to be available for the entire application. All pages can access data from a single location rather than having multiple copies of it serving each request.
Datastores in ASP.Net application is not permanent. It is lost when our application is restarted or our web server restarts.
Application state data is generally maintained by writing handlers for the events:
- Application_Start
- Application_End
- Application_Error
- Session_Start
- Session_End
Ex:-
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.";
}
Session State:
ASP.NET allows us to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, we can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using our application, each user session has a different session state. In addition, if a user leaves our application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary.
We can use session state to accomplish the following tasks:
i. Uniquely identify the browser or client-device requests and map them to individual session instances on the server. This allows us to track which pages a user saw on our site during a specific visit.
ii. Store session-specific data on the server for use across multiple browsers or client-device requests during the same session. This is perfect for storing shopping cart information.
iii. Raise appropriate session management events. In addition, you can write the application code leveraging these events.
ASP.NET session state supports several different storage options for session data:
a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer.
b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic.
c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities.
d. Custom Enables us to specify a custom storage provider. We also need to implement a custom storage provider.
e. Off Disables session state. You should disable session state if we are not using it to improve performance. Advantages of Client – Side State Management:
1. Better Scalability: With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.
2. Supports multiple Web servers: With client-side state management, we can distribute incoming requests across multiple Web servers with no changes to our application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client’s state information. We can use multiple servers with server-side state management, but we need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where the state is stored in a central database that all Web servers access).
Advantages of Server – Side State Management:
1. Better security: Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, we should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.
2. Reduced bandwidth: If we store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing our costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all because they often have very slow connections. Instead, we should store large amounts of state management data (say, more than 1 KB) on the server.
No comments:
Post a Comment