Showing posts with label State Management. Show all posts
Showing posts with label State Management. Show all posts

July 7, 2009

Pass values using session

In this example, I will create a page, add Session variables to the page and then retrieve and update the Session variables. Session variables in asp.net store objects. That is we can pass in an Integer, Double or any other object to Session. Session provide a better way to temporarily store data for a client compared to hidden fields, viewstate or query string since session can span over multiple pages.

In the page, I only have a Button control to perform postback to the page itself.

    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </form>


In Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session.IsNewSession)//check if new session
            {
                Response.Write("new session");
                SetSession();//set session variables
            }
            if (IsPostBack)
            {
                Response.Write("my name is " +Session["myName"].ToString());
                Response.Write("<br/>counter is " + Session["counter"].ToString());

                if ((int)(Session["counter"]) == 5)
                {
                    Session.Abandon();//clear the session
                }
                else
                {
                    Session["counter"] = ((int)Session["counter"]) +1;//update session variable counter
                }
            }
        }


I am at first checking if it is a new session or not. If it is, writing a message to the page and also setting the session variables using SetSession() method.

Then, I am checking if the page is a postback or not. If it is, I am writing values of the Session variables. Then, I am checking if the value of Session variable counter (of type integer) has reached the value of 5 or not. If so, then clearing the Session using Session.Abandon() method. Otherwise, increasing the value of the Session variable counter.

The code for SetSession() method is below.

private void SetSession()
        {
            Session["myName"] = "Shahed";//add string to session
            Session["counter"] = 0;//add integer to session                   
        }


As you can see, I am adding to Session variables "myName" and "counter". The values of the variable are defined.

Here is the code of the Button click handler.

protected void Button1_Click(object sender, EventArgs e)
        {
            //method to perform postback
        }


May 30, 2009

Read n Write Cookie

A cookie can be used to store user data on the client side. Data may contain state information and user preferences. The cookie is stored as a text file on the client's system if the cookie is persistent or in browser's session's memory if the cookie is temporary. Using cookies is a handy way to store data on the client but the user, at the same time, can delete a cookie or disable cookie from the browser settings. A cookie is a better way to hold data, compared to hidden fields and query string, since the data can be stored on the client even if the client starts viewing a different page.

In Asp.Net application, a cookie can be created by adding a value to the Response.Cookies.HttpCookieCollection. Once a cookie is added, the value of the cookie can be read by using the Request.Cookies property.

In the following example, a cookie is added in the Page_Load method by adding a value to the Respose.Cookies collection and the value is read on a button click.

protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cookies["name"].Value = "shahed"; //value of cookie "name"
        Response.Cookies["name"].Domain = "localhost"; // domain for the cookie
        Response.Cookies["name"].Expires = DateTime.Now.AddDays(1);//expire date
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["name"] != null)//check if cookie exist
        {
            Response.Write("Cookie name:\t" + Request.Cookies["name"].Name + "<br/>");//name of cookie
            Response.Write("Cookie Value:\t " + Request.Cookies["name"].Value + "<br/>");//value of cookie
            Response.Write("Cookie Expires:\t" + Request.Cookies["name"].Expires + "<br/>");//expiry date of cookie
            Response.Write("Cookie Domain:\t" + Request.Cookies["name"].Domain + "<br/>");//domain of cookie
        }       
    }


In Page_Load method, a cookie with name "name" is added. The expiry date is set to be one day and it is scoped for "localhost" domain. There is a button on the main which when clicked, checks if the cookie exists, and if so writes the properties of the cookie.

May 14, 2009

Store data in HiddenField

Data can be stored in a page using asp.net HiddenField control. The HiddenField does not show any output to the page but can be viewed from the page source of the page. Also, one of the limitations of the HiddenField is that only string data can be stored in the page.

The HiddenField control is declared as follows.

<asp:HiddenField ID="HiddenField1" runat="server" />

String values can be added to the HiddenField using the value attribute.

<asp:HiddenField ID="HiddenField1" runat="server" Value="some data" />

The page source shows how the HiddenField is generated.

<input type="hidden" name="HiddenField1" id="HiddenField1" value="some data" />
The HiddenField control can be accessed from code-behind of the page using it's ID attribute like any other asp.net control. To assign values to thecontrol, use the following code,

HiddenField1.Value = "some new data";

To find the value of the control, use the following code,

string data = HiddenField1.Value;

May 7, 2009

Pass Values Using Query Strings

