Wednesday, 24 April 2013

All About AspDotnet


ASP.NET

What is ASP.Net?

ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.
ASP.Net works on top of the HTTP protocol and uses the HTTP commands and policies to set a browser-to-server two-way communication and cooperation.
ASP.Net is a part of Microsoft .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in either of the following languages:
  • C#
  • Visual Basic .Net
  • Jscript
  • J#
ASP.Net is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages.

ASP.Net Web Forms Model:

ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:
  • Page state
  • Session state
The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state. To clear the concept, let us take up an example of a shopping cart as follows.
User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown in a different page, say the cart page. Only HTTP cannot keep track of all the information coming from various pages. ASP.Net session state and server side infrastructure keeps track of the information collected globally over a session.
The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields.
This way the server becomes aware of the overall application state and operates in a two-tiered connected way.

ASP.Net Component Model:

The ASP.Net component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes:
  • Server side counterparts of almost all HTML elements or tags, like <form> and <input>.
  • Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control.
ASP.Net is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.Net web application is made of pages. When a user requests an ASP.Net page, the IIS delegates the processing of the page to the ASP.Net runtime system.
The ASP.Net runtime transforms the .aspx page into an instance of a class, which inherits from the base class Page of the .Net framework. Therefore, each ASP.Net page is an object and all its components i.e., the server-side controls are also objects.

Components of .Net Framework 3.5

Before going to the next session on Visual Studio.Net, let us look at the various components of the .Net framework 3.5. The following table describes the components of the .Net framework 3.5 and the job they perform:
Components and their Description
(1) Common Language Runtime or CLR
It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation.Those codes which are directly managed by the CLR are called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.
(2) .Net Framework Class Library
It contains a huge library of reusable types . classes, interfaces, structures and enumerated values, which are collectively called types.
(3) Common Language Specification
It contains the specifications for the .Net supported languages and implementation of language integration.
(4) Common Type System
It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.
Metadata and Assemblies
Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and set of resources like image files etc.
(5) Windows Forms
This contains the graphical representation of any window displayed in the application.
(6) ASP.Net and ASP.Net AJAX
ASP.Net is the web development model and AJAX is an extension of ASP.Net for developing and implementing AJAX functionality. ASP.Net AJAX contains the components that allow the developer to update data on a website without a complete reload of the page.
(7) ADO.Net
It is the technology used for working with data and databases. It provides accesses to data sources like SQL server, OLE DB, XML etc. The ADO .Net allows connection to data sources for retrieving, manipulating and updating data.
(8) Windows Workflow Foundation (WF)
It helps in building workflow based applications in Windows. It contains activities, workflow runtime, workflow designer and a rules engine.
(9)Windows Presentation Foundation
It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations and more.
(10) Windows Communication Foundation (WCF)
It is the technology used for building and running connected systems.
(11) Windows CardSpace
It provides safety of accessing resources and sharing personal information on the internet.
(12) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language SQL.


ASP.NET PROVIDES AN ABSTRACTION LAYER ON TOP OF HTTP ON WHICH THE WEB APPLICATIONS ARE BUILT. IT PROVIDES HIGH-LEVEL ENTITIES LIKE CLASSES AND COMPONENTS WITHIN AN OBJECT-ORIENTED PARADIGM.
THE KEY DEVELOPMENT TOOL FOR BUILDING ASP.NET APPLICATIONS AND FRONT ENDS IS VISUAL STUDIO. IN THESE TUTORIALS, WE WILL WORK ON VISUAL STUDIO 2008.
VISUAL STUDIO IS AN INTEGRATED DEVELOPMENT ENVIRONMENT FOR WRITING, COMPILING AND DEBUGGING THE CODE. IT PROVIDES A COMPLETE SET OF DEVELOPMENT TOOLS FOR BUILDING ASP.NET WEB APPLICATIONS, WEB SERVICES, DESKTOP APPLICATIONS AND MOBILE APPLICATIONS.

The Visual Studio IDE:

The new project window allows choosing an application template from the available templates.
Visual Studio IDE
When you start a new web site, ASP.NET provides the starting folders and files for the site, including two files for the first web form of the site.
The file named Default.aspx contains the HTML and asp code that defines the form, and the file named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for vb coding) contains the code in the language you have chosen and this code is responsible for the form's works.
The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use the designer to design a web form, to add code to the control on the form so that the form works according to your need, you use the code editor.

WAYS TO WORK WITH VIEWS AND WINDOWS:

The following are the ways to work with different windows:
  • To change the Web Forms Designer from one view to another, click on the Design or source button.
  • To close a window, click on the close button on the upper right corner and to redisplay, select it from the View menu.
  • To hide a window, click on its Auto Hide button; the window changes into a tab, to redisplay again click on the Auto Hide button again.
  • To size a wind just drag it.
views and windows

ADDING FOLDERS AND FILES TO YOUR WEB SITE:

When a new web form is created, Visual Studio automatically generates the starting HTML for the form and displays it in Source view of the web forms designer. The Solution Explorer is used to add any other files, folders or any existing item on the web site.
  • To add a standard folder, right-click on the project or folder under which you are going to add the folder in the Solution Explorer and choose New Folder.
  • To add an ASP.Net folder, right-click on the project in the Solution Explorer and select the folder from the list.
  • To add an existing item to the site, right-click on the project or folder under which you are going to add the item in the Solution Explorer and select from the dialog box.

Projects and Solutions:

A typical ASP.Net application consists of many items: the web content files (.aspx), source files (e.g., the .cs files), assemblies (e.g., the .dll files and .exe files), data source files (e.g., .mdb files), references, icons, user controls and miscellaneous other files and folders. All these files that make up the website are contained in a Solution.
When a new website is created VB2008 automatically creates the solution and displays it in the solution explorer.
Solutions may contain one or more projects. A project contains content files, source files, and other files like data sources and image files. Generally the contents of a project are compiled into an assembly as an executable file (.exe) or a dynamic link library (.dll) file.
Typically a project contains the following content files:
  • Page file (.aspx)
  • User control (.ascx)
  • Web service (.asmx)
  • Master page (.master)
  • Site map (.sitemap)
  • Website configuration file (.config)

Building and Running a Project:

The application is run by selecting either Start or Start Without Debugging from the Debug menu, or by pressing F5 or Ctrl-F5. The program is built i.e. the .exe or the .dll files are generated by selecting a command from the Build menu.

ASP.Net life cycle specifies, how:
  • ASP.Net processes pages to produce dynamic output
  • The application and its pages are instantiated and processed
  • ASP.Net compiles the pages dynamically
The ASP.Net life cycle could be divided into two groups:
  1. Application Life Cycle
  2. Page Life Cycle

ASP.Net Application Life Cycle:

The application life cycle has the following stages:
  • User makes a request for accessing application resource, a page. Browser sends this request to the web server.
  • A unified pipeline receives the first request and the following events take place:
    • An object of the ApplicationManager class is created.
    • An object of the HostingEnvironment class is created to provide information regarding the resources.
    • Top level items in the application are compiled.
  • Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.
  • An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:
  • Initialization
  • Instantiation of the controls on the page
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.Net page:
  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.
