Can you explain State Management in Asp.Net with code samples?

by jack| Views: 4691

Can you please explain State Management in Asp.Net with code samples in C#

i wants to know both type of State Management in Asp.Net even its:-

Server Side State Management in Asp.Net

Client Side State Management in Asp.Net

Answers (4)
 
Gourav Said..

State Management in Asp.Net


Why state Management is important?
Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol so web page is a stateless, which means that it is not capable of storing any information by itself. Because whenever a request for a web page comes from the client, by post-back of a web page the same page will not be returned to the client after processing. So all information associated with the page and the controls on the page would be lost with each round trip. Web server does not have any idea about the requests from where they coming means from same client or new clients. On each request web pages are created and destroyed.

Example of a stateless webpage is that a user is filling its online bank registration form and by mistake it fills some wrong information and after click on submit button its returned back due to invalid information, on this stage user would lost its whole filled information which he was filling from last one hour. So this kind of situations makes the need of State Management of a web page.

Solution of the above problem lies in State Management.

State management is the process by which you maintain state and page information over multiple requests for the same or different pages. ASP.Net technology offers following state management techniques.

Types of State Management in Asp.Net:

Client side state Management: View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways.

  • View state

  • Control state

  • Hidden fields

  • Cookies

  • Query strings


  • Server side state Management: application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.

  • Session State

  • Application State

  • Profile Properties



  • Client side State Management in Asp.Net:

    View State: ASP.Net technology provides View State feature to the web forms. View State is used to remember controls state when page is posted back to server. Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

    ASP.Net stores view state on client site in hidden field __ViewState in encrypted form. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, for multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.

    Code Semple:
    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if(ViewState["NameOfUser"] != null)
    NameLabel.Text = ViewState["NameOfUser"].ToString();

    else
    NameLabel.Text = "Not set yet...";

    }

    protected void SubmitForm_Click(object sender, EventArgs e)
    {
    ViewState["NameOfUser"] = NameField.Text;
    NameLabel.Text = NameField.Text;

    }

    }


    View state can be used for storing any type of data because it is of object type. View state provides good performance for application without giving any load to server. You can enable and disable view state behavior of page and its control by specifying 'enableViewState' property to true and false. You can also store custom information in the view state as described in above code sample. This information can be used in round trips to the web server.
    Gourav Said..

    Cookie: a cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. Cookies are one of several ways to store data about web site visitors during the time when web server and browser are not connected. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.

    Common use of cookies is to remember users between visits. You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.

    Create a cookie in ASP.NET:The System.Web namespace offers a class called HttpCookie to create cookies.

    // Use this line when you want to save a cookie
    Response.Cookies["MyCookieName"].Value = "MyCookieValue";

    // How long will cookie exist on client hard disk
    Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

    // To add multiple key/value pairs in single cookie
    Response.Cookies["VisitorData"]["FirstName"] = "Richard";
    Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();


    Read a cookie in ASP.NET:
    string MyCookieValue;
    // We need to perform this check first, to avoid null exception
    // if cookie not exists
    if(Request.Cookies["MyCookieName"] != null)
    MyCookieValue = Request.Cookies["MyCookieName"].Value;


    Delete cookie in ASP.NET:To delete existing cookie we actually just set its expiration time to some time in the past. You can do it with code like this:
    // First check if cookie exists
    if (Request.Cookies["MyCookieName"] != null)
    {
    //Set its expiration time somewhere in the past
    Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(-1);

    }


    Query String: A query string is information that is appended to the end of a page URL. They are commonly used to hold data like page numbers or search terms or other data that isn't confidential. Unlike ViewState and hidden fields, the user can see the values which the query string holds without using special operations like View Source.

    A typical query string might look like the following example:

    http://www.merithub.com/addpost.aspx?UserType=2&PostType=3

    In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called “UserType” and the other called “PostType".

    The Query String Structure: As written earlier, query strings are appended to the end of a URL. First a question-mark(?) is appended to the URL's end and then every parameter that we want to hold in the query string. The parameters declare the parameter name followed by = symbol which followed by the data to hold. Every parameter is separated with the ampersand(&) symbol. You should always use the HttpUtility.UrlEncode method on the data itself before appending it.

    Get Query String Values on PageLoad:
    Private void Page_Load (object sender, System.EventArgs e)
    {
    string _userType = "";
    string _postType = "";

    if(Request.QueryString["UserType "] != null )
    _userType = Request.QueryString["UserType"];


    if(Request.QueryString["PostType "] != null )
    _postType = Request.QueryString["PostType"];

    }





    Gourav Said..

    Hidden fields: Hidden fields technique is widely used in ASP.NET programing. This is used to store a value that needs to be persisted across posts to the server. Hidden fields are html input control with hidden type that store hidden data in the html. It is rendered as an element. An example for a hidden field can look like this:
    < input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
    In the example above, I chose to show the event target hidden field in order to indicate that even in postback mechanism hidden fields are being used. The data stored in a hidden field is available when the form is processed on the server or when we use javascript. You can use the HiddenField control to store state values. It can store only one value in their value property. The value is saved as a string and therefore in order to use it for other types you need to perform casting. Hidden field’s data is submitted to the server only in HTTP post operation. You can see the stored data easily by using the View Source operation of the browser. The value of a HiddenField is rendered to the client browser, so it is not suitable for storing security-sensitive values. Be aware not to use hidden fields to store confidential data! The values has page context and therefore when you leave a page the data stored in the hidden fields is disposed.
    Server Side State Management:
    Session State: ASP.NET allows you to save values by using session state. This is an instance of the HttpSessionState class. Session state provides a place to store values that will persist across page requests. You can store values that need to be persisted for the duration of a user's session in session variables. These variables are unique to each user session and can be accessed in any ASP.NET page within an application. You can set and access session information from within an ASP.NET application. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. You can set and access session information from within an ASP.NET application. For example
    //Assign a value to the myvariable session variable. Session["myvariable"] = "somevalue"; //Retrieve the value of the myvariable session variable. string myString; if (Session["myvariable"] != null)
    myString = (string)Session["myvariable"];
    It is important to remember that session variables are now objects. Thus, to avoid a run-time error, you should check whether the variable is set before you try to access it. Session variables are automatically discarded after they are not used for the time-out setting. The Session Timeout is adjustable through a web.config setting but increasing the timeout value can put memory pressure on your server that may be undesirable. < sessionState timeout="number of minutes" /> Other commonly used Session methods are: Session.Abandon(): removes the Session and all items that it contains Session.Clear(): removes all items from the Session Session.RemoveAll(): removes all items from the Session Session.Remove("itemName"): removes the item that was stored under the name "itemName" ASP.NET supports three modes of session state: InProc: (The Default) Session state exists within the process the web is using. StateServer: Session data is sent to the configured stateserver service. SQLServer: Session data is store in the configured sql server database. Note You can use all three modes with in-memory cookie or cookieless session ID persistence. You can use session state to accomplish the following tasks:
  • Uniquely identify browser or client-device requests and map them to an individual session instance on the server.
  • Store session-specific data on the server for use across multiple browser or client-device requests within the same session.
  • Raise appropriate session management events. In addition, you can write application code leveraging these events.


  • Gourav Said..


    Application State: Application state is a global storage mechanism accessible from all pages in the Web application and is useful for storing information that needs to be maintained between server round-trips and between pages.Application state is stored in the memory of the windows process which is processing user requests on the web server.

    In ASP.Net, application state is an instance of HttpApplicationState class and it exposes key-value pairs to store information. Its instance is automatically created when a first request is made to web application by any user and same state object is being shared across all subsequent users. It is useful for storing information that needs to be maintained between server round trips and between requests for pages.

    Once you add your application-specific information to application state, the server manages it. Following is an example of using application state in an application.
    //Stroing information in application state
    lock (this)
    {
    Application["NickName"] = "Merithub";

    }
    //Retrieving value from application state
    lock (this)
    {
    string str = Application["NickName"].ToString();

    }




    Profile Properties:
    ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database.

    In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

    To use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism such as an XML file, or even to a web service.

    Because data that is placed in profile properties is not stored in application memory, it is preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing data. Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web garden.



    So, in the above illustrations, we understood the practical concepts of using different State Management techniques in ASP.Net techonology.



    Register or Login to Post Your Opinion/Answer