Sunday 19 May 2013

ASP.net


ASP.NET - Introduction 

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 - Environment Setup

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

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.

ASP.NET - First Example

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


ASP.NET - Event Handling

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


ASP.NET - Server Side

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


ASP.NET - Server Controls

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


ASP.NET - HTML Server Controls

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

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.

ASP.NET - Basic Controls

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

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" %>



ASP.NET - Database Access

ASP.Net allows the following sources of data to be accessed and used:
  • Databases (e.g., Access, SQL Server, Oracle, MySQL)
  • XML documents
  • Business Objects
  • Flat files
ASP.Net hides the complex processes of data access and provides much higher level of classes and objects through which data is accessed easily. These classes hide all complex coding for connection, data retrieving, data querying and data manipulation.
ADO.Net is the technology that provides the bridge between various ASP.Net control objects and the backend data source. We will come to ADO.Net in due time. In this tutorial, we will look at data access and working with the data without going into the details of its inner workings.

Retrieve and display data:

It takes two types of data controls to retrieve and display data in ASP.Net:
  1. A data source control . it manages the connection to the data, selection of data and other jobs like paging and caching of data etc.
  2. A data view control . it binds and displays the data and allows data manipulation.
We will discuss the data binding and data source controls in details later. In this section, we will use a SqlDataSource control to access data and a GridView control to display and manipulate data.
We will also use an Access database, which has details about .Net books available in the market. Name of our database is ASPDotNetStepByStep.mdb and we will use the data table DotNetReferences.
The table has the following columns: ID, Title, AuthorFirstName, AuthorLastName, Topic, and Publisher.
Here is a snapshot of the data table:
Data Table
Let us directly move to action, take the following steps:
(1) Create a web site and add a SqlDataSourceControl on the web form.
SqlDataSourceControl
(2) Click on the Configure Data Source Link.
Configure Data Source
(3) Click on the New Connection button to establish connection with a database.
Connection with a database
(4) Once the connection is set up, you may save it for further use. At the next step, you are asked to configure the select statement:
Select statement

(5) Select the columns and click next to complete the steps. Observe the WHERE, ORDER BY, AND the Advanced. Buttons. These buttons allow you to provide the where clause, order by clause and specify the insert, update and delete commands of SQL respectively. This way, you can manipulate the data.
(6) Add a GridView control on the form. Choose the data source and format the control using AutoFormat option.
AutoFormat
(7) After this the formatted GridView control displays the column headings, and the application is ready to run.
GridView control
(8) Finally Run the application
Database Result
The content file code:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="dataaccess.aspx.cs" 
         Inherits="datacaching.WebForm1" %>

<!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:SqlDataSource ID="SqlDataSource1" 
   runat="server" 
   ConnectionString=
   "<%$ ConnectionStrings:ASPDotNetStepByStepConnectionString%>" 
   ProviderName=
   "<%$ ConnectionStrings:
        ASPDotNetStepByStepConnectionString.ProviderName %>" 
   SelectCommand="SELECT [Title], [AuthorLastName], 
                         [AuthorFirstName], [Topic] 
                  FROM [DotNetReferences]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" 
   runat="server" 
   AutoGenerateColumns="False" 
   CellPadding="4" 
   DataSourceID="SqlDataSource1" 
   ForeColor="#333333" 
   GridLines="None">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" 
SortExpression="Title" />
<asp:BoundField DataField="AuthorLastName" 
HeaderText="AuthorLastName" 
SortExpression="AuthorLastName" />
<asp:BoundField DataField="AuthorFirstName" 
HeaderText="AuthorFirstName" 
SortExpression="AuthorFirstName" />
<asp:BoundField DataField="Topic" 
HeaderText="Topic" SortExpression="Topic" />
</Columns>
<FooterStyle BackColor="#5D7B9D" 
Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" 
ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" 
Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True"  
ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>
</html>


ASP.NET - ADO.net

ADO.Net provides a bridge between the front end controls and the back end database. The ADO.Net objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data.
The following figure shows the ADO.Net objects at a glance:
ADO.Net objects

The DataSet Class:

The data set represents a subset of the database. It does not have a continuous connection to the database. To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between two tables.
Following table shows some important properties of the DataSet class:
PropertiesDescription
CaseSensitiveIndicates whether string comparisons within the data tables are case-sensitive.
ContainerGets the container for the component.
DataSetNameGets or sets the name of the current data set.
DefaultViewManagerReturns a view of data in the data set.
DesignModeIndicates whether the component is currently in design mode.
EnforceConstraintsIndicates whether constraint rules are followed when attempting any update operation.
EventsGets the list of event handlers that are attached to this component.
ExtendedPropertiesGets the collection of customized user information associated with the DataSet.
HasErrorsIndicates if there are any errors.
IsInitializedIndicates whether the DataSet is initialized.
LocaleGets or sets the locale information used to compare strings within the table.
NamespaceGets or sets the namespace of the DataSet.
PrefixGets or sets an XML prefix that aliases the namespace of the DataSet.
RelationsReturns the collection of DataRelation objects.
TablesReturns the collection of DataTable objects.
Following table shows some important methods of the DataSet class:
MethodsDescription
AcceptChangesAccepts all changes made since the DataSet was loaded or this method was called.
BeginInitBegins the initialization of the DataSet. The initialization occurs at run time.
ClearClears data.
CloneCopies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
CopyCopies both the structure and data.
CreateDataReader()Returns a DataTableReader with one result set per DataTable, in the same sequence as the tables appear in the Tables collection.
CreateDataReader(DataTable[])Returns a DataTableReader with one result set per DataTable.
EndInitEnds the initialization of the data set.
Equals(Object)Determines whether the specified Object is equal to the current Object.
FinalizeFree resources and perform other cleanups.
GetChangesReturns a copy of the DataSet with all changes made since it was loaded or the AcceptChanges method was called.
GetChanges(DataRowState)Gets a copy of DataSet with all changes made since it was loaded or the AcceptChanges method was called, filtered by DataRowState.
GetDataSetSchemaGets a copy of XmlSchemaSet for the DataSet.
GetObjectDataPopulates a serialization information object with the data needed to serialize the DataSet.
GetTypeGets the Type of the current instance.
GetXMLReturns the XML representation of the data.
GetXMLSchemaReturns the XSD schema for the XML representation of the data.
HasChanges()Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows.
HasChanges(DataRowState)Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows, filtered by DataRowState.
IsBinarySerializedInspects the format of the serialized representation of the DataSet.
Load(IDataReader, LoadOption, DataTable[])Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.
Load(IDataReader, LoadOption, String[])Fills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet.
Merge()Merges the data with data from another DataSet. This method has different overloaded forms.
ReadXML()Reads an XML schema and data into the DataSet. This method has different overloaded forms.
ReadXMLSchema(0Reads an XML schema into the DataSet. This method has different overloaded forms.
RejectChangesRolls back all changes made since the last call to AcceptChanges.
WriteXML()Writes an XML schema and data from the DataSet. This method has different overloaded forms.
WriteXMLSchema()Writes the structure of the DataSet as an XML schema. This method has different overloaded forms.

The DataTable Class:

The DataTable class represents the tables in the database. It has the following important properties; most of these properties are read only properties except the PrimaryKey property:
PropertiesDescription
ChildRelationsReturns the collection of child relationship.
ColumnsReturns the Columns collection.
ConstraintsReturns the Constraints collection.
DataSetReturns the parent DataSet.
DefaultViewReturns a view of the table .
ParentRelationsReturns the ParentRelations collection.
PrimaryKeyGets or sets an array of columns as the primary key for the table.
RowsReturns the Rows collection.
Following table shows some important methods of the DataTable class:
MethodsDescription
AcceptChangesCommits all changes since the last AcceptChanges.
ClearClears all data from the table.
GetChangesReturns a copy of the DataTable with all changes made since the AcceptChanges method was called.
GetErrorsReturns an array of rows with errors.
ImportRowsCopies a new row into the table.
LoadDataRowFinds and updates a specific row, or creates a new one, if not found any.
MergeMerges the table with another DataTable.
NewRowCreates a new DataRow.
RejectChangesRolls back all changes made since the last call to AcceptChanges.
ResetResets the table to its original state.
SelectReturns an array of DataRow objects.

The DataRow Class:

The DataRow object represents a row in a table. It has the following important properties:
PropertiesDescription
HasErrorsIndicates if there are any errors .
ItemsGets or sets the data stored in a specific column .
ItemArraysGets or sets all the values for the row.
TableReturns the parent table .
Following table shows some important methods of the DataRow class:
MethodsDescription
AcceptChangesAccepts all changes made since this method was called.
BeginEditBegins edit operation.
CancelEditCancels edit operation.
DeleteDeletes the DataRow .
EndEditEnds the edit operation.
GetChildRowsGets the child rows of this row.
GetParentRowGets the parent row.
GetParentRowsGets parent rows of DataRow object.
RejectChangesRolls back all changes made since the last call to AcceptChanges.

The DataAdapter Object:

The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the data set to contain data from more than one database or other data source.

The DataReader Object:

The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a connection oriented access to the data records in the database. These objects are suitable for read-only accesses, such as populating a list and then breaking the connection.

DbCommand and DbConnection Objects:

The DbConnection object represents a connection to the data source. The connection could be shared among different command objects.
The DbCommand object represents the command or a stored procedure sent to the database from retrieving or manipulating data.

Example:

So far, we have used tables and databases already existing in our computer. In this example, we will create a table, add column, rows and data into it and display the table using a GridView object.
The source file:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="createdatabase._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:GridView ID="GridView1" runat="server">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
The code behind file:
namespace createdatabase
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            DataSet ds = CreateDataSet();
            GridView1.DataSource = ds.Tables["Student"];
            GridView1.DataBind();
         }
      }
      private DataSet CreateDataSet()
      {
         //creating a DataSet object for tables
         DataSet dataset = new DataSet();

         // creating the student table
         DataTable Students = CreateStudentTable();
         dataset.Tables.Add(Students);
         return dataset;
      }
      private DataTable CreateStudentTable()
      {
         DataTable Students = new DataTable("Student");

         // adding columns
         AddNewColumn(Students, "System.Int32", "StudentID");
         AddNewColumn(Students, "System.String", "StudentName");
         AddNewColumn(Students, "System.String", "StudentCity");

         // adding rows
         AddNewRow(Students, 1, "M H Kabir", "Kolkata");
         AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
         AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
         AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
         AddNewRow(Students, 1, "Rajat Mishra", "Patna");

         return Students;
      }

      private void AddNewColumn(DataTable table, 
                                string columnType, 
                                string columnName)
      {
         DataColumn column = table.Columns.Add(columnName, 
                                 Type.GetType(columnType));
      }

      //adding data into the table
      private void AddNewRow(DataTable table, int id, 
                            string name, string city)
      {
         DataRow newrow = table.NewRow();
         newrow["StudentID"] = id;
         newrow["StudentName"] = name;
         newrow["StudentCity"] = city;
         table.Rows.Add(newrow);
      }
   }
}
When you run the program observe the following:
  • The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control.
  • The Createdataset() method is a user defined function, which creates a new DataSet object and then calls anther user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set.
  • The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows for the table as well as to add data to the rows.