Following are the page life cycle events:
  • PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  • InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  • LoadViewState . LoadViewState event allows loading view state information into the controls.
  • LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.
  • PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  • Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  • LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
  • PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  • PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  • SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  • UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

    An ASP.Net page is made of number of server controls along with the HTML controls, text and images. Sensitive data from the page and the states of different controls on the page are stored in hidden fields and forms the context of that page request.
    ASP.Net runtime controls all association between a page instance and its state. An ASP.Net page is an object of the Page Class or inherited from it.
    All the controls on the pages are also objects of the related control class inherited from a parent Control class. When a page is run an instance of the page object is created along with all its content controls.
    An ASP.Net page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections:
    • Page directives
    • Code Section
    • Page Layout

    PAGE DIRECTIVES:

    The page directives set up the environments for the page to run. The @Page directive defines page-specific attributes used by the ASP.Net page parser and compiler. Page directives specify how the page should be processed, and which assumptions are to be taken about the page.
    It allows importing namespaces, loading assemblies and registering new controls with custom tag names and namespace prefixes. We will discuss all of these concepts in due time.

    CODE SECTION:

    The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.Net follows an object model. Now, these objects raises events when something happens on the user interface, like a user clicks a button or moves the cursor. How these events should be handled? That code is provided in the event handlers of the controls, which are nothing but functions bound to the controls.
    The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly.

    PAGE LAYOUT:

    The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript and HTML tags:
    The following code snippet provides a sample ASP.Net page explaining pafe directives, code section and page layout written in C#:
    <!-- directives -->
    <% @Page Language="C#" %>
    
    <!-- code section -->
    <script runat="server">
    private void convertoupper(object sender, EventArgs e)
    {
     string str = mytext.Value;
     changed_text.InnerHtml = str.ToUpper();
    }
    </script>
    
    <!-- Layout -->
    <html>
    <head> <title> Change to Upper Case </title> </head>
    <body>
    <h3> Conversion to Upper Case </h3>
    <form runat="server">
     <input runat="server" id="mytext" type="text" />
     <input runat="server" id="button1" type="submit" 
        value="Enter..." OnServerClick="convertoupper"/>
    <hr />
    <h3> Results: </h3>
    <span runat="server" id="changed_text" />
    </form>
    </body>
    </html>
    
    Copy this file to the web server's root directory. Generally it is c:\inetput\wwwroot. Open the file from the browser to run it and it should generate following result:
    ASP.NET First Example

    Using Visual Studio IDE:

    Let us develop the same example using Visual Studio IDE. Instead of typing the code, you can just drag the controls into the design view:
    ASP.NET First Example 2
    The content file is automatically developed. All you need to add is the Button1_Click routine, which is as follows:
    protected void Button1_Click(object sender, EventArgs e)
    {
         string buf = TextBox1.Text;
         changed_text.InnerHtml = buf.ToUpper();
    }
    
    The content file code is:
    <%@ Page Language="C#" AutoEventWireup="true" 
                           CodeBehind="Default.aspx.cs" 
                           Inherits="firstexample._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>
    </head>
    <body>
       <form id="form1" runat="server">
       <div>
          <asp:TextBox ID="TextBox1" runat="server" Width="224px">
          </asp:TextBox>
          <br />
          <br />
          <asp:Button ID="Button1" runat="server" Text="Enter..." 
                      Width="85px" onclick="Button1_Click" />
          <hr />
          <h3> Results: </h3>
          <span runat="server" id="changed_text" />
       </div>
       </form>
    </body>
    </html>
    
    Run the example either from Debug menu, or by pressing Ctrl-F5 or by right clicking on the design view and choosing 'View in Browser' from the popup menu. This should generate following result:
    ASP.NET First Example 3

    What is an Event?

    Event is an action or occurrence like mouse click, key press, mouse movements, or any system generated notification. The processes communicate through events. For example, Interrupts are system generated events. When events occur the application should be able to respond to it.
    In ASP.Net an event is raised on the client, and handled in the server. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.
    The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler, and if it has, the event handler is executed.

    Event Arguments:

    ASP.Net event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is called the event argument.
    The general syntax of an event is:
    private void EventName (object sender, EventArgs e);
    

    Application and Session Events:

    The most important application events are:
    • Application_Start . it is raised when the application/website is started
    • Application_End . it is raised when the application/website is stopped
    Similarly, the most used Session events are:
    • Session_Start . it is raised when a user first requests a page from the application
    • Session_End . it is raised when the session ends

    Page and Control Events:

    Common page and control events are:
    • DataBinding . raised when a control bind to a data source
    • Disposed . when the page or the control is released
    • Error . it is an page event, occurs when an unhandled exception is thrown
    • Init . raised when the page or the control is initialized
    • Load . raised when the page or a control is loaded
    • PreRender . raised when the page or the control is to be rendered
    • Unload . raised when the page or control is unloaded from memory

    Event Handling Using Controls:

    All ASP.Net controls are implemented as classes, and they have events which are fired when user performs certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling these events there are in-built attributes and event handlers. To respond to an event, the event handler is coded.
    By default Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.
    The asp tag for a button control:
    <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
    
    The event handler for the Click event:
    Protected Sub btnCancel_Click(ByVal sender As Object, 
                                  ByVal e As System.EventArgs) 
                                  Handles btnCancel.Click
    End Sub
    
    An event can also be coded without a Handles clause. Then the handler must be named according to the appropriate event attribute of the control.
    The asp tag for a button control:
    <asp:Button ID="btnCancel" runat="server" Text="Cancel" 
                                  Onclick="btnCancel_Click" />
    
    The event handler for the Click event:
    Protected Sub btnCancel_Click(ByVal sender As Object, 
                                  ByVal e As System.EventArgs)
    End Sub
    
    The common control events are:
    EventAttributeControls
    ClickOnClickButton, image button, link button, image map
    CommandOnCommandButton, image button, link button
    TextChangedOnTextChangedText box
    SelectedIndexChangedOnSelectedIndexChangedDrop-down list, list box, radio button list, check box list.
    CheckedChangedOnCheckedChangedCheck box, radio button
    Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click events like, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events.
    For example, the change events or selection events, such as, TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.

    Default Events:

    The default event for the Page object is the Load event. Similarly every control has a default event. For example, default event for the button control is the Click event.
    The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:
    ControlDefault Event
    AdRotatorAdCreated
    BulletedListClick
    ButtonClick
    CalenderSelectionChanged
    CheckBoxCheckedChanged
    CheckBoxListSelectedIndexChanged
    DataGridSelectedIndexChanged
    DataListSelectedIndexChanged
    DropDownListSelectedIndexChanged
    HyperLinkClick
    ImageButtonClick
    ImageMapClick
    LinkButtonClick
    ListBoxSelectedIndexChanged
    MenuMenuItemClick
    RadioButtonCheckedChanged
    RadioButtonListSelectedIndexChanged

    Example:

    This example has a simple page with a label control and a button control on it. As the page events like, Page_Load, Page_Init, Page_PreRender etc. takes place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label.
    Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'.
    The markup file (.aspx):
    <%@ Page Language="C#" AutoEventWireup="true" 
                              CodeBehind="Default.aspx.cs" 
                              Inherits="eventdemo._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>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
         <asp:Label ID="lblmessage" runat="server" >
         </asp:Label>
            <br />
            <br />
            <br />
         <asp:Button ID="btnclick" runat="server" Text="Click" 
                     onclick="btnclick_Click" />
        </div>
        </form>
    </body>
    </html>
    
    Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:
    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;
    
    namespace eventdemo
    {
    public partial class _Default : System.Web.UI.Page
    {
       protected void Page_Load(object sender, EventArgs e)
       {
         lblmessage.Text += "Page load event handled. <br />";
         if (Page.IsPostBack)
         {
           lblmessage.Text += "Page post back event handled.<br/>";
         }
      }
      protected void Page_Init(object sender, EventArgs e)
      {
        lblmessage.Text += "Page initialization event handled.<br/>";
      }
      protected void Page_PreRender(object sender, EventArgs e)
      {
        lblmessage.Text += "Page prerender event handled. <br/>";
      }
      protected void btnclick_Click(object sender, EventArgs e)
      {
        lblmessage.Text += "Button click event handled. <br/>";
      }
     }
    }
    
    Run the page. The label shows page load, page initialization and the page pre-render events. Click the button to see effect:
    ASP.NET Event Example
    We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.Net Page class. The page class has the following extremely useful properties that correspond to intrinsic objects like:
    • Session.
    • Application
    • Cache
    • Request
    • Response
    • Server
    • User
    • Trace
    We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object and the Response object.

    The Server Object:

    The Server object in Asp.Net is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs.

    PROPERTIES AND METHODS OF THE SERVER OBJECT:

    The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.
    The following table provides a list of the properties:
    PropertyDescription
    MachineNameName of server's computer
    ScriptTimeOutGets and sets the request time-out value in seconds.
    The following table provides a list of some important methods:
    MethodDescription
    CreateObject(String)Creates an instance of the COM object identified by its ProgID (Programmatic ID)
    CreateObject(Type)Creates an instance of the COM object identified by its Type
    Equals(Object)Determines whether the specified Object is equal to the current Object
    Execute(String)Executes the handler for the specified virtual path in the context of the current request.
    Execute(String, Boolean)Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections
    GetLastErrorReturns the previous exception.
    GetTypeGets the Type of the current instance.
    HtmlEncodeChanges an ordinary string into a string with legal HTML characters.
    HtmlDecodeConverts an Html string into an ordinary string
    ToStringReturns a String that represents the current Object
    Transfer(String)For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page.
    UrlDecodeConverts an URL string into an ordinary string
    UrlEncodeTokenWorks same as UrlEncode, but on a byte array that contains Base64-encoded data
    UrlDecodeTokenWorks same as UrlDecode, but on a byte array that contains Base64-encoded data
    MapPathReturn the physical path that corresponds to a specified virtual file path on the server
    TransferTransfers execution to another web page in the current application

    The Request Object:

    The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser.
    The information presented by this object is wrapped up by the higher level abstractions (the web control model), however, this object helps in checking some information like the client browser and cookies.

    PROPERTIES AND METHODS OF THE REQUEST OBJECT:

    The following table provides some noteworthy properties of the Request object:
    PropertyDescription
    AcceptTypesGets a string array of client-supported MIME accept types.
    ApplicationPathGets the ASP.NET application's virtual application root path on the server.
    BrowserGets or sets information about the requesting client's browser capabilities.
    ContentEncodingGets or sets the character set of the entity-body.
    ContentLengthSpecifies the length, in bytes, of content sent by the client.
    ContentTypeGets or sets the MIME content type of the incoming request.
    CookiesGets a collection of cookies sent by the client.
    FilePathGets the virtual path of the current request.
    FilesGets the collection of files uploaded by the client, in multipart MIME format.
    FormGets a collection of form variables.
    HeadersGets a collection of HTTP headers.
    HttpMethodGets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.
    InputStreamGets the contents of the incoming HTTP entity body.
    IsSecureConnectionGets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).
    QueryStringGets the collection of HTTP query string variables.
    RawUrlGets the raw URL of the current request.
    RequestTypeGets or sets the HTTP data transfer method (GET or POST) used by the client.
    ServerVariablesGets a collection of Web server variables.
    TotalBytesGets the number of bytes in the current input stream.
    UrlGets information about the URL of the current request.
    UrlReferrerGets information about the URL of the client's previous request that linked to the current URL.
    UserAgentGets the raw user agent string of the client browser.
    UserHostAddressGets the IP host address of the remote client.
    UserHostNameGets the DNS name of the remote client.
    UserLanguagesGets a sorted string array of client language preferences.
    The following table provides a list of some important methods:
    MethodDescription
    BinaryReadPerforms a binary read of a specified number of bytes from the current input stream.
    Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
    GetTypeGets the Type of the current instance.
    MapImageCoordinatesMaps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.
    MapPath(String)Maps the specified virtual path to a physical path.
    SaveAsSaves an HTTP request to disk.
    ToStringReturns a String that represents the current Object
    ValidateInputCauses validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

    The Response Object:

    The Response object represents the server's response to the client request. It is an instance of the System.Web.HttpResponse class.
    In ASP.Net, the Response object does not play a vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves.
    However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip.

    PROPERTIES AND METHODS OF THE RESPONSE OBJECT:

    The following table provides some noteworthy properties of the Response object:
    PropertyDescription
    BufferGets or sets a value indicating whether to buffer output and send it after the complete response is finished processing.
    BufferOutputGets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.
    CharsetGets or sets the HTTP character set of the output stream.
    ContentEncodingGets or sets the HTTP character set of the output stream.
    ContentTypeGets or sets the HTTP MIME type of the output stream.
    CookiesGets the response cookie collection.
    ExpiresGets or sets the number of minutes before a page cached on a browser expires.
    ExpiresAbsoluteGets or sets the absolute date and time at which to remove cached information from the cache
    HeaderEncodingGets or sets an Encoding object that represents the encoding for the current header output stream.
    HeadersGets the collection of response headers.
    IsClientConnectedGets a value indicating whether the client is still connected to the server.
    OutputEnables output of text to the outgoing HTTP response stream.
    OutputStreamEnables binary output to the outgoing HTTP content body.
    RedirectLocationGets or sets the value of the Http Location header.
    StatusSets the Status line that is returned to the client.
    StatusCodeGets or sets the HTTP status code of the output returned to the client.
    StatusDescriptionGets or sets the HTTP status string of the output returned to the client.
    SubStatusCodeGets or sets a value qualifying the status code of the response.
    SuppressContentGets or sets a value indicating whether to send HTTP content to the client.
    The following table provides a list of some important methods:
    MethodDescription
    AddHeaderAdds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP.
    AppendCookieInfrastructure. Adds an HTTP cookie to the intrinsic cookie collection.
    AppendHeaderAdds an HTTP header to the output stream.
    AppendToLogAdds custom log information to the Internet Information Services (IIS) log file.
    BinaryWriteWrites a string of binary characters to the HTTP output stream.
    ClearContentClears all content output from the buffer stream.
    CloseCloses the socket connection to a client.
    EndSends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.
    Equals(Object)Determines whether the specified Object is equal to the current Object
    FlushSends all currently buffered output to the client.
    GetTypeGets the Type of the current instance.
    PicsAppends a HTTP PICS-Label header to the output stream.
    Redirect(String)Redirects a request to a new URL and specifies the new URL.
    Redirect(String, Boolean)Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
    SetCookieUpdates an existing cookie in the cookie collection.
    ToStringReturns a String that represents the current Object.
    TransmitFile(String)Writes the specified file directly to an HTTP response output stream, without buffering it in memory.
    Write(Char)Writes a character to an HTTP response output stream.
    Write(Object)Writes an Object to an HTTP response stream.
    Write(String)Writes a string to an HTTP response output stream.
    WriteFile(String)Writes the contents of the specified file directly to an HTTP response output stream as a file block.
    WriteFile(String, Boolean)Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

    Example:

    The following simple example has a text box control where the user can enter name, a button to send the information to the server and a label control to display the URL of the client computer.
    The content file:
    <%@ Page Language="C#" AutoEventWireup="true" 
                           CodeBehind="Default.aspx.cs" 
                           Inherits="server_side._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>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        Enter your name:<br />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" 
                        OnClick="Button1_Click" Text="Submit" />
            <br />
            <asp:Label ID="Label1" runat="server"/>
    
        </div>
        </form>
    </body>
    </html>
    
    The code behind for Button1_Click:
    protected void Button1_Click(object sender, EventArgs e)
    {
       if (!String.IsNullOrEmpty(TextBox1.Text))
       {
           // Access the HttpServerUtility methods through
           // the intrinsic Server object.
           Label1.Text = "Welcome, " +
           Server.HtmlEncode(TextBox1.Text) +
           ".<br/> The url is " +
           Server.UrlEncode(Request.Url.ToString());
        }
    
     }
    
    Run the page to see the following result
    ASP.NET Server Side

    Controls are small building blocks of the graphical user interface, which includes text boxes, buttons, check boxes, list boxes, labels and numerous other tools, using which users can enter data, make selections and indicate their preferences.
    Controls are also used for structural jobs, like validation, data access, security, creating master pages, data manipulation.
    ASP.Net uses five types of web controls, which are:
    • HTML controls
    • HTML Server controls
    • ASP.Net Server controls
    • ASP.Net Ajax Server controls
    • User controls and custom controls
    ASP.Net server controls are the primary controls used in ASP.Net. These controls again could be grouped into the following categories:
    • Validation controls - these are used to validate user input and work by running client-side script
    • Data source controls - these controls provides data binding to different data sources
    • Data view controls - these are various lists and tables, which can bind to data from data sources for display
    • Personalization controls - these are used for personalization of a page according to the user's preference, based on user information
    • Login and security controls - these controls provide user authentication
    • Master pages - these provides consistent layout and interface throughout the application
    • Navigation controls - these helps in navigation, for example, the menus, tree view etc.
    • Rich controls - these implements special features, for example, AdRotator control, FileUpload control, Calendar control etc.
    The basic syntax for using server controls is:
    <asp:controlType  ID ="ControlID" 
                         runat="server" 
                         Property1=value1  [Property2=value2] />
    
    However, visual studio has the following features, which helps in error free coding:
    • Dragging and dropping of controls in design view
    • IntelliSense feature that displays and auto-completes the properties
    • The properties window to set the property values directly

    Properties of the Server Controls

    The ASP.Net server controls with a visual aspect are derived from the WebControl class and inherit all the properties, events and methods of this class.
    The WebControl class itself and some other server controls that are not visually rendered, e.g., the PlaceHolder control or XML control etc., are derived from the System.Web.UI.Control class.
    ASP.Net server controls inherit all properties, events and methods of the WebControl and System.Web.UI.Control class.
    The following table shows the inherited properties, which are common to all server controls:
    PropertyDescription
    AccessKeyPressing this key with the Alt key moves focus to the control
    AttributesIt's the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
    BackColorBackground colour.
    BindingContainerThe control that contains this control's data binding.
    BorderColorBorder colour.
    BorderStyleBorder style.
    BorderWidthBorder width.
    CausesValidationIndicates if it causes validation.
    ChildControlCreatedIt indicates whether the server control's child controls have been created.
    ClientIDControl ID for HTML markup.
    ContextThe HttpContext object associated with the server control.
    ControlsCollection of all controls contained within the control
    ControlStyleThe style of the Web server control.
    CssClassCSS class
    DataItemContainerGets a reference to the naming container if the naming container implements IDataItemContainer.
    DataKeysContainerGets a reference to the naming container if the naming container implements IDataKeysControl.
    DesignModeIt indicates whether the control is being used on a design surface.
    DisabledCssClassGets or sets the CSS class to apply to the rendered HTML element when the control is disabled.
    EnabledIndicates whether the control is grayed out
    EnableThemingIndicates whether theming applies to the control.
    EnableViewStateIndicates whether the view state of the control is maintained.
    EventsGets a list of event handler delegates for the control.
    FontFont .
    ForecolorForeground colour.
    HasAttributesIndicates whether the control has attributes set.
    HasChildViewStateindicates whether the current server control's child controls have any saved view-state settings.
    HeightHeight in pixels or %.
    IDIdentifier for the control.
    IsChildControlStateClearedIndicates whether controls contained within this control have control state.
    IsEnabledGets a value indicating whether the control is enabled
    IsTrackingViewStateIt indicates whether the server control is saving changes to its view state.
    IsViewStateEnabledIt indicates whether view state is enabled for this control.
    LoadViewStateByIdIt indicates whether the control participates in loading its view state by ID instead of index.
    PagePage containing the control.
    ParentParent control.
    RenderingCompatibilityIt specifies the ASP.NET version that rendered HTML will be compatible with.
    SiteThe container that hosts the current control when rendered on a design surface.
    SkinIDGets or sets the skin to apply to the control. (
    StyleGets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.
    TabIndexGets or sets the tab index of the Web server control.
    TagKeyGets the HtmlTextWriterTag value that corresponds to this Web server control.
    TagNameGets the name of the control tag.
    TemplateControlThe template that contains this control.
    TemplateSourceDirectoryGets the virtual directory of the Page or control containing this control.
    ToolTipGets or sets the text displayed when the mouse pointer hovers over the Web server control.
    UniqueIDUnique identifier
    ViewStateGets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
    ViewStateIgnoreCaseIt indicates whether the StateBag object is case-insensitive.
    ViewStateModeGets or sets the view-state mode of this control.
    VisibleIt indicates whether a server control is visible.
    WidthGets or sets the width of the Web server control.

    Methods of the Server Controls

    The following table provides the methods of the server controls:
    MethodDescription
    AddAttributesToRenderAdds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag.
    AddedControlCalled after a child control is added to the Controls collection of the Control object.
    AddParsedSubObjectNotifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's control collection.
    ApplyStyleSheetSkinApplies the style properties defined in the page style sheet to the control.
    ClearCachedClientIDInfrastructure. Sets the cached ClientID value to null.
    ClearChildControlStateDeletes the control-state information for the server control's child controls.
    ClearChildStateDeletes the view-state and control-state information for all the server control's child controls.
    ClearChildViewStateDeletes the view-state information for all the server control's child controls.
    CreateChildControlsUsed in creating child controls.
    CreateControlCollectionCreates a new ControlCollection object to hold the child controls.
    CreateControlStyleCreates the style object that is used to implement all style related properties.
    DataBindBinds a data source to the server control and all its child controls.
    DataBind(Boolean)Binds a data source to the server control and all its child controls with an option to raise the DataBinding event.
    DataBindChildrenBinds a data source to the server control's child controls.
    DisposeEnables a server control to perform final clean up before it is released from memory.
    EnsureChildControlsDetermines whether the server control contains child controls. If it does not, it creates child controls.
    EnsureIDCreates an identifier for controls that do not have an identifier.
    Equals(Object)Determines whether the specified Object is equal to the current Object.
    FinalizeAllows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
    FindControl(String)Searches the current naming container for a server control with the specified id parameter.
    FindControl(String, Int32)Searches the current naming container for a server control with the specified id and an integer
    FocusSets input focus to a control.
    GetDesignModeStateGets design-time data for a control.
    GetTypeGets the Type of the current instance.
    GetUniqueIDRelativeToReturns the prefixed portion of the UniqueID property of the specified control.
    HasControlsDetermines if the server control contains any child controls.
    HasEventsIndicates whether events are registered for the control or any child controls.
    IsLiteralContentDetermines if the server control holds only literal content.
    LoadControlStateRestores control-state information.
    LoadViewStateRestores view-state information.
    MapPathSecureRetrieves the physical path that a virtual path, either absolute or relative, maps to.
    MemberwiseCloneCreates a shallow copy of the current object.
    MergeStyleCopies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control.
    OnBubbleEventDetermines whether the event for the server control is passed up the page's UI server control hierarchy.
    OnDataBindingRaises the data binding event.
    OnInitRaises the Init event.
    OnLoadRaises the Load event.
    OnPreRenderRaises the PreRender event.
    OnUnloadRaises the Unload event.
    OpenFileGets a Stream used to read a file
    RemovedControlCalled after a child control is removed from the Controls collection of the Control object.
    RenderRenders the control to the specified HTML writer.
    RenderBeginTagRenders the HTML opening tag of the control to the specified writer.
    RenderChildrenOutputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.
    RenderContentsRenders the contents of the control to the specified writer.
    RenderControl(HtmlTextWriter)Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.
    RenderEndTagRenders the HTML closing tag of the control into the specified writer.
    ResolveAdapterGets the control adapter responsible for rendering the specified control.
    SaveControlStateSaves any server control state changes that have occurred since the time the page was posted back to the server.
    SaveViewStateSaves any state that was modified after the TrackViewState method was invoked.
    SetDesignModeStateSets design-time data for a control.
    ToStringReturns a String that represents the current object.
    TrackViewStateCauses the control to track changes to its view state so they can be stored in the object's view state property.

    Example:

    Let us look at a particular server control - a tree view control. A Tree view control comes under navigation controls. Other Navigation controls are: Menu control and SiteMapPath control.
    Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes using the Tree view node editor:
    ASP.NET Edit Nodes
    Once you have created the nodes, it looks like the following in design view:
    ASP.NET Edit Nodes2
    The AutoFormat... task allows you to format the tree view:
    ASP.NET AutoFormat
    Add a label control and a text box control on the page and name them lblmessage and txtmessage respectively.
    Write few lines of code to ensure that when a particular node is selected, the label control displays the node text and the text box displays all child nodes under it, if any. The code behind file should look like this:
    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;
     
    namespace eventdemo
    {
      public partial class treeviewdemo : System.Web.UI.Page
      {
        protected void Page_Load(object sender, EventArgs e)
       { 
          txtmessage.Text = " "; 
       }
       protected void TreeView1_SelectedNodeChanged(object sender, 
                                                    EventArgs e)
       {
        txtmessage.Text = " "; 
        lblmessage.Text = "Selected node changed to: " + 
                           TreeView1.SelectedNode.Text;
        TreeNodeCollection childnodes = 
                           TreeView1.SelectedNode.ChildNodes;
        if(childnodes != null)
        {
          txtmessage.Text = " ";
          foreach (TreeNode t in childnodes)
          {
             txtmessage.Text += t.Value;
          }
        }
       }
      }
    }
    
    Run the page to see the effects. You will be able to expand and control the nodes.
    ASP.NET Control Nodes

STATE MANAGEMENT

CHAPTER - 1 

Introduction 
This article does an overview of state management techniques in ASP.NET. I will be discussing about the various types of state management techniques both client side and server side. 

BACKGROUND

STATE MANAGEMENT MEANS TO PRESERVE STATE OF A CONTROL, WEB PAGE, OBJECT/DATA, AND USER IN THE APPLICATION EXPLICITLY BECAUSE ALL ASP.NET WEB APPLICATIONS 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.

USING THE CODE 

Types of state management  

There are two types of state management techniques: client side and server side.

Client side

  1. Hidden Field
  2. View State
  3. Cookies
  4. Control State
  5. Query Strings

Server side

  1. Session
  2. Application

Levels of state management 

  1. Control level: In ASP.NET, by default controls provide state management automatically.
  2. Variable or object level: In ASP.NET, member variables at page level are stateless and thus we need to maintain state explicitly.
  3. Single or multiple page level: State management at single as well as multiple page level i.e., managing state between page requests.
  4. User level: State should be preserved as long as a user is running the application.
  5. Application level: State available for complete application irrespective of the user, i.e., should be available to all users.
  6. Application to application level: State management between or among two or more applications.

CLIENT SIDE METHODS

1. Hidden field

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.
Let us see with a simple example how to use a hidden field. These examples increase a value by 1 on every "No Action Button" click. The source of the hidden field control is. 
<asp:HiddenField ID="HiddenField1" runat="server"  />  
In the code-behind page:
protected void Page_Load(object sender, EventArgs e)
{
   if (HiddenField1.Value != null)
   {
    int val= Convert.ToInt32(HiddenField1.Value) + 1;
    HiddenField1.Value = val.ToString();
    Label1.Text = val.ToString();
   }
}
protected void Button1_Click(object sender, EventArgs e)
{
  //this is No Action Button Click
}

2. View state

View state is another client side state management mechanism provided by ASP.NET to store user's data, i.e., sometimes the user needs to preserve data temporarily after a post back, then the view state is the preferred way for doing it. It stores data in the generated HTML using hidden field not on the server. 
View State provides page level state management i.e., as long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost. View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserilization on each post back. View state is enabled by default for all server side controls of ASP.NET with a propertyEnableviewState set to true.
Let us see how ViewState is used with the help of the following example. In the example we try to save the number of postbacks on button click.
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

3. Cookies

Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.
A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request. 

Types of Cookies

1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
Let us see how to create persistence cookies. There are two ways, the first one is:   
Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10); 
And the second one is:  
HttpCookie aCookieValPer = new HttpCookie("Persistance");
aCookieValPer.Value = "This is A Persistance Cookie";
aCookieValPer.Expires = DateTime.Now.AddSeconds(10);
Response.Cookies.Add(aCookieValPer);
2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Let us see how to create a non persistence cookies. There are two ways, the first one is:
Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistance Cookie";
And the second way is:
HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");
aCookieValNonPer.Value = "This is A Non Persistance Cookie;
Response.Cookies.Add(aCookieValNonPer);how to create cookie : 
How to read a cookie:
if (Request.Cookies["NonPersistance"] != null)
Label2.Text = Request.Cookies["NonPersistance"].Value;
Let's understand persistence and non persistence cookies more clearly with a diagram:
Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

