Contents

Monday, 4 July 2016


Cookies

Cookies are usually used to store user identity or we can say user data. Cookies are small text files which is created by the client browser and are stored in the hard drive. 

When a user makes an initial request for a page the server creates a cookie for that user and stores it in the hard drive and then again the same user tries to access a page in the same web site, the cookie stored is matched and then it grants the access.  Cookies can be send from one page to another after creation. It is not possible in the case of View State variables as it works for a single page.

There are two types of cookies:

  • Persistent Cookie  
  • Non-Persistent Cookie

Persistent Cookie

When we set an expiry time to a cookie it is known as Persistent Cookie. It remains stored till the time expires.

Example

Let us take the following example:

Design


 This application will save the details entered in the textbox into the cookie when we will click the save button. When we will click display button it displays the saved cookie in the two labels below the button.

Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class WebForm2 : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)  //save button
        {
            //Creating cookie and saving the value.
            HttpCookie cookie = new HttpCookie("User Details");
            cookie["Name"] = TextBox1.Text;
            cookie["Blog Name"] = TextBox2.Text;
            //Setting the expire time to 30 days
            cookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(cookie);
        }

        protected void Button2_Click(object sender, EventArgs e)   //display button
        {
            //Cookie request.
            HttpCookie cookie = Request.Cookies["User Details"];
            if (cookie != null)
            {
                Label1.Text = cookie["Name"];
                Label2.Text = cookie["Blog Name"];
            }
        }
    }
}

Output




This is the output after the whole process. Now if you close the browser and then open the page again and display without saving the new cookie, it will display the retained value in the cookie that we saved earlier. This is because we are using the persistent cookie and we gave the expiry time of 30 days. So it will be retained for that period of time.

Non-Persistent Cookie

Non-Persistent Cookies are not saved permanently in the hard drive. It is retain as long as the user is not closing the browser. When the browser is closed all non-persistent cookies are cleared automatically.

Design

Same as above example



Code Behind


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class WebForm2 : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)  //save button
        {
            //Creating cookie and saving the value.
            HttpCookie cookie = new HttpCookie("User Details");
            cookie["Name"] = TextBox1.Text;               //Note that expiry time is not specified
            cookie["Blog Name"] = TextBox2.Text;
            Response.Cookies.Add(cookie);
        }

        protected void Button2_Click(object sender, EventArgs e)   //display button
        {
            //Cookie request.
            HttpCookie cookie = Request.Cookies["User Details"];
            if (cookie != null)
            {
                Label1.Text = cookie["Name"];
                Label2.Text = cookie["Blog Name"];
            }
        }
    }
}

Output



Output is also same as that of persistent cookies.But when we close the browser after this all the cookies are cleared. So when we load the page again in the browser and click display without entering the value in the textbox the label will remain empty as cookies are not retained after the browser is closed.


Friday, 1 July 2016


View State

View State is a Client Side management technique which is used to hold values even after the postback. It is mainly used for storing temporary data like small calculations, final results etc. It is a page level state management which means it holds value only for the current page where you have added the view state code. We cannot used this technique to store values across webpages.

View State values are stored in the generated HTML hidden field. View State is enabled by default is every ASP.NET page.

Lets take the same example which we have used in "Chapter 7: Why HTTP protocol is called stateless protocol?"

Design



 Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace httpstateless
{
    public partial class ViewState : System.Web.UI.Page    {
        string name, blog;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            name = TextBox1.Text;
            blog = TextBox2.Text;
            TextBox1.Text = "";
            TextBox2.Text = "";
            ViewState["name"] = name;
            ViewState["blog"] = blog;
           
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = Convert.ToString(ViewState["name"]);
            TextBox2.Text = Convert.ToString(ViewState["blog"]);
        }
    }
}

Output

Before clicking save:


After Clicking save:


After Restore:


If you right click the page and then select view page source you can find an input field which has type="hidden". This is automatically created. All viewstate values are stored here in encrypted format.

Points to remember

  • View State is a page level state management technique.
  • It can hold any type of data.
  • It is stored in the hidden field.
  • It is mainly used to store temporary data.
  • It is not used to store large data.


Managing State

In previous post i told you about the stateless nature of HTTP protocol. So in order to store a value we need a mechanism which will hold a value even after a button click or a page request.That mechanism should also allow us to access these values later. We have different types of state management techniques these are:

 Client Side Technique

  • View State
  • Cookies
  • Query String
  • Hidden Field
  • Control State 