When the page is run, it returns the rows of the table so created:
ADO.Net Result


ASP.NET - File Uploading

ASP.Net has two controls that allow the users to upload files to the web server. Once the server receives the posted file data, the application can save it, check it or ignore it. The following controls allow the file uploading:
  • HtmlInputFile - an HTML server control
  • FileUpload - and ASP.Net web control
Both the controls allow file uploading, but the FileUpload control automatically sets the encoding of the form, whereas the HtmlInputFile does not do so.
In this tutorial, we will use the FileUpload control. The FileUpload control allows the user to browse for and select the file to be uploaded, providing a Browse button and a text box for entering the filename.
Once, the user has entered the filename in the text box, by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax for using the FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />
The FileUpload class is derived from the WebControl class, and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:
PropertiesDescription
FileBytesReturns an array of the bytes in a file to be uploaded..
FileContentReturns the stream object pointing to the file to be uploaded.
FileNameReturns the name of the file to be uploaded.
HasFileSpecifies whether the control has a file to upload.
PostedFileReturns a reference to the uploaded file.
The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following important properties, which are much used:
PropertiesDescription
ContentLengthReturns the size of the uploaded file in bytes.
ContentTypeReturns the MIME type of the uploaded file
FileNameReturns the full filename.
InputStreamReturns a stream object pointing to the uploaded file.

Example:

The following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type and file length.
In the design view, the form looks like:
File Upload
The content file:
<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
   <asp:FileUpload ID="FileUpload1" runat="server" />
   <br /><br />
   <asp:Button ID="btnsave" runat="server" 
               onclick="btnsave_Click" Text="Save" 
               Width="85px" />
   <br /><br />
   <asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>