4. Control State

Control State is another client side state management technique. Whenever we develop a custom control and want to preserve some information, we can use view state but suppose view state is disabled explicitly by the user, the control will not work as expected. For expected results for the control we have to use Control State property. Control state is separate from view state.
How to use control state property: Control state implementation is simple. First override the OnInit() method of the control and add a call for the Page.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information.

SERVER SIDE

1. Session   

Session management is a very strong technique to maintain state. Generally session is used to store user's information and/or uniquely identify a user (or say browser). The server maintains the state of user information by using a session ID. When users makes a request without a session ID, ASP.NET creates a session ID and sends it with every request and response to the same user.
How to get and set value in Session:
Session["Count"] = Convert.ToInt32(Session["Count"]) + 1;//Set Value to The Session
Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion 
Let us see an example where we save the count of button clicks in a session, and save the “number of redirects to the same page” button click in a query string. Here I have set the expiry to 10 minutes. After starting the application, the application variable exists till the end of the application. A session variable will expire after 10 minutes (if it is idle). A query string contains the value in URL so it won’t depend on the user idle time and could be used by the server anytime it is passed with a request.  

Session Events in ASP.NET  

To manage a session, ASP.NET provides two events: session_start and session_end that is written in a special file called Global.aspx in the root directory of the project. 
Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.  
void Session_Start(object sender, EventArgs e)
{
   Session["Count"] = 0;  // Code that runs when a new session is started
}
Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the case of In proc mode not in the state server and SQL Server modes. 
There are four session storage mechanisms provided by ASP.NET:
  • In Proc mode 
  • State Server mode  
  • SQL Server mode 
  • Custom mode  