Server Side Technique

  • Session State
  • Application State
These all will be explained in detail in upcoming post.


Tuesday, 28 June 2016


Why HTTP is called stateless protocol?

Http is called stateless protocol because each user request  for a page is served without storing the previous request. All the request are treated differently.  So after rendering it has no clue of the previous request. It doesn't maintain any state or session by its own.

We may see this with a help of an example.

In our example i will input my name and blog name in two textboxes. After that when i click save button i will store these in two variables and when the restore button is pressed it should restore the value from these variables. Lets see what happens.

Design



Code Behind



Output


After clicking save button:



After clicking restore button:


Surprise.....!! After clicking restore button then also the textboxs are blank. This is because the http protocols are stateless. So the variables used in the program(i.e.  name and blog) cannot retain their values after button click.

So to solve this we have many techniques which will be discussed in the upcoming post.


What is isPostback?

Postback is a way to send information from the client  to the server and after processing it back to the client. So sometimes in our project we need to check whether the page loading is done by the user action(for eg. Button  click) or it is an initial loading of the page. To check this we have a property of the page called isPostback property.

It is mainly used in pageloads to check whether the page loading is done by the initial request or not. 

Let  us look one example to make this more clear.

For example, if we want to  display a name as "guest" in a label on the initial loading of the page and then take a username from the user and display it in that label.

To do this we need to keep in mind that we need the name "guest" only when the page is first loaded and after the button  click we need to show the name of the user that is entered in the textbox.

Design




Code Behind


Output

On initial load:



After entering my name and clicking the display button:


Thursday, 23 June 2016


ASP.NET Page Life Cycle Events

In previous post i told you about Button_Click() event. This event was called when we click a button. In the similar way, ASP.NET page has life cycle events and methods which are called when the page is executed. When a page is requested by the user it will first load it into the server memory and then process it and displays it into the browser. When we close the browser it unloads the content from the memory. All these steps events are called to perform each take. This happens automatically. We can even override these events for our application.

Page Life Cycle Events

  • PreInit
It is the first event in the life cycle. It checks the IsPostBack property i.e the page is loaded for the first time or not. This event also sets the master page if it is used in the application(Details of Master page will be covered later).

        protected void Page_PreInit(object sender, EventArgs e)
        {

        }

  • Init
 This event initialize all the controls and its control properties.

         protected void Page_Init(object sender, EventArgs e)
        {

        }

  • InitComplete
It is raised when the initialization is complete. Here viewstate variables are loaded.

        protected void Page_InitComplete(object sender, EventArgs e)
        {

        }

  • PreLoad
 In this event postback data and viewstate are loaded.

        protected void Page_PreLoad(object sender, EventArgs e)
        {

        }

  • Load
In this event the page is loaded. We can add code in this event if we want something to be done when the page is loaded. For example, if we want to check the IsPostback() property we can write it here.

        protected void Page_Load(object sender, EventArgs e)
        {

        }

  •  Control Events
 This event handles the postback events like button click, TextBox control's TextChanged events.

        protected void Button1_Click(object sender, EventArgs e)
        {

        }


  • LoadComplete
 This event show the end of page loading.

        protected void Page_LoadComplete(object sender, EventArgs e)
        {

        }

  • PreRender
This event is called just before the output in rendered. 

        protected void Page_PreRender(object sender, EventArgs e)
        {

        }

  • PreRenderComplete
It ensures the completion of PreRender event.

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {

        }
  • SaveStateComplete
 All control's state are saved. Viewstate information is also saved.

        protected void Page_SaveStateComplete(object sender, EventArgs e)
        {

        }

  • UnLoad
This event is the last event called to unload all the controls recursively and at last the page itself.

        protected void Page_UnLoad(object sender, EventArgs e)
        {

        }
Now let us code these things.
Create a page having one label and a button for button click event.
Design
 
CodeBehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace page_life_cycle_event
{
    public partial class WebForm1 : System.Web.UI.Page
    {
       
        protected void Page_PreInit(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "PreInit";
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "Init";
        }
        protected void Page_InitComplete(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "InitComplete";
        }
        protected void Page_PreLoad(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "PreLoad";
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "Load";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "Button Click";
        }
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "LoadComplete";
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "PreRender";
        }
        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "PreRenderComplete";
        }
        protected void Page_SaveStateComplete(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "SaveStateComplete";
        }
        protected void Page_UnLoad(object sender, EventArgs e)
        {
            Label1.Text = Label1.Text + "</br>" + "Unload";
        }
    }
}