The code behind the save button:
protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   if (FileUpload1.HasFile)
   {
      try
      {
      sb.AppendFormat(" Uploading file: {0}", 
                                  FileUpload1.FileName);
      //saving the file
      FileUpload1.SaveAs("<c:\\SaveDirectory>" + 
                                  FileUpload1.FileName);
      //Showing the file information
      sb.AppendFormat("<br/> Save As: {0}", 
                         FileUpload1.PostedFile.FileName);
      sb.AppendFormat("<br/> File type: {0}",   
                         FileUpload1.PostedFile.ContentType);
      sb.AppendFormat("<br/> File length: {0}", 
                         FileUpload1.PostedFile.ContentLength);
      sb.AppendFormat("<br/> File name: {0}", 
                         FileUpload1.PostedFile.FileName);
      }
      catch (Exception ex)
      {
      sb.Append("<br/> Error <br/>");
      sb.AppendFormat("Unable to save file <br/> {0}", 
                         ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}
Note the following:
  • The StringBuilder class is derived from System.IO namespace, so it should be included.
  • The try and catch blocks are used for catching errors, and display the error message.


ASP.NET - Ad Rotator

The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in AdvertisementFile and Target property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator  runat = "server" 
                AdvertisementFile = "adfile.xml"  
                Target = "_blank" />
Before going into details of the AdRotator control and its properties, let us look into the construction of the advertisement file.

The Advertisement File:

The advertisement file is an XML file, which contains the information about the advertisements to be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup language that enables you to store data in a structured format by using meaningful tags. The term 'extensible' implies that you can extend you ability to describe a document by defining meaningful tags for your application.
XML is not a language in itself, like HTML but, a set of rules for creating new markup languages. It is a meta-markup language. It allows developers to create custom tag sets for special uses. It structures, stores and transport information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined tags delineating the data. There are the following standard XML elements that are commonly used in the advertisement file:
ElementDescription
AdvertisementsEncloses the advertisement file
AdDelineates separate ad
ImageUrlThe image that will be displayed
NavigateUrlThe link that will be followed when the user clicks the ad
AlternateTextThe text that will be displayed instead of the picture if it cannot be displayed
KeywordKeyword identifying a group of advertisements. This is used for filtering
ImpressionsThe number indicating how often an advertisement will appear
HeightHeight of the image to be displayed
WidthWidth of the image to be displayed
Apart from these tags, customs tags with custom attributes could also be included. The following code illustrates an advertisement file ads.xml:
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
   Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>

Properties and events of the AdRotator Class:

The AdRotator class is derived from the WebControl class and inherits its properties. Apart from those the AdRotator class has the following properties:
PropertiesDescription
AdvertisementFileThe path to the advertisement file.
AlternateTextFeildThe element name of the field where alternate text is provided; default value is AlternateText.
DataMemberThe name of the specific list of data to be bound when advertisement file is not used.
DataSourceControl from where it would retrieve data.
DataSourceIDId of the control from where it would retrieve data.
FontSpecifies the font properties associated with the advertisement banner control.
ImageUrlFieldThe element name of the field where the URL for the image is provided; default value is ImageUrl.
KeywordFilterFor displaying the keyword based ads only.
NavigateUrlFieldThe element name of the field where the URL to navigate to is provided; default value is NavigateUrl.
TargetThe browser window or frame that displays the content of the page linked.
UniqueIDObtains the unique, hierarchically qualified identifier for the AdRotator control.
Following are the important events of the AdRotator Class:
EventsDescription
AdCreatedIt is raised once per round trip to the server after creation of the control, but before the page is rendered
DataBindingOccurs when the server control binds to a data source.
DataBoundOccurs after the server control binds to a data source.
DisposedOccurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested
InitOccurs when the server control is initialized, which is the first step in its lifecycle.
LoadOccurs when the server control is loaded into the Page object.
PreRenderOccurs after the Control object is loaded but prior to rendering.
UnloadOccurs when the server control is unloaded from memory.

Working with the AdRotator Control

Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
   <asp:AdRotator ID="AdRotator1" 
                runat="server" AdvertisementFile ="~/ads.xml"
                onadcreated="AdRotator1_AdCreated" />
  
</div>
</form>
The ads.xml file and the image files should be located in the root directory of the web site.
Try to run the above application an dobserve that each time the page is reloaded, the ad is changed.

ASP.NET - Calendars

The calendar control is a functionally rich web control, which provides the following capabilities:
  • Displaying one month at a time
  • Selecting a day, a week or a month
  • Selecting a range of days
  • Moving from month to month
  • Controlling the display of the days programmatically
The basic syntax for adding a calendar control is:
<asp:Calender ID = "Calendar1" runat = "server"></asp:Calender>

Properties and Events of the Calendar Control

The calendar control has many properties and events, using which you can customize the actions and display of the control. The following table provides some important properties of the Calendar control:
PropertiesDescription
CaptionGets or sets the caption for the calendar control.
CaptionAlignGets or sets the alignment for the caption.
CellPaddingGets or sets the number of space between the data and the cell.s border.
CellSpacingGets or sets the space between cells.
DayHeaderStyleGets the style properties for the section that displays the day of the week.
DayNameFormatGets or sets format of days of the week.
DayStyleGets the style properties for the days in the displayed month.
FirstDayOfWeekGets or sets the day of week to display in the first column.
NextMonthTextGets or sets the text for next month navigation control; default value is >
NextPrevFormatGets or sets the format of the next and previous month navigation control.
OtherMonthDayStyleGets the style properties for the days on the Calendar control that are not in the displayed month.
PrevMonthTextGets or sets the text for previous month navigation control; default value is <
SelectedDateGets or sets the selected date.
SelectedDatesGets a collection of DateTime objects representing the selected dates.
SelectedDayStyleGets the style properties for the selected dates.
SelectionModeGets or sets the selection mode that specifies whether the user can select a single day, a week or an entire month.
SelectMonthTextGets or sets the text for the month selection element in the selector column.
SelectorStyleGets the style properties for the week and month selector column.
SelectWeekTextGets or sets the text displayed for the week selection element in the selector column.
ShowDayHeaderGets or sets the value indicating whether the heading for the days of the week is displayed.
ShowGridLinesGets or sets the value indicating whether the gridlines would be shown.
ShowNextPrevMonthGets or sets a value indicating whether next and previous month navigation elements are shown in the title section.
ShowTitleGets or sets a value indicating whether the title section is displayed.
TitleFormatGets or sets the format for the title section.
TitlestyleGet the style properties of the title heading for the Calendar control.
TodayDayStyleGets the style properties for today's date on the Calendar control.
TodaysDateGets or sets the value for today.s date.
UseAccessibleHeaderGets or sets a value that indicates whether to render the table header <th> HTML element for the day headers instead of the table data <td> HTML element.
VisibleDateGets or sets the date that specifies the month to display.
WeekendDayStyleGets the style properties for the weekend dates on the Calendar control.
The Calendar control has the following three most important events that allow the developers to program the calendar control. These are:
EventsDescription
SelectionChangedIt is raised when a day, a week or an entire month is selected
DayRenderIt is raised when each data cell of the calendar control is rendered.
VisibleMonthChangedIt is raised when user changes a month

Working with the Calendar Control

Putting a bare-bone calendar control without any code behind file provides a workable calendar to a site, which shows the month and days of the year. It also allows navigating to next and previous months.
Calendar
Calendar controls allow the users to select a single day, a week or an entire month. This is done by using the SelectionMode property. This property has the following values:
PropertiesDescription
DayTo select a single day
DayWeekTo select a single day or an entire week
DayWeekMonthTo select a single day, a week or an entire month
NoneNothing can be selected
The syntax for selecting days:
<asp:Calender ID = "Calendar1" 
                 runat = "server"
                 SelectionMode="DayWeekMonth">
</asp:Calender>
When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol appears for selecting the week and a >> symbol appears to the left of the days' name for selecting the month.
Calendar2

Example:

The following example demonstrates selecting a date and displays the date in a label:
The content file:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="calendardemo._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> Your Birthday:</h3>
        <asp:Calendar ID="Calendar1" 
             runat="server" 
             SelectionMode="DayWeekMonth"
             onselectionchanged="Calendar1_SelectionChanged">
        </asp:Calendar>
    </div>
    <p>Todays date is: 
        <asp:Label ID="lblday" runat="server"></asp:Label>
    </p>
    <p>Your Birday is: 
        <asp:Label ID="lblbday" runat="server"></asp:Label>
    </p>
    </form>
</body>
</html>
The event handler for the event SelectionChanged:
protected void Calendar1_SelectionChanged(object sender, 
                                          EventArgs e)
{
    lblday.Text = Calendar1.TodaysDate.ToShortDateString();
    lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}
When the file run should produce the following output:
Calendar3


ASP.NET - AJAX Control

AJAX stands for Asynchronous JavaScript and XML. This is a cross platform technology which speeds up response time. The AJAX server controls add script to the page which is executed and processed by the browser.
However like other ASP.Net server controls, these AJAX server controls also can have methods and event handlers associated with them, which are processed on the server side.
The control toolbox in the Visual Studio IDE contains a group of controls called the 'AJAX Extensions'
AJAX Extensions

The ScriptManager Control

The ScriptManager control is the most important control and must be present on the page for other controls to work.
It has the basic syntax:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If you create an 'Ajax Enabled site' or add an 'AJAX Web Form' from the 'Add Item' dialog box, the web form automatically contains the script manager control. The ScriptManager control takes care of the client-side script for all the server side controls.

The UpdatePanel Control:

The UpdatePanel control is a container control and derives from the Control class. It acts as a container for the child controls within it and does not have its own interface. When a control inside it triggers a post back, the UpdatePanel intervenes to initiate the post asynchronously and update just that portion of the page.
For example, if a button control is inside the update panel and it is clicked, only the controls within the update panel will be affected, the controls on the other parts of the page will not be affected. This is called the partial post back or the asynchronous post back.

Example:

Add an AJAX web form in your application. It will contain the script manager control by default. Insert an update panel. Place a button control along with a label control within the update panel control. Place another set of button and label outside the panel.
The design view looks as follows:
ScriptManager
The source file is as follows:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnpartial" runat="server" 
            onclick="btnpartial_Click" Text="Partial PostBack"/>
<br />
<br />
<asp:Label ID="lblpartial" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<p>
 </p>
<p>
Outside the Update Panel</p>
<p>
<asp:Button ID="btntotal" runat="server" 
    onclick="btntotal_Click" Text="Total PostBack" />
</p>
<asp:Label ID="lbltotal" runat="server"></asp:Label>
</form>
Both the button controls have same code for the event handler:
string time = DateTime.Now.ToLongTimeString();
lblpartial.Text = "Showing time from panel" + time;
lbltotal.Text = "Showing time from outside" + time;
Observe that when the page is run, if the total post back button is clicked, it updates time in both the labels but if the partial post back button is clicked, it only updates the label within the update panel.
update panel
A page can contain more than one update panel with each panel containing other controls like a grid and displaying different part of data.
When a total post back occurs, the content of the update panel is updated by default. This default mode could be changed by changing the UpdateMode property of the control. Let us look at other properties of the update panel.

Properties of the UpdatePanel Control:

The following table shows the properties of the update panel control:
PropertiesDescription
ChildrenAsTriggersThis property indicates whether the post backs are coming from the child controls which will cause the update panel to refresh.
ContentTemplateIt is the content template and defines what appears in the update panel when it is rendered.
ContentTemplateContainerRetrieves the dynamically created template container object and used for adding child controls programmatically.
IsInPartialRenderingIndicates whether the panel is being updated as part of the partial post back.
RenderModeShows the render modes. The available modes are Block and Inline.
UpdateModeGets or sets the rendering mode by determining some conditions.
TriggersDefines the collection trigger objects each corresponding to an event causing the panel to refresh automatically.

Methods of the UpdatePanel Control:

The following table shows the methods of the update panel control:
MethodsDescription
CreateContentTemplateContainerCreates a Control object that acts as a container for child controls that define the UpdatePanel control's content.
CreateControlCollectionReturns the collection of all controls that are contained in the UpdatePanel control.
InitializeInitializes the UpdatePanel control trigger collection if partial-page rendering is enabled.
UpdateCauses an update of the content of an UpdatePanel control.
The behaviour of the update panel depends upon the values of the UpdateMode property and ChildrenAsTriggers property:
UpdateModeChildrenAsTriggersEffect
AlwaysFalseIllegal parameters.
AlwaysTrueUpdatePanel refreshes if whole page refreshes or a child control on it posts back.
ConditionalFalseUpdatePanel refreshes if whole page refreshes or a triggering control outside it initiates a refresh.
ConditionalTrueUpdatePanel refreshes if whole page refreshes or a child control on it posts back or a triggering control outside it initiates a refresh.

The UpdateProgress Control:

The UpdateProgress control provides a sort of feedback on the browser while one or more update panel controls are being updated. For example while a user logs in or waits for server response while performing some database oriented job.
It provides a visual acknowledgement like "Loading page...", indicating the work is in progress.
The syntax for the UpdateProgress control is:
<asp:UpdateProgress ID="UpdateProgress1" 
              runat="server" 
              DynamicLayout="true" 
              AssociatedUpdatePanelID="UpdatePanel1" >
<ProgressTemplate>
   Loading...
</ProgressTemplate>
</asp:UpdateProgress>
The above snippet shows a simple message within the ProgressTemplate tag, however it could be an image or other relevant controls. The UpdateProgress control will display for every asynchronous postback unless it is assigned to a single update panel using the AssociatedUpdatePanelID property.

Properties of the UpdateProgress Control

The following table shows the properties of the update progress control:
PropertiesDescription
AssociatedUpdatePanelIDGets and sets the ID of the update panel with which this control is associated.
AttributesGets or sets the cascading style sheet (CSS) attributes of the UpdateProgress control.
DisplayAfterGets and sets the time in milliseconds after which the progress template is displayed. The default is 500.
DynamicLayoutIndicates whether the progress template is dynamically rendered.
ProgressTemplateIndicates the template displayed during an asynchronous post back which takes more time than the DisplayAfter time.

Methods of the UpdateProgress Control

The following table shows the methods of the update progress control:
MethodsDescription
GetScriptDescriptorsReturns a list of components, behaviors, and client controls that are required for the UpdateProgress control's client functionality.
GetScriptReferencesReturns a list of client script library dependencies for the UpdateProgress control.

The Timer Control:

The timer control is used to initiate the post back automatically. This could be done in two ways:
(1) Setting the Triggers property of the UpdatePanel control:
<Triggers>
<asp:AsyncPostBackTrigger 
                ControlID="btnpanel2" 
                EventName="Click" />
</Triggers>
(2) Placing a timer control directly inside the UpdatePanel to act as a child control trigger. A single timer can be the trigger for multiple UpdatePanels.
<asp:UpdatePanel ID="UpdatePanel1" 
                 runat="server" 
                 UpdateMode="Always">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
<asp:Label ID="Label1" runat="server" 
           Height="101px" Width="304px">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>


ASP.NET - Error Handling

Error handling in ASP.Net has three aspects:
  1. Tracing - tracing the program execution at page level or application level.
  2. Error handling - handling standard errors or custom errors at page level or application level
  3. Debugging - stepping through the program, setting break points to analyze the code
In this tutorial, we are going to discuss tracing and error handling and we will look into debugging in the next tutorial.
To understand the concepts, create the following sample application. It has a label control, a dropdown list and a link. The dropdown list loads an array list of famous quotes and the selected quote is shown in the label below. It also has a hyperlink which has a nonexistent link.
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="errorhandling._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>Tracing, debugging and error handling</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblheading" runat="server" 
            Text="Tracing, Debuggin and Error Handling">
        </asp:Label>
        <br />
        <br />
        <asp:DropDownList ID="ddlquotes" 
        runat="server" AutoPostBack="True" 
        onselectedindexchanged="ddlquotes_SelectedIndexChanged">
        </asp:DropDownList>
        <br />
        <br />
        <asp:Label ID="lblquotes" runat="server">
        </asp:Label>
        <br />
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" 
        NavigateUrl="mylink.htm">Link to:</asp:HyperLink>
    </div>
    </form>
</body>
</html>
The code behind file:
public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         string[,] quotes = 
        {
        {"Imagination is more important than Knowledge.", 
         "Albert Einsten"},
        {"Assume a virtue, if you have it not",
         "Shakespeare"},
        {"A man cannot be comfortable without his own 
         approval", "Mark Twain"},
        {"Beware the young doctor and the old barber",
         "Benjamin Franklin"},
       {"Whatever begun in anger ends in shame",
         "Benjamin Franklin"}
     };
     for (int i=0; i<quotes.GetLength(0); i++)
        ddlquotes.Items.Add(new ListItem(quotes[i,0], 
        quotes[i,1]));
     }
   }
   protected void ddlquotes_SelectedIndexChanged(object sender, 
                                                 EventArgs e)
   {
     if (ddlquotes.SelectedIndex != -1)
     {
       lblquotes.Text = String.Format("{0}, Quote: {1}", 
          ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue);
     }
   }
}