In Process mode: In proc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server is restarted the session values will be lost.
<configuration>
 <sessionstate mode="InProc" cookieless="false" timeout="10" 
    stateConnectionString="tcpip=127.0.0.1:80808" 
    sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration> 
In State Server mode: This mode could store session in the web server but out of the application pool. But usually if this mode is used there will be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the web config file and start the aspnet_state service.
<configuration><sessionstate mode="stateserver" cookieless="false" 
   timeout="10"  stateConnectionString="tcpip=127.0.0.1:42424"  
   sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/> </configuration> 
In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is overhead from serialization and deserialization of session data. This mode should be used when reliability is more important than performance. 
<configuration>
    <sessionstate mode="sqlserver" cookieless="false" timeout="10" 
       stateConnectionString="tcpip=127.0.0.1:4  2424" 
       sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
Custom Session mode: Generally we should prefer in proc state server mode or SQL Server mode but if you need to store session data using other than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized even generating session ID, data store, and also security. 
Attributes  Description 
Cookieless true/false  Indicates that the session is used with or without cookie. cookieless set to true indicates sessions without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless set to false is the default set. 
timeout Indicates the session will abound if it is idle before session is abounded explicitly (the default time is 20 min).
StateConnectionStringIndicates the session state is stored on the remote computer (server). This attribute is required when session mode is StateServer
SqlConnectionStringIndicates the session state is stored in the database. This attribute is required when session mode is SqlServer

