State Management in C#

What is State Management in C#?State management tells how you store information over the lifetime of your application. This information can be a users name or shopping cart for an online shopping site.

Q. Why State Management is used ?
 Ans: We know all web page uses HTTP and HTTP is a stateless protocol. Means no state will be maintain on web page bu default.

2 Types of State Management-
-Client Side
-Server Side

Client Side State Management -

View State
One of the most common ways to store information is in view state. View state uses a hidden field that ASP.NET automatically insert when rendering page into HTML.
It’s a perfect place to store information that’s used for multiple postbacks in a single web page.

this.ViewState["Counter"] = 1;

Code that retrieves the counter from view state:
int counter;
counter = (int)this.ViewState["Counter"];

Cross Page Posting

Transferring or posting data from one page to another page is called cross page posting.

 protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            lblResult.Text = "You came from - " + PreviousPage.Title;
        }
    }

Query String
Another common approach is to pass information using a query string in the URL.
The query string is the portion of the URL after the question mark (?).The advantage of the query string is that it’s lightweight.
Example : Response.Redirect("mypage.aspx?productid=50");
To Get query string data on another page:
string productid = Request.QueryString["productid"].ToString();

Cookies
Cookies provide another way that you can store information for later use.  Cookies are small files that are created in the clients system memory.
One advantage of cookies is that they work transparently without the user being aware that information needs to be stored.
If user disable cookies, then some web application cause problems which require them.
Also, users might manually delete the cookie files stored on their hard drives.

C# code to use cookies
//Create a object of cookies
HttpCookie cookie = new HttpCookie("GeoLocation");
cookie["Language"] = "Hindi";  //assign value for cookie
cookie["Country"] = "INDIA";
//Add cookie
Response.Cookies.Add(cookie);
//You may also set cookie expiry date
cookie.Expires = DateTime.Now.AddYears(1);

Hidden Field- This is a control which can be assign a value to maintain state.


Server Side State Management
Session State
Session state management is one of ASP.NETs premiere features. It allows you to store any  type of data in memory on the server. The information is protected, because it is never transmitted  to the client, and it’s uniquely bound to a specific session.
Session state is ideal for storing information such as the items in the current user’s shopping basket when the user browses from one page to another.
//Assign value to session

Session["user"] = userloggedin name;

Session is a global variable.

You may add session time out,
Session.Timeout = 25;//25 is in minutes

Mode of Session State
InProc - InProc is the default mode, and it makes the most sense for small websites. It  provides the best performance but the least durability.
If you restart your server your session will be lost. InProc will not work for web farm  with load balancing where multiple web servers are involved.
If the web servers use InProc mode, each one will have its own private collection of session data.

State Server - With this setting, ASP.NET will use a separate Windows service for state management.
When using the StateServer setting, you need to specify a value for the stateConnectionString setting.  This string identifies the TCP/IP address of the computer that is running the StateServer service and its port number.This allows you to host the StateServer on another computer. If you don’t change this setting, the local server
will be used (set as address 127.0.0.1).

Before using State Server you need to start "ASP.NET State Service"

SQL Server - This setting instructs ASP.NET to use an SQL Server database to store session information, as identified by the sqlConnectionString attribute. This is the most resilient state store but also the slowest by far. To use this method of state management, you’ll need to have a server with SQL  Server installed.
You need to install the special stored procedures and temporary session databases. These stored procedures take care of storing and retrieving the session information.
To do this you need to run -  aspnet_regsql.exe

If your web application is using Load balancing, sql mode is right session mode for you.

Custom  -  When using custom mode, you need to indicate which session state store provider to use by supplying the customProvider attribute. The customProvider attribute indicates the name of the class. The class may be part of your web application.

Application State - Application state allows you to store global objects that can be accessed by any client. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
For example, you could create a global.asax event handler that tracks how many sessions have been created or how many requests have been received on a page.

Comments

Popular

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners