Showing posts with label ViewState. Show all posts
Showing posts with label ViewState. Show all posts

Monday, April 29, 2013

how to use ViewState In Asp.Net


What is view state

View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
View state is the method that the ASP.NET page framework uses by default to preserve page and control values between round trips. When the HTML for the page is rendered, the current state of the page and values that need to be retained during postback are serialized into base64-encoded strings and output in the view state hidden field or fields. You can change the
default behavior and store view state in another location such as a SQL Server database by implementing a custom PageStatePersister class to store page data. For an example of storing page state on a stream rather than in a hidden page field,
see the example for the PageStatePersister class.
Example: If you want to add one variable in View State,

ViewState["Var"]=Count;

For Retrieving information from View State:   

string Test=ViewState["TestVal"];

Advantages of view state

This are the main advantage of using View State:
•           Easy to implement
•           No server resources are required
•           Enhanced security features ,like it can be encoded and compressed.

Disadvantages of view state

This are the main disadvantages of using View State:
•           It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
•           Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
•           It does not have any support on mobile devices.

When we should use view state

A few point you should remember when you select view state for maintain your page state.
•           Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
•           Try to avoid storing secure data in view state

When we should avoid view state

You won't need view state for a control for following cases,
•           The control never change
•           The control is repopulated on every postback
•           The control is an input control and it changes only of user actions.

Where is view state stored

View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology.
It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.
Suppose you have written a simple code , to store a value of control:

ViewState["Value"] = MyControl.Text;

Now, Run you application, In Browser, RighClick > View Source , You will get the following section of code

<input type=”hidden” id=”_viewstate” name=”viewstate” value=”dsfefgbgigguwgbdbwqwugyucffvufebcbenhgbc”/>

Now , look at the value. looks likes a encrypted string, This is Base64 Encoded string, this is not a encoded string. So it can easily be decoded. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read. Any body can decode that string and read the original value. so be careful about that. There is a security lack of view state.

How to store object in view state

We can store an object easily as we can store string or integer type variable. But what we need? we need to convert it into stream of byte. because as I already said , view state store information in hidden filed in the page. So we need to use Serialization. If object which we are trying to store in view state ,are not serializable , then we will get a error message .
Just take as example,

//Create a simple class and make it as Serializable
[Serializable]
public class student
{
    public int Roll;
    public string Name;
    public void AddStudent(int intRoll,int strName)
      {
        this.Roll=intRoll;
        this.Name=strName;
           }
}

Now we will try to store object of "Student" Class in a view state.

//Store Student Class in View State
student _objStudent = new student();
_objStudent.AddStudent(2, "Abhijit");
ViewState["StudentObject"] = _objStudent;

//Retrieve Student information view state
 student _objStudent;
_objStudent = (student)ViewState["StudentObject"];

How to trace your view state information

If you want to trace your view state information, by just enable "Trace" option of Page Directive

<% Language=”C#” AutoEventWireup=”true”  Trace=”ture” %>

Now Run your web application, You can view the details of View State Size along with control ID inControl Tree Section. Don't worry about "Render Size Byte" , this only the size of rendered control.
Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turn off view state for a single control , set EnableViewState Property of that control to false. e.g:

TextBox1.EnableViewState =false;

To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.

<% Language=”C#” enbleviewsate=’’false”

Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information,
ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.For enabling the same, you have to use the same property just set them as True as for example, for a single control we can enabled view state in following way,

TextBox1.EnableViewState =true;

and for a page level, 
<% Language=”C#” enbleviewsate=’’ture”

How to make view state secure

As I already discuss View state information is stored in a hidden filed in a form of Base64 EncodingString, and it looks like:

<input type=”hidden” id=”_viewstate” name=”viewstate” value=”dsfefgbgigguwgbdbwqwugyucffvufebcbenhgbc”/>

Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
•           First, you can make sure that the view state information is tamper-proof by using "hash code". You can do this by adding "EnableViewStateMAC=true" with your page directive. MAC Stands for "Message Authentication Code"

<% Language=”C#” enbleviewsate=’’ture” enbleviewsate mac=”true”

A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
•           Second option is to set ViewStateEncryptionMode="Always" with your page directives, which will encrypt the view
state data. You can add this in following way

<% Language=”C#” enbleviewsate=’’ture”  ViewStateEncrypsationMode=”Always”