2. Application

Application state is a server side state management technique. The date stored in application state is common for all users of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level state management. Data stored in the application should be of small size.  
How to get and set a value in the application object:
Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object 

Application events in ASP.NET

There are three types of events in ASP.NET. Application event is written in a special file called Global.asax. This file is not created by default, it is created explicitly by the developer in the root directory. An application can create more than one Global.asax file but only the root one is read by ASP.NET.

Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file. 
void Application_Start(object sender, EventArgs e)
{
    Application["Count"] = 0;
}
Application_Error: It is raised when an unhandled exception occurs, and we can manage the exception in this event.
Application_End: The Application_End event is raised just before an application domain ends because of any reason, may IIS server restarting or making some changes in an application cycle.  
So we have talked about various types of state management techniques in this article. I have tried to touch several topics in this article but the main intention for this article was to get the user familiar with the various state management techniques that exist in ASP.NET. The details for all these techniques will make a complete article by itself which I will try to post in future. 


The HTML server controls are basically the original HTML controls but enhanced to enable server side processing. The HTML controls like the header tags, anchor tags and input elements are not processed by the server but sent to the browser for display.
They are specifically converted to a server control by adding the attribute runat="server" and adding an id attribute to make them available for server-side processing.
For example, consider the HTML input control:
<input type="text" size="40">
It could be converted to a server control, by adding the runat and id attribute:
<input type="text" id="testtext" size="40" runat="server">

Advantages of using HTML Server Controls

Although ASP.Net server controls can perform every job accomplished by the HTML server controls, the later controls are useful in the following cases:
  • Using static tables for layout purposes
  • Converting a HTML page to run under ASP.Net