Tracing:

To enable page level tracing, you need to modify the Page directive and add a Trace attribute as:
<%@ Page Language="C#" AutoEventWireup="true" 
            CodeBehind="Default.aspx.cs"
            Inherits="errorhandling._Default"
            Trace ="true" %>
Now when you run the file, you get the tracing information:
Tracing Info
It provides the following information at the top:
  • Session ID
  • Status Code
  • Time of Request
  • Type of Request
  • Request and Response Encoding
The status code sent from the server, each time the page is requested shows the name and time of error if any. The following table shows the common HTTP status codes :
NumberDescription
Informational (100 - 199)
100Continue
101Switching protocols
Successful (200 - 299)
200OK
204No content
Redirection (300 - 399)
301Moved permanently
305Use proxy
307Temporary redirect
Client Errors (400 - 499)
400Bad request
402Payment required
404Not found
408Request timeout
417Expectation failed
Server Errors (500 - 599)
500Internal server error
503Service unavailable
505HTTP version not supported
Under the top level information is the Trace log, which provides details of page life cycle. It provides elapsed time in seconds since the page was initialized.
Tracing Info2
The next section is control tree, which lists all controls on the page in a hierarchical manner:
Tracing Info3
Last in the Session and Application state summaries, cookies and headers collections, followed by list of all server variables.
The Trace object allows you to add custom information to the trace output. It has two methods to accomplish this: the Write method and the Warn method.
Change the Page_Load event handler to check the Write method:
protected void Page_Load(object sender, EventArgs e)
{
   Trace.Write("Page Load");
   if (!IsPostBack)
   {
      Trace.Write("Not Post Back, Page Load");
      string[,] quotes = 
.......................
Run to observe the effects:
Tracing Info4
To check the Warn method, let us forcibly enter some erroneous code in the selected index changed event handler:
try
{
   int a = 0;
   int b = 9 / a;
}
catch (Exception e)
{
   Trace.Warn("UserAction", "processing 9/a", e);
}
Try-Catch is a C# programming construct. The try block holds any code that may or may not produce error and the catch block catches the error. When the program is run, it sends the warning in the trace log.
Tracing Info5
Application level tracing applies to all the pages in the web site. It is implemented by putting the following code lines in the web.config file:
<system.web>
<trace enabled="true" />
</system.web>

Error Handling:

Although ASP.Net can detect all runtime errors, still some subtle errors may still be there. Observing the errors by tracing is meant for the developers, not for the users.
Hence, to intercept such occurrence, you can add error handing settings in the web.config file of the application. It is application wide error handling. For example, you can add the following lines in the web.config file:
<configuration>
	<system.web>
	<customErrors mode="RemoteOnly"
		defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"	/>
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
<configuration>
The <customErrors> section has the possible attributes:
  • Mode: It enables or disables custom error pages. It has the three possible values:
    • On: displays the custom pages.
    • Off: displays ASP.Net error pages (yellow pages)
    • remoteOnly: displays custom errors to client, display ASP.Net errors locally
  • defaultRedirect: It contains the URL of the page to be displayed in case of unhandled errors.
To put different custom error pages for different type of errors, the <error> sub tags are used, where different error pages are specified, based of the status code of the errors.
To implement page level error handling, the Page directive could be modified:
<%@ Page Language="C#" AutoEventWireup="true" 
            CodeBehind="Default.aspx.cs"
            Inherits="errorhandling._Default"
            Trace ="true" 
            ErrorPage="PageError.htm" %>


ASP.NET - Data Sources Controls

A data source control interacts with the data-bound controls and hides the complex data binding processes. These are the tools that provide data to the data bound controls and support execution of operations like insertions, deletions, sorting and updates.
Each data source control wraps a particular data provider-relational databases, XML documents or custom classes and helps in:
  • Managing connection.
  • Selection of data
  • Managing presentation aspects like paging, caching etc.
  • Manipulation of data
There are many data source controls available in ASP.Net for accessing data from SQL Server, from ODBC or OLE DB servers, from XML files and from business objects.
Based on type of data, these controls could be divided into two categories: hierarchical data source controls and table-based data source controls.
The data source controls used for hierarchical data are:
  • XMLDataSource-allows binding to XML files and strings with or without schema information
  • SiteMapDataSource-allows binding to a provider that supplies site map information
The data source controls used for tabular data are:
Data source controlsDescription
SqlDataSourcerepresents a connection to an ADO.Net data provider that returns SQL data, including data sources accessible via OLEDB and QDBC
ObjectDataSourceallows binding to a custom .Net business object that returns data
LinqdataSourceallows binding to the results of a Linq-to-SQL query (supported by ASP.Net 3.5 only)
AccessDataSourcerepresents connection to a Microsoft Access database

The Data Source Views

Data source views are objects of the DataSourceView class and represent a customized view of data for different data operations like sorting, filtering etc.
The DataSourceView class serves as the base class for all data source view classes, which define the capabilities of data source controls.
Following table provides the properties of the DataSourceView class:
PropertiesDescription
CanDeleteIndicates whether deletion is allowed on the underlying data source.
CanInsertIndicates whether insertion is allowed on the underlying data source.
CanPageIndicates whether paging is allowed on the underlying data source.
CanRetrieveTotalRowCountIndicates whether total row count information is available.
CanSortIndicates whether the data could be sorted.
CanUpdateIndicates whether updates are allowed on the underlying data source.
EventsGets a list of event-handler delegates for the data source view.
NameName of the view.
Following table provides the methods of the DataSourceView class:
MethodsDescription
CanExecuteDetermines whether the specified command can be executed.
ExecuteCommandExecutes the specific command.
ExecuteDeletePerforms a delete operation on the list of data that the DataSourceView object represents.
ExecuteInsertPerforms an insert operation on the list of data that the DataSourceView object represents.
ExecuteSelectGets a list of data from the underlying data storage.
ExecuteUpdatePerforms an update operation on the list of data that the DataSourceView object represents.
DeletePerforms a delete operation on the data associated with the view.
InsertPerforms an insert operation on the data associated with the view.
SelectReturns the queried data.
UpdatePerforms an update operation on the data associated with the view.
OnDataSourceViewChangedRaises the DataSourceViewChanged event.
RaiseUnsupportedCapabilitiesErrorCalled by the RaiseUnsupportedCapabilitiesError method to compare the capabilities requested for an ExecuteSelect operation against those that the view supports.

The SqlDataSource Control

The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two important properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax for the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" runat="server" 
                             DataSourceID="MySqlSource">
Configuring various data operations on the underlying data depends upon the various properties (property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource control, which provides the programming interface of the control:
Property GroupDescription
DeleteCommand,
DeleteParameters,
DeleteCommandType
Gets or sets the SQL statement, parameters and type for deleting rows in the underlying data.
FilterExpression,
FilterParameters
Gets or sets the data filtering string and parameters.
InsertCommand,
InsertParameters,
InsertCommandType
Gets or sets the SQL statement, parameters and type for inserting rows in the underlying database.
SelectCommand,
SelectParameters,
SelectCommandType
Gets or sets the SQL statement, parameters and type for retrieving rows from the underlying database.
SortParameterNameGets or sets the name of an input parameter that the command's stored procedure will use to sort data
UpdateCommand,
UpdateParameters,
UpdateCommandType
Gets or sets the SQL statement, parameters and type for updating rows in the underlying data store.
The following code snippet shows a data source control enabled for data manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName  %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
.....
.....
</asp:SqlDataSource>

The ObjectDataSource Control:

The ObjectDataSource Control enables user-defined classes to associate the output of their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource control.
Following are two important aspects of binding business objects:
  • The bindable class should have a default constructor, be stateless, and have methods that can be mapped to select, update, insert and delete semantics.
  • The object must update one item at a time, batch operations are not supported.
Let us go directly to an example to work with this control. The student class is our class to be used with an object data source. This class has three properties: a student id, name and city. It has a default constructor and a GetStudents method to be used for retrieving data.
The student class:
public class Student
{
   public int StudentID { get; set; }
   public string Name { get; set; }
   public string City { get; set; }
   public Student()
   { }
   public DataSet GetStudents()
   {
      DataSet ds = new DataSet();
      DataTable dt = new DataTable("Students");
      dt.Columns.Add("StudentID", typeof(System.Int32));
      dt.Columns.Add("StudentName", typeof(System.String));
      dt.Columns.Add("StudentCity", typeof(System.String));
      dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
      dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
      ds.Tables.Add(dt);
      return ds;
   }
}
Take the following steps to bind the object with an object data source and retrieve data:
  • Create a new web site. Add a class (Students.cs) to it by right clicking the project from the Solution Explorer, adding a class template and placing the above code in it.
  • Build the solution so that the application can use the reference to the class.
  • Place a object data source control in the web form.
  • Configure the data source by selecting the object.
selecting the object
  • Select a data method(s) for different operations on data. In this example, there is only one method.
Select a data method
  • Place a data bound control like grid view on the page and select the object data source as its underlying data source
Data Bound Control
  • At this stage, the design view should look like the following:
Object Data Source
  • Run the project, it retrieves the hard coded tuples from the students class.
Object Data Result

The AccessDataSource Control:

The AccessDataSource control represents a connection to an Access database. It is based on the SqlDataSource control and provides simpler programming interface. The following code snippet provides the basic syntax for the data source:
<asp:AccessDataSource ID="AccessDataSource1" 
            runat="server" 
            DataFile="~/App_Data/ASPDotNetStepByStep.mdb" 
            SelectCommand="SELECT * FROM [DotNetReferences]">
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it can also be used for performing insert, update or delete operations. This is done using the ADO.Net commands and parameter collection.
Updates are problematic for Access databases from within an ASP.Net application because an Access database is a plain file and the default account of the ASP.Net application might not have the permission to write to the database file.

ASP.NET - Data Binding

Every ASP.Net web form control inherits the DataBind method from its parent Control class, which gives it an inherent capability to bind data to at least one of its properties. This is known as simple data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into their structure through a DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative data binding.
The data source controls help the data-bound controls implement functionalities like, sorting, paging and editing data collections. We have already seen declarative data binding in the previous tutorial.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
  • DataBoundControl
  • HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
  • ListControl
  • CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these controls are:
  • BulletedList
  • CheckBoxList
  • DropDownList
  • ListBox
  • RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the abstract class CompositeDataBoundControl. These controls are:
  • DetailsView
  • FormView
  • GridView
  • RecordList

Simple Data Binding:

Simple data binding involves the read-only selection lists. These controls can bind to an array list or fields from a database. Selection lists takes two values from the database or the data source; one value is displayed by the list and the other is considered as the value corresponding to the display.
Let us take up a small example to understand the concept. Create a web site with a bulleted list and a SqlDataSource control on it. Configure the data source control to retrieve two values from your database (we will be using the same DotNetReferences table as in the previous chapter).
Choosing a data source for the bulleted list control involves:
  • Selecting the data source control
  • Selecting a field to display, which is called the data field
  • Selecting a field for the value
Choose Data Source
When the application is run, check that the entire title column is bound to the bulleted list and displayed.
Choose Data Source2

Declarative Data Binding:

We have already used declarative data binding in the previous tutorial using GridView control. The other composite data bound controls capable of displaying and manipulating data in a tabular manner are the DetailsView, FormView and RecordList control.
In the next tutorial, we will look into the technology for handling database, i.e, ADO.Net.
However, the data binding involves the following objects:
  • A dataset that stores the data retrieved from the database
  • The data provider, which retrieves data from the database, using a command over a connection
  • The data adapter that issues the select statement stored in the command object; it is also capable of update the data in a database by issuing Insert, Delete, and Update statements.
Relation between the data binding objects:
Declarative Data Binding

Example:

Take the following steps:
Step (1): Create a new website. Add a class named booklist by right clicking on the solution name in the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it booklist.cs
using System;
using System.Data;
using System.Configuration;
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 databinding
{
    public class booklist
    {
        protected String bookname;
        protected String authorname;
        public booklist(String bname, String aname)
        {
            this.bookname = bname;
            this.authorname = aname;

        }
        public String Book
        {
            get
            {
                return this.bookname;
            }
            set
            {
                this.bookname = value;
            }
        }
        public String Author
        {
            get
            {
                return this.authorname;
            }
            set
            {
                this.authorname = value;
            }
        }
    }
}
Step (2): Add four list controls on the page-a list box control, a radio button list, a check box list and a drop down list and four labels along with these list controls. The page should look like this in design view:
List box control
The source file should look as the following:
<form id="form1" runat="server">
<div>
<table style="width: 559px">
<tr>
<td style="width: 228px; height: 157px;">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" 
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox></td>
<td style="height: 157px">
<asp:DropDownList ID="DropDownList1" runat="server" 
AutoPostBack="True" 
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>             
</tr>
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<td style="height: 40px">
<asp:Label ID="lbldrpdown" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td style="width: 228px; height: 21px">
</td>
<td style="height: 21px">
</td>              
</tr>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
                      AutoPostBack="True" 
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList></td>
<td style="height: 21px">
<asp:CheckBoxList ID="CheckBoxList1" runat="server" 
            AutoPostBack="True" 
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList></td>                
</tr>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label></td>
<td style="height: 21px">
<asp:Label ID="lblchklist" runat="server">
</asp:Label></td>           
</tr>
</table>       
</div>
</form>
Step (3): Finally write the following code behind routines for the application:
public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      IList bklist = createbooklist();
      if (!this.IsPostBack)
      {
         this.ListBox1.DataSource = bklist;
         this.ListBox1.DataTextField = "Book";
         this.ListBox1.DataValueField = "Author";
         this.DropDownList1.DataSource = bklist;
         this.DropDownList1.DataTextField = "Book";
         this.DropDownList1.DataValueField = "Author";
         this.RadioButtonList1.DataSource = bklist;
         this.RadioButtonList1.DataTextField = "Book";
         this.RadioButtonList1.DataValueField = "Author";
         this.CheckBoxList1.DataSource = bklist;
         this.CheckBoxList1.DataTextField = "Book";
         this.CheckBoxList1.DataValueField = "Author";
         this.DataBind();
      }
   }
   protected IList createbooklist()
   {
      ArrayList allbooks = new ArrayList();
      booklist bl;
      bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");
      allbooks.Add(bl);
      bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");
      allbooks.Add(bl);
      bl = new booklist("DATA STRUCTURE", "TANENBAUM");
      allbooks.Add(bl);
      bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");
      allbooks.Add(bl);
      bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");
      allbooks.Add(bl);
      bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");
      allbooks.Add(bl);
      return allbooks;
   }
   protected void ListBox1_SelectedIndexChanged(object sender, 
                                              EventArgs e)
   {
      this.lbllistbox.Text = this.ListBox1.SelectedValue;
   }
   protected void DropDownList1_SelectedIndexChanged(
                                  object sender, EventArgs e)
   {
      this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
   }
   protected void RadioButtonList1_SelectedIndexChanged(
                                  object sender, EventArgs e)
   {
      this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
   }
   protected void CheckBoxList1_SelectedIndexChanged(
                                   object sender, EventArgs e)
   {
      this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
   }
}
Observe the following:
  • The booklist class has two properties bookname and authorname.
  • The createbooklist method is a user defined method that creates an array of booklist objects named allbooks.
  • The Page_Load event handler ensures that a list of books is created. The list is of IList type, which implements the IEnumerable interface and capable of being bound to the list controls. The page load event handler binds the IList object 'bklist' with the list controls. The bookname property is to be displayed and the authorname property is considered as the value.
  • When the page is run, if the user selects a book, its name is selected and displayed by the list controls whereas the corresponding labels display the author name, which is the corresponding value for the selected index of the list control.
Data Binding Results


ASP.NET - Personalization

Web sites are designed for repeated visits from the users. Personalization allows a site to remember its user and his/her information details and presents an individualistic environment to each user.
ASP.Net provides services for personalizing a web site to suit a particular client's taste and preference.

Understanding Profiles:

ASP.Net personalization service is based on user profile. User profile defines the kind of information about the user that the site will need, for example, name, age, address, date of birth, phone number etc.
This information is defined in the web.config file of the application and ASP.Net runtime reads and uses it. This job is done by the personalization providers.
The user profiles obtained from user data is stored in a default database created by ASP.Net. You can create your own database for storing profiles. The profile data definition is stored in the configuration file web.config.

Example:

Let us create a sample site, where we want our application to remember user details like name, address, date of birth etc. Add the profile details in the web.config file within the <system.web> element.
<profile>
	<properties>
	  <add name="Name" type ="String"/>
	  <add name="Birthday" type ="System.DateTime"/>
	  <group name="Address">
		<add name="Street"/>
		<add name="City"/>
		<add name="State"/>
		<add name="Zipcode"/>
	  </group>
	</properties>
  </profile>
</system.web>
</configuration>
When the profile is defined in the web.config file, the profile could be used through the Profile property found in the current HttpContext and also available via page.
Add the text boxes to take the user input as defined in the profile and add a button for submitting the data:
Personalization
Update Page_load to display profile information :
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!this.IsPostBack)
      {
      ProfileCommon pc=this.Profile.GetProfile(Profile.UserName);
      if (pc != null)
      {
         this.txtname.Text = pc.Name;
         this.txtaddr.Text = pc.Address.Street;
         this.txtcity.Text = pc.Address.City;
         this.txtstate.Text = pc.Address.State;
         this.txtzip.Text = pc.Address.Zipcode;
         this.Calendar1.SelectedDate = pc.Birthday;
       }
       }
    }
}
Write the following handler for the Submit button, for saving the user data into the profile:
protected void btnsubmit_Click(object sender, EventArgs e)
{
  ProfileCommon pc=this.Profile.GetProfile(Profile.UserName);
  if (pc != null)
  {
     pc.Name = this.txtname.Text;
     pc.Address.Street = this.txtaddr.Text;
     pc.Address.City = this.txtcity.Text;
     pc.Address.State = this.txtstate.Text;
     pc.Address.Zipcode = this.txtzip.Text;
     pc.Birthday = this.Calendar1.SelectedDate;
     pc.Save();
  }
}
Observe: When the page is executed for the first time, the user information need to be entered. However, next time the user details would be automatically loaded.