It ViewStateEncryptionMode has three different options to set:
•           Always
•           Auto
•           Never
 Always, mean encrypt the view state always, Never means, Never encrypt the view state data and AutoSays , encrypt
if any control request specially for encryption. For auto , control must callPage.RegisterRequiresViewStateEncryption() method for request encryption.

•           we can set the Setting for "EnableViewStateMAC" and ViewStateEncryptionMode" in web.configalso.

<System>
<page EnbleViewtateMac=’’true’’ ViewstateEncrypationMode=’’Always’’>
</page></System>

Note : Try to avoid View State Encryption if not necessary , because it cause the performance issue.

Thursday, October 11, 2012

How to Binding a Calendar Control in a Text box ASP.NET

How to Binding a Calendar Control in a Text box ASP.NET

First u create .Aspx or view page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Calendar.aspx.cs" Inherits="Calendar" %>

<!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 id="Head1" runat="server">
    <title>Eco Friend & Co. - Time Tracker - Select Date</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta name="generator" content="Microsoft Visual Studio, see http://msdn.microsoft.com/vstudio/" />
    <meta name="Description" content="Select a date" />
    <meta name="copyright" content="Copyright (c) 2011 Eco Friend & Company. All rights reserved." />
</head>
<body>
    <form id="form1" runat="server">
        <div id="calbg">
            <div id="calcontent">
                <fieldset>
                    <legend>SeleSelect a date: </legend>
                    <asp:DropDownList ID="MonthSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="MonthSelect_SelectedIndexChanged"></asp:DropDownList>
                    &nbsp;
                    <asp:DropDownList ID="YearSelect" runat="server" AutoPostBack="True" OnSelectedIndexChanged="YearSelect_SelectedIndexChanged">
                    </asp:DropDownList>
                    <asp:Calendar ID="Cal" runat="server" ShowTitle="False" ShowNextPrevMonth="False"
                         DayNameFormat="FirstTwoLetters" FirstDayOfWeek="Sunday" OnSelectionChanged="Cal_SelectionChanged">
                        <TodayDayStyle Font-Bold="True" ForeColor="White" BackColor="#990000"></TodayDayStyle>
                        <DayStyle BorderWidth="2px" ForeColor="#666666" BorderStyle="Solid" BorderColor="White"
                            BackColor="#EAEAEA"></DayStyle>
                        <DayHeaderStyle ForeColor="#649CBA"></DayHeaderStyle>
                        <SelectedDayStyle Font-Bold="True" ForeColor="#333333" BackColor="#FAAD50"></SelectedDayStyle>
                        <WeekendDayStyle ForeColor="White" BackColor="#BBBBBB"></WeekendDayStyle>
                        <OtherMonthDayStyle ForeColor="#666666" BackColor="White"></OtherMonthDayStyle>
                    </asp:Calendar>
                    <br />
                    <table>
                        <tr>
                            <td valign="middle" colspan="2">
                                Date Selected:
                                <asp:Label ID="lblDate" runat="server">
                                </asp:Label>
                                <input id="datechosen" type="hidden" name="datechosen" runat="server">
                            </td>
                        </tr>
                        <tr>
                            <td valign="middle">
                                <asp:Button ID="OKButton" runat="server" Text="OK" />
                             </td>
                            <td valign="middle">
                                <asp:Button ID="CancelButton" runat="server" Text="Cancel" OnClientClick="javascript:self.close()"/>
                            </td>
                        </tr>
                    </table>
                </fieldset>
            </div>
        </div>
    </form>
</body>
</html>