The following table describes the HTML server controls:
Control NameHTML tag
HtmlHead<head>element
HtmlInputButton<input type=button|submit|reset>
HtmlInputCheckbox<input type=checkbox>
HtmlInputFile<input type = file>
HtmlInputHidden<input type = hidden>
HtmlInputImage<input type = image>
HtmlInputPassword<input type = password>
HtmlInputRadioButton<input type = radio>
HtmlInputReset<input type = reset>
HtmlText<input type = text|password>
HtmlImage<img> element
HtmlLink<link> element
HtmlAnchor<a> element
HtmlButton<button> element
HtmlButton<button> element
HtmlForm<form> element
HtmlTable<table> element
HtmlTableCell<td> and <th>
HtmlTableRow<tr> element
HtmlTitle<title> element
HtmlSelect<select> element
HtmlGenericControlAll HTML controls not listed

Example:

The following example uses a basic HTML table for layout. It uses some text boxes for getting input from the users like, name, address, city, state etc. It also has a button control, which is clicked to get the user data displayed on the last row of the table.
The page should look like this in the design view:
ASP.NET Server Controls
The code for the content page shows the use of the HTML table element for layout.
<%@ Page Language="C#" AutoEventWireup="true" 
                       CodeBehind="Default.aspx.cs" 
                       Inherits="htmlserver._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>
<style type="text/css">
   .style1
   {  
       width: 156px;
   }
   .style2
   {
      width: 332px;
   }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 54%;">
<tr>
<td class="style1">Name:</td>
<td class="style2">
<asp:TextBox ID="txtname" runat="server" Width="230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">Street</td>
<td class="style2">
<asp:TextBox ID="txtstreet" runat="server" Width="230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">City</td>
<td class="style2">
<asp:TextBox ID="txtcity" runat="server" Width="230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">State</td>
<td class="style2">
<asp:TextBox ID="txtstate" runat="server" Width="230px">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="style1"> </td>
<td class="style2"></td>
</tr>
<tr>
<td class="style1"></td>
<td ID="displayrow" runat ="server" class="style2">
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" 
            onclick="Button1_Click" Text="Click" />
</form>
</body>
</html>
The code behind the button control:
protected void Button1_Click(object sender, EventArgs e)
{
 string str = "";
 str += txtname.Text + "<br />";
 str += txtstreet.Text + "<br />";
 str += txtcity.Text + "<br />";
 str += txtstate.Text + "<br />";
 displayrow.InnerHtml = str;
}
observe the followings
  • The normal HTML tags has been used for the page layout.
  • The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it.


ASP.Net client side coding has two aspects:
  • Client side scripts: that would run on the browser and in turn would speed up the execution of page. For example, client side data validation which can catch invalid data and warn the user accordingly without making a round trip to the server.
  • Client side source code: that the ASP.NET pages generate. For example, the HTML source code of an ASP.NET page contains a number of hidden fields and automatically injected blocks of JavaScript code, which keeps information like view state or does other jobs to make the page work.

Client Side Scripts:

All ASP.Net server controls allow calling client side code written using JavaScript or VBScript. Some ASP.Net server controls use client side scripting to provide responses to the users without posting back to the server, for example, the validation controls, which we will discuss in due time.
Apart from these scripts the Button control has a property OnClientClick, which allows executing client-side script, when the button is clicked.
The traditional and server HTML controls has the following events that can execute a script when they are raised:
EventDescription
onblurWhen the control loses focus
onfocusWhen the control receives focus
onclickWhen the control is clicked
onchangeWhen the value of the control changes
onkeydownWhen the user presses a key
onkeypressWhen the user presses an alphanumeric key
onkeyupWhen the user releases a key
onmouseoverWhen the user moves the mouse pointer over the control
onserverclickIt raises the ServerClick event of the control, when the control is clicked

Client Side Source Code

We have already discussed that, ASP.NET pages are generally written in two files:
  • The content file or the markup file ( .aspx)
  • The code-behind file
The content file contains the HTML or ASP.Net controls tags and literals to form the structure of the page and the code behind file contains the class definition. At run time, the content file is parsed and transformed into a page class.
This class along with the class definition in the code file and some other system generated code make the executable code (assembly) that processes all posted data and generates the response and sends it back to the client.
Consider the simple page:
<%@ Page Language="C#" AutoEventWireup="true" 
                       CodeBehind="Default.aspx.cs" 
                       Inherits="clientside._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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
      <asp:Button ID="Button1" runat="server" 
        OnClick="Button1_Click" Text="Click" />
    </div>
    <hr />
    <h3><asp:Label ID="Msg" runat="server" Text=""></asp:Label>
    </h3>
    </form>
</body>
</html>
When this page is run on the browser, the View Source option shows the HTML page sent to the browser by the ASP.Net runtime:
<!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><title>
 Untitled Page
</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
value="/wEPDwUKMTU5MTA2ODYwOWRk31NudGDgvhhA7joJum9Qn5RxU2M=" />
</div>
 
<div>
<input type="hidden" name="__EVENTVALIDATION" 
id="__EVENTVALIDATION" 
value="/wEWAwKpjZj0DALs0bLrBgKM54rGBhHsyM61rraxE+KnBTCS8cd1QDJ/"/>
</div>

<div>
<input name="TextBox1" type="text" id="TextBox1" />  
<input type="submit" name="Button1" value="Click" id="Button1" />
</div>

<hr />
<h3><span id="Msg"></span></h3>
</form>
</body>
</html>
Looking closely at the code would reveal that first two <div> tags contain the hidden fields which store the view state and validation information.
In this section, we will discuss the basic controls available in ASP.NET

Button Controls:

ASP .Net provides three types of button controls: buttons, link buttons and image buttons. As the names suggest a button displays text within a rectangular area, a link button displays text that looks like a hyperlink. And an Image Button displays an image.
When a user clicks a button control, two events are raised Click and Command.
Basic syntax for button controls:
<asp:Button ID="Button1" runat="server" 
            onclick="Button1_Click" Text="Click" />
Common Properties of the Button control:
PropertyDescription
TextThe text displayed by the button. This is for button and link button controls only.
ImageUrlFor image button control only. The image to be displayed for the button.
AlternateTextFor image button control only. The text to be displayed if the browser can't display the image.
CausesValidationDetermines whether page validation occurs when a user clicks the button. The default is true.
CommandNameA string value that's passed to the Command event when a user clicks the button.
CommandArgumentA string value that's passed to the Command event when a user clicks the button.
PostBackUrlThe URL of the page that should be requested when the user clicks the button.

Text Boxes and Labels:

Text box controls are typically used to accept input from the user. A text box control can accept one or more lines to text depending upon the setting of the TextMode attribute.
Label controls provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display a text that does not change, you use the literal text.
Basic syntax for text controls:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox
Common Properties of the Text Box and Labels:
PropertyDescription
TextModeSpecifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that accepts more than one line of text and the Password causes the characters that are entered to be masked. The default is SingleLine.
TextThe text content of the text box
MaxLengthThe maximum number of characters that can be entered into the text box.
WrapIt determines whether or not text wraps automatically for multi-line text box; default is true.
ReadOnlyDetermines whether the user can change the text in the box; default is false, i.e., the user can change the text.
ColumnsThe width of the text box in characters. The actual width is determined based on the font that's used for the text entry
RowsThe height of a multi-line text box in lines. The default value is 0, means a single line text box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.

Check Boxes and Radio Buttons:

A check box displays a single option that the user can either check or uncheck and radio buttons present a group of options from which the user can select just one option.
To create a group of radio buttons, you specify the same name for the GroupName attribute of each radio button in the group. If more than one group is required in a single form specify a different group name for each group.
If you want a check box or radio button to be selected when it's initially displayed, set its Checked attribute to true. If the Checked attribute is set for more than one radio button in a group, then only the last one will be selected.
Basic syntax for check box:
<asp:CheckBox ID= "chkoption" runat= "Server"> 
</asp:CheckBox>
Basic syntax for radio button:
<asp:RadioButton ID= "rdboption" runat= "Server"> 
</asp: RadioButton>
Common Properties of the Check Boxes and Radio Buttons:
PropertyDescription
TextThe text displayed next to the check box or radio button.
CheckedSpecifies whether it is selected or not, default is false.
GroupNameName of the group the control belongs to.