Query string is a common way to transfer values from one page to another or to store it in the page URL. The query string values are stored in the form of strings and are appended to the URL. A typical query string will http://shahed-kazi.blogspot.com/index.html?country=australia .

The browser understands the filename to be index.html and anything characters after the "?" as the query string. In this example, there is one query string with key country and value australia. Multiple values can be added to the URL like http://shahed-kazi.blogspot.com/index.html?firstname=shahed&city=sydney .
Here, there are 2 query strings country with value australia and city with value sydney. The query string value are separated with a "&".

One of the disadvantage of using query strings is that the values and the variable names are visible to the user. Also, a user can easily change the value of the variables and construct a different url. Therefore, sensitive information cannot be passed on page to another using this method.

Another disadvantage is that there is a limitation on the number of characters in a URL. The limit is 2083 characters. Therefore, large amount of data cannot be passed using query strings technique.

Sensitive information should not be stored in the query strings. For example, if we run a call in the database based on the data on the query string - a user can easily modify the URL and run a query that will hang the site. Also, if we are updating the data source based on a query string - a user modifying the query string may result in updating the data source with invalid data. That's
why it is important to validate the data.

Now, I will create an example page with 2 TextBox controls, create a URL with the textbox values and display the values in a second page.

First Page:

<form id="form1" runat="server">

<div>

First Name:<asp:TextBox ID="FirstNameTextBox" runat="server"></asp:TextBox><br />

Last Name: <asp:TextBox ID="LastNameTextBox" runat="server"></asp:TextBox><br />

<asp:ButtonID="Button1" runat="server" Text="Continue" onclick="Button1_Click" />

</div>

</form>

In code-behind, Button1 onclick event,

string firstname = FirstNameTextBox.Text;

string lastname = LastNameTextBox.Text;

Response.Redirect("page2.aspx?firstname=" + firstname + "&lastname=" + lastname);

page2.aspx looks like below,

<form id="form1" runat="server">

<div>

First Name : <asp:Label ID="FirstNameLabel" runat="server" Text=""></asp:Label><br
/>

Last Name: <asp:Label ID="LastNameLabel" runat="server" Text=""></asp:Label>

</div>

</form>

In this page, the label controls will be populated with values from the query string.

In Page_Load method in code-behind page,

protected void Page_Load(object sender, EventArgs e)

{

FirstNameLabel.Text = Server.HtmlEncode(Request.QueryString["firstname"]);

LastNameLabel.Text = Server.HtmlEncode(Request.QueryString["lastname"]);

}

The page will now show the values in the Label controls as in the query strings.

Also, note that I have encoded the string using Server.HtmlEncode. This method will automatically convert all the html characters into not html characters.

To use special characters like "&" in the query string, use the UrlEncode method of the Server class. For example, use the url like

string url = "http://shahed-kazi.blogspot.com/2009/05/pass-values-using-query-strings.html?id=" + Server.UrlEncode("hello & world");

When viewed in the browser, the URL will be automatically converted to http://shahed-kazi.blogspot.com/2009/05/pass-values-using-query-strings.html?id=hello+%26+world

May 6, 2009

Store Values in ViewState

ASP.NET has a built in mechanism for storing values of controls known as ViewState. The ViewState property provides a key-value object for storing values between multiple requests of the same page. ASP.NET saves the state of the page and controls as a hashed string in the page as a hidden variable, ViewState.

When a page is run, the ViewState property can be seen from the source code of the page.

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 
value
="/wEWAgL3ku32BwLs0bLrBqcPjj4o1kvxlT2D91sy/YSkJDTh" />

Custom data can be stored in the ViewState property. If a value has to be stored for a user in page, ViewState is an easy way to achieve this. Please note that ViewState property is only accessible from the page only. If the user visits a different page, the ViewState property will be lost.

Let's create a string containing a date and store it in the ViewState.

string date = DateTime.Now.ToString();

ViewState["date"] = date;

An alternative way of achieving this would be to

ViewState.Add("date", date);

The values stored in the ViewState can also be retrieved as follows.

if ((string)ViewState["date"] != null)

{

string date2 = (string)ViewState["date"];

}

Here, I am checking there a ViewState property named "date". If so, assign the value to string date2.

In ViewState, objects can also be stored/ For example, we can store a DateTime object like below

ViewState.Add("date3", DateTime.Now);

and retrieve the object like

DateTime date3 = (DateTime)ViewState["date3"];


Reference: Shahed Kazi at AspNetify.com