then Aspx.cs design 


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Calendar : System.Web.UI.Page
{
    public string controlToEdit;
    public string isPostBack;

    public Calendar()
    {
        LoadComplete += new EventHandler(Page_LoadComplete);
    }
    void Page_Load(object sender, EventArgs e)
    {
     
        if (!Page.IsPostBack)
        {
            controlToEdit = Request.QueryString["controlID"];
            Session.Add("controlToEdit", controlToEdit);
            isPostBack = Request.QueryString["isPostBack"];
            Session.Add("isPostBack", isPostBack);


            // Cast first day of the week from web.config file.  Set it to the calendar
            //Cal.FirstDayOfWeek = (System.Web.UI.WebControls.FirstDayOfWeek)Convert.ToInt32(ConfigurationManager.AppSettings["FirstDayOfWeek"]);

            // Select the Correct date for Calendar from query string
            // If fails, pick the current date on Calendar
            try
            {
                Cal.SelectedDate = Cal.VisibleDate = Convert.ToDateTime(lblDate.Text);
            }
            catch
            {
                Cal.SelectedDate = Cal.VisibleDate = DateTime.Today;
            }
            // Fills in correct values for the dropdown menus
            FillCalendarChoices();
            SelectCorrectValues();
        }
        else
        {
            if (Session["controlToEdit"] != null)
                controlToEdit = (string)Session["controlToEdit"];
            if (Session["isPostBack"] != null)
                isPostBack = (string)Session["isPostBack"];
        }
    }
    void Page_LoadComplete(object sender, System.EventArgs e)
    {
        OKButton.OnClientClick = "javascript:window.opener.SetControlValue('" + this.controlToEdit + "','" + lblDate.Text + "','" + this.isPostBack + "');";
    }

    protected void FillCalendarChoices()
    {
        DateTime thisdate = (DateTime.Now).AddYears(5);

        // Fills in month values
        for (int x = 0; x < 12; x++)
        {
            // Loops through 12 months of the year and fills in each month value
            ListItem li = new ListItem(thisdate.ToString("MMMM"), thisdate.Month.ToString());
            MonthSelect.Items.Add(li);
            //to add next next month name to the monthselect drop downlist control like aug then sept and so on....
            thisdate = thisdate.AddMonths(1);
        }

        // Fills in year values and change y value to other years if necessary
        for (int y = 2000; y <= thisdate.Year; y++)
        {
            YearSelect.Items.Add(y.ToString());
        }
     
    }

    protected void SelectCorrectValues()
    {
        lblDate.Text = Cal.SelectedDate.ToShortDateString();
        datechosen.Value = lblDate.Text;
        MonthSelect.SelectedIndex = MonthSelect.Items.IndexOf(MonthSelect.Items.FindByValue(Cal.SelectedDate.Month.ToString()));
        YearSelect.SelectedIndex = YearSelect.Items.IndexOf(YearSelect.Items.FindByValue(Cal.SelectedDate.Year.ToString()));
    }

    protected void Cal_SelectionChanged(object sender, System.EventArgs e)
    {
        Cal.VisibleDate = Cal.SelectedDate;
        SelectCorrectValues();
    }

    protected void MonthSelect_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Cal.SelectedDate = Cal.VisibleDate
            = new DateTime(Convert.ToInt32(YearSelect.SelectedItem.Value),
                           Convert.ToInt32(MonthSelect.SelectedItem.Value), 1); ;
        SelectCorrectValues();
    }

    protected void YearSelect_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Cal.SelectedDate = Cal.VisibleDate
            = new DateTime(Convert.ToInt32(YearSelect.SelectedItem.Value),
                           Convert.ToInt32(MonthSelect.SelectedItem.Value), 1); ;
        SelectCorrectValues();
     
    }
 
}


and call and other page
create only aspx page not need and code of it.

<%@ 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>
    <script type="text/javascript" src="javascript/script.js">
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
         <a href="javascript:OpenPopupPage('Calendar.aspx','<%= txtDate.ClientID %>','<%= Page.IsPostBack %>');">
                    <img src="images/icon-calendar.gif" /></a>
    </div>
    </form>
</body>
</html>


Wednesday, October 3, 2012

Hacking ViewState


Articles that talk about viewstate always say, it is less secure and not good for keeping secure information. Let us see how a viewstate value can be hacked.
Data kept in Viewstate is serialized using LosFormater, a less known class used for serialization. LosFormatteris helpful to serialize simple types and it produces ASCII string representation of the object graph. The following code shows using LosFormatter.
 [Serializable]
  class Customer
  {
       public Customer(int age,string name) {
           this.Age = age;
           this.Name = name;
       }
       public int Age { get; set; }
       public string Name { get; set; }
  }
  
  string Serialize() {
        
     // Creating customer object
     Customer customer = new Customer(25,"Navaneeth");

     // formatting
     LosFormatter formatter = new LosFormatter();
     using (StringWriter output = new StringWriter()) {
        formatter.Serialize(output, customer);
        return output.ToString();
     }
  }
The above code serializes the object graph and produces an ASCII string which can be transmitted over HTTP.
The following code shows decrypting viewstate values.

This gives you a clear explanation of why secured data should not be kept on viewstate.