List Controls:

ASP.Net provides the controls: drop-down list, list box, radio button list, check box list and bulleted list. These control let a user choose from one or more items from the list.
List boxes and drop-down list contain one or more list items. These lists could be loaded either by code or by the ListItem Collection Editor.
Basic syntax for list box control:
<asp:ListBox ID="ListBox1" 
      runat="server" 
      AutoPostBack="True" 
      OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax for a drop-down list control:
<asp:DropDownList ID="DropDownList1" 
     runat="server" 
     AutoPostBack="True" 
     OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common Properties of List box and Drop-down Lists:
PropertyDescription
ItemsThe collection of ListItem objects that represents the items in the control. This property returns an object of type ListItemCollection.
RowsSpecifies the number of items displayed in the box. If actual list contains more rows than displayed then a scroll bar is added.
SelectedIndexThe index of the currently selected item. If more than one item is selected, then the index of the first selected item. If no item is selected, the value of this property is -1.
SelectedValueThe value of the currently selected item. If more than one item is selected, then the value of the first selected item. If no item is selected, the value of this property is an empty string("").
SelectionModeIndicates whether a list box allows single selections or multiple selections.
Common Properties of each list item objects:
PropertyDescription
TextThe text displayed for the item
SelectedIndicates whether the item is selected.
ValueA string value associated with the item.
It is important to notes that:
  • To work with the items in a drop-down list or list box, you use the Items property of the control. This property returns a ListItemCollection object which contains all the items of the list.
  • The SelectedIndexChanged event is raised when the user selects a different item from a drop-down list or list box.

The List Item Collections:

The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the list. Items in a ListItemCollection are numbered from 0.
When the items into a list box are loaded using strings like: lstcolor.Items.Add("Blue") . then both the Text and Value properties of the list item are set to the string value you specify. To set it differently you must create a list item object and then add that item to the collection.
The ListItem Collection Editor is used to add item to a drop-down list or list box. This is used to create a static list of items. To display the Collection Editor select Edit item from the smart tag menu, or select the control and then click the ellipsis button from the Item property in the Properties window.
Common Properties of List Item Collection:
PropertyDescription
Item(integer)A ListItem object that represents the item at the specified index.
CountThe number of items in the collection.
Common methods of List Item Collection:
MethodsDescription
Add(string)Adds a new item to the end of the collection and assigns the string parameter to the Text property of the item.
Add(ListItem)Adds a new item to the end of the collection.
Insert(integer, string)Inserts an item at the specified index location in the collection, and assigns the string parameter to the Text property of the item.
Insert(integer, ListItem)Inserts the item at the specified index location in the collection.
Remove(string)Removes the item with the Text value same as the string.
Remove(ListItem)Removes the specified item.
RemoveAt(integer)Removes the item at the specified index as the integer.
ClearRemoves all the items of the collection.
FindByValue(string)Returns the item whose Value is same as the string.
FindByValue(Text)Returns the item whose Text is same as the string.

Radio Button list and Check Box list

A radio button list presents a list of mutually exclusive options. A check box list presents a list of independent options. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.
Basic syntax for radio button list:
<asp:RadioButtonList ID="RadioButtonList1" 
   runat="server"
   AutoPostBack="True" 
   OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Basic syntax for check box list:
<asp:CheckBoxList ID="CheckBoxList1" 
   runat="server" 
   AutoPostBack="True" 
   OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common Properties of Check Box and Radio Button Lists:
PropertyDescription
RepeatLayoutThis attribute specifies whether the table tags or the normal html flow to use while formatting the list when it is rendered. The default is Table
RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical
RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

Bulleted lists and Numbered lists:

The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.
Basic syntax of a bulleted list:
<asp:BulletedList ID="BulletedList1" runat="server">
</asp:BulletedList>
Common Properties of the Bulleted List:
PropertyDescription
BulletStyleThis property specifies the style and looks of the bullets, or numbers.
RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical
RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

HyperLink Control:

The HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
   HyperLink
</asp:HyperLink>
It has the following important properties:
PropertyDescription
ImageUrlPath of the image to be displayed by the control
NavigateUrlTarget link URL
TextThe text to be displayed as the link
TargetThe window or frame which will load the linked page.

Image Control:

The image control is used for displaying images on the web page, or some alternative text, if the image is not available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
PropertyDescription
AlternateTextAlternate text to be displayed
ImageAlignAlignment options for the control
ImageUrlPath of the image to be displayed by the control
In this tutorial, we have covered the basic controls theoretically. In coming topics, we will be using these controls in examples.
ASP.Net directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework.
The syntax for declaring a directive is:
<%@  directive_name attribute=value  [attribute=value]  %>
In this section, we will just introduce the ASP.Net directives and we will use most of these directives throughout the tutorials.

The Application Directive

The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file.
The basic syntax for a sample Application directive is:
<%@ Application Language="C#" %>
The attributes of the Application directive are:
AttributesDescription
Inheritsthe name of the class from which to inherit
Descriptiontext description of the application. Parsers and compilers ignore this
Languagelanguage used in code blocks

The Assembly Directive

The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking or in the page file or a user control file for linking to a page or user control.
The basic syntax for a sample Assembly directive is:
<%@ Assembly Name ="myassembly" %>
The attributes of the Assembly directive are:
AttributesDescription
Namethe name of the assembly to be linked
Srcthe path to the source file to be linked and compiled dynamically

The Control Directive

The Control directive is used with the user controls and appears in the user control (.ascx) files.
The basic syntax for a sample Control directive is:
<%@ Control Language="C#"  EnableViewState="false" %>
The attributes of the Control directive are:
AttributesDescription
AutoEventWireupthe Boolean value that enables or disables automatic association of events to handlers
ClassNamefile name for the control
Debugthe Boolean value that enables or disables compiling with debug symbols
Descriptiontext description of the control page, ignored by compiler
EnableViewStatethe Boolean value that indicates whether view state is maintained across page requests
Explicitfor VB language, tells the compiler to use Option Explicit mode
Inheritsthe class from which the control page inherits
Languagelanguage for code and script
Srcthe filename for the code-behind class
Strictfor VB language, tells the compiler to use the Option Strict mode

The Implements Directive

The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface.
The basic syntax for an Implements directive is:
<%@ Implements  Interface="interface_name" %>

The Import Directive

The Import directive imports a namespace into a web page, user control pate of application. If the Import directive is specified in the global.asax, then it will apply to the entire application. If it is in a page of user control page, then it would apply to that page or control.
The basic syntax for an Import directive is:
<%@ namespace="System.Drawing" %>

The Master Directive

The Master directive specifies a page file as being the mater page.
The basic syntax for a sample MasterPage directive is:
<%@ MasterPage Language="C#"  AutoEventWireup="true" 
    CodeFile="SiteMater.master.cs" Inherits="SiteMaster"  %>

The MasterType Directive

The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed.
The basic syntax for a MasterType directive is:
<%@ MasterType attribute="value"[attribute="value" ...]  %>

The OutputCache Directive

The OutputCache directive controls the output caching policies of a web page or a user control. We will discuss this directive in details, in data caching.
The basic syntax for a OutputCache directive is:
<%@ OutputCache Duration="15" VaryByParam="None"  %>

The Page Directive

The Page directive defines the attributes specific to the page file for the page parser and the compiler.
The basic syntax for a Page directive is:
<%@ Page Language="C#"  AutoEventWireup="true" 
    CodeFile="Default.aspx.cs" Inherits="_Default"  Trace="true" %>
The attributes of the Page directive are:
AttributesDescription
AutoEventWireupthe Boolean value that enables or disables Page events that are being automatically bound to methods; for example, Page_Load
Bufferthe Boolean value that enables or disables HTTP response buffering
ClassNameclass name for the page
ClientTargetthe browser for which server controls should render content
CodeFilename of the code behind file
Debugthe Boolean value that enables or disables compilation with debug symbols
Descriptiontext description of the page, ignored by the parser
EnableSessionStateenables, disables or makes session state read-only
EnableViewStatethe Boolean value that enables or disables view state across page requests
ErrorPageURL for redirection if an unhandled page exception occurs
Inheritsthe name of the code behind or other class
Languageprogramming language for code
Srcfile name of the code behind class
Traceenables or disables tracing
TraceModeindicates how trace messages are to be displayed - sorted by time or category
Transactionindicates if transactions are supported
ValidateRequestthe Boolean value that indicates whether all input data is validated against a hardcoded list of values