Attributes for the <add> Element

Apart from the name and type attributes that we have used, there are other attributes to the <add> element. Following table illustrates some of these attributes:
AttributesDescription
nameThe name of the property.
typeBy default the type is string but it allows any fully qualified class name as data type.
serializeAsThe format to use when serializing this value.
readOnlyA read only profile value cannot be changed, by default this property is false.
defaultValueA default value that will be used if the profile does not exist or does not have information.
allowAnonymousA Boolean value indicating whether this property can be used with the anonymous profiles.
ProviderThe profiles provider that should be used to manage just this property.

Anonymous Personalization:

Anonymous personalization allows the user to personalize the site before identifying themselves. For example, Amazon.com allows the user to add items in the shopping cart before they log in. To enable this feature, the web.config file could be configured as:
<anonymousIdentification enabled ="true"
cookieName=".ASPXANONYMOUSUSER"
cookieTimeout="120000"
cookiePath="/"
cookieRequiresSSL="false"
cookieSlidingExpiration="true"
cookieprotection="Encryption"
coolieless="UseDeviceProfile"/>


ASP.NET - Debugging

Debugging allows the developers to watch how the code works in a step-by-step manner, how the values of the variables change, how the objects are created and destroyed etc.
When the site is run for the first time, Visual Studio displays a prompt asking whether it should be enabled for debugging:
Debugging Info
When debugging is enabled, the following lines of codes are shown in the web.config:
<system.web>
		<compilation debug="true">
		<assemblies>
		..............
		</assemblies>
		</compilation>	