Now just run the application.

When page loads and the output will be:



After Button Click:



Thursday, 16 June 2016


Creating a simple Web Application

Now let us look at a simple example in which we will make three TextBoxs(textbox are use to take input from user) and a button(buttons are used to submit a page to the server). We will input 2 number in the first two TextBoxs and the last textbox will contain the sum of two numbers when we will click on the button.

Now let us begin by designing the page.

  • So first we need to open an asp.net web application which i already explain you how to do it in my chapter 1 please refer it if needed. After that a default.aspx page display. It is the default page which is loaded when you open a new web application. This page already contains some default styling. Follow picture shows the design and code view of default.aspx.
       DESIGN VIEW


        CODE VIEW


  • If you need a blank web page/form then you can simply add it by going to the solution explorer in that you can find the web application name(here it is Web Application7) right click on that then click on add then new item as show below.
 


  • A new dialog box opens up where you can find Web Form. Just click on that give a name to the webpage below(here i am keeping WebForm1.aspx and the click on add.
 
  •  A new page will display in the middle of the screen. And if you click on the design view button you can see that it is a blank page which has nothing on it. 
        DESIGN VIEW

        
  • Now in the design view type anything like "First Number" after that simply drag and drop a textbox from the toolbox present on your left side of the screen. Repeat it for the "Second Number" after that add a button for the page submission(If Toolbox is not present then you can add it by going to View -> Toolbox or simple pressing Ctrl+Alt+X). After doing that the design would look like this.

  •   Now in order to manipulate any property of the controls we can do it in the property window. For example if we need to change the name of the Button to "Calculate", first click on the button which need the change after that go to property window which is on the right side. There you can find a field named Text, there you can change the name for Button to Calculate.
  • Now our design is complete. Lets move onto the code behind part where we will do a little bit of coding. This is needed because if we will run this page without coding the page will not do the task which we want on button click. The page will display as it is as we made in the design view. It will also take values in textbox but the button click event will not work and also the result will not be displayed in the third textbox. 
  • Now in order to move to the code behind double click on the button in the design view. The code behind will look like this.
  • You can see the code behind named WebForm.aspx.cs. This is where we write the C# code. In this page you may see a function like this.
           protected void Button1_Click(object sender, EventArgs e)
         {

          }
This is the button click event. This is called when the button is click. Leave the rest part on the code in this page as i will cover it in the upcoming posts. 
  • Now in this function we have to perform addition operation and display the result in the third TextBox. So in order to do that we have to fetch the values entered in the textbox. This can be done by simply writing the "ID of the Textbox".Text (ID can be found of the textbox just by click the textbox which you want to find the ID and go to property window and you may check the Id from the ID field). The following is the code.
       protected void Button1_Click(object sender, EventArgs e)
        {
            int res=Convert.ToInt32(TextBox1.Text) + Convert.ToInt32(TextBox2.Text);
            TextBox3.Text = Convert.ToString(res);
        }

I think some of you are surprised with this code as some are thinking why did i use Convert.ToInt. We can simple write the following code.
     protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox3.Text =TextBox1.Text + TextBox2.Text;
        }
Sorry to say the above code will not work as expected because Textboxs always return string values. So if we right the above code it will concatenate the two string and show the result in the third textbox but we don't want that. That is why we converted both the textboxs to int and stored in the res variable which is also an integer type. After that we convert the integer to string as Textboxs accepts string values only.

  • Now the are done with the program. Now just run the program by clicking on the play button on the to of the page. The output will look like this.

To stop the running application close the browser and then click on stop present in the upper portion of the application.

  • Now we are left with one more thing. We can see that the third textbox value can be manipulated by changing the vale from 24 to any other value but we don't want that. We can solve the problem by changing the property of that textbox. Set the Enabled property to false. This will do it. Now when we run the application we are disabled with the privilege of changing the value of the third TextBox. and that TextBox turns to grey in colour. After the change it will look like this.
  
  • Now to save the application press Ctrl+Shift+S or go to File -> Save All.