The PreviousPageType Directive

The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.
The basic syntax for a sample PreviousPagetype directive is:
<%@ PreviousPageType attribute="value"[attribute="value" ...]   %>

The Reference Directive

The Reference directive indicates that another page or user control should be compiled and linked to the current page.
The basic syntax for a sample Reference directive is:
<%@ Reference Page ="somepage.aspx" %>

The Register Directive

The Register derivative is used for registering the custom server controls and user controls.
The basic syntax for a sample Register directive is:
<%@ Register Src="~/footer.ascx" TagName="footer" 
    TagPrefix="Tfooter" %>




HTTP ( Hyper Text Transfer Protocol) is a stateless protocol. When the client disconnects from the server, the ASP.Net engine discards the page objects. This way each web application can scale up to serve numerous requests simultaneously without running out of server memory.
However, there need to be some technique to store the information between requests and to retrieve it when required. This information i.e., the current value of all the controls and variables for the current user in the current session is called the State.
ASP.Net manages four types of state:
  1. View State
  2. Control State
  3. Session State
  4. Application State

View State:

The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is again post back the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
  • The entire application - by setting the EnableViewState property in the <pages> section of web.config file
  • A page - by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#" EnableViewState="false" %>
  • A control - by setting the Control.EnableViewState property.
It is implemented using a view state object defined by the StateBag class which defines a collection of view state items. The state bag is a data structure containing attribute/value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
PropertiesDescription
Item(name)The value of the view state item with the specified name. This is the default property of the StateBag class
CountThe number of items in the view state collection
KeysCollection of keys for all the items in the collection
ValuesCollection of values for all the items in the collection
The StateBag class has the following methods
MethodsDescription
Add(name, value)Adds an item to the view state collection and existing item is updated
ClearRemoves all the items from the collection
Equals(Object)Determines whether the specified object is equal to the current object.
FinalizeAllows it to free resources and perform other cleanup operations.
GetEnumeratorReturns an enumerator that iterates over all the key/value pairs of the StateItem objects stored in the StateBag object.
GetTypeGets the Type of the current instance.
IsItemDirtyChecks a StateItem object stored in the StateBag object to evaluate whether it has been modified.
Remove(name)Removes the specified item.
SetDirtySets the state of the StateBag object as well as the Dirty property of each of the StateItem objects contained by it.
SetItemDirtySets the Dirty property for the specified StateItem object in the StateBag object.
ToStringReturns a String representing the state bag object.

EXAMPLE:

The following example demonstrates the concept of storing view state. Let us keep a counter, which is incremented each time the page is post back by clicking a button on the page. A label control shows the value in the counter.
The markup file:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="statedemo._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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>View State demo</h3>
    Page Counter:
    <asp:Label ID="lblCounter" runat="server" />
    <asp:Button ID="btnIncrement" runat="server" 
                Text="Add Count" 
                onclick="btnIncrement_Click" />
    </div>
    </form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
        public int counter
        {
            get
            {
                if (ViewState["pcounter"] != null)
                {
                    return ((int)ViewState["pcounter"]);
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                ViewState["pcounter"] = value;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            lblCounter.Text = counter.ToString();
            counter++;
        }
}
This would produce following result:
View State Demo

Control State:

Control state cannot be modified, accessed directly or disabled.

Session State:

When a user connects to an ASP.Net website, a new session object is created. When session state is turned on, a new session state object is created for each new request. This session state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data like inventory or supplier list, or a customer record or shopping cart. It can also keep information about the user and his preference and keep track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of session state items.
The HttpSessionState class has the following properties:
PropertiesDescription
SessionIDThe unique session identifier
Item(name)The value of the session state item with the specified name. This is the default property of the HttpSessionState class
CountThe number of items in the session state collection
TimeOutGets and sets the amount of time, in minutes, allowed between requests before the session-state provider terminates the session.
The HttpSessionState class has the following methods:
MethodsDescription
Add(name, value)Adds an item to the session state collection
ClearRemoves all the items from session state collection
Remove(name)Removes the specified item from the session state collection
RemoveAllRemoves all keys and values from the session-state collection.
RemoveAtDeletes an item at a specified index from the session-state collection.
The session state object is a name-value pair, to store and retrieve some information from the session state object the following code could be used:
void StoreSessionInfo()
{
 String fromuser = TextBox1.Text;
 Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
 String fromuser = Session["fromuser"];
 Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can store all the primitive data types and arrays composed of primitive data types, as well as the DataSet, DataTable, HashTable, and Image objects, as well as any user defined class that inherits from the ISerializable object.

EXAMPLE:

The following example demonstrates the concept of storing session state. There are two buttons on the page, a text box to enter string and a label to display the text stored from last session.
The mark up file:
<%@ 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>
</head>
<body>
  <form id="form1" runat="server">
  <div>
        &nbsp; &nbsp; &nbsp;
 <table style="width: 568px; height: 103px">
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblstr" runat="server" 
          Text="Enter a String" Width="94px">
 </asp:Label>
 </td>
 <td style="width: 317px">
 <asp:TextBox ID="txtstr" runat="server" Width="227px">
 </asp:TextBox>
 </td>
 </tr>
 <tr>
 <td style="width: 209px"></td>
 <td style="width: 317px"></td>
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Button ID="btnnrm" runat="server" 
          Text="No action button" Width="128px" />
 </td>
 <td style="width: 317px">
 <asp:Button ID="btnstr" runat="server" 
          OnClick="btnstr_Click" Text="Submit the String" />
 </td> 
 </tr>
 <tr>
 <td style="width: 209px">
 </td>
 <td style="width: 317px">
 </td>  
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblsession" runat="server" 
          Width="231px">
 </asp:Label>
 </td>
 <td style="width: 317px">
 </td>
 </tr>
 <tr>
 <td style="width: 209px">
 <asp:Label ID="lblshstr" runat="server">
 </asp:Label>
 </td>
 <td style="width: 317px">
 </td>
 </tr>
 </table>
  </div>
  </form>
</body>
</html>
It should look like the following in design view:
session design view
The code behind file is given here:
public partial class _Default : System.Web.UI.Page 
{
    String mystr;
    protected void Page_Load(object sender, EventArgs e)
    {
        this.lblshstr.Text = this.mystr;
        this.lblsession.Text = (String)this.Session["str"];
    }
    protected void btnstr_Click(object sender, EventArgs e)
    {
        this.mystr = this.txtstr.Text;
        this.Session["str"] = this.txtstr.Text;
        this.lblshstr.Text = this.mystr;

        this.lblsession.Text = (String)this.Session["str"];
    }
}
Run the file and observe how it works:
session run view

Application State

An ASP.Net application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users.
To provide for the use of application state, ASP.Net creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc and to keep track of users visiting the site.
The HttpApplicationState class has the following properties:
PropertiesDescription
Item(name)The value of the application state item with the specified name. This is the default property of the HttpApplicationState class.
CountThe number of items in the application state collection.
The HttpApplicationState class has the following methods:
MethodsDescription
Add(name, value)Adds an item to the application state collection .
ClearRemoves all the items from the application state collection.
Remove(name)Removes the specified item from the application state collection.
RemoveAllRemoves all objects from an HttpApplicationState collection.
RemoveAtRemoves an HttpApplicationState object from a collection by index.
Lock()Locks the application state collection so only the current user can access it.
Unlock()Unlocks the application state collection so all the users can access it.
Application state data is generally maintained by writing handlers for the events:
  • Application_Start
  • Application_End
  • Application_Error
  • Session_Start
  • Session_End
The following code snippet shows the basic syntax for storing application state information:
Void Application_Start(object sender, EventArgs e)
{
  Application["startMessage"] = "The application has started.";
}
Void Application_End(object sender, EventArgs e)
{
  Application["endtMessage"] = "The application has ended.";
}

No comments:

Post a Comment