</system.web>
The Debug toolbar provides all the tools available for debugging:
Debugging toolbar

Breakpoints:

Breakpoints specifies the runtime to run a specific line of code and then stop execution so that the code could be examined and perform various debugging jobs like, changing the value of the variables, step through the codes, moving in and out of functions and methods etc.
To set a breakpoint, right click on the code and choose insert break point. A red dot appears on the left margin and the line of code is highlighted:
Breaking Highlighted
Next when you run the code, you can observe the behavior of the code:
Breaking Highlighted2
At this stage, you can step through the code, observe the execution flow and examine the value of the variables, properties, objects etc.
You can modify the properties of the breakpoint from the Properties menu obtained by right clicking the breakpoint glyph:
Breaking Dropdown
The location dialog box shows the location of the file, line number and the character number of the selected code. The condition menu item allows you to enter a valid expression, which is evaluated when the program execution reaches the breakpoint:
Breaking Condition
The Hit Count menu item displays a dialog box that shows the number of times the break point has been executed.
Breaking Point
Clicking on any option presented by the drop down list will open an edit field where a target hit count is entered. This is particularly helpful in analyzing loop constructs in code.
Breaking Point2
The Filter menu item allows setting a filter for specifying machines, processes or threads or any combination, for which the breakpoint will be effective.
Breaking Filters
The When Hit menu item allows you to specify what to do when the break point is hit.
Breaking Point3

The Debug Windows:

Visual Studio provides the following debug windows – each of which shows some program information. The following table lists the windows:
WindowDescription
ImmediateDisplays variables and expressions.
AutosDisplays all variables in the current and previous statements.
LocalsDisplays all variables in the current context.
WatchDisplays up to four different sets of variables.
Call StackDisplays all methods in the call stack.
ThreadsDisplays and control threads.


ASP.NET - LINQ

Most applications are data-centric and most of these data repositories are however, relational databases. Over the years designers and developers have designed applications based on object models.
These objects were responsible for connecting to the data access components - called the data access layer (DAL). There are however, two things to consider:
  • All the data needed in an application are not stored in the same source. The source could be a relation database, some business objects, XML file, or on web services.
  • Accessing in-memory object is simpler and less expensive than accessing data from a database or XML file.
  • The data accessed are not used directly, but needs to be sorted, ordered, grouped, altered etc.
So if there is one tool that makes all kinds of data access easy, that allows joining data from such disparate data sources and perform standard data processing operations, in few lines of codes, it would be of great help.
LINQ or Language-Integrated Query is such a tool. LINQ is set of extensions to the .Net Framework 3.5 and its managed languages that sets the query as an object. It defines a common syntax and a programming model to query different types of data using a common language.
The relational operators like Select, Project, Join, Group, Partition, Set operations etc., are implemented in LINQ and the C# and VB compilers in the .Net framework 3.5, which support the LINQ syntax makes it possible to work with a configured data store without resorting to ADO.Net.
For example querying the Customers table in the Northwind database, using LINQ query in C#, the code would be:
var data = from c in dataContext.Customers
where c.Country == "Spain"
select c;
Where:
  • The 'from' keyword logically loops through the contents of the collection.
  • The expression with the 'where' keyword is evaluated for each object in the collection.
  • The 'select' statement selects the evaluated object to add to the list being returned.
  • The 'var' keyword is for variable declaration. Since the exact type of the returned object is not known, it indicates that the information will be inferred dynamically.
LINQ query can be applied to any data-bearing class that inherits from IEnumerable<T>, here T is any data type, for example List<Book>.
Let us look at an example to understand the concept. The example uses the following class: Books.cs
public class Books
{
   public string ID {get; set;}
   public string Title { get; set; }
   public decimal Price { get; set; }
   public DateTime DateOfRelease { get; set; }

