31 January 2014

Asp.Net State Management

State management means to maintaining  state of a control, web page, object/data, and user in the application explicitly because all ASP.net Web are stateless, i.e., by default, for each page posted to the server, the state of controls is lost. Nowadays all web apps demand a high level of state management from control to application level.

The state management  can be at done at Client side  and server side

Client Side State Management:

       Storing page information using client-side options doesn't use server resources. These options typically have minimal security but fast server performance because the demand on server resources is modest

·         View state
·         Control state
·         Hidden fields
·         Cookies
·         Query strings

Server Side State Management:

      Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management

·         Application state
·         Session state
·         Profile properties
·         Database support

30 January 2014

Asp.net Client State Management - Cookies

      Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately.

      Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected.

      Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a page.

      For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed.

      Cookies are used for many purposes; all relating to helping the Web site remember users.

      For example, a site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.


Types of Cookies

There two type of cookies in ASP.NET

    1) Persistent cookies
    2) Non-persistent cookies

 Persistent cookies:
     Cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired.
Example to Create  Persistent cookies:
    public void SetPersistentCookies(string name, string value)
   {
     HttpCookie cookie = new HttpCookie(name);

    cookie.Value = value;
     cookie.Expires = Convert.ToDateTime(“12/12/2008″);
     Response.Cookies.Add(cookie);
   }
Non-persistent cookies:

    Cookies are saved only while your web browser is running.They can be used by a web server only until you close your browser.They are not saved on your disk.
    
Example to Create  Persistent cookies:

     public void SetNonPersistentCookies(string name, string value)
       {
           HttpCookie cookie = new HttpCookie(name);
           cookie.Value = value;
           Response.Cookies.Add(cookie);
      }

Cookies Implementation

Creating/Writing Cookies

There are many ways to create cookies; I am going to outline some of them below:

Way 1 (by using HttpCookie class)
 W//First way
HttpCookie StudentCookies = new HttpCookie("StudentCookies");
StudentCookies.Value = TextBox1.Text;
StudentCookies.Expires = DateTime.Now.AddHours (1);
Response.Cookies.Add (StudentCookies);

Way 2 (by using Response directly)
//Second Way
Response. Cookies["Student Cookies"].Value = TextBox1.Text;
Response.Cookies ["Student Cookies"].Expires = DateTime.Now.AddDays(1);

Way 3 (multiple values in same cookie)
//Writing Multiple values in single cookie
Response.Cookies ["Student Cookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Omkar";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Varun";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);

Reading/Getting Cookies

In the above code, I have used many ways to write or create cookies so I need to write here using all the above ways separately.

For Way 1
string roll = Request.Cookies["StudentCookies"].Value; //For First Way

For Way 2
string roll = Request.Cookies["StudentCookies"].Value;  //For Second Way

For Way 3

//For Multiple values in single cookie
String roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"];
roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"];

Cookie Limitations

          Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. The user ID can then be used to identify the user and read user information from a database or other data store

          Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.A cookie limitation that you might encounter is that users can set their browser to refuse cookies. 

        However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is session state, but session state depends on cookies

Asp.net Client State Management - Query String

       For passing variables content between pages ASP.NET gives us several choices. One choice is using Query String property of Request Object


Implementing Query String:

Private void btnSubmit_Click (object sender, System.EventArgs e)
{
Response.Redirect ("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
}

Our first code part builds a query string for your application and sends contents of your textboxes to second page. Now how to retrieve these values from second page. Put this code to second page 

Page_load:

Private void Page_Load(object sender, System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString ["Name"];
this.txtBox2.Text = Request.QueryString ["LastName"];
}

Request.QueryString is used to retrieve these values

private void Page_Load(object sender, System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString[0];
this.txtBox2.Text = Request.QueryString[1];
}

Advantages of this approach:
  • It is very easy. 
Disadvantages of this approach:
  •  Query String have a max length, If you have to send a lot information this approach does not work.
  •   Query String is visible in your address part of your browser so you should not use it with sensitive information.
  •   Query String cannot be used to send & and space characters.


Asp.net Client State Management - Hidden Fields

     The Hidden Field control is used to store a value that needs to be persisted across posts to the server. It is rendered as an <input type= "hidden"/> element.
Normally view state, session state, and cookies are used to maintain the state of a Web Forms page. However, if these methods are disabled or are not available, you can use the Hidden Field control to store state values.

         To specify the value for a Hidden Field control, use the Value property. You can provide a routine that gets called every time the value of the Hidden Field control changes between posts to the server by creating an event handler for the Value Changed event.

Implementation of Hidden Field:

DEMO : HiddenField

            <asp:HiddenField ID="HiddenField1" runat="Server" Value="This is the Value of Hidden field" />
            <asp:Button ID="Button1" runat="Server" OnClick="ChangeLabelText" Text="Change Label Text to Hiidden Field Value" />                                        
                   
            // CODE BEHIND
            // Fires when Button is clicked
            protected void ChangeLabelText(object sender, EventArgs e)
            {
                Label1.Text = hiddeFieldValue.Value;
            }
                   


Advantages:

a. Easy to implement
b. Hidden fields are supported by all browsers
c. Enables faster access of information because data is stored on client side

Disadvantages:

a. Not secure because the data is stored on Client side.
b. Decreases page performance if too many hidden fields
c. Only support single value.

29 January 2014

Client Side State Management -View State

The View State allows ASP.NET to repopulate form fields on each post back to the server, making sure that a form is not automatically cleared when the user hits the submit button. All this happens automatically, unless you turn it off, but you can actually use the View State for your own purposes as well.

  Please keep in mind though, that while cookies and sessions can be accessed from all your pages on your website, View State values are not carried between pages. 


  Here is a simple example of using the View State to carry values between post backs:
<%@ 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>ViewState</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox runat="server" id="NameField" />
        <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />
        <asp:Button runat="server" id="RefreshPage" text="Just submit" />
        <br /><br />
        Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />
    </form> 
</body>
</html>
And the CodeBehind:
using System;
using System.Data;
using System.Web;

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;
    }
}
Try running the project, enter your name in the textbox and press the first button. The name will be saved in the ViewState and set to the Label as well. No magic here at all. Now press the second button. This one does nothing at all actually, it just posts back to the server

 As you will notice, the NameLabel still contains the name, but so does the textbox. The first thing is because of us, while the textbox is maintained by ASP.NET it self. Try deleting the value and pressing the second button again. You will see that the textbox is now cleared, but our name label keeps the name, because the value we saved to the ViewState is still there! 


ViewState is pretty good for storing simple values for use in the form

28 January 2014

Asp.net Client Side State Management-Control State

    Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips.

    The View State property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.

   The Control State property allows you to persist property information that is specific to a control and cannot be turned off like the View State property.

Control state implementation:

      First, override the OnInit method of the control and add the call for the Page.RegisterRequiresControlState method with the instance of the control to register. Then, override the  LoadControlState and SaveControlState in order to save the required state information.

public class ControlStateWebControl : Control
{
   #region Members 
      private string _strStateToSave;
  #endregion
  #region Methods
  protected override void OnInit(EventArgs e)
   {
     Page.RegisterRequiresControlState(this);
     base.OnInit(e);
    }
   protected override object SaveControlState()
   {
    return _strStateToSave;
   }
  protected override void LoadControlState(object state)
  {
     if (state != null)
     {
       strStateToSave = state.ToString();
     }
  }
#endregion
 }

You need to remember only one thing – the control state takes away the choice to disable View State. You should only use it whenever you have to keep state information that without it your control won’t work.