   public static List<Books> GetBooks()
  {
     List<Books> list = new List<Books>();
     list.Add(new Books { ID = "001", 
     Title = "Programming in C#", 
     Price = 634.76m, 
     DateOfRelease = Convert.ToDateTime("2010-02-05") });
     
     list.Add(new Books { ID = "002", 
     Title = "Learn Jave in 30 days", 
     Price = 250.76m, 
     DateOfRelease = Convert.ToDateTime("2011-08-15") });
     
     list.Add(new Books { ID = "003", 
     Title = "Programming in ASP.Net 4.0", 
     Price = 700.00m, 
     DateOfRelease = Convert.ToDateTime("2011-02-05") });
     
     list.Add(new Books { ID = "004", 
     Title = "VB.Net Made Easy", 
     Price = 500.99m, 
     DateOfRelease = Convert.ToDateTime("2011-12-31") });
     
     list.Add(new Books { ID = "005", 
     Title = "Programming in C", 
     Price = 314.76m, 
     DateOfRelease = Convert.ToDateTime("2010-02-05") });
     
     list.Add(new Books { ID = "006", 
     Title = "Programming in C++", 
     Price = 456.76m, 
     DateOfRelease = Convert.ToDateTime("2010-02-05") });
     
     list.Add(new Books { ID = "007", 
     Title = "Datebase Developement", 
     Price = 1000.76m, 
     DateOfRelease = Convert.ToDateTime("2010-02-05") });
     return list;
  }

}
The web page using this class has a simple label control, which will display the titles of the books. The Page_Load event creates a list of books and returns the titles by using LINQ query:
public partial class simplequery : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      List<Books> books = Books.GetBooks();
      var booktitles = from b in books select b.Title;

      foreach (var title in booktitles)
         lblbooks.Text += String.Format("{0} <br />", title);
   }
}
When the page is run, the label will display the results of the query:
LINQ Result
The above LINQ expression:
var booktitles = 
from b in books 
select b.Title;
Is equivalent to the following SQL query:
SELECT Title from Books

LINQ Operators:

Apart from the operators used so far, there are several other operators, which implement all query clauses. Let us look at some of the operators and clauses.

The Join clause:

The 'join clause' in SQL is used for joining two data tables and displays a data set containing columns from both the tables. LINQ is also capable of that. To check this, add another class named Saledetails.cs in the previous project:
public class Salesdetails
{
   public int sales { get; set; }
   public int pages { get; set; }
   public string ID {get; set;}

   public static IEnumerable<Salesdetails> getsalesdetails()
   { 
      Salesdetails[] sd = 
      {
      new Salesdetails { ID = "001", pages=678, sales = 110000},
      new Salesdetails { ID = "002", pages=789, sales = 60000},
      new Salesdetails { ID = "003", pages=456, sales = 40000},
      new Salesdetails { ID = "004", pages=900, sales = 80000},
      new Salesdetails { ID = "005", pages=456, sales = 90000},
      new Salesdetails { ID = "006", pages=870, sales = 50000},
      new Salesdetails { ID = "007", pages=675, sales = 40000},
      };
      return sd.OfType<Salesdetails>();
   }
}
Add the codes in the Page_Load event handler to query on both the tables using the join clause:
protected void Page_Load(object sender, EventArgs e)
{
   IEnumerable<Books> books = Books.GetBooks();
   IEnumerable<Salesdetails> sales = 
                       Salesdetails.getsalesdetails();
   var booktitles = from b in books
             join s in sales
             on b.ID equals s.ID
             select new { Name = b.Title, Pages = s.pages };
   foreach (var title in booktitles)
      lblbooks.Text += String.Format("{0} <br />", title);
}
The resulted Page:
LINQ Result2

The Where clause:

The 'where clause' allows adding some conditional filters to the query. For example, if you want to see the books, where the number of pages are more than 500, change the Page_Load event handler to:
var booktitles = from b in books
          join s in sales
          on b.ID equals s.ID
          where s.pages > 500
          select new { Name = b.Title, Pages = s.pages };
The query returns only those rows, where the number of pages is more than 500:
LINQ Result3

The Orderby and Orderbydescending clauses:

These clauses allow sorting the query results. To query the titles, number of pages and price of the book, sorted by the price, write the following code in the Page_Load event handler:
var booktitles = from b in books
                 join s in sales
                 on b.ID equals s.ID
                 orderby b.Price
                 select new { Name = b.Title, 
                 Pages = s.pages, Price = b.Price};
The returned tuples are:
LINQ Result4

The Let clause:

The let clause allows defining a variable and assigning it a value calculated from the data values. For example, to calculate the total sale from the above two sales, you need to calculate:
TotalSale = Price of the Book * Sales
To achieve this, add the following code snippets in the Page_Load event handler:
The let clause allows defining a variable and assigning it a value calculated from the data values. For example, to calculate the total sale from the above two sales, you need to calculate:
var booktitles = from b in books
     join s in sales
     on b.ID equals s.ID
     let totalprofit = (b.Price * s.sales)
     select new { Name = b.Title, TotalSale = totalprofit};
The resultant query page looks like:
LINQ Result5


ASP.NET - Web Services

A web service is a web-based functionality accessed using the protocols of the web to be used by the web applications. There are three aspects of web service development:
  • Creating the web service
  • Creating a proxy
  • Consuming the web service

Creating the Web Service:

A web service is an web application which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture like the ASP.Net web pages, although it does not have an user interface.
To understand the concept let us create a web service that will provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This web service will have three methods:
  • A defaullt HelloWorld method
  • A GetName Method
  • A GetPrice Method
Take the following steps to create the web service:
Step (1): Select File--> New --> Web Site in Visual Studio, and then select ASP.Net Web Service.
Step (2): A web service file called Service.asmx and its code behind file, Service.cs is created in the App_Code directory of the project.
Step (3): Change the names of the files to StockService.asmx and StockService.cs.
Step (4): The .asmx file has simply a WebService directive on it:
<%@ WebService Language="C#" 
                  CodeBehind="~/App_Code/StockService.cs" 
                  Class="StockService" %>
Step (5): Open the StockService.cs file, the code generated in it is the basic Hello World service. The default web service code behind file looks like the following:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace StockService
{
   /// <summary>
   /// Summary description for Service1
   /// <summary>
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   [ToolboxItem(false)]
   // To allow this Web Service to be called from script, 
   // using ASP.NET AJAX, uncomment the following line. 
   // [System.Web.Script.Services.ScriptService]
   public class Service1 : System.Web.Services.WebService
   {
     [WebMethod]
     public string HelloWorld()
     {
        return "Hello World";
     }
   }
}
Step (6): Change the code behind file to add the two dimensional array of strings for stock symbol, name and price and two web methods for getting the stock information.
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, 
// using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class StockService : System.Web.Services.WebService
{
   public StockService () {
     //Uncomment the following if using designed components 
     //InitializeComponent(); 
   }
   string[,] stocks =
   {
   {"RELIND", "Reliance Industries", "1060.15"},
   {"ICICI", "ICICI Bank", "911.55"},
   {"JSW", "JSW Steel", "1201.25"},
   {"WIPRO", "Wipro Limited", "1194.65"},
   {"SATYAM", "Satyam Computers", "91.10"}
   };

   [WebMethod]
   public string HelloWorld() {
      return "Hello World";
   }
   [WebMethod]
   public double GetPrice(string symbol)
   { 
      //it takes the symbol as parameter and returns price
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return Convert.ToDouble(stocks[i, 2]);
      }
      return 0;
   }
   [WebMethod]
   public string GetName(string symbol)
   {
      // It takes the symbol as parameter and 
      // returns name of the stock
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
           return stocks[i, 1];
      }
      return "Stock Not Found";
   }
}
Step (7) : Running the web service application gives a web service test page, which allows testing the service methods.
Stock Service
Step (8) : Click on a method name, and check whether it runs properly.
Get Name
Step (9): For testing the GetName method, provide one of the stock symbols, which are hard coded, it returns the name of the stock
the name of the stock

Consuming the Web Service:

For using the web service, create a web site under the same solution. This could be done by right clicking on the Solution name in the Solution Explorer. The web page calling the web service should have a label control to display the returned results and two button controls one for post back and another for calling the service.
The content file for the web application is as follows:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="wsclient._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>Using the Stock Service</h3>
    <br />
    <br />
    <asp:Label ID="lblmessage" runat="server"></asp:Label>
    <br />
    <br />
    <asp:Button ID="btnpostback" runat="server" 
                onclick="Button1_Click" 
                Text="Post Back" Width="132px" />
       
    <asp:Button ID="btnservice" runat="server" 
                onclick="btnservice_Click" 
                Text="Get Stock" Width="99px" />
    </div>
</form>
</body>
</html>
The code behind file for the web application is as follows:
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;

//this is the proxy
using localhost;

namespace wsclient
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
     {
        if (!IsPostBack)
           lblmessage.Text = "First Loading Time: " + 
           DateTime.Now.ToLongTimeString();
        else
           lblmessage.Text = "PostBack at: " + 
           DateTime.Now.ToLongTimeString();
     }
     protected void btnservice_Click(object sender, EventArgs e)
     {
       StockService proxy = new StockService();
       lblmessage.Text = String.Format("Current SATYAM Price:{0}",
       proxy.GetPrice("SATYAM").ToString());
     }
   }
}

Creating the Proxy:

A proxy is a stand-in for the web service codes. Before using the web service, a proxy must be created. The proxy is registered with the client application. Then the client application makes the calls to the web service as it were using a local method.
The proxy takes the calls, wraps it in proper format and sends it as a SOAP request to the server. SOAP stands for Simple Object Access Protocol. This protocol is used for exchanging web service data.
When the server returns the SOAP package to the client, the proxy decodes everything and presents it to the client application.
Before calling the web service using the btnservice_Click, a web reference should be added to the application. This creates a proxy class transparently, which is used by the btnservice_Click event.
protected void btnservice_Click(object sender, EventArgs e)
{
  StockService proxy = new StockService();
  lblmessage.Text = String.Format("Current SATYAM Price: {0}", 
  proxy.GetPrice("SATYAM").ToString());
}
Take the following steps for creating the proxy:
Step (1): Right click on the web application entry in the Solution Explorer and click on 'Add Web Reference'.
Add Web Reference
Step (2): Select 'Web Services in this solution'. It returns the StockService reference.
Select Web Services
Step (3): Clicking on the service opens the test web page. By default the proxy created is called 'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the client application.
Stock Service 2
Include the proxy in the code behind file by adding:
 using localhost;


ASP.NET - Multi Threading

A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations like database access or some intense I/O operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application.
So far we have written programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.
In .NET, the threading is handled through the System.Threading namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program.

Creating Thread:

A thread is created by creating a Thread object, giving its constructor a ThreadStart reference.
ThreadStart childthreat = new ThreadStart(childthreadcall);

The Thread Life Cycle:

The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread :
  • The Unstarted State: it is the situation when the instance of the thread is created but the Start method has not been called.
  • The Ready State: it is the situation when the thread is ready to run and waiting CPU cycle.
  • The Not Runnable State: a thread is not runnable, when:
    • Sleep method has been called
    • Wait method has been called
    • Blocked by I/O operations
  • The Dead State: it is the situation when the thread has completed execution or has been aborted.

The Thread Priority:

The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority.
The priorities could be categorised as:
  • Above normal
  • Below normal
  • Highest
  • Lowest
  • Normal
Once a thread is created its priority is set using the Priority property of the thread class.
NewThread.Priority = ThreadPriority.Highest;

Thread Properties & Methods:

The Thread class has the following important properties:
PropertyDescription
CurrentContextGets the current context in which the thread is executing.
CurrentCultureGets or sets the culture for the current thread.
CurrentPrincipleGets or sets the thread's current principal (for role-based security).
CurrentThreadGets the currently running thread.
CurrentUICultureGets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.
ExecutionContextGets an ExecutionContext object that contains information about the various contexts of the current thread.
IsAliveGets a value indicating the execution status of the current thread.
IsBackgroundGets or sets a value indicating whether or not a thread is a background thread.
IsThreadPoolThreadGets a value indicating whether or not a thread belongs to the managed thread pool.
ManagedThreadIdGets a unique identifier for the current managed thread.
NameGets or sets the name of the thread.
PriorityGets or sets a value indicating the scheduling priority of a thread.
ThreadStateGets a value containing the states of the current thread.
The Thread class has the following important methods:
MethodsDescription
AbortRaises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
AllocateDataSlotAllocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
AllocateNamedDataSlotAllocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegionNotifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.
BeginThreadAffinityNotifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.
EndCriticalRegionNotifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.
EndThreadAffinityNotifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.
FreeNamedDataSlotEliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetDataRetrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
GetDomainReturns the current domain in which the current thread is running.
GetDomainIDReturns a unique application domain identifier.
GetNamedDataSlotLooks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.
InterruptInterrupts a thread that is in the WaitSleepJoin thread state.
JoinBlocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms.
MemoryBarrierSynchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
ResetAbortCancels an Abort requested for the current thread.
SetDataSets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead.
StartStarts a thread.
SleepMakes the thread pause for a period of time.
SpinWaitCauses a thread to wait the number of times defined by the iterations parameter
VolatileRead()Reads the value of a field. The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache. This method has different overloaded forms.
VolatileWrite()Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms.
YieldCauses the calling thread to yield execution to another thread that is ready to run on the current processor. The operating system selects the thread to yield to.

Example:

The following example illustrates the uses of the Thread class. The page has a label control for displaying messages from the child thread. The messages from the main program is directly displayed using the Response.Write() method. So it appears on the top of the page.
The source file is as follows:
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="threaddemo._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>Thread Example</h3>
    </div>
    <asp:Label ID="lblmessage" runat="server" Text="Label">
    </asp:Label>
    </form>
</body>
</html>
The code behind file is as follows:
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;
using System.Threading;

namespace threaddemo
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         ThreadStart childthreat = 
                          new ThreadStart(childthreadcall);
         Response.Write("Child Thread Started <br/>");
         Thread child = new Thread(childthreat);
         child.Start();
         Response.Write(
            "Main sleeping  for 2 seconds.......<br/>");
         Thread.Sleep(2000);
         Response.Write(
            "<br/>Main aborting child thread<br/>");
         child.Abort();
      }
      public void childthreadcall()
      {
      try{
         lblmessage.Text = "<br />Child thread started <br/>";
         lblmessage.Text += "Child Thread: Coiunting to 10";
         for( int i =0; i<10; i++)
         {
            Thread.Sleep(500);
            lblmessage.Text += "<br/> in Child thread </br>";
         }
         lblmessage.Text += "<br/> child thread finished";
      }
      catch(ThreadAbortException e)
      {
         lblmessage.Text += "<br /> child thread - exception";
      }
      finally{
         lblmessage.Text += "<br /> child thread 
                           - unable to catch the exception";
      }
      }
   }
}
Observe the following:
  • When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page.
  • The second thread runs and sends messages to the label control.
  • The main thread sleeps for 2000 ms, during which the child thread runs.
  • The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated.
  • Control returns to the main thread.
When executed the program sends the following messages:
ASP.NET Thread


ASP.NET 4.0 - Deployment

There are two categories of ASP.Net deployment:
  • Local deployment – in this case the entire application is contained within a virtual directory and all the contents and assemblies are contained within it and available to the application.
  • Global deployment – in this case, assemblies are available to every application running on the server.
There are different techniques used for deployment, however, we will discuss the following most common and easiest ways of deployment:
  • XCOPY deployment
  • Copying a Website
  • Creating a set up project

XCOPY Deployment:

XCOPY deployment means making recursive copies of all the files to the target folder on the target machine. You can use any of the commonly used techniques:
  • FTP transfer
  • Using Server Management tools providing replication on a remote site
  • MSI installer application
XCOPY deployment simply copies the application file to the production server and set a virtual directory there. You need to set a virtual directory using the Internet Information Manager Microsoft Management Consol (MMC snap-in).

Copying a Website:

The Copy Web Site option is available in Visual Studio. It is available from the Website --> Copy Web Site menu option. This menu items allows copying the current web site to another local or remote location. It is a sort of integrated FTP tool.
Using this option, you connect to the target destination, select the desired copy mode:
  • Overwrite
  • Source to Target Files
  • Sync UP Source And Target Projects
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is done from Visual Studio environment. However, there are the following problems with both the above deployment methods:
  • You pass on your source code
  • There is no pre-compilation and related error checking for the files
  • The initail page load will be slow

Creating a Setup Project:

In this method you use Windows Installer and package your web applications so it is ready to deploy on the production server. Visual Studio allows you to build deployment packages. Let us test this on one of our existing project, say the data binding project.
Open the project and take the following steps:
Step (1): Select File -> Add-> New Project with the website root directory highlighted in the Solution Explorer.
Step (2): Select Setup and Deployement, under Other Project Types. Select Setup Wizard.
Select Setup Wizard
Step (3): Choosing the default location ensures that the set up project will be located in its own folder under the root directory of the site. Click on okay to get the first splash screen of the wizard.
splash screen Wizard
Step (4): The second screen asks to choose a project type. Select 'Create a setup for a web application'.
splash screen Wizard2
Step (5): Next, the third screen asks to choose project outputs from all the projects in the solution. Check the check box next to 'Content Files from...'
splash screen Wizard3
Step (6): The fourth screen allows including other files like ReadMe. However, in our case there is no such file. Click on finish.
splash screen Wizard4
Step (7): The final screen displays a summary of settings for the set up project.
splash screen Wizard5
Step (8): The Set up project is added to the Solution Explorer and the main design window shows a file system editor
splash screen Wizard6
Step (9): Next step is to build the setup project. Right–click on the project name in the Solution Explorer and select Build.
splash screen Wizard7
Step (10): When build is completed, you get the following message in the Output window:
splash screen Wizard8
Two files are created by the build process:
  • Setup.exe
  • Setup-databinding.msi
You need to copy these files to the server and double-clicking the setup file will cause the content of the .msi file to be installed on the local machine.






















No comments:

Post a Comment