You are on page 1of 274

Chapter 1

Introducing ASP.NET
Web applications have revolutionized the way business is conducted. These applications
enable organizations to share and access information from anywhere and at anytime. This has
majorly moved the focus of application development from desktop applications to Web
applications. One of the most popular server-side technologies used today for developing
Web applications is ASP.NET.
This chapter introduces the basics of Web development. It also discusses the architecture,
functioning, and features of ASP.NET. In addition, it explains how to develop ASP.NET
applications.

Objectives
In this chapter, you will learn to:
Identify the basics of Web development
Explore ASP.NET
Develop ASP.NET applications

Introducing Web Development


Among all technologies, the Internet has been the fastest growing technology. Ever since its
inception, the Internet has evolved exponentially. In the recent years, it has changed the way
business is conducted.
Prior to the evolution of the Internet, organizations were unable to create awareness about
themselves because the communication media were limited. Moreover, the organizations
could deliver only limited information by using the existing communication media such as
television and radio. However, with the inception of the Internet, organizations found a new
medium through which they could reach a larger range of people irrespective of their
geographical locations. Therefore, organizations increasingly became dependent on the
Internet for sharing and accessing information. This resulted in changing the focus of
application development from desktop applications to Web applications.
Web applications are programs that are executed on a Web server and accessed from a Web
browser. These applications enable organizations to share and access information on the
Internet and corporate intranets. This information can be accessed from anywhere and at any
time. In addition, Web applications can support online commercial transactions popularly
known as e-commerce. An online store accessed through a Web browser is an example of a
Web application.
A Web application consists of Web pages. Web pages can be of the following types:

Static Web Page: A Web page that consists of only Hyper Text Markup Language
(HTML) is a static Web page. A static Web page does not respond dynamically to the
actions performed by a user.
Dynamic Web Page: A Web page that responds dynamically to the actions
performed by a user is a dynamic Web page and an application that consists of
dynamic Web pages is a dynamic Web application. Such an application can be created
by using server-side scripts, client-side scripts, or both in addition to HTML pages.

Server-Side Scripting
With the increase in the usage of the Internet as the information medium, organizations are
creating dynamic Web applications. Dynamic Web applications enable a user to:

Retrieve data from a database that may not reside on the computer where the Web
server is located.
Submit data from HTML forms.
Get information based on the input.

To incorporate these features in a Web application, you need to implement server-side


scripting. Server-side scripting provides users with dynamic content that is based on the
information stored at a remote location, such as a back-end database. Server-side scripting
includes code written in server-side scripting languages, such as Active Server Pages (ASP)
and Java Server Pages (JSP). A server-side script is executed on the Web server.
When a browser requests for information on a website that is created by using server-side
technology, the Web server to which the request is sent, first processes the script and then
sends the results back to the browser. For example, if a Web page includes a server-side
script to display the current time of the system on which the website is hosted, the script will
be processed at the server and the current system time will be sent back to the browser.
The following figure shows the working of server-side scripts.

Working of Server-Side Scripts

Client-Side Scripting
Client-side scripting enables you to develop Web pages that can dynamically respond to user
input without having to interact with a Web server. Suppose, you have a Web application that
requires users to enter the user name and password before displaying the home page. You
need to ensure that a user does not leave the user name and password fields blank. To check
whether a user has left the user name and password fields blank, you can write client-side
scripts.
In addition to providing dynamic content, a client-side script helps reduce network traffic
because it does not need to interact with a Web server to provide dynamic response to the
user input. Client-side scripting also speeds up the response time of a Web application. This
happens because a Web server is not overloaded with the job of processing the client-side
script for every client. Scripting languages, such as VBScript and JavaScript, are used to
write client-side scripts.
The following figure shows the working of client-side scripts.

Working of Client-Side Scripts


Limitations of Client-Side Scripting
In spite of the all the advantages, client-side scripting has some major limitations. These
limitations are:

Browser support: Client-side scripting is not supported equally by all browsers and
operating systems.
Isolation: Client-side scripts cannot access server-side resources. It is difficult and
requires a lot of coding to access a file or interact with a database on the server by
using client-side scripts.

Security: Client-side scripts are visible to the end users. Therefore, they can be
tampered by malicious users.
Thin clients: Web-enabled devices such as mobile phones, palmtop computers, and
Personal Digital Assistants (PDAs) can communicate with Web servers. These
devices act as thin clients that can use Web applications containing server-side
scripting. However, these devices do not support client-side scripting such as
JavaScript or VBScript.

Note
In spite of all the limitations, client-side scripting is still in use. ASP.NET allows you to use
client-side scripting in addition to the server-side scripting to create rich and responsive Web
applications.

Exploring ASP.NET
ASP.NET is a server-side technology that enables programmers to create dynamic Web
applications. It has a number of advanced features such as simplicity, security, and scalability
that help you develop robust Web applications. These advanced features of ASP.NET are
based on the .NET Framework.

ASP.NET in the .NET Framework


ASP.NET is built on the Microsoft .NET Framework. Microsoft introduced the .NET
Framework to help developers create globally distributed software with Internet functionality
and interoperability.
The following figure displays the elements of an ASP.NET application and how the elements
fit in the broader context of the .NET Framework.

Elements of an ASP.NET Application in the .NET Framework


The preceding figure indicates that an ASP.NET application has the following elements:

Web Form Pages: Enable you to include user interfaces, such as Text box control,
List box control, and the application logic of Web applications.
Configuration Files: Enable you to store the configuration settings of an ASP.NET
application.
XML Web Service Files: Define a Web service that can be called by an ASPX file
over the Internet or from a local network.

Web forms and the state management feature of ASP.NET constitute the ASP.NET Page
Framework. There are also a number of runtime services available in ASP.NET. The
ASP.NET runtime services include view state, session state, and application state
management, Web security, and the caching mechanism of ASP.NET applications. The
runtime services of ASP.NET interact with .NET Framework base classes, which in turn,
interact with the Common Language Runtime (CLR) to provide a robust Web-based
development environment.

Working of an ASP.NET Application


After creating an ASP.NET application, the ASP.NET files need to be stored on a Web server
such as Internet Information Services (IIS) server, which is the Web server for the Windows

platform. The Web server processes the ASP.NET files and then executes the scripts. Finally,
the results are sent to the Web browser that requested the ASP.NET file.
The following figure depicts how a Web server processes a request for an ASP.NET file.

Processing of a Request for an ASP.NET File


The steps involved in the execution of an ASP.NET file are:
1. A Web browser sends a request for an ASP.NET file to a Web server by using a
Uniform Resource Locator (URL).
2. The Web server, such as IIS, receives the request and retrieves the appropriate
ASP.NET file from the disk or memory.
3. The Web server forwards the ASP.NET file to the ASP.NET script engine for
processing.
4. The ASP.NET script engine reads the file and executes any server-side script it
encounters.
5. The processed ASP.NET file is generated as an HTML page.
6. The Web server then sends the HTML page to the client.
7. The Web browser interprets the output and displays it.
A Web server generates and sends only the HTML output to the client. As a result, it helps to
hide the code of the ASP.NET file from the users who access an ASP.NET Web page.

Note
ASP.NET script engine is the engine that processes the server-side scripts contained in an
ASP.NET application. After processing the scripts, the engine renders the result as an HTML
document and sends it back to the browser.

Features of ASP.NET
In addition to hiding the code of the ASP.NET file from the users, ASP.NET has the
following advanced features that help develop robust Web applications:

Compiled code: The code written in ASP.NET is compiled and not interpreted. This
makes ASP.NET applications faster to execute than other server-side scripts, such as
the scripts written in a previous version of ASP that are interpreted.
Power and flexibility: ASP.NET applications are based on CLR. As a result, the
power and flexibility of the .NET platform is available to ASP.NET applications.
ASP.NET applications enable you to ensure that the .NET Framework class library,
messaging, and data access solutions are seamlessly accessible on the Web. ASP.NET
is also language-independent. As a result, you can choose any .NET language to
develop your application.
Simplicity: ASP.NET enables you to build user interfaces that separate application
logic from the presentation content. In addition, CLR simplifies application
development by using managed code services, such as automatic reference counting
and garbage collection. Therefore, ASP.NET makes it easy to perform common tasks
ranging from form submission and client authentication to website configuration and
deployment.
Manageability: ASP.NET enables you to manage Web applications by storing the
configuration information in an Extensible Markup Language (XML) file. You can
open the XML file and modify it.
Scalability: ASP.NET has been designed with scalability in mind. It has features that
help improve performance in a multiprocessor environment.
Security: ASP.NET provides a number of options for implementing security and
restricting user access to a Web application. All these options are configured within
the configuration file.
Extensibility: ASP.NET provides a number of options to create an extensible Web
application. For example, you can create custom controls and extend the default
Hypertext Transfer Protocol (HTTP) pipeline. The path through which the data flows
from the client to the server is called the HTTP pipeline. It is a technique in which
multiple HTTP requests are written out to a single socket without waiting for the
corresponding responses. It improves the page loading time.

Developing ASP.NET Applications


You can create ASP.NET applications by using any text editor. However, this will take a
substantial amount of time because you will have to create the applications by creating all the
Web page classes and coding the Web page controls manually. In addition to being timeconsuming, this process increases the possibility of inducing errors that could otherwise be
avoided by using a design tool. A design and productivity tool, such as Visual Studio,
provides various features that enable the developers to quickly create robust ASP.NET
applications. Some of the Visual Studio IDE features are:

Integrated error checking: Visual Studio can detect various problems such as data
type conversion errors, missing namespaces or classes, and undefined variables.
When you type code, Visual Studio detects and underlines these problems.

The Web form designer: Visual Studio provides the Web form designer that enables
you to create a Web page by simply dragging the ASP.NET controls to the
appropriate location and configuring their properties. The actual Web page markup is
created automatically.
An integrated Web server: Web applications need to be hosted on a Web server
such as IIS to be accessible for the users. Therefore, you need to install IIS on the
development computer to test the applications. However, if you are creating a Web
application by using Visual Studio, you need not install IIS on the computer. This is
because Visual Studio has an integrated development Web server that enables you to
run a Web application directly from the design environment.
Developer productivity enhancements: Visual Studio provides features such as
automatic statement completion and color-coded syntax that makes coding quick and
efficient. In addition, Visual Studio has an integrated debugger that allows you to
watch code execution, pause your program at any point, and inspect the contents of
any variable. This helps in debugging the code quickly and efficiently.
Complete extensibility: Visual Studio allows you to use macros, change project
templates, and even add your own custom add-ins. This provides you to extend the
existing functionality of the existing environment.

Creating an ASP.NET Web Application


You can use ASP.NET to create websites and Web services. A website is the user interface of
your application. Generally, a website represents a web application front-end, with screens,
Cascading Style sheets (CSS), and User Interface (UI) components. A Web service enables
you to remotely access certain functions at the server side. It enables the exchange of data in
a client-to-server or a server-to-server environment over the Web by using the Simple Object
Access Protocol (SOAP). A Web service does not have a user interface.

Anatomy of an ASP.NET Application


ASP.NET applications are generally divided into multiple Web pages. Every Web page in an
ASP.NET application shares a common set of resources and configuration settings. These
resources and configuration settings cannot be shared by the Web pages from any other
ASP.NET application, even if they are on the same Web server.
Every ASP.NET application is executed inside a separate application domain. These
application domains ensure that even if a Web application causes a fatal error, it does not
affect other applications that are currently running on the same computer. Application

domains also restrict a Web page in one application from accessing the in-memory
information of another application. Each Web application is a separate entity that has its own
set of data. It can be described as a combination of files, pages, handlers, modules, and
executable code that can be invoked from a virtual directory on a Web server.
The following figure shows a Web server that is hosting four Web applications.

A Web Server Hosting Four Web Applications

Note
A virtual directory is a directory that is exposed to the public on a Web server.

Directories Used in ASP.NET Web Applications


An ASP.NET application uses some specialized directories. The following table lists these
directories with their descriptions.
Directory

Description

Bin

Stores all the compiled .NET components


(DLLs) that an ASP.NET Web application
uses. For example, if you create a custom
component, you need to place the component
in this directory. Once placed in the Bin
directory, the component can be used by any
ASP.NET application.

App_Code

Stores source code files that are dynamically


compiled to be used in the Web application.
It is similar to the Bin directory except for
one difference. It contains source code files
whereas the Bin directory contains compiled
assemblies.

App_Browsers

Stores browser definition files. Browser


definition files are XML files that define a
browser with its properties, capabilities, and
features. This information is used by
ASP.NET server controls to determine the
browser that has requested the page and
render the appropriate markup for that
browser.

App_GlobalResources

Stores global resources that are accessible to


every page in the Web application. It is used
for localization purposes where you want a
website to display content in more than one
language.

App_LocalResources

Stores .resx files that are accessible to a


specific page only.

App_WebReferences

Stores references to Web services that are


used by the Web application.

App_Data

Stores data such as database files and XML


files that are used by the application. It is not
mandatory to store data files in this
directory.

App_Themes

Stores the themes that are used in the Web


application.

Directories Used in an ASP.NET Application

Some of the subdirectories given in the preceding table are created in specific applications.
For example, the App_Themes directory is created when you use themes in your application.
Files Used in ASP.NET Web Applications
The ASP.NET Web applications can include different types of files. The following table lists
some of the important file types with their descriptions.
File Name

Description

Ends with .aspx

These are ASP.NET Web pages that contain


the user interface and, optionally, the
underlying application code. Users request
or navigate directly to one of these pages to
start a Web application.

Ends with .ascx

These are ASP.NET user controls. These


controls are similar to Web pages, except
that the user cannot access these files
directly. Instead, they must be hosted inside
an ASP.NET Web page. User controls allow
you to develop a small piece of user interface
and reuse it in as many Web forms as you
want without repeating code.

Ends with .asmx

These are ASP.NET Web services. Web


services are collections of methods that can
be called over the Internet. Web services
work differently than Web pages. However,
they still share the same application
resources, configuration settings, and
memory.

web.config

This is the XML-based configuration file for


ASP.NET applications. It includes settings
for customizing features such as security,
state management, and memory management.

Global.asax

This is the global application file. You can


use this file to define global variables
(variables that can be accessed from any
Web page in the Web application). It is
mostly used for defining the overall
application events related to the Application
& Session object.

Ends with .cs

These are code-behind files that contain C#


code. These files allow you to separate the
application logic from the user interface of a
Web page.

Ends with .ashx

These are default HTTP handlers for all Web


handlers that do not have a user interface
and that include the @ WebHandler directive.

Files Used in an ASP.NET Application


Configuration Files Used in ASP.NET Web Applications
ASP.NET uses a hierarchy of configuration files to keep application configuration settings
separate from the application code. A configuration file is an XML file that contains
configuration settings for an application and has a .config extension.
It provides the following benefits:

Provides control and flexibility over the way you run applications.
Eliminates the need to recompile the application every time a setting changes.
Controls access to protected resources, and the location of remote applications and
objects by defining configuration settings.

To understand the benefits of configuration files, consider an example. Suppose, your Web
application includes a number of forms that are required to connect to an SQL Server
database. You have written the code to create the connection on each of these forms.
However, if the location of the database is modified, you will have to update the code for
connecting to the database in each form. A better option is to store the details of the
connection string in a configuration file for the Web application and refer to the connection
string from within the code. As a result of this, even if the database location is changed, only
the connection string in the configuration file needs to be updated.
ASP.NET allows you to easily edit the configuration data before, or after an application is
deployed on the server. The files in the configuration hierarchy allow you to make
configuration settings at different levels.
The following table lists the levels, the corresponding configuration files, and their
description.

Configuration Files with Their Levels and Descriptions


The two files included in the hierarchy of configuration files are machine.config and
web.config. The machine.config file always resides at the root of the configuration hierarchy
and contains the global and default settings for all .NET Framework applications on the
server. The web.config file can reside at multiple levels in the hierarchy. In case two versions
of the same configuration setting exist at different hierarchal levels, local settings will take
precedence over global settings.

ASP.NET Web Page Code Model


A Web page is made up of the following two components:

The visual portion: Refers to the static HTML and ASP.NET server controls that
define the layout of a Web page.
The programming logic: Refers to the code that is required to interact with the Web
page.

ASP.NET provides two models for managing the visual elements and code:

Single-file page model


Code-behind page model

The Single-File Page Model


In the single-file page model, HTML markup of the page and its programming code are in the
same physical .aspx file. The programming code is contained in a <script> block that
specifies the attribute runat="server".
The first line in the .aspx file contains the @Page directive. Every .aspx file should include the
@Page directive. The @Page directive provides ASP.NET with the basic information about
how to compile the Web page. It also indicates the language that will be used for coding and
the way to connect the event handlers. The syntax of the page directive is:
<%@ Page Language="C#"%>

At run time, the compiler converts a single-file page into a class that derives from the
System.Web.UI.Page class.
The single-file page model provides the following advantages:

In pages with less code, keeping the programming code and the HTML markup in a
single file proves to be very convenient while studying the file.
Pages written by using the single-file model are slightly easier to deploy or to send to
another programmer because there is only one file.
A single-file page is easier to rename because there is no dependency between files.
Managing files in a source code control system is slightly easier because the page is
self-contained in a single file.

The Code-Behind Page Model


In the code-behind page model, HTML markup is kept in one file (with extension .aspx) and
the programming code in another file (with extension .cs or .vb). The code file contains a
partial class, which indicates that the class contains only some of the total code that makes up
the full class for the page. The partial class inherits from a base Page class (either
System.Web.UI.Page or a class derived from System.Web.UI.Page).
There are two differences in the .aspx page between the single-file and the code-behind
models:
1. In the code-behind model, there is no <script> block with the runat="server"
attribute.
2. In the code-behind model, the @Page directive contains attributes that reference an
external file and a class, as shown in the following example:
<%@ Page Language="C#" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
In the preceding example, the CodeFile attribute specifies the code-behind

file with
which the page is associated, and the Inherits attribute specifies a code-behind class
for the page to inherit. This class can be any class that is derived from the Page class.
This attribute is used with the CodeFile attribute, which contains the path to the
source file for the code-behind class.

When the page is compiled, ASP.NET creates a new partial class for the .aspx file. This class
is a peer of the code-behind partial class file and contains the declarations for the controls of
the page. Finally, ASP.NET generates a class that inherits from the partial class created from
the .aspx file and the code-behind partial class. The generated class is compiled into an
assembly that runs in order to render output to the browser.
The code-behind model provides the following advantages:

It allows a developer to separate the UI display from the UI processing, thereby


enabling the programmer to reuse the programming logic.
It enables a developer to quickly debug the code because the code is not clubbed with
the UI.
It enables developers to quickly create a Web application by separating the design and
development functions. For example, designers can work on the .aspx file and at the
same time programmers can implement logics in the code-behind file.

The Page Class


All Web forms are instances of the ASP.NET Page class, which is defined in the
System.Web.UI namespace. The Page class inherits the TemplateControl class, which, in
turn, inherits the Control class. As a result, the Page class provides useful events that can be
used in the code.
Page Events
ASP.NET uses an event-driven model of programming. This model of ASP.NET defines a
sequence of events that are raised during the lifecycle of a Web page. The following table
lists some of the page events.
Event

Description

Init

It is the first event that occurs when the


server executes an ASP.NET page. It occurs
only once in the entire lifecycle of an
ASP.NET page.

Load

It is fired after the Init event, when the page


is requested for the first time and whenever
the page is reloaded. This event can be used
to initialize the variables and the state of the
controls that are used in the page.

Unload

It represents the last event that occurs in the

lifecycle of an ASP.NET page. This event is


used to perform final cleanup work, such as
the closing of open database connections,
discarding objects, or closing files.
Page Events and Their Description

Intrinsic Objects of ASP.NET


ASP.NET has a number of built-in objects that are programmed using methods, properties,
and collections. These objects are made available to the Page object, which is an instance of
the System.Web.UI.Page class from which all ASP.NET pages are inherited.
ASP.NET provides the following built-in objects:

Application
Request
Response
Server
Session
HttpContext

Application
The Application object provides a reference to an object of the HttpApplicationState
class. The Application object is used to store information that is defined for the entire Web
application. For example, the connection string, which is used to connect to the database
server, is defined for the entire Web application. Therefore, the connection string can be
stored in the Application object. The following table describes some of the properties of the
Application object.
Property

Description

Count

Returns the number of objects in the


HttpApplicationState collection.

Item

Provides access to an object in the


HttpApplicationState collection.

Application Objects Properties with Description


The Application object provides various methods and properties. The following table
describes some of the methods of the Application object.
Method

Description

public void Lock()

Blocks the access to an Application variable


or object. The Lock() method enables access

synchronization when more than one process


is accessing a particular variable or object.
public void UnLock()

Releases the lock procured on an


Application variable or object.

Application Objects Methods with Description


Request
The Request object provides a reference to an object of the HttpRequest class. The object
enables ASP.NET applications to access information sent by the client during a Web request.
The following table describes some of the properties of the Request object.
Property

Description

ApplicationPath

Returns the application root path of


ASP.NET on the server. This is a read-only
property.

Url

Returns a URI object, which will contain the


complete address of the requested page. This
is a read-only property.

UserHostAddress

Returns the IP host address of the requesting


client.

UserLanguage

Returns a sorted string array containing the


language preferences of the client.

Browser

Returns the HttpBrowserCapabilities


object, which contains information about the
browser capability of the client.

Cookies

Returns the HttpCookieCollection object,


which provides access to the cookie variables
of the client.

QueryString

Provides access to the parameters passed


from the client to the server along with a
GET request.

Request Objects Properties with Description


The following table describes an important method of the Request object.
Description

Method

byte[] BinaryRead(int)

Helps retrieve the data sent to the server


from the client as part of a post request and

stores it in an array.
Request Objects Method with Description
Response
The Response object provides a reference to an object of the HttpResponse class. The object
enables ASP.NET applications to send information to the client. The following table
describes some of the properties of the Response object.
Property

Description

Buffer

Sets the buffer feature of the Response


object. When the Buffer property is set to
true, the Response object buffers the
responses together. When the Buffer property
is set to false, the Response object sends the
response as it receives. The default value is
true.

Cache

Provides access to the caching policy, such


as the expiration time and privacy settings of
the Web page. This is a read-only property.

ContentType

Sets or gets the type of data that is sent to the


client through the Response object.

Cookies

Sets a cookie to the client browser.

IsClientConnected

Returns a Boolean value indicating whether


the client is connected or disconnected.

Response Objects Properties with Description


The following table describes some of the methods of the Response object.
Method

Description

public void Clear()

Clears the content in the buffer of the


Response object.

public void Close()

Closes the connection to the client.

public void End()

Sends the buffered data to the client and


closes the connection to the client. The End()
method will raise an
Application_EndRequest event.

public void Flush()

Sends the data in the buffer to the client but


does not close the connection to the client.

public void Redirect(string)

Redirects the new URL specified in the string


parameter to the client.

public void Write(string)

Writes a string on the form. It is an


overloaded method.

Response Objects Methods with Description

Server
The Server object provides a reference to an object of the HttpServerUtility class. The
Server object provides methods that can be used to access the methods and properties of the
Web server. The following table describes some of the properties of the Server object.
Property

Description

MachineName

Returns the name of the server machine.

ScriptTimeout

Helps get and set the request timeout in


seconds for the Web server.

Server Objects Properties with Description


The following table describes some of the methods of the Server object.
Method

Description

public void ClearError()

Clears the last error that has occurred on the


server.

public object CreateObject(String)

Creates the server instance of a COM object.

public Exception GetLastError()

Returns an Exception object, which


represents the last error that occurred on the
server.

public string MapPath(string path)

Returns the physical file path on the Web


server that corresponds to the specified
virtual path.

public void Transfer(string)

Terminates the processing of the current


page and loads the page specified in the
string format.

Server Objects Methods with Description


Session
The Session object provides a reference to an object of the HttpSessionState class. The
Session object enables ASP.NET applications to keep the state of the application as
modified or changed by a client. It also provides access to the session wide cache, which can
be used to store information pertaining to the client.
A session starts when a client logs on to a website and ends when he/she logs off from the
website. The session is also terminated if the client remains inactive for a specific period. The
default timeout period is 20 minutes. The following table describes some of the properties of
the Session object.
Property

Description

Count

Returns the number of items in the sessionstate collection.

SessionID

Returns the unique session ID assigned for a


session.

Timeout

Enables to get and set the period in minutes


that is allowed between requests by the client
before the session-state provider terminates
the session.

Session Objects Properties with Description


The following table describes some of the methods of the Session object.
Method

Description

public void Add(string name, object


value)

Adds a new item to the session-state


collection.

public void Clear()

Clears all the values stored in the sessionstate collection.

public void Remove(string name)

Deletes an item from the session-state


collection.

Session Objects Methods with Description


HttpContext
The HttpContext object holds information about the current HTTP request. A new
HttpContext object is created for every request sent to an ASP.NET application. The new
object is created at the beginning of a request and destroyed when the request is completed.
The HttpContext object holds current request-specific information such as Request,

Response, Server, and Session.


HttpContext object.

The following table describes some of the properties of the

Property

Description

AllErrors

Gets an array of errors that are accumulated


while processing an HTTP request.

ApplicationInstance

Gets or sets the HttpApplication object for


the current HTTP request.

Timestamp

Gets the initial timestamp of the current


HTTP request.

Users

Gets or sets security information for the


current HTTP request.

HTTPContext Objects Properties with Description


The following table describes some of the methods of the HttpContext object.
Method

Description

public void AddError(Exception


errorInfo)

Adds an exception to the exception collection


for the current HTTP request.

public void ClearError()

Clears all errors for the current HTTP


request.

public object GetConfig(string name)

Returns requested configuration information


for the current HTTP request.

HttpContext Objects Methods with Description

Summary
In this chapter, you learned that:

Web pages can be of the following types:


o Static Web Page
o Dynamic Web Page
Server-side scripting provides users with dynamic content that is based on the
information stored at a remote location.
Client-side scripting enables you to develop Web pages that can dynamically respond
to user input without having to interact with a Web server.
An ASP.NET application has the following elements:
o Web Form Pages
o Configuration Files
o XML Web Service Files

ASP.NET has the following advanced features that help develop robust Web
applications:
o Compiled code
o Enriched tool support
o Power and flexibility
o Simplicity
o Manageability
o Scalability
o Security
o Extensibility
A Web form is made up of the following two components:
o The visual portion
o The programming logic
ASP.NET provides two models for managing the visual elements and code:
o Single-file page model
o Code-behind page model
ASP.NET provides the following built-in objects:
o
o
o
o
o
o

Application
Request
Response
Server
Session
HttpContext

Reference Reading
Introducing Web Development
Reference Reading:
Books

Reference Reading: URLs

Mastering Web
Development with
Microsoft Visual Studio
2005 by John Paul
Mueller Beginning
ASP.NET 3.5 in VB: by
Matthew MacDonald

http://en.wikipedia.org/wiki/Server-side_scripting
http://www.eggheadcafe.com/articles/20041016.asp

Exploring ASP.NET
Reference Reading:
Books

Reference Reading: URLs

Programming ASP.NET:
Building Web
Applications and Services

http://en.wikipedia.org/wiki/.NET_Framework
http://en.wikipedia.org/wiki/ASP.NET

with ASP.NET 3.5 by


Jesse Liberty, Dan
Hurwitz Essential ASP.
NET with Examples in
C#: by Fritz Onion

http://articles.techrepublic.com.com/5100-10878_115771721.html

Developing ASP.NET Applications


Reference Reading:
Books

Reference Reading: URLs

ASP.NET in a Nutshell:
by G. Andrew Duthie,
Matthew MacDonald
Developing Web
Applications with Visual
Basic.NET and ASP.NET
by John Alexander, Billy
Hollis

http://www.asp.net/
http://www.microsoft.com/learning/en/us/syllabi/2310Bfinal.mspx

Chapter 2

Working with Controls


The success of an application largely depends upon its user interface. For an application to be
successful, its interface needs to be attractive and easy-to-use. Such a user interface can be
designed by using various types of controls provided in ASP.NET.
ASP.NET provides various types of controls that can be added to a Web form to make it
interactive. However, while developing an application, you may face a situation where the
built-in controls do not fulfill your requirements. In such a situation, you need to create
custom controls.
This chapter provides an overview of the controls used in an ASP.NET application. It also
discusses how to create custom controls and implement them in a Web application.

Objectives
In this chapter, you will learn to:
Use ASP.NET Web Server controls
Create custom controls

Using ASP.NET Web Server Controls


In the earlier days of Web development, the programmers had to use HTML controls to
design a Web application because there were no other controls available. The HTML controls
do not provide any built-in methods and events. Programmers had to manually write the
methods and events by using client-side scripts to create a dynamic Web page. This is a timeconsuming process. In addition, it is insecure because the client-side scripts are visible to the
users when they view the source for the Web page.
ASP.NET solves this problem by providing server controls. Server controls are the
fundamental building blocks that are specifically designed to work with Web forms in an
ASP.NET application. Server controls can be rendered as markup text on a Web browser and
are capable of executing the program logic on the server. Server controls also provide built-in
methods and events. This eliminates the need for writing the events and methods manually. In
addition, it provides security to the application because the program logic is executed on the
Web server and only the result is sent back to the browser in the HTML format, thus, hiding
the program logic from the user.
Each server control provides an object-oriented programmable interface. Therefore, each
server control is an object with methods, properties, and events associated with it.
Server controls can be viewed as special HTML tags, which are processed by the server. The
advantages of using server controls are:

Automatic state maintenance: ASP.NET server controls provide a property called


EnableViewState, which can be set to true to enable the server controls to maintain
their state after a postback.

Note
Postback is the process by which a browser posts information back to itself. It can
also be defined as the process by which a browser posts information back to the
server by requesting the same page.

Browser independent rendering: When an ASP.NET page is requested, the server


generates the corresponding HTML code for all the server controls in the page. The
HTML code generated is specific to the Web browsers used by the clients. This
feature saves programmers from developing different versions of the page for
different Web browsers.
Easily programmable model: Server controls are implemented as objects in
ASP.NET. This makes the server control programming model similar to the
traditional object-oriented programming model, making it easy to program server
controls.

Note
In addition to the server controls, ASP.NET provides HTML controls. Most HTML controls
are similar to server controls. However, there is a major difference. Unlike server controls,
HTML controls are processed by the Web browser.
To understand the processing of the server controls in a Web page, you need to understand
the sequence of their processing and how they are rendered on a Web page.

Processing of Server Controls on a Web Page


The processing of a server control depends on two situations, whether the page is requested
for the first time by the client or it is posted back to the Web server when the user interacts
with the Web page.
When a page is requested for the first time, the server controls are processed in the following
sequence:
1. Initializing: The server creates an instance of the server control.
2. Loading: The instance of the control is loaded onto the page object in which it is
defined.

3. PreRendering: The control is updated with the changes made to it by the user. This
phase prepares the control for rendering.
4. Saving: The state information of the control is saved. For example, if a value is set for
the control during the Load event, it is embedded in the HTML tag that will be
returned to the browser.
5. Rendering: The server creates the corresponding HTML tag for the control.
6. Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed.
7. Unloading: All cleanup tasks, such as destroying the instances of server controls are
performed. This is the final event in the life cycle of a server control.
When the Web page is posted back to the Web server, the server controls are processed in the
following sequence:
1. Initializing: The server creates an instance of the server control.
2. Loading view state: The view state of the control, posted by the client, is reloaded
into the new instance of the control.
3. Loading control instance: The instance of the control is loaded onto the page object
in which it is defined.
4. Loading the postback data: The server searches any data corresponding to the
control that is loaded in the data posted by the client.
5. PreRendering: The control is updated with the changes made in it by the user. This is
done in preparation for rendering.
6. Saving: The change in the state of the controls between the current request and the
previous request of the page is saved. For each change, the corresponding event is
raised. For example, if the text of a textbox is changed, the new text is saved and a
TextChanged event is raised.
7. Rendering: The server creates the corresponding HTML tag for the control.
8. Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed.
9. Unloading: All cleanup tasks like destroying the instances of server control are
performed. This is the final event in the life cycle of a server control.
The following figure illustrates the processing of a server control.

Processing of a Server Control

Note
In ASP.NET, Web page refers to an instance of thePage class and a Web form refers to the
Web page and all the controls on it.

Types of Server Controls


ASP.NET provides various types of server controls. These controls can be classified into the
following categories:

HTML Server Controls


Web Server Controls
Validation Controls

HTML Server Controls

In traditional websites, HTML controls were used to enable users to interact with the website.
Developers had to write the methods and events for these controls manually to provide
functionality to them. This was a very tedious task. In addition, these controls were processed
by the Web browser that is on the client-side, which does not provide the functionality for
validating the user input or managing the state.
To overcome these limitations, ASP.NET provides the HTML server controls, which are
processed by the Web server and make full use of the .NET Framework utilities such as
validation. Some of the common HTML server controls are:

HtmlAnchor Control
HtmlInputText Control
HtmlInputCheckBox Control
HtmlInputRadioButton Control
HtmlSelect Control

HtmlAnchor Control

The HtmlAnchor control works like the HTML <a> tag but runs on the server. It is used to
direct the user from one page to another. The following table lists some properties of the
HtmlAnchor control.
Property

Description

ID

Gets or sets a unique identifier to the HtmlAnchor


control for reference at the server.

Href

Gets or sets the URL of the page to which the


control is linked.

Name

Gets or sets a unique identifier to the HtmlAnchor


control for reference at the client side.

Target

Gets or sets the frame or window in which the


page specified in the Href property will load. The
default value is _self. As a result the linked page
will be loaded in the same window.

Title

Gets or sets the value of the tooltip attribute of


the <a> tag that is displayed when the mouse
pauses over the control.

Properties of the HtmlAnchor Control

When you click the HtmlAnchor control, the ServerClick event is raised. Consider the
following markup:
<a id="myAnchor1" href="URLLocation" runat="server">Click here</a>
<a id="myAnchor2" OnServerClick="myFunction" runat="server">Click here</a>

The preceding markup illustrates the HTML code of two HtmlAnchor server controls with
the name myAnchor1 and myAnchor2, as specified by the id attribute. When myAnchor1 is
clicked, the browser navigates to the new location, URLLocation, as specified in the href
attribute. When myAnchor2 is clicked, the function, myFunction, attached to the
ServerClick event is invoked. The OnServerClick attribute is used to attach an event
handler to the ServerClick event.
HtmlInputText Control

The HtmlInputText control works like the HTML <input type="text"> tag but runs on the
server. The HtmlInputText server control is used to gather information from the user. The
following table lists some properties of the HtmlInputText control.
Property

Description

ID

Gets or sets a unique identifier to the


HtmlInputText control for reference at the server.

Type

Sets Type="Text" or Type ="Password" to


specify the mode of work.

Name

Gets or sets a unique identifier to the


HtmlInputText control for reference at the client
side.

Size

Gets or sets the width of the control.

MaxLength

Gets or sets the value for the maximum


characters that can be entered in the textbox.

Value

Gets or sets the value of the textbox or password


box.

Properties of the HtmlInputText Control


The commonly used method of the HtmlInputText control is OnServerChange. The
OnServerChange method is invoked in response to the ServerChange event. The

ServerChange

event is triggered when either a new text message is entered or a change is


made to the existing text in the HtmlInputText control. The following markup illustrates the
HTML code of two HtmlInputText controls:
<input type="text" id="txtName1" maxlength="12" runat="server">
<input type="text" id="txtName2" maxlength="15" runat="server">

The preceding markup illustrates the HTML code of two HtmlInputText server controls with
the names txtName1 and txtName2, as specified by the id attributes. The txtName1 can
accommodate a maximum of 12 characters whereas txtName2 can accommodate a maximum
of 15 characters, as specified by the maxlength attribute.
HtmlInputCheckBox Control

The HtmlInputCheckBox control works as the HTML <input type="checkbox"> tag but
runs on the server. The HtmlInputCheckBox control is useful to implement questions that can
have only two answers, such as yes/no or true/false. For example, do you like Coffee? The
answer is either yes or no.
The following table lists some properties of the HtmlInputCheckBox control.
Property

Description

ID

Gets or sets a unique identifier to the


HtmlInputCheckBox control for reference at the
server.

Name

Gets or sets a unique identifier to the


HtmlInputCheckBox control for reference at the
client side.

Checked

Checks whether the check box is selected or not.

Value

Gets or sets the value of the HtmlInputCheckBox


control.

Properties of the HtmlInputCheckBox Control


When you select or clear a check box, the ServerChange event is raised. The ServerChange
event triggers the associated event handler when the page consisting the check box is
submitted to the server. The following markup illustrates the HTML code for the
HtmlInputCheckBox control:
<input type="checkbox" id="MyCheckBox1" OnServerChange="FunctionCheckBox"
runat="server">

The preceding markup uses an HtmlInputCheckBox control named MyCheckBox1, as


specified by the id attribute. The OnServerChange attribute is used to attach an event handler
to the ServerChange event. When the MyCheckBox1 HtmlInputCheckBox control is selected
or cleared, the FunctionCheckBox method attached to its ServerChange event is invoked.
HTMLInputRadioButton Control

The HtmlInputRadioButton control works as the HTML <input type="radio"> tag but
runs on the server. You can use the HtmlInputRadioButton control to implement multiplechoice questions, where a user can select only one option.
The following table lists some properties of the HtmlInputRadioButton control.
Property

Description

ID

Gets or sets a unique identifier to the


HtmlInputRadioButton control for reference at
the server.

Checked

Gets or sets the status of the radio button. This


property will return true if the radio button is
selected.

Name

Sets the name of the option button group.

Value

Gets or sets the value of the


HtmlInputRadioButton control.

Properties of the HtmlInputRadioButton Control


When the HtmlInputRadioButton control changes its state from the previous state on the
server, the ServerChange event is generated. You can use the following markup to
implement the HtmlInputRadioButton control:
<input type="radio" id="MyRadioButton" name="GroupRadio" value="Titanic"
OnServerChange="FunctionRadio" runat="server"> Titanic

The preceding markup uses an HtmlInputRadioButton control named MyRadioButton, as


specified by the id attribute. The MyRadioButton HtmlInputRadioButton control belongs to a
group GroupRadio as specified by the name attribute. When MyRadioButton is selected or
cleared, the FunctionRadio method attached to its ServerChange event is invoked. The
OnServerChange attribute is used to attach an event handler to the ServerChange event.

HtmlSelect Control

The HtmlSelect control is same as the HTML <select> element but it runs on the server.
This control is used to create a list box. The HtmlSelect control is used when a user has to
select an option from a list of options. The following table lists some properties of the
HtmlSelect control.
Property

Description

ID

Gets or sets a unique identifier to the HtmlSelect


control for reference at the server.

Name

Gets or sets a unique identifier to the HtmlSelect


control for reference at the client side.

Items

Gets the list of items.

Multiple

Specifies whether multiple items can be selected.

SelectedIndex

Gets the Index of the selected item.

Size

Sets the number of visible items in the list.

Value

Gets the value of the selected item.

Properties of the HtmlSelect Control


When an item is selected in the HtmlSelect control, the ServerChange event is generated.
The following markup illustrates how to implement the HtmlSelect control:
<select Runat="Server" size=4>
<option>Titanic</option>
<option>The Lords of the Ring</option>
<option>Matrix Reloaded</option>
<option>Harry Potter</option>
</select>

The preceding markup creates a list box containing four movie names as list items. Out of
these movie names only one can be selected at a time.

Web Server Controls


Web server controls are created on the server and require a runat="server" attribute to
work. This attribute indicates that the element should be treated as a server control and will
be processed at the server. However, unlike the HTML server controls, Web server controls
do not necessarily map to any existing HTML elements and may represent more complex
elements. Some of the most commonly used Web server controls are:

TextBox Control
Label Control
ListBox Control
CheckBox and CheckBoxList Control
RadioButton and RadioButtonList Control
AdRotator Control
Calendar Control
DropDownList Control
ImageButton Control
Button Control
Wizard Control
MultiView Control
HyperLink Control
FileUpload Control
XML Control
Substitution Control

TextBox Control

The TextBox control is used to obtain information, such as text, numbers, and dates from
users in a Web form. You can set a TextBox control as single-line, password, or multi-line
TextBox control. By default, a TextBox control is single-line that allows users to type
characters in a single line only. A password TextBox control is similar to the single-line
TextBox control, but masks the characters typed by users and displays them as asterisks (*).
A multi-line TextBox displays multiple lines and allows text wrapping.
The properties of a TextBox control determine the appearance of the TextBox control. The
following table lists some properties of the TextBox control.
Property

Description

Text

Gets and sets the text in a TextBox control.

Height

Gets and sets the height of the control.

Rows

Allows you to set the vertical size of the TextBox


control and takes a value in number of rows. If
you set both the Height and Rows properties, the

Height property takes precedence.


Wrap

Allows you to set the word wrap behavior in a


multi-line TextBox control. The text wraps
automatically if the value is set to True. However,
if the value is set to False, the user has to press
the carriage return key to move to the next line.

Properties of the TextBox Control


Label Control

The Label control is used to display static text in a Web form that cannot be edited by the
user. The Text property of the Label control can be set to modify the controls caption. The
following table lists some properties of the Label control.
Property

Description

Text

Gets or sets the text of the Label control.

Visible

Displays or hides the Label control.

Properties of the Label Control


ListBox Control

The ListBox control is a collection of list items. It allows users to select one or more items
from the list. The following table lists some properties of the ListBox control.
Property

Description

Items

Represents the collection of list items in the


ListBox control.

Rows

Sets the vertical size of the ListBox control and


takes a value in number of rows. If the control
contains more than the specified number of
items, a vertical scrollbar is displayed. If you set
both the Height and Rows properties, the Height
property takes precedence.

SelectionMode

Sets the number of items that can be selected. To


allow users to select only one item, you need to
set the SelectionMode property to Single. To
allow users to select multiple items, you need to
set the SelectionMode property to Multiple. To
select more than one item, users can hold the
CTRL or SHIFT key while selecting the items.

Properties of the ListBox Control


The items can be added to a ListBox control by using:

Static item addition method: In this method, the items are added during the design
phase.
Dynamic item addition method: In this method, the items are added during run time.

CheckBox and CheckBoxList Controls

A check box provides you with independent choices or options that you can select. You can
add check boxes to a Web form by using either the CheckBox control or the CheckBoxList
control. The CheckBox control provides you with a single check box whereas the
CheckBoxList control is a collection of several check boxes. The choice between using the
CheckBox control and using the CheckBoxList control depends on the requirement. The
CheckBox control provides more control over the layout of the check boxes on a page. For
instance, you can set the font and color of check boxes individually or include text between
different check boxes. The CheckBoxList control is a better choice if you need to add a series
of check boxes.
The following table lists some properties of the CheckBox and CheckBoxList controls.

Properties of the CheckBox and CheckBoxList Controls

Note
Methods for adding items to a CheckBoxList control are similar to the methods used to add
items to the ListBox control.
RadioButton and RadioButtonList Controls

Radio buttons provide a set of choices or options that you can select. You can add radio
buttons to a Web form by using either the RadioButton control or the RadioButtonList
control. The RadioButton control is a single radio button that you can work with whereas the
RadioButtonList control is a collection of radio buttons. Usually, you use radio buttons in a
group. A group of radio buttons provides a set of mutually exclusive options. You can select
only one radio button in a group.
You can group a set of radio buttons in the following ways:

Place a set of RadioButton controls in a page and assign them manually to a group by
using the GroupName property.
Place a RadioButtonList control in a page. The radio buttons in this control are
grouped by default.

After you add a RadioButtonList control, you need to add individual radio buttons. You can
do so by using the Items property in the same way as you do for the CheckBoxList control.
Similar to the CheckBox and CheckBoxList controls, the RadioButton control offers more
control over the layout of the radio buttons on the page.
The following table lists some properties of the RadioButton and RadioButtonList controls.

Properties of the RadioButton and RadioButtonList Controls

Note
The methods for adding items to a RadioButtonList control are similar to the methods for
adding items to the ListBox control.
AdRotator Control

The AdRotator control is used to display flashing banner advertisements on Web pages. This
control is capable of displaying advertisements randomly. AdRotator is one of the rich Web
controls available in ASP.NET. The following table lists some properties of the AdRotator
control.
Property

Description

AdvertisementFile

Sets the path to an XML file that contains a list of


banner advertisements to display. The XML file
contains multiple <Ad> elements, one for each
advertisement that you want to display. Each
<Ad> element contains an <ImageUrl> element
that specifies the URL of the image and an
<Impressions> element that specifies weights
for each image. These weights define the relative
probability of an image being displayed.

KeywordFilter

Specifies the filter criteria based on which


advertisements of specific categories will be
displayed on a Web page.

Target

Specifies the name of the Web browser window


that will display the contents of the linked Web
page when the AdRotator control is clicked. This
parameter can also take any of the following
HTML frame-related keywords:
_top: Loads the linked page into the topmost

window
_blank: Loads the linked page into a new

browser window
_self: Loads the linked page in the same

window
_parent: Loads the linked page in the parent

window of the window that contains the link

Properties of the AdRotator Control


Calendar Control

The Calendar control is used to display a one-month calendar. Users can use this control to
view dates or select a specific day, week, or month. Calendar is one of the rich web controls
available in ASP.NET. The following table lists some properties of the Calendar control.
Property

Description

DayNameFormat

Specifies the name format of the days of a week.

VisibleDate

Specifies the month to be displayed in the


Calendar control. This property is updated after
the VisibleMonthChanged event is raised.

FirstDayOfWeek

Specifies the day of the week to be displayed in


the first column of the Calendar control.

SelectedDate

Represents the date selected in the Calendar


control.

SelectionMode

Specifies whether a user can select a day, a week,


or a month. The default value of this property is
Day.

Properties of the Calendar Control


DropDownList Control

The DropDownList control allows users to select an item from a set of predefined items,
where each item is a separate object with its own properties, such as Text, Value, and
Selected. You can add items to a DropDownList control by using the Items property. Unlike
the ListBox control, you can select only one item at a time and the list of items remains
hidden until the user clicks the drop-down button. The following table lists some properties
of the DropDownList control.

Property

Description

Items

Represents the collection of list items in the


DropDownList control.

Width

Gets or sets the width of the DropDownList


control and takes the value in pixels.

Height

Gets or sets the vertical size of the DropDownList


control and takes the value in pixels.

Properties of the DropDownList Control


ImageButton Control

The ImageButton control is similar to a button control but unlike the button control, it can
also display an image. The ImageButton control has a few properties that are identical to the
Image control. It inherits these properties from the Image control. It also has a few properties
that are identical to the Button control. The following table lists some properties of the
ImageButton control.
Property

Description

AlternativeText

Gets or sets the alternative text that is displayed


in the Image control when a Web browser does
not support images.

CausesValidation

Specifies whether validation will be performed


when the Button control is clicked. If the value is
False, the form submitted by the button is not
validated. The default value of this property is
True.

CommandArgument

Passes a value to the Command event along with


the associated command name when the button
is clicked.

ImageAlign

Gets or sets the alignment of the image. The


possible values for this property are Top, Left,
Right, Middle, Bottom, AbsBottom, AbsMiddle,
Baseline, Middle, NotSet, and TextTop.

ImageURL

Specifies the URL of the image to be displayed.

CommandName

Gets or sets the command name associated with


the Button control that is passed to the
Command event.

Properties of the ImageButton Control


Button Control

The Button control is generally used to submit the data that is entered by a user as an input in
a Web application. When the user clicks a button control on a Web page, the page is posted
back to the Web server, and the click event is triggered. ASP.NET provides three types of
button controls; Button, LinkButton, and ImageButton.
The following table describes how these buttons appear on a Web page.
Control

Description

Button

Rendered as a standard command button that is


rendered as an HTML input element.

LinkButton

Rendered as a hyperlink on a Web page. It


contains client-side script that causes the form to
be posted back to the server.

ImageButton

Rendered in the form of a graphic button. It is


used for presenting a rich button appearance.

Types of Button Control


The following table lists some common properties of all the three Button controls.
Property

Description

ID

Gets or sets the unique identifier assigned to the


button control.

Text

Gets or sets the text that is displayed on the


Button control.

PostBackURL

Gets or sets the URL of the Web page to which


the data is posted.

Enabled

Gets or sets a value indicating whether the


button control is enabled.

ToolTip

Gets or sets the text displayed when the mouse


pointer hovers over the button control.

Common Properties of Button Controls


Wizard Control

A wizard is a group of forms used to accomplish a particular task. ASP.NET provides a


Wizard control that is used to enable a user to perform a task step-by-step or to collect user
input related to the task. A Wizard control contains a series of forms that describe the whole
task. It provides an easy mechanism that allows you to build steps, add a new step, or reorder
the steps.
With the help of the Wizard control, a user can move between steps, which create a simple
user experience for performing a task. As a developer, you need not worry about preserving
data across the Web pages as the control maintains the state while a user performs the various
steps of the wizard.
The following table lists some properties of the Wizard control.
Property

Description

ID

Gets or sets the unique identifier assigned to the


Wizard control.

WizardSteps

Gets a collection of all the WizardStepBase


objects that are defined for the control.

EnableViewState

Gets or sets a value indicating whether the


Wizard control persists its view state, and the
view state of any child controls it contains.

Enabled

Gets or sets a value indicating whether the


Wizard control is enabled.

ToolTip

Gets or sets the text displayed when the mouse

pointer hovers over the Wizard control.

Properties of the Wizard Control


MultiView Control

A Multiview control is a set of View controls. These View controls, in turn, contain child
controls such as buttons and textboxes. A Web application dynamically displays a View
control to a user based on certain criteria such as user identity, preferences, or information
passed in a query string parameter. It is used to present alternate views of information.
The following table lists some properties of the MultiView control.
Property

Description

ID

Gets or sets the unique identifier assigned to the


MultiView control.

Views

Gets the collection of View controls in the


MultiView control.

Visible

Gets or sets a value that indicates whether a


MultiView control is rendered as UI on the page.

Properties of the MultiView Control


HyperLink Control

A HyperLink control is used to link all the Web pages in a Web application. By using a
HyperLink control, a user can easily move between the Web pages. It is rendered as a
clickable text or an image on a Web page. A HyperLink control does not raise an event in the
server code when a user clicks it. Instead, it simply performs navigation. In other words, it
directs the user to another Web page. The following table lists some properties of the
HyperLink control.
Property

Description

Text

Specifies the text displayed as a hyperlink on a


Web browser.

ImageUrl

Creates a graphical link when you set the URL


property of the control to a .gif, .jpg, or other

Web graphic file.


NavigateUrl

Specifies the URL of the page to which you want


to link.

Target

Indicates the ID of a target window or frame in


which you want to display as a linked page.

Properties of the HyperLink Control


FileUpload Control

The FileUpload control enables users to send a file from their computer to the server. It is
useful for allowing users to upload various types of files such as pictures, text files, or other
files. The files that are to be uploaded are submitted to the server as part of the browser
request during postback.
The FileUpload control displays a textbox to type the name of the file that is to be uploaded
on the server. It also displays a Browse button that that can be used to browse for the file. The
following table lists some properties of the FileUpload control.
Property

Description

Filename

Gets the name of the file on the client computer


to be uploaded.

HasFile

Gets a value that indicates whether the control


contains a file.

Properties of the FileUpload Control


XML Control

The XML control is used to write the output of an XML document on a Web page. The XML
output appears at the location of the control on the Web page. The following table lists some
properties of the XML control.
Property

Description

Document

Gets or sets the XML document to be displayed.

DocumentContent

Sets a string that contains the XML document to


display.

DocumentSource

Gets or sets the path of the XML document


whose output is to be displayed.

Properties of the XML Control


Substitution Control

The Substitution control is used on the Web pages that are configured to be cached. It allows
you to create areas on the page that can be updated dynamically and integrated into the
cached page.
When a page is cached, the entire output of the page is cached. However, there may be
situations wherein you need to cache a page but want to update the selected portions of the
page on each request. For updating the selected portions in a cached page, you can place the
Substitution control in the cached page and insert dynamic content into the Substitution
control. The following table lists some properties of the Substitution control.
Property

Description

MethodName

Gets or sets the name of the method to be


invoked when the Substitution control executes.

Site

Gets information about the container that hosts


the current control when rendered on a design
surface.

Properties of the Substitution Control


Validation Controls
Validation is the process of checking something against a certain criterion. There are various
situations where validation is required. One such situation is when a user fills out a form for
which the minimum age required is 18 years. In such a situation, when the user submits the
form, the age must be validated against the criterion. If the criterion is satisfied, the form is
accepted, otherwise it is rejected. Such type of validation can be implemented on a website
by using the ASP.NET validation controls.
ASP.NET provides the following validation controls that can be attached to input controls to
validate the values that are entered by the user:

RequiredFieldValidator Control

RegularExpressionValidator Control
CompareValidator Control
RangeValidator Control
ValidationSummary Control
CustomValidator Control

RequiredFieldValidator Control

The RequiredFieldValidator control is used to check whether a server control, added to a


Web form, has a value or not. For example, you can use this validation control to check
whether a user has entered any value in the password textbox.
The following table lists some properties of the RequiredFieldValidator control.
Property

Description

ControlToValidate

Specifies the ID of the control to be validated.

ErrorMessage

Specifies the error message to be displayed when


the validation condition fails.

Text

Specifies the error message displayed by the


control.

Properties of the RequiredFieldValidator Control


RegularExpressionValidator Control

The RegularExpressionValidator control is used to check whether the server control added to
a Web form matches with a specific regular expression or not. The regular expression can be
the format of a telephone number or an e-mail address.
The following table lists some properties of the RegularExpressionValidator control.
Property

Description

ControlToValidate

Specifies the ID of the control to be validated.

ErrorMessage

Specifies the error message to be displayed when


the validation condition fails.

ValidationExpression

Specifies the regular expression, when


performing validation.

Properties of the RegularExpressionValidator Control


CompareValidator Control

The CompareValidator control is used to compare the entered value with another value. The
other value can be a number or a value entered into another control. The following table lists
some properties of the CompareValidator control.
Property

Description

ControlToCompare

Specifies the ID of the control that will be used to


compare values.

ControlToValidate

Specifies the ID of the control to be validated.

ErrorMessage

Specifies the error message to be displayed when


the validation condition fails.

ValueToCompare

Specifies the ID of the control to be compared.

Properties of the CompareValidator Control


RangeValidator Control

The RangeValidator control is used to check whether the value of a particular Web form field
is within the range specified by the RangeValidator controls MinimumValue and the
MaximumValue properties. The MinimumValue and MaximumValue properties can contain
dates, numbers, currency amounts, or strings.
The following table lists some properties of the RangeValidator control.
Property

Description

ControlToValidate

Specifies the ID of the control to be validated.

ErrorMessage

Specifies the error message to be displayed when


the validation condition fails.

MaximumValue

Specifies the maximum value.

MinimumValue

Specifies the minimum value.

Properties of the RangeValidator Control


ValidationSummary Control

The ValidationSummary control is used to summarize all errors and display the error list at a
location specified by the user on the Web page. The following table lists some properties of
the ValidationSummary control.
Property

Description

HeadText

Gets or sets the text to be displayed at the top of


the summary.

ShowMessageBox

Displays the error message in a pop-up message


box when the value of this property is True.

ShowSummary

Enables or disables the summary of error


messages.

Properties of the ValidationSummary Control


CustomValidator Control

The CustomValidator control is used to perform user-defined validations that cannot be


performed by standard validation controls. The following table lists some properties of the
CustomValidator control.
Property

Description

ControlToValidate

Specifies the ID of the control that is to be


validated.

ErrorMessage

Specifies the error message to be displayed when


validation condition fails.

Properties of the CustomValidator Control

Server Control Events


Every server control has some events associated with it. An event is a message that contains
details about the user action, such as the cause of the event and the control on which the event
occurred.

When a user interacts with a server control, its corresponding event is invoked and the code
written on the event is executed. For example, when a user clicks a button, the Click event of
the button control is invoked and the code written on the event is executed.
Most of the ASP.NET events pass the following two arguments:

Sender Object: This is the first argument and is an instance of System.Object class.
This represents the control that raised the event.
Event Object: This is an instance of System.EventArgs class. This contains
information about the event that is generated.

ASP.NET Server Control Event Model


In traditional client-based Web applications, the events are raised and processed on the client
machine. However, in ASP.NET, events associated with the server controls originate on the
client but the processing of the events happens only on the server. ASP.NET supports two
types of events:

Postback events: In postback events, a Web page is sent back to the server for
processing. When a user clicks a button, the click event of the button causes a Web
page to be posted back to the server. When a Web page is posted back to the server,
the server processes the page and sends it back to the user.
Nonpostback events: In nonpostback events, a Web page does not immediately cause
a postback. For example, change events in HTML server controls and Web server
controls, such as the TextBox control, are captured but do not immediately cause a
post. These events are cached by the control until the next time a post occurs. When a
post occurs, the page is processed on the server and all the pending events are raised
and processed.

Event Handlers
When an event is raised, the corresponding event handler is searched and the code written in
the event handler is executed. If you want your application to perform some action when an
event is raised, you need to add an event handler for that event.
The various approaches that can be used to work with event handlers include:

Using default events


Using non-default events
Using the AutoEventWireup capabilities of a Web form
Creating centralized event-handlers

Using Default Events

Every control exposes an event that is designated as the default event. A default event is an
event that is most commonly associated with a control. For example, the Click event is the
default event of a Button control. Default events are handled by a default event handler.

Using Non-Default Events

In addition to the default event, each control exposes other events, called non-default events.
For example, the Command event is a non-default event of a Button control. Non-default
events are handled by non-default event handlers.

Using the AutoEventWireup Capabilities of a Web Form

ASP.NET provides the event wire-up capability to a Web form using which events can be
automatically associated with event-handling procedures having well-defined names and
signatures. Event wire-ups determine the procedures that need to be called when objects raise
events. To enable the event wire-up capability of a Web form, you need to set the
AutoEventWireUp attribute of the .aspx page to true. By default, the AutoEventWireUp
attribute of the .aspx pages is set to true, as shown in the following markup:
<%@ Page Language="C#" AutoEventWireup="true"%>

The AutoEventWireup attribute can have two values, true or false. When the value is set to
true, the ASP.NET runtime does not require events to specify event handlers, such as
Page_Load and Page_Init. This means that in Visual C#, you do not have to initialize and
create the delegate structures. However, when the value is set to false, the events need to
specify event handlers explicitly.
Creating Centralized Event-Handlers

There are situations when you want to associate the same event handler with different
controls. Such situations can be handled by using a centralized event handler. A centralized
event handler eliminates the need for declaring separate event handlers for different
ASP.NET objects. You can create one centralized event handler that can perform appropriate
action at runtime.
When you create a single event handler to respond to multiple events that should trigger
different actions, you need to determine which event invoked the event handler. To determine
which control caused the event, you need to perform the following steps:
1. Declare a variable in the event handler with a type that matches the control that raised
the event.
2. Assign the sender argument of the event handler to the variable, casting it to the
appropriate type.

3. Examine the ID property of the variable to determine which object raised the event.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1"
onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button2"
onclick="Button1_Click" />

In the preceding example, the event handler Button1_Click is associated with both the
button controls. You need to write the event handler in such a manner that it will determine
which control has caused the event. The following code snippet illustrates how to write such
an event handler:
protected void Button1_Click(object sender, EventArgs e)
{
Button mybtn = (Button)sender;
switch (mybtn.ID)
{
case "Button1": Response.write("You have clicked Button
1");
break;
case "Button2": Response.write ("You have clicked Button
2");
break;
}
}

The preceding code works well to define a centralized event handler for the Click event of
the Button control. However, if you need to create a centralized event handler for the
Command event of two button controls, the preceding code will not work because the
Command event passes a different set of arguments to its event handler.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1" CommandName="Prev"
onCommand="Button1_Command" />
<asp:Button ID="Button2" runat="server" Text="Button2" CommandName="Next"
onCommand="Button1_Command" />

In the preceding example, the event handler Button1_Command is associated with both the
button controls. You need to write the event handler in such a manner that it will determine
which control has caused the event. The following code snippet illustrates how to write such
an event handler:
protected void Button1_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Prev": Response.Write("You clicked the Prev
button");
break;
case "Next": Response.Write("You clicked the Next
button");
break;
}

Loading Controls Dynamically


There are situations where you need to add controls dynamically to a Web page. Consider a
situation where you are designing a registration form for an insurance company. The form
has a section where the persons seeking insurance have to enter the name and age of their
family members. The number of family members varies from user to user. Therefore, you
cannot add the textboxes for entering the name and age at the design time. Such a situation
can be handled by adding the controls at run time. Adding controls to a Web page at run time
makes a website flexible, interactive, and user-friendly.
When adding a control dynamically to a Web page, you need to place them in a container so
as to make the Web page well-structured. Two controls that act as containers when adding
controls dynamically are:

PlaceHolder
Panel

PlaceHolder
A PlaceHolder control is used as a container that is not visible in a Web application. It is
added to a Web page to hold other controls on the page. The PlaceHolder control reserves a

place in the structure of the Web page for other controls that are added dynamically. The
following markup adds a PlaceHolder control to a Web page:
<asp:PlaceHolder id="PlaceHolder1" runat="server"/>

The following code snippet shows how to add a Button control and a literal in a PlaceHolder
control:
void Page_Load(object sender, EventArgs e)
{
//creates an instance of a button control.
Button Button1 = new Button();
Button1.Text = "Button 1";
// Adds the button control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Button1);
// creates an instance of a literal control.
Literal Literal1 = new Literal();
Literal1.Text = " Dynamically loaded controls";
// Adds the literal control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Literal1);
}

Panel
A Panel control is also used as a container for other controls. The only difference between a
PlaceHolder and a Panel control is that a Panel control renders div tag around all the child
controls in the panel where as a PlaceHolder will only render its child controls. This makes
panels useful when you want to apply a css class to a container. The following code snippet
shows how to add a Label control to a Panel control:
//Creating an instance of a Label control
Label TestLabel = new Label();
TestLabel.Text = "testlabel";
//Adding the Label control to a Panel control
Panel1.Controls.Add(TestLabel);

Adding Event Handlers Dynamically

An event handler for a control is usually created at design time. However, it can also be
created dynamically at run time for the controls that are created dynamically. For example, to
create a Button control dynamically and associate an event handler to it at run time, you need
to write the following code in the .cs file of a Web page:
protected void Page_Load(object sender, EventArgs e)
{
Button btn=new Button();
btn.Text = "Click Me";
form1.Controls.Add(btn);//Adding button to the form
btn.Click += new EventHandler(btn_Click);
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Hello");
}

Implementing Generic Handler


The .aspx files are the default HTTP handler for all ASP.NET pages. However, there may be
situations wherein you want that instead of .aspx files the request is handled by generic
handlers. For example, you have created the ProductDetails page in which you are displaying
the details of a product. This page has a button control, clicking on which a page having the
image of the product is displayed. Instead of using a Web page to display an image, you can
use a generic handler.
A generic handler can be used when you want to display the output of a text file, XML file,
or display an image. This is because a generic handler uses fewer resources as compared to
Web pages. Therefore, it enhances the performance of your Web application.
The generic handler provides a class that implements the IHttpHandler interface. The class
provides the ProcessRequest method and the IsReusable property. The ProcessRequest
method is responsible for processing individual HTTP requests. This method is used to write
the code that produces the output for the handler. The IsReusable property specifies whether

the IHttpHandlerFactory object can put the handler in a pool and reuse it to increase
performance. The IHttpHandlerFactory object is the object that calls the appropriate
handler.
Consider the following example:
<%@ WebHandler Language="C#" Class="SimpleHandler" %>

using System;
using System.Web;

public class SimpleHandler : IHttpHandler


{
public void ProcessRequest(HttpContext context)
{
HttpResponse r = context.Response; //Create and initialize an
//HttpResponse object
r.ContentType = "image/png";

//Set the Content type for the

//HttpResponse object
//Write the image
r.WriteFile(@"~\images\4.JPG");
}

public bool IsReusable


{
get {return true;}
}
}

In the preceding example, the generic handler is used to display an image.

Note
You can navigate to a generic handler by using the Respose.redirect() method. For
example, you want that on clicking the Show Picture button on the default.aspx page, the
generic handler MyHandler.ashx is displayed in the browser. For this, you need to write the
following code snippet in the event handler for the Click event of the button:
Response.Write(MyHandler.ashx);

Creating Custom Controls


Developers use various Web server controls to enable users to interact with the Web pages.
There might be a situation where you need some functionality that is not provided by the inbuilt Web server controls or you might want to reuse the same set of controls, which you
have added to one Web page, on another Web page. For example, you have created a
customized Login page with two labels, two textboxes, and one button to enable the user to
log on to a website. You want to reuse the same Login page in all other Web applications. In
such a case, you can create a custom control with the required customizations and then reuse
it in as many Web applications as you want.
Custom controls are controls that are created by combining two or more controls and can be
reused in multiple Web applications. You can create the following types of custom controls:

Web User Controls


Web Custom Controls
Templated User Controls

Web User Controls


Web user controls are containers that can be created by combining one or more Web server
controls. After creating a Web user control, you can treat it as a unit and define properties and
methods for it. Web user controls are similar to ASP.NET Web pages in the context that they
contain both a user interface page and code.
A Web user control is created in the same way as you create an ASP.NET page. However, it
differs from an ASP.NET Web page in the following ways:

The file name extension of a user control is .ascx.


A user control contains the @Control directive instead of the @Page directive.

User controls cannot run as stand-alone files. They need to be added to ASP.NET
pages to make them work.
User controls do not have <html>, <body>, or <form> elements in them. These
elements must be present on the Web page that is hosting these controls.

A Web user control on a Web page must be registered before it is used. You can register a
Web user control by using the @Register directive as illustrated in the following markup:
<%@Register TagPrefix="ABC" TagName="Header" Src="mycontrol.ascx" %>

The preceding markup contains the following three attributes:

TagPrefix: Specifies the alias to associate with the namespace of the user control.
TagName: Specifies the alias to associate with the class of the user control.
Src: Specifies the virtual path of the file containing the user control.

After registering the control, you can include it on the page by writing the markup as shown
in the following example:
<ABC:Header ID=mycontrol1 runat="Server"/>

Web Custom Controls


There may be situations where you need a new control with properties that are not provided
by any of the existing server controls. In such situations, you cannot use a Web user control
because a Web user control is created by combining one or more server controls. Such
situations can be handled by writing code to create a new control. These controls are known
as Web custom controls.
Web custom controls provide an approach to reuse logic in an ASP.NET application. Web
custom controls are written as classes. Web custom controls are written entirely by using
managed code and have no markup files. These controls are compiled into an assembly
before the deployment of the application.
Web custom controls are of the following three types:

Controls that combine two or more existing controls: This type of control is known
as a composite control and can be created by defining a class that derives from the
System.Web.UI.Control or System.Web.UI.WebControl class and overrides the
CreateChildControls method of the base class. In addition, the class can expose
public properties that will be accessible to the pages that use this control.
Controls that extend the functionality of an existing control: This type of control
is created when an existing control meets most of your requirements but lacks some
features. In such a situation, you can customize the existing control by defining a class

that derives from the class corresponding to the existing control. You can then add
new properties and override existing methods and events of the base class to modify
the functionality of the control.
Controls that are not similar to any existing control: This type of control is created
when none of the existing controls meets your requirement. In such a case, you can
create a custom control by deriving from the System.Web.UI.Control or
System.Web.UI.WebControl class, adding public properties to this class, and
overriding existing methods of the base class.

Templated User Controls


A templated user control allows developers to modify the layout of its user interface by
defining their own templates. Templated user controls allow the separation of control data
from its presentation. They do not have a user interface; instead they simply implement a
naming container and include a class whose properties and methods are accessible to the host
page. The user interface of the control is defined at the time of designing the Web page on
which the templated control is to be used.
To create a templated user control, you need to perform the following steps:
1. Add an ASP.NET PlaceHolder control in the .ascx file of the user control to specify
the place where you want the template to appear.
2. Implement a property of type ITemplate in the code of the user control.
3. Define a server control class that implements the INamingContainer interface as a
container in which an instance of the template can be created. This class is called the
templates naming container.
4. Apply the TemplateContainer attribute to the property that implements ITemplate
and pass the type of the templates naming container as the argument to the attributes
constructor.
5. For each data item, write code in the Page_Init event handler of the user control to:
1. Create an instance of the naming container class.

2. Create an instance of the template in the naming container.


3. Add the naming container instance to the Controls property of the PlaceHolder server
control.

Note
Repeater, DataList, and GridView Web server controls are the examples of built-in
Templated controls. These controls will be discussed in detail later in the course.

Summary
In this chapter, you learned that:

Server controls are the fundamental building blocks that are specifically designed to
work with Web forms in an ASP.NET application.
Server controls provide:
o
o
o

1.

Automatic state maintenance.


Browser independent rendering.
Easily programmable model.

The sequence in which a server control is processed when the page is requested for
the first time is:
Initializing
2. Loading
3. PreRendering
4. Saving
5. Rendering
6. Disposing
7. Unloading

The sequence in which a server control is processed when the Web page is posted
back to the Web browser is:
0.

Initializing
1. Loading view state
2. Loading control instance
3. Loading the postback data
4. PreRendering
5. Saving
6. Rendering
7. Disposing
8. Unloading

The various types of server controls provided by ASP.NET can be classified into the
following categories:
o
o
o
o

HTML server Controls


Web server Controls
Validation Controls
User Controls

An event is a message that contains details about the user action, such as the cause of
the event and the control on which the event occurred.
The two arguments passed by all events in ASP.NET are:
o
o

Sender Object
Event Object

The two types of events in ASP.NET server control event model are:
o
o

Postback events
Nonpostback events

The two controls that act as container when adding controls dynamically are:
o
o

PlaceHolder
Panel

The two types of custom controls are:


o
o
o

Web User Controls


Web Custom Controls
Template User Controls

Reference Reading
Using ASP.NET Web Server Controls
Reference Reading: Books

Reference Reading: URLs

Chris Hart, John


Kauffman, Beginning
ASP.NET.3.5

http://msdn2.microsoft.com/en-us/library/zsyt68f1.aspx
http://msdn2.microsoft.com/en-us/library/k26w4zzx.aspx

Creating Custom Controls


Reference
Reading:
Books

Reference Reading: URLs

Profession
al Web
Parts and
Custom
Controls
with

http://www.codersource.net/published/view/290/creating_custom_controls_in_a
sp_net.aspx
http://msdn.microsoft.com/en-us/library/ms837926.aspx

ASP.NET
3.5 by
Peter
Vogel
Developin
g .NET
Custom
Controls
and
Designers
Using C#
by James
Henry

Chapter 3

Introducing Styles, Themes, and Master


Pages
You can create a website by creating several Web pages connected to each other. However, a
professional website requires much more than creating individual Web pages and connecting
them. The look and feel of the text on a professional website should be consistent across all
the Web pages. All the information and controls should appear in a standard consistent
format across all the Web pages. In addition, all the Web pages should have a standard
layout. All this can be achieved by using styles, themes, and master pages.
This chapter discusses how to work with styles, and themes. In addition, it discusses how to
define a standard layout for all the Web pages on a website by using master pages.

Objectives
In this chapter, you will learn to:
Work with styles
Work with themes
Work with master pages

Working with Styles


The look and feel of a Web page depends upon the appearance and arrangement of the
HTML elements contained in it. Therefore, you need to format the HTML elements
contained in your Web page to make it look attractive. Formatting each HTML element
individually will be a tedious and complex task. In addition, it does not bring about
consistency in the appearance of all the Web pages on the website. Styles provide a solution
to this problem by enabling a programmer to apply consistent formatting across the entire
website.
Styles are used to define a set of formatting options, which can be reused to format different
HTML elements on a single or multiple Web pages. You can define styles in any of the
following ways:

Using Inline Styles


Using an Embedded Style Sheet
Using an External (Linked) Style Sheet

Using Inline Styles

Inline styles are style definitions that are applied to the style property of a particular HTML
element, and are placed directly inside the element on which it has to be implemented. Inline
styles are used when you want to apply one-time formatting to an HTML element.
To use inline styles in a Web page, you need to use the style attribute in the relevant HTML
tag. For example, if you want to display the text of a paragraph in italicized Arial font, you
have to define the style for the tag as shown in the following markup:
<p style="font-family:arial;font-style:italic">
...
...
</p>

In the preceding markup, the style applied to the <p> tag will be applied to all text written
within the <p> </p> tag in the preceding example only.

Using an Embedded Style Sheet


An embedded style sheet is a group of styles that are defined by using the <style> tag. This
tag needs to be placed within the <head> </head> tag on your Web page. The embedded
style sheet is used when you want to apply a unique style to the various elements on a Web
page.
The embedded style sheet enables you to define all the styles for a Web page at one place.
This reduces the time required to design a Web page because you need not define the
properties for the tags individually. You can define the properties for the desired elements
once in the embedded style sheet and the properties will be implemented to all the elements
throughout your Web page.
For example, consider the following markup:
<html> <head>
<title>
An Embedded Style
</title>
<style type="text/css">
h1 { font-style:italic;background:yellow;color:red }
p { font-style:bold;color:blue}
</style>
</head>

<body>
<h1> An Embedded Style </h1>
<p> Embedded style sheet is a part of HTML document.
</p>
</body>
</html>

In the preceding markup, the <style> tag is used to define an embedded style sheet. The
<style> tag defines the properties for the <h1> and tag. All the <h1> and tags defined
within the Web page will inherit the style defined in the <style> tag.

Using an External (Linked) Style Sheet


The style definitions in an external style sheet are stored in a separate file having the .css
extension. An external style sheet is used when you want to apply the same style rules to
more than one Web page on a website. The external style sheet can contain styles for
individual elements or generic styles that can be applied to any element. For example, you
can create a stylesheet by the name style.css containing the style definitions for the <h1> tag,
as shown in the following code snippet:
h1
{
font-weight: bold;
font-size: large;
color: green;
font-family: Verdana, Arial, Sans-Serif;
}

The preceding style can only be applied to the <h1> tags. You can also create generic styles,
as shown in the following code snippet:
.heading
{
font-weight: bold;
font-size: large;
color: green;
font-family: Verdana, Arial, Sans-Serif;

The preceding style can be applied to any element on the Web page.
After the .css file is created, it has to be linked with HTML documents on which the styles
are to be implemented. This can be done by using the <link> tag. The link> tag should be
defined within the <head> element of the HTML document. The following markup shows
how to link an external style sheet to an HTML document by using the <link> tag:
<head>
<link rel=stylesheet href="style.css" type="text/css">
</head>

In the preceding markup, rel=stylesheet specifies that the document will use a style sheet,
href="style.css" specifies that the document will refer to the file, style.css, for the style
definition, and type="text/css" signifies that it refers to a .css file for picking up the style
definitions.

Note
To apply generic styles created in an external style sheet to an element, you need to include
the class=<name of the style>" or cssClass="<name of the style>" attribute in the
element.

Working with Themes

The style sheet rules are limited to a fixed set of style attributes, such as fonts, borders, and
foreground and background colors. These rules cannot control other aspects of ASP.NET
controls, such as organizing items into rows and columns in the CheckBoxList control,
specifying graphics for a TreeView control, and specifying the template layout of a GridView
control. This gap can be filled by using the ASP.NET themes.
ASP.NET themes are a collection of properties that enable you to define the appearance of
Web pages and controls on your website. A theme can include skin files, cascading style
sheet files (.css files), and graphics. By applying a theme, you can give Web pages a
consistent appearance across your website.

Creating a Theme
You can use a theme in Web applications by creating a skin file and attaching it to the Web
pages on which you want to apply the theme. Skin files are used to define the property
settings for ASP.NET Web server controls. Generally, skin files are created and stored in a
theme folder. This theme folder is placed inside the folder named App_Themes. All the
themes in a Web application are placed inside the App_Themes folder. This folder is placed
inside the top-level directory of your Web application.
For example, you can create a folder named Mytheme for your Web application named
MyApp. This theme folder will be placed inside the MyApp\App_Themes folder and
contains the skin file(s) for the theme.
You can define multiple themes for your Web application. Each theme in a Web application
can be defined in a separate folder inside the App_Themes folder. However, you can apply
only one theme on a given page at a time.
Consider a scenario wherein you want to create a skin file for providing consistent
appearance to all the button controls in your Web page. For this, you want to specify the
ForeColor and BackColor properties of the button controls. To set the ForeColor and
BackColor properties of the button controls, you need to type the following markup in the
skin file:
<asp:Button runat="server" ForeColor="White" BackColor="Orange"/>

The runat="server" attribute is mandatory. However, other attributes are optional and are
used according to the requirement.
You can create multiple skin files in a theme directory or place all the control tags in a single
skin file. ASP.NET treats all the skin files in a theme directory as part of the same theme
definition.

Applying a Theme

You can apply a theme either to a particular Web page or to all the Web pages on a website.
If a theme is applied to a particular Web page, the theme settings are applied only to that Web
page. However, if you apply the theme to the entire website, the theme settings are applied to
all the Web pages on the website.
Applying a Theme to a Web Page
To apply a theme to a particular Web page, you need to bind the theme at the page level. If
you bind the theme at the page level, the styles and skins are only applied to that Web page
and its controls. To bind a theme at the page level, you need to set the Theme attribute of the
@Page directive. For example, the following @Page directive specifies that the theme,
MyTheme, is applied to the Web page:
<%@Page Language="C#" AutoEventWireup="true"
Inherits="_Default" Theme="MyTheme" %>

CodeFile="Default.aspx.cs"

If you have defined settings for the control locally as well as in the theme, the settings
defined in the theme override the local control settings. This strategy enables the theme to
create a consistent look across all the Web pages, even if you have set the control properties
locally.
However, if you have used a stylesheet theme, the local page settings override the settings
defined in the stylesheet theme. You can use stylesheet theme if you want the theme to be
applied only to those controls whose settings have not explicitly been defined at the page
level.
To apply a stylesheet theme to a Web page, you need to set the StyleSheetTheme attribute of
the @Page directive as shown in the following directive:
<%@Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" StyleSheetTheme="MyTheme" %>

If you do not want the theme property to be applied to a particular control, you can set the
EnableTheming property of that control on the Web page to false, as shown in the
following markup:
<asp:Button ID="Button1" runat="server" ... EnableTheming="false" />

In the preceding markup, no theme will be applied to the button control, Button1. However,
the settings defined in the theme will still be applied to other button controls, whose
EnableTheming property is not set to false.
Applying Themes Dynamically

In addition to applying a theme at the design time, you can apply a theme dynamically. To
apply a theme dynamically, you need to set the Page.Theme or Page.StyleSheetTheme
property in your code. These properties must be set in the Page_PreInit event. For example,
you have created a skin file, SkinFile.skin, in the MyTheme folder. To set this theme
dynamically, you need to write the following code snippet:
protected void Page_PreInit(object sender, EventArgs e)

{
Page.Theme = "MyTheme"; //name of the folder in which you
//have stored the skin file.
}

Similarly, you can set the SkinID property of a control dynamically to attach it to a different
named skin.
Applying a Theme to a Website
To apply the theme to all the Web pages on a website, you need to bind the theme at the
website level. If you bind the theme at the website level, the styles and skins are applied to all
the Web pages and controls on the website unless you override a theme for an individual Web
page.
To apply a theme to the entire website, you need to configure the <pages> element in the
web.config file, as shown in the following markup:
<configuration>
<system.web>
<pages theme="MyTheme">
...
</pages>
</system.web>
</configuration>

Creating Multiple Skins


Skin files standardize the look and feel of controls across all the Web pages on a website.
However, there may be situations where you want multiple occurrences of a control to appear
differently on the same Web page. For example, you can have many labels on your Web
page. Each label can look different depending on whether they are being used for headings or
body text. ASP.NET allows you to create multiple settings for the same control by using
multiple skins.
When you create more than one theme for the same control, ASP.NET generates an error
stating that a control can have a single default skin. This error can be avoided by using a
named skin. A named skin can be created by supplying the SkinID attribute. The following
markup is used to create multiple skins for a button control:
<asp:Button runat="server" ForeColor="White" BackColor="Orange"/>

<asp:Button runat="server" ForeColor="White" BackColor="Green"


SkinID="AlternateSkin"/>

In the preceding markup, the first is the default skin whereas the second with the SkinID
attribute is known as the named skin. Default skins are applied automatically whereas named
skins can be applied to a control by setting the SkinID attribute of the control, as shown in
the following code-snippet:
<asp:Button ID="Button1" runat="server" SkinID="AlternateSkin" />

In the preceding example, the named skin, AlternateSkin, is applied to the button control.

Working with Master Pages


A website contains multiple Web pages connected to each other. There are certain
components that need to be present across all the Web pages on the website. For example,
there could be a company logo and a navigation bar that need to appear on each page of the
website. The placement and appearance of this logo and navigation bar should remain
consistent across all the pages. Therefore, you need to copy the logo and navigation bar on
each page individually. You also need to make sure that the logo and the navigation bar are
placed at the same position on all the pages to maintain a consistent look and feel. Moreover,
any changes in the logo or navigation bar at a later stage will require you to make changes on
each page of the website. This is a complex and time-consuming process of creating Web
pages. This process can be simplified and made quicker by using master pages.
ASP.NET provides you with the master pages feature. This feature enables you to create a
page layout that you can use with selected or all Web pages on your website. Master pages
are used to create a consistent look and feel for your website.
Master pages are similar to ordinary ASP.NET pages and can contain static text, HTML
elements, and server controls. The file extension of master pages is .master. You cannot view
master pages directly on a browser. In order to view master pages on a browser, they must be
used by other Web pages, known as content pages. Master pages define the structure and
common ingredients of the content pages.

Creating a Master Page


The ordinary .aspx page in ASP.NET contains the @Page directive. However, the master page
in ASP.NET replaces the @Page directive with a special @Master directive, as shown in the
following markup:

<%@Master Language="C#" CodeFile="MyMaster.master.cs" Inherits="MasterPage"


%>

In addition to the @Master directive, the master page contains the following elements:

HTML or ASP.NET Elements: You can use any HTML or ASP.NET element in
your master page. For example, you can use an HTML table to define the layout,
static text to display the copyright information, an element to display the company
logo, and ASP.NET server controls to create navigation for your website on the
master page.
ContentPlaceHolder Controls: ContentPlaceHolder controls are that portion of the
master page that a content page can change. A master page should contain at least one
ContentPlaceHolder control.

Connecting Master Pages and Content Pages


Once you have created the master page, you need to connect it to the content pages to
standardize the layout of the website. To bind a master page with the content page, you need
to include the MasterPageFile attribute in the @Page directive of the content page. This
attribute points to the master page to be used with the content page, as shown in the following
markup:
<%@Page Language="C#" MasterPageFile="~/Master1.master" Title="Content
Page"%>

In the preceding markup, the MasterPageFile attribute binds the content page to the
Master1.master page. The path for the master page starts with ~/. It specifies the root
website folder. If you directly specify the master page filename without using ~/, ASP.NET
checks a predetermined subfolder named MasterPages for the master page. If you have not
created the folder or the master page is not found in that folder, ASP.NET searches the root
website folder for the master page.
In addition to the MasterPageFile attribute, the @Page directive of the content page contains
another attribute, Title. The master page file contains the <Title> tag within the <Head>
tag. If a title is specified in the master page, it will also be displayed in the content page
because the content page cannot modify the contents of the master page. However, the title
specified in the master page can be overridden in the content page by the using the Title
attribute.
The source code of the content page is different from that of a normal page. This is due to the
fact that the content page cannot define anything that is already defined in the master page
such as the <head> section, the root <html> element, and the <body> element. It can only
supply a Content tag that corresponds to the ContentPlaceHolder in the master page. The
Content tag is the place where you can insert the content for the content page.
The following figure shows how the place holder content for the master page is supplied by
the content page.

Content Page Supplying the Placeholder Content to the Master Page


In the preceding figure, the content page is supplying the content for the content placeholders
in the master file. The content placeholders in the content page must have the same ID as that
of the content placeholders in the master page.

Note
You can also connect a content page to a master page at run time. For this, you need to write
the following code within the Page_PreInit event handler:
Page.MasterPageFile = "~/MasterPage.Master";

Creating Nested Master Pages


Master pages are used to standardize the look and feel of all the Web pages on a website.
However, sometimes it is required that some of the Web pages on a website should follow
certain standard features in addition to the features provided by the master pages. In such
situations, you can implement the nested master pages.

Consider an example wherein a website is using a master page for displaying the company
logo in the header and a TreeView control on the left side for navigation. Some of the Web
pages on the website require a footer to be displayed in addition to the header and the
TreeView control provided by the master page. This can be implemented by using a nested
master page.
Similar to master pages, the extension of the nested master page file is .master. Like any
content page, a nested master page contains the <Content> controls that are mapped to the
<ContentPlaceHolder> controls on a master page. In addition, a nested master page
contains content placeholders of its own to display the content supplied by its own content
pages.

Interacting with a Master Page Programmatically


There are situations wherein you may want to change the layout of the master page through a
particular content page. One such situation is when you want to hide the navigation controls,
which are implemented in the master page to have more space to see the page content in a
particular content page.
You cannot implement this functionality in the master page because then the navigation
controls will not be visible in any of the content pages. Similarly, you cannot implement it by
using the content page because it involves modifying a fixed portion of the master page,
which cannot be done through the content page.
One way to implement this is by adding a public property to the master page class. This
property, when set to false, automatically hides the navigation controls. Such a property can
be added to the master page class by writing the following code snippet:
public partial class MyMasterPage : System.Web.UI.MasterPage
{
public bool ShowNavigation
{
get
{
return TreeView1.Visible;
}
set
{
TreeView1.Visible = value;
}

}
}

The scope of the preceding property is declared as public so that it can be accessed by other
classes. This property cannot be directly accessed by the content pages. To access this
property, the content pages have to use the built-in Page.Master property. However, you
cannot access the ShowNavigation property directly by using the
Page.Master.ShowNavigation statement. This is because the Page.Master property does
not have any information about the custom properties that have been added in derived master
page class. To access such custom properties from the content page, you need to cast the
Page.Master object to the appropriate type, as shown in the following code snippet:
protected void btnHide_Click(object sender, EventArgs e)
{
MyMasterPage master = (MyMasterPage)this.Master;
master.ShowNavigation = false;
}
protected void btnShow_Click(object sender, EventArgs e)
{
MyMasterPage master = (MyMasterPage)this.Master;
master.ShowNavigation = true;
}

In the preceding code snippet, MyMasterPage is the name of the master page class and
ShowNavigation is the public property of the MyMasterPage class.

Summary
In this chapter, you learned that:

Styles are used to define a set of formatting options that can be reused on a single or
multiple Web pages.
Styles can be defined in any of the following ways:
o

Using Inline Styles

o
o

Inline styles are style definitions that are applied to the style property of a particular
HTML element.
An embedded style sheet is a group of styles that are defined by using the <style>
tag.
The style definitions in an external style sheet are stored in a separate file having the
.css extension.
ASP.NET themes are a collection of properties that enable you to define the
appearance of Web pages and controls on your website.
You can apply a theme either to a particular Web page or to all the Web pages on a
website.
To bind a theme at the page level, you need to set the Theme attribute of the @Page
directive.
To apply a theme to the entire website, you need to configure the <pages> element in
the web.config file.
You can create more than one theme for the same control.
Master pages enable you to create a page layout that you can use with selected or all
Web pages on your website.
A master page contains the following elements:
o
o

Using an Embedded Style Sheet


Using an External (Linked) Style Sheet

HTML or ASP.NET Elements


ContentPlaceHolder Controls

To bind a master page with the content page, you need to include the
MasterPageFile attribute in the @Page directive of the content page.
Content pages can interact with the master pages programmatically.

Reference Reading
Working with Styles
Reference Reading: Books

Reference Reading: URLs

Beginning ASP.NET 3.5


with C# by Chris Hart,
John Kauffman, David
Sussman, Chris Ullman

http://www.west-wind.com/WebLog/posts/158367.aspx
http://www.15seconds.com/issue/040105.htm

Working with Themes


Reference Reading: Books

Reference Reading: URLs

Essential ASP.Net 3.5 by


Fritz Onion, Keith Brown

http://www.15seconds.com/issue/040105.htm

Working with Master Pages


Reference
Reading:
Books

Reference Reading: URLs

Chris Hart,
John
Kauffman,
Beginning
ASP.NET.3.5

http://quickstarts.asp.net/QuickStartv20/aspnet/doc/masterpages/default.aspx
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/masterpages/default.aspx
http://www.beansoftware.com/ASP.NET-Tutorials/Master-Pages.aspx

Chapter 4

Navigating Websites
A website is a collection of interconnected Web pages. Users need to navigate between these
Web pages to get the required information. Navigation between Web pages can be made
easier by implementing a proper navigation system. Such a system can be implemented by
using site maps and navigation controls provided by ASP.NET.
This chapter provides an overview of site maps. In addition, it discusses how to implement
navigation on a website by using the navigation controls provided by ASP.NET.

Objectives
In this chapter, you will learn to:
Work with site maps
Work with navigation controls

Working with Site Maps


A website is a collection of Web pages. The information that needs to be shared by the
website is contained in these Web pages. Therefore, these Web pages should be linked in
such a manner that a user can easily move to the desired page. Moving between the Web
pages on a website is known as navigation. To provide a smooth navigation on a website, you
need to provide a path that can direct a user to any part or Web page on the website. This path
is known as the navigation path.
A navigation path describes the structure of a website and acts as a roadmap for a user. A
properly structured navigation path enables a user to easily navigate to any part or section of
a website and adds to the popularity of the website. However, in most of the traditional
websites a proper navigation path was not provided and the users could move between Web
pages either by clicking a button or by clicking a hyperlink placed on the Web pages. For
this, the developers had to write the same code on every Web page to place the buttons or
hyperlinks. It was a time-consuming process.
To overcome this problem, ASP.NET provides the site navigation feature that provides a
consistent way to navigate a website. This feature enables you to store the structure of your
website at a central location. This structure contains the links to all the Web pages on your
website and is known as a site map. This site map containing the links to all the Web pages
can be rendered in lists or navigation menus on each page by including specific Web server
controls such as a TreeView, a SiteMapPath, or a Menu.

Defining a Site Map

To provide a consistent way to navigate a website, you need to define the hierarchical
structure of the website by using a site map. A site map is an XML file that describes the
hierarchical and logical structure of the website. It stores links to all the Web pages on a
website. These links can be rendered through navigation controls.
To create a site map, you need to create an XML file with the .sitemap extension. This file
must be located in the application root directory. Every .sitemap file contains the <siteMap>
element. All the information regarding the site map is written within the opening and closing
tags of the <siteMap> element, as shown in the following example:
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
...
</siteMap>

In the preceding example, the xmlns attribute of the siteMap element tells ASP.NET that the
XML file uses the ASP.NET site map standard.
A site map defines the hierarchical structure of the Web pages on a website. To create the
hierarchical structure, you need to use the <siteMapNode> element within the opening and
closing tags of the <siteMap> element. Each page in the hierarchical structure is represented
by a <siteMapNode> element. The <siteMapNode> element contains various attributes, as
shown in the following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx" />

In the preceding example, the title attribute specifies the text that is usually used as link text.
The description attribute specifies the text that acts as a tool tip. The url attribute specifies
the linked page.

Note
The SiteMapPath control is one of the navigation controls that display the navigation
structure of a website. It is discussed in detail in the next section.
Creating Hierarchical Group of Links in Site Maps
There are situations when you want the Web pages in a site map to be divided into groups.
One such situation is when you want to display the Home page as the root node and all other
Web pages such as the products page within the root node (Home page). To represent such a
group in the site map file, you need to place one <siteMapNode> element inside another. For
this, you need to split the <siteMapNode> element into a start and an end tag, as shown in the
following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx">

...
</siteMapNode>

You can add more <siteMapNode> elements within the root <siteMapNode> element and
create a group, as shown in the following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx">
<siteMapNode title="Software" description="Software choices"
url="~/software.aspx" />
<siteMapNode title="Hardware" description="Hardware choices"
url="~/hardware.aspx" />
</siteMapNode>

The preceding example creates a hierarchical group of links. In this example, the Home group
contains two more pages, software and hardware. This hierarchical group of links is
represented as shown in the following figure.

A Hierarchical Group of Links

Note
A site map must always have a single root node. All the other nodes must be contained inside
this root-level node.

Note
Two site map nodes in a .sitemap file cannot have the same URLs. This is because the site
map information is stored as a collection where each item is indexed by its unique URL.

Binding a Page to a Site Map


Once the navigation structure of a website is defined in the site map file, it needs to be bound
to a Web page. To bind the site map file to a Web page, you need to add the
SiteMapDataSource control to the Web page. You can add the SiteMapDataSource control to
the Web page by using the following code:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

After adding the SiteMapDataSource control, you need to add navigation controls to the Web
page. The navigation controls are linked to the SiteMapDataSource control and are capable
of displaying the navigation structure contained in the site map file. To use a navigation
control, such as a TreeView control, you need to use the following code:
<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="SiteMapDataSource1"/>

Configuring the Site Map Provider


ASP.Net provides various navigation controls that enable users to display the navigation
structure, stored in the Web.sitemap file, on a Web page. These controls use the default sitemap provider or the XMLSiteMapProvider class to read site-map information from the
Web.sitemap file. However, there are situations wherein instead of using the default site-map
provider you may want to implement your own site-map provider. Some of the situations are:

When you want to store the site-map information in a data source that is not supported
by the default site-map provider.
When you want to use a data source other than the Web.sitemap file.

You can create a custom site-map provider by creating a class that inherits the
SiteMapProvider abstract class from the System.Web namespace and implementing the
abstract members that are exposed by the SiteMapProvider class. The following table lists
the methods that need to be implemented in the custom site-map provider.
Method

Description

FindSiteMapNode

Gets an instance of the SiteMapNode class


that represents a page.

GetChildNodes

Gets the child nodes of a specific instance of

the SiteMapNode class.


GetParentNode

Gets the parent node of a specific instance of


the SiteMapNode class.

GetRootNodeCore

Gets the root node of all the nodes that are


managed by the current provider.

The Methods that need to be Implemented in the Custom Site-Map Provider


After creating the custom class and implementing the preceding methods, you need to
configure the custom provider as the default provider in the web.config file. This can be done
by using the markup as shown in the following example:
<configuration>
<system.web>
<siteMap defaultProvider="CustomProvider">
<providers>
<add
name="MyProvider"
type="<type name>"
siteMapFile = "<path>/siteMap.txt"/>
</providers>
</siteMap>
</system.web>
</configuration>

In the preceding example, a custom site-map provider is created that is using a text file to
store the navigation structure. The defaultProvider attribute of the siteMap element
specifies the name of the custom site-map provider class. You need to specify the complete
path of the text file in the siteMapFile attribute.
If you want to have the same functionalities as provided by the default site-map provider but
want to use a data store other than the Web.sitemap file, then you need to configure the
web.config file as shown in the following example:
<siteMap>
<providers>

<add name="MusicManiaSiteMap" type="System.Web.XMLSiteMapProvider"


siteMapFile="MusicMania.sitemap"/>
</providers>
</siteMap>

Note
If you are using a custom site-map provider, you need to explicitly set the SiteMapProvider
property of the SiteMapDataSource control.

Implementing Navigation by Using


Navigation Controls
The process of implementing navigation on websites includes creating a navigation structure
and associating it with navigational controls. This can be done by defining a structure of the
site in a site map file and binding it with the page by using the SiteMapDataSource control.
After this, you need to associate the SiteMapDataSource control with any of the following
three navigational controls:

The SiteMapPath Control


The TreeView Control
The Menu Control

The SiteMapPath Control


The SiteMapPath control is one of the navigation controls that display the navigation
structure of a website. The navigation structure or the navigation path of the website
displayed in the SiteMapPath control is known as breadcrumb. A breadcrumb shows the
users current page location and displays a link as a hierarchical path back to the home page.
This allows the user to navigate up the hierarchy by using these links.
Consider a scenario where a user visits the Home page of a website. From within the Home
page, the user navigates to the Products page. Further, the user navigates to the Sports page
from the Products page. In this scenario, the SiteMapPath control will display the path in the
form of links as shown in the following figure.

Path Displayed by the SiteMapPath Control

The preceding path indicates that the user is currently on the Sports page. The user can
navigate either to the Home page or to the Products page by clicking the corresponding link
displayed as a breadcrumb in the SiteMapPath control.
The SiteMapPath control obtains navigation data from the site map. This data includes
information about the pages on your website, such as the URL, title, description, and location
in the navigation hierarchy.
Properties of the SiteMapPath Control
You can use various properties of a SiteMapPath control to customize its appearance. The
following table lists some properties of the SiteMapPath control.
Property

Description

ShowToolTips

Shows the description text when a user


hovers the mouse pointer over the site map
path.

ParentLevelsDisplayed

Sets the maximum number of levels above the


page that is currently displayed on the users
Web browser.

PathDirection

Allows you to set the direction of the path of


navigation. If you specify the property to
RootToCurrent, the path will be from the
root page to the current page. If you specify
the property to CurrentToRoot, the path will
be in reverse order.

PathSeparator

Indicates the characters that will be placed


between each level in the path. The default is
the greater-than symbol (>).

Properties of the SiteMapPath Control

The TreeView Control


A TreeView control is used to display hierarchical data. Therefore, it can be used to display
the navigational structure of a website. Using a TreeView control, you can show a portion of
the site map or the entire site map. The hierarchy of the Web pages in the site map is shown
in the form of nodes and subnodes. All the nodes or subnodes are represented as links. These
links enable you to navigate to a new page.
To use the TreeView control on a Web page, you need to add a SiteMapDataSource control
to the Web page. Next, you need to set the DataSourceID property of the TreeView control
to the ID of the existing SiteMapDataSource control.
To use a TreeView control effectively, you must understand the properties of the TreeView
control.

Properties of the TreeView Control


The properties of a TreeView control allow you to change the appearance of the control. The
following table lists some properties of the TreeView control.
Property

Description

NodeIndent

Sets the number of pixels between each level


of node in the TreeView control.

ImageSet

Allows you to use a predefined collection of


node images for collapsed, expanded, and
nonexpendable nodes.

ShowLines

Adds lines that connect every node.

ExpandDepth

Specifies how many levels of nodes will be


visible at first.

Properties of the TreeView Control

The Menu Control


The Menu control is another control that supports hierarchical data. Therefore, it can also be
used to display the navigational structure of a website. The Menu control displays
hierarchical data in the form of a main menu and submenus. It only displays the main menu
on a Web page. When a user hovers over an option in the main menu, a drop-down menu is
displayed containing links to other Web pages in the hierarchy. This avoids congestion on a
Web page when many links are to be displayed.
To use the Menu control on a Web page, you need to add a SiteMapDataSource control to the
Web page. Next, you need to set the DataSourceID property of the Menu control to the ID of
the existing SiteMapDataSource control.
A Menu control is similar to a TreeView control as they both display the hierarchical
navigation system of a website. However, there are some differences between these two
controls.
The following table lists the differences between Menu and TreeView controls.
Menu Control

TreeView Control

Can display a single submenu at a time.

Can expand arbitrary number of node


branches at a time.

Displays only root level node on a Web page.


All other node items appear as pop-up when
a user hovers over a node with the mouse
pointer.

Displays all the levels of nodes on the Web


page.

Supports templates.

Does not support templates.

Does not support check boxes for any node.

Supports check boxes for nodes.

Supports horizontal and vertical layouts.

Supports only vertical layout.

Differences between the Menu and the TreeView Control

Summary
In this chapter, you learned that:

A navigation path describes the structure of a website and acts as a roadmap for a
user.
A site map is an XML file that describes the hierarchical and logical structure of the
website.
A site map stores links to all the Web pages on a website.
After creating the site map file, you need to bind it to a Web page.
The site map can be bound to a Web page by using the SiteMapDataSource control.
After adding the SiteMapDataSource control, you need to add a navigational control
to the Web page.
The three navigational controls provided by ASP.NET are:
o The SiteMapPath Control
o The TreeView Control
o The Menu Control

Reference Reading
Working with Site Maps
Reference Reading:
Books

Reference Reading: URLs

Beginning ASP.NET 3.5


in VB 2005: From Novice
to Professional by
Matthew MacDonald

http://msdn.microsoft.com/en-us/library/aa479320.aspx
http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx
http://blogs.techrepublic.com.com/programming-and-

development/?p=456
Implementing Navigation by Using Navigation Controls
Reference Reading:
Books

Reference Reading: URLs

Beginning ASP.NET 3.5


in VB 2005: From Novice
to Professional by
Matthew MacDonald

http://support.microsoft.com/kb/913721

Chapter 5

Managing State in Web Applications


Web pages and ASP.NET Framework use HTTP protocol to communicate between a Web
browser and a Web server. HTTP is a stateless protocol and cannot automatically indicate
whether the sequential requests are coming from the same or different clients. Therefore,
when a Web page is posted to the server, a new instance of the Web page class is created.
This results in the loss of all the information associated with the page and the controls placed
on it.
To overcome this limitation, ASP.NET provides the state management feature. In addition, it
provides a feature called caching that helps you improve the performance of your Web
application.
This chapter discusses the various client-side and server-side state management options
provided by ASP.NET. In addition, it discusses how to improve the performance of a Web
application by using caching.

Objectives
In this chapter, you will learn to:
Implement client-side state management
Implement server-side state management
Manage state by using cross-page posting
Implement caching

Implementing Client-Side State


Management
A new instance of the Web page class is created each time the page is posted to the server. In
traditional Web programming, this would typically mean that all information associated with
the page and the controls on the page would be lost with each round trip.
Consider an example. Suppose a user fills up some personal information on a Web form.
While filling up this information, the user selects a country from a drop-down list on the Web
page. As soon as the user selects a country, the page needs to be posted back to the server to
retrieve a list of state names, which need to be populated in another drop-down list on the
same Web page. When the page is posted to the server, a new instance of the Web page class

will be created, and therefore, all information previously entered on the Web page will be
lost. This problem can be solved by using client-side state management.
Client-side state management allows you to store information either on a Web page or on a
client computer. Such state management improves the performance of a Web application
because it reduces the load on the server. The various options available to implement clientside state management are:

Hidden Fields
View State
Control State
Cookies
Query Strings

Note
You can store only a limited amount of information by using client-side state management.

Hidden Fields
A hidden field is a control similar to a TextBox control. However, unlike a TextBox control,
it does not render in a Web browser. As a result, a user cannot type anything in it.
Hidden fields can be used to store information that needs to be submitted along with the Web
page, but should not be displayed on the page. For example, when the details of a product are
displayed on a Web page, the ID of the product can be stored in a hidden field. If the user
orders the product, the information stored in the hidden field will be sent to the server and the
corresponding product will be added to the shopping cart.
Hidden fields can also be used to pass session information to and from forms, transparently.
Consider an example. Suppose the home page of your website asks a user to specify his or
her favorite color. When the user clicks the submit button to move to another page, say
Page1.aspx, the information about the favorite color can be passed on to a hidden field on
Page1.aspx and the information can be used to change the background color of the page to
the specified color. Similarly, when the user moves from Page1.aspx to another page, say
Page2.aspx, the information in the hidden field on Page1.aspx can be passed on to a hidden
field on Page2.aspx. This information, again, can be used to change the background color of
Page2.aspx to the specified color.
To pass the information from one page to another, you can invoke the Server.Transfer
method on the Click event of a Button control, as shown in the following example:
protected void Button1_Click(object sender, EventArgs e)
{

Server.Transfer("Page2.aspx");
}

The target page can access the passed information by referring to individual controls on the
source page, as shown in the following example:
String name = Request.Form["TextBox1"];
String color = Request.Form["HiddenField1"];

Note
To ensure that the passed values are available to the target page, you must submit the page
by using the HTTP Post method.
A hidden field acts as a repository for any page-specific information that you want to store
directly in a page. The advantages of using hidden form fields are:

A hidden field can store page-specific information without accessing any Web server
or Web browser resource.
A hidden field can be easily implemented in an ASP.NET Web form page. You just
need to add the HiddenField control to a Web page and use the Value property of the
control to set its value.

Some limitations of using hidden form fields are:

You can view the information stored in the hidden field by accessing the source of the
Web page. Therefore, the values stored in hidden form fields are not very secure.
A hidden field does not support more than a single value field to store information.
The hidden fields are stored in a page. Therefore, storing large values in hidden form
fields can slow down the processing of the page.
If you use hidden fields, you must submit your pages to the server using the HTTP
POST method instead of requesting the page using the page URL. You cannot take
advantage of hidden fields if a page is processed in response to a link or the HTTP
GET method.

View State
Each Web page and controls on the page have a property called ViewState. This property is
used to automatically save the values of the Web page and each control on the Web page
prior to rendering the page. This, in turn, enables you to retain the page and control-specific
values between round trips to the server.
The view state is implemented with the help of a hidden form field called __ViewState. This
hidden form field is automatically created in every Web page.

When ASP.NET executes a Web page on the Web server, the values stored in the ViewState
property of the page and controls on it are collected and formatted into a single encoded
string. This encoded string is then assigned to the Value attribute of the hidden form field,
__ViewState, and is sent to the client as part of the Web page.
During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore
the values in __ViewState. When the page is initialized during postback, ASP.NET
Framework parses the view state string to restore the information displayed on the page.
The view state of a Web page or a control consists of the cumulative property values of the
page or the control. To preserve these values across stateless HTTP requests, Web pages and
controls in ASP.NET use an instance of the StateBag class.
The StateBag class is the primary storage mechanism for HTML and server controls. This
class works like a dictionary object and allows you to store items as a key/value pair in it. It
accepts a string as a key and an object as its value. Items added to this class are automatically
added to the hidden __ViewState form variable.
Storing Information in View State
Information in the form fields on a Web page is automatically added to the view state. In
addition to the information contained in form fields, the view state can be used to store some
additional information. For example, you can store a key-value pair, Counter=1, in the view
state by using the following code:
ViewState["Counter"] = 1;

In the preceding code snippet, a key by the name Counter is stored in the view state and the
value 1 is assigned to the key. If currently no key has the name Counter, a new key will be
added automatically. If a key with the name Counter already exists, it will be replaced.
Retrieving Information from View State
A value stored in view state can be retrieved by using code. For example, you can retrieve the
value of the key, Counter, from view state by using the following code snippet:
int counter;
counter = (int) ViewState["Counter"];

In the preceding code snippet, the value stored in the key, Counter is converted to an integer
before storing it into an integer variable.
Enabling and Disabling View State
By default, the ViewState property of a Web page and the controls on the Web page is
enabled. However, you can disable this property for a Web page or any particular control on
the Web page. This is required when you have a large volume of information to maintain.
However, maintaining large volume of information leads to a significantly slower rendering

of a Web page. Therefore, disabling the ViewState property is important when users are
accessing a Web page with limited bandwidth.
You also need to disable the ViewState property for users using mobile devices. This is
because mobile devices may not have enough storage space for storing large volumes of
information.
You can enable or disable the ViewState property of a Web page or an individual control by
setting the EnableViewState property of the Web page or the control to True or False. You
can set the EnableViewState property of a Web page by using the @Page directive, as shown
in the following example:
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false"
CodeFile="Page1.aspx.cs" Inherits="Page1" %>

To determine the effect of enabling and disabling the ViewState property of a control,
consider an example. Add a Label and a Button control to a Web page and type the following
code in the Page_Load event handler:
if(!IsPostBack)
{
Label1.Text="Hello World";
}

Note
By default, a Button Web server control submits a page back to itself.
When this page is loaded for the first time, the message, Hello World, is displayed in the
Label control. When the user clicks the button, the message is still displayed on the Label
control. This is because the default value of the EnableViewState property of the Label
control is True.
To see the effect of disabling the ViewState property, set the EnableViewState property of
the Label control to False and execute the application. When this page is loaded for the first
time, the message, Hello World, is displayed in the Label control. However, when the button
is clicked, the Label control displays the default text, Label. This is because the Label control
does not maintain its state when its EnableViewState property is set to False.

Note

If the EnableViewState property of a Web page is set to False, ViewState is not maintained
for any control on that Web page, even if the EnableViewState property of a control on the
Web page is set to True.
The advantages of using view state are:

The values in view state are stored in a standard HTML format as part of a Web page.
Therefore, no Web server resource is required to maintain it.
The view state can be easily implemented on the ASP.NET Web page. You just need
to set the EnableViewState property of a Web page and server controls.
The values in view state are hashed, compressed, and encoded for Unicode
implementations. Therefore, values in view state are more secure than the values
stored in hidden fields.

View state also has the following limitations:

Storing large values can cause a page to slow down when users display it or post it
because view state is stored in the Web page.
View state is stored in a hidden field on a Web page. Although view state stores data
in a hashed format, it can be tampered with. The information in the hidden field can
be seen if the page output source is viewed directly, creating a potential security issue.

Control State
You can use the ViewState property to preserve page and control values between round trips
to the Web server. If you disable the ViewState property of a page, the ViewState of the
controls on that page is not maintained. This can lead to improper functioning of some
controls on the page. For example, the state of the selected node in a TreeView control needs
to be maintained for the control to function properly across postbacks.
To enable persistence of property information that is specific to a control, ASP.NET allows
you to store the state of a control by using a client-side state maintenance mechanism called
control state. Unlike view state, the control state cannot be disabled at the page level.
Therefore, if your Web page contains controls whose state must be maintained, you can use
the control state mechanism to store their state.
You can implement control state on a custom Web control by overriding the following
methods of the base class:

OnInit: This method should contain the following lines of code:


Page.RegisterRequiresControlState(this); base.OnInit(e);
SaveControlState: This method should return a public property of the

control
(whose state needs to be saved) or an object array containing the values of all the
public properties of the control.
LoadControlState: This method should set the value of the public properties to the
values contained in the object passed to the LoadControlState method as an
argument.

Cookies
Cookies are used to store small pieces of information related to a users computer, such as its
IP address, browser type, operating system, and Web pages last visited. The purpose of
storing this information is to offer a personalized experience to the user. For example, if a
user has logged on to your website for the first time, the name of the user can be stored in a
cookie. This information can be retrieved later on when the same user visits the website again
to greet the user with his/her name.
Cookies are sent to a client computer along with the page output. These Cookies are stored on
the clients computer. When a browser requests the same page the next time, it sends the
cookie along with the request information. The Web server reads the cookie and extracts its
value. It then process the Web page according to the information contained in the cookie and
renders it on the Web browser.
Types of Cookies
Cookies can either be temporary or persistent. Temporary cookies exist in the memory space
of a browser. When the browser is closed, all temporary cookies added to the browser are
lost. Temporary cookies are also known as session cookies.
A temporary cookie is useful for storing information required for only a short time or that
should not be written to disk on the client computer for security reasons. For example, a
temporary cookie can be created to store the user name. The user name stored in the cookie
can be retrieved and displayed on every page of the website.
A persistent cookie is saved as a text file in the file system of the client computer. Persistent
cookies are used when you want to store information for a longer period. For example,
persistent cookies can be used to store customized user settings for a website. This helps in
customizing the website when the user visits the website again.
While creating a persistent cookie, you can set the expiration date of the cookie, which
defines the duration for which the cookie will be stored on the client computer. If you do not
set the expiration date of a cookie, the cookie is maintained as a temporary cookie, as part of
the user's session information. Once the user session is finished, the cookie is discarded.
Persistent cookies can be created as shown in the following example:
Response.Cookies["userName"].Value = "Peter";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
Response.Cookies["lastVisited"].Value = DateTime.Now.ToString();

Response.Cookies["lastVisited"].Expires = DateTime.Now.AddDays(2);

In the preceding example, two cookies, username and lastVisited, are created. The user name
Peter is stored in the first cookie and the date and time when the user, Peter, last visited the
site is stored in the second cookie. The expiry period for both the cookies is set as 2 days. If
you do not set the expiry period for the cookies, the cookies will be created as temporary
cookies.
You can also store multiple values in a single cookie. For example, instead of creating
separate cookies for storing the user name and last visited information, you can create a
single cookie that can hold both the values. Such a cookie can be created as shown in the
following example:
Response.Cookies["userInfo"]["userName"] = "Peter";
Response.Cookies["userInfo"]["lastVisited"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(2);

In the preceding example, the cookie, userInfo, with two subkeys, userName and lastVisited,
is created.
Reading Cookies
You can access the value of a cookie by using the Request built-in object. However, if you
want to modify a cookie, you need to use the Response built-in object of ASP.NET.
The following example reads the value of a cookie that stores a single value:
if (Request.Cookies["userName"].Value != null)
{
Label1.Text = Request.Cookies["userName"].Value;
}

In the preceding example, the value in the cookie, userName, is checked for null. If the value
is not null, the value is assigned to the Text property of the Label control.
Similarly, you can read the values from a cookie that stores multiple values. The following
example reads values from a cookie that stores multiple values:
if (Request.Cookies["userInfo"] != null)
{
Label1.Text = Request.Cookies["userInfo"]["userName"]);
Label2.Text = Request.Cookies["userInfo"]["lastVisited"]);
}

In the preceding example, the value in the cookie, userInfo, is checked for null. If the value
is not null, the value of the subkeys, userName and lastVisited, is assigned to the Text
properties of the Label controls.
Advantages and Disadvantages of Cookies
Cookies provide several advantages. Some advantages of using cookies are:

A cookie is stored on the client computer and can be read by the server after a request
for a page is posted. Therefore, no server resource is involved in maintaining the
cookie.
A cookie is a text-based data structure that contains key-value pairs. Therefore, it is
easy to create and manipulate cookies.
A cookie can either expire when the browser session ends or exist indefinitely on the
client computer, subject to the expiration rules on the client.

However, cookies also have the following limitations:

Cookies that are stored on the client computers have a limited size. Most browsers
allow cookies to be up to 4096 bytes in size. Therefore, you cannot store a large
amount of data in a cookie.
Users can disable cookies to prevent them from being stored on the hard disk of their
computer. If a user denies permission for cookies, an ASP.NET Web application
cannot store cookies on the client computer.
Users can tamper with cookies because cookies are stored on the client computer.

Query String
Sometimes, it is required to transfer information from one page to another. For example, on
an online book shopping website, a Web form displays the list of categories of books. When
the user selects a category, another page with detailed information about the selected category
is displayed. This process requires you to transfer the information about the selected category
to the other page so that the relevant details can be displayed. You can perform this task by
using a query string.
A query string provides a simple way to pass information from one page to another. It is the
part of a URL that appears after the Question mark (?) character. Consider the following
URL:
http://www.MyBookStore.com/search?Category=fiction
In the preceding URL, the query string defines a variable, category, which contains the string,
fiction.
You can pass data from one page to another page in the form of a query string by using the
Response.Redirect method, as shown in the following example:
Response.Redirect("BooksInfo.aspx?Category=fiction");

In the preceding example, the string fiction is stored in the variable Category and is sent to
the BooksInfo.aspx page. The information stored in the variable Category can be retrieved on
the BooksInfo.aspx page by using the following syntax:
String cat = Request.QueryString["Category"];

The preceding example returns the string fiction.


You can pass multiple values from one page to another by using a query string. For this, the
values must be separated with the ampersand (&) symbol, as shown in the following
example:
Response.Redirect("BooksInfo.aspx?Category=fiction&Publisher=Sams");

Note
There should be no blank space before and after the ampersand (&) symbol.
In the preceding example, the strings, fiction and Sams, are stored in the variables,
Category and Publisher, respectively. The information stored in these variables can be
retrieved on the BooksInfo.aspx page by using the following syntax:
String cat = Request.QueryString["Category"];
String pub = Request.QueryString["Publisher"];

Note
To ensure that the query string values are available during page processing, you must submit
the page by using the HTTP Get method.
Advantages and Disadvantages of Query Strings
The advantages of using query strings are:

A query string is contained in the HTTP request for a specific URL. Therefore, no
server resource is involved in processing a query string.
Many Web browsers support passing values in a query string. Therefore, if you create
a Web application that passes information from one page to another using a query
string, it will be processed in most of the browsers.

Query strings have the following limitations:

They can be used only with the HTTP GET method.


The information in a query string is directly visible to the users in the browser
window. Therefore, you need to encrypt this information to ensure that any
confidential information is not exposed. This causes an additional overhead to Web
application development. In addition, query strings are not useful for storing sensitive
data.
There is a limit to the amount of information that you can pass from one page to
another using query strings because most browsers support up to 255 characters of
URL.

Implementing Server-Side State


Management
There are situations where you need to store the state information at the server-side. One such
situation is when you want to know the number of users logged on to the Web application.
Server-side state management enables you to manage application and session-related
information on the server. This reduces the amount of information to be sent to the client to
preserve state.
ASP.NET provides the following options to manage state at the server side:

Application State
Session State
Profile Properties

Application State
ASP.NET provides application state as a means of storing application-specific information
such as objects and variables. The information in the application state is stored in a key-value
pair and is used to maintain data consistency between server round trips and between pages.
Application state is created the first time a user accesses any URL resource in an application.
After an application state is created, the application-specific information is stored in it. All
the information stored in the application state is shared among all the pages of the Web
application by using the HttpApplicationState class. The HttpApplicationState class is
accessed by using the Application property of the HttpContext object.

Note
Application state variables are global for an ASP.NET application. However, the values
stored in the application state variables are accessible only from the code running within the
context of the originating application. Other applications running in the system cannot
access or modify the values.

Storing Information in Application State


You can add application-specific information to an application state by creating variables and
objects and adding them to the application state. Variables and objects added to the
application state are global to an ASP.NET application. For example, you can create a
variable called MyVariable with the value Hello and store it in the application state by using
the following code snippet:
Application ["MyVariable"] = "Hello";

After the application in which you declared MyVariable is executed, any page in the
application can retrieve the value of MyVariable. To read the value of MyVariable, you can
use the following code snippet:
string val = (string) Application["MyVariable"];

You can also add complex objects, such as a Collection or a Dataset, in the application state.
For example, you can add a dataset to an application state by using the following code
snippet:
DataSet ds = new DataSet();
Application ["DataSet"] = ds;

Removing Information from Application State


In addition to adding variables and objects to application state, you can remove an existing
object or variable from application state. For example, you can remove the application
variable MyVariable from the application state, by using the following code snippet:
Application.Remove(["MyVariable"]);

You can also remove all the application state variables and objects by using the following
code snippet:
Application.RemoveAll();

After an object is added to an application state, it remains in the application state until the
application is shut down, the Global.asax file is modified, or the item is explicitly removed
from the application state.
Handling Application Events
Application state has the following events that you can capture to manipulate an ASP.NET
Web application:

Application.Start:

This event is raised when the application receives the first


request for a Web page. It is also raised on the next request after the server, Web
service, or website has been restarted. The event handler for this event usually
contains code for initializing the application variables.

Application.End:

This event is raised the server, Web service, or website is stopped


or restarted. The event handler for this event usually contains code to clean up the
resources that the application has used.
Application.Error: This event is raised when an unhandled error occurs.

You can handle the preceding events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Considerations While Using Application State
The application state variables are global to an application. Therefore, it is important to
consider the following issues while storing any value in an application state variable:

The memory occupied by variables stored in an application state is not released until
the value is either removed or replaced. Therefore, the number of variables and
objects in an application state should be minimum. Otherwise, it will be an overhead
on the Web server and the server response will be slow.
Multiple pages within an application can simultaneously access the values stored in an
application state. Therefore, explicit synchronization methods need to be used to
avoid deadlocks and access violations.

Synchronizing Application State


Multiple pages within an ASP.NET Web application can simultaneously access the values
stored in an application state. This can result in conflicts and deadlocks. For example, you
can add a variable named PageCounter in the application state to keep track of the number of
times a page has been requested. If two users access a Web page simultaneously, there will be
an attempt to update the value of the variable PageCounter by both the users which could
result in data inconsistency. To avoid such situations, the HttpApplicationState class
provides two methods, Lock() and Unlock(). These methods allow only one thread at a time
to access application state variables and objects.

Note
Each browsers request for a Web page initiates a new thread on the Web server.
Calling the Lock() method on an Application object causes ASP.NET to block attempts by
the code running on other worker threads to access anything in the application state. These
threads are unblocked only when the thread that called the Lock() method calls the
corresponding Unlock() method on the Application object. Consider the following example:
Application.Lock();
if (Application["PageCounter"] == null)
{

Application["PageCounter"]=1;
}
else
{
Application["PageCounter"]=(int)Application["PageCounter"]+1;
Response.Write(Application["PageCounter"]);
}
Application.UnLock();

In the preceding example, the Lock() method is called before accessing the value of the
PageCounter variable. This ensures that the variable cannot be modified simultaneously by
any other thread. After calling the Lock() method, the value of the PageCounter variable is
modified. After the modification is done, the UnLock() method is called to release the
imposed lock on the PageCounter application state variable. Then, the variable can be
modified by other threads.

Note
It is not required to call the Unlock() method explicitly because the .NET Framework
automatically removes the lock when the request completes or times out, or when an
unhandled error occurs during request execution and causes the request to fail.

Note
The Lock() method locks all the items in the application state object. In other words, you
cannot selectively lock items in an application state.
The advantages of using the application state are:

Application state is easy to use and is consistent with other .NET Framework classes.
Storing information in application state involves maintaining only a single copy of the
information.

Application state has the following limitations:

The data stored in an application state is lost when the Web server containing the
application state fails due to a server crash, upgrade, or shutdown.
Application state requires server memory and can affect the performance of the server
and the scalability of the Web application, if it occupies too much memory space.

You can implement application state to increase the performance of the Web application. For
example, storing relatively static dataset in an application state can enhance Website
performance by reducing the overall number of data requests to a database. However, it is
important to remember that application state variables containing large blocks of information
can reduce Web server performance as server load increases. In addition, the memory
occupied by a variable stored in an application state is not released until the value is either
removed or replaced. Therefore, it is preferred to use application state variables with small,
and less frequently changed datasets.

Session State
In ASP.NET, session state is used to store session-specific information for a Web application.
Unlike application state, the scope of session state is limited to the current browser session. If
multiple users are accessing a Web application, each will have a different session state. If a
user exits from a Web application and returns later, the user will have a different session
state.
Session state is structured as a key-value pair for storing session-specific information that
needs to be maintained between server round trips and between requests for pages.
The session state has a built-in support in ASP.NET. The built-in session state feature
automatically performs the following actions:

Identify and classify requests coming from a browser into a logical application session
on the server.
Store session-specific data on the server for use across multiple browser requests.
Raise session lifetime-related events, such as Session.Start and Session.End,
which can be handled in the Global.asax file.
Automatically release session data if a browser does not access an application within
a specified timeout period.

When a user first requests a page from an ASP.NET website, the website automatically adds
a session cookie to the client browser. This cookie is named ASP.NET_SessionID cookie.
This cookie is used for the remainder of the users visit to the website.
Identifying a Session

Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID string
containing American Standard Code for Information Interchange (ASCII) characters. The
SessionID strings are communicated across client/server requests either by means of an
HTTP cookie or by using a modified URL with the embedded SessionID string. The
SessionStateModule class is responsible for generating or obtaining SessionID strings.
Similar to the application state, you can store objects and variables in a session state. By
default, a session variable is active for 20 minutes without any user interaction. In an
ASP.NET Web application, the objects stored in the session state are stored on the server.
Using the Session State
The syntax for adding and retrieving items from the session state is basically the same as for
adding items to a pages view state. The following example adds the variable, MyVariable,
with value HELLO in the session state:
Session["MyVariable"]="HELLO";

You can retrieve the value of the variable, MyVariable, by using the following statement:
String val = (string) Session["MyVariable"];

The preceding statement returns the value of the variable, MyVariable.


You need to consider the following issues when adding variables and objects to a session
state:

Any variable or object that you add to a session state is available only until the user
closes the browser window. The variables and objects are automatically removed
from session state if the user does not request a page for more than 20 minutes
because it is the default value.
Any variable or object added to a session state is related to a particular user. For
example, you can store different values for MyVariable for two different users
accessing the Web page and each user can access only the value that is assigned to
him/her.
Any object that supports serialization can be added to the session state. The objects
stored in session state are stored on the server. Therefore, session objects are not
subject to the same size limitations as cookies.

Session state is global to the entire application for the current user. Session state is not lost if
the user revisits a Web page by using the same browser window. However, session state can
be lost in the following ways:

When the user closes and restarts the browser.


When the user accesses the same Web page through a different browser window.
When the session times out because of inactivity.
When the Session.Abandon() method is called within the Web page code.

Similar to an application state, you can remove an object or a variable added to the session
state by using either the Remove() method, or the RemoveAll() method based on the
requirement.
Handling Session Events
Session state has the following events that you can capture to manipulate an ASP.NET Web
application:

Session.Start:

This event is raised when a user requests the first page from a
website, and is useful for initializing session variables.
Session.End: This event is raised when a user session expires or when the
Session.Abandon method is called.

You can capture both these events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Configuring Session State
Session state can be configured through the web.config file for the application. The
web.config file allows you to set advanced options such as the timeout and the session state
mode. The following markup shows some important options that can be set for the
<sessionState> element:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<sessionState
cookieless="UseCookies" cookieName="ASP.NET_SessionId"
timeout="20"
mode="InProc" />
</system.web>
</configuration>

The preceding markup uses the following session state attributes:

cookieless
timeout
mode

The cookieless attribute

The cookieless attribute specifies whether a cookie should be used or not. The following
table lists the values that the cookieless attribute can have with their description.
Value

Description

UseCookies

Specifies that cookies are always used, even if the


browser or device does not support cookies or
cookies are disabled. It is the default value. If the
device does not support cookies, the session
information will be lost over subsequent
requests, because each request will get a new ID.

UseUri

Specifies that cookies are never used.

UseDeviceProfile

Specifies ASP.NET to choose whether to use


cookies by examining the
BrowserCapabilities object. It does not take
into account that the user may have disabled
cookies in a browser that supports them.

AutoDetect

Specifies that cookies should be used if the


browser supports them. ASP.NET determines
whether the browser supports cookies by
attempting to set and retrieve a cookie.

Values of the Cookieless Attribute


The timeout attribute

The timeout attribute is an important attribute of the <sessionState> element. It specifies


the number of minutes that ASP.NET will wait, without receiving a request, before
abandoning the session.
The value for the timeout attribute should be set such that it is short enough to allow the
server to reclaim valuable memory after a client stops using the application. At the same
time, the value should be long enough to allow a client to pause and continue a session
without losing it.
The timeout attribute can also be set programmatically, as shown in the following code
snippet:
Session.Timeout = 15;

The mode attribute

The mode attribute specifies where the session state values are to be stored. The mode attribute
can have the following values:

Custom:
InProc:

Specifies custom data store to store session-state information.


Specifies that the information is to be stored in the same process as the
ASP.NET worker threads. This is the only mode in which the Session.End event is
raised.
Off: Specifies that the session state is disabled.
SQLServer: Specifies that the session state is to be stored by using an out-of-process
SQL Server database to store state information.
StateServer: Specifies that the session state is to be stored in an out-of-process
ASP.NET state service.

Disabling the Session State


By default, session state is enabled for all the pages in a Web application. If you need to
improve the performance of the Web application, you can disable session state for Web
pages. This can be done by using the EnableSessionState attribute in the page directive, as
shown in the following code:
<%@ Page EnableSessionState=False %>

You can also disable session state for all pages of a Web application by setting the mode
attribute to Off in the web.config file, as shown in the following figure.

Mode Attributes in a Web.config File


If you want to retrieve objects from session state but do not want to add objects to it, you can
set the EnableSessionState attribute to ReadOnly.

Note
In ASP.NET, the mode attribute is case-sensitive.

Profile Properties
Many Web applications provide users with the option to personalize the application. This can
be done by storing and using information that is unique to a user. This information can be
used to present the user with a personalized version of the Web application.
Consider an example. Suppose, you have created a website for online shopping of books. A
user has used the website to purchase books from the IT category. This information can be
stored as a profile property for that user. When the same user visits the website again, you
can use the information stored in the profile properties to display the latest books in the IT
category to the user.
ASP.NET provides the profiles feature to implement personalization in Web applications.
Although it is possible to store user preferences without using profiles, using it enables
developers to store preferences without writing much code. These preferences are stored as
named properties in profiles. The preferences can be stored in the form of simple data types,
complex data structures, or .NET Framework classes.
The profile information is stored in the aspnetdb.mdf file. It is created automatically when
you use any membership or profiles features for the first time. However, this automatic
creation of the aspnetdb.mdf file relies on SQL Server 2005 Express. If youre using another
version of SQL Server, you need to modify the profile configuration and create the database
manually.

Note
The membership feature will be discussed later in this course.

By default, the connection string in the profile configuration is named as LocalSqlServer.


You can modify this connection string in the machine.config file. The machine.config
settings apply to all the ASP.NET applications. Therefore, if you have to modify the
connection string for a single application, it is advisable to use the web.config file.
To modify the connection string by using the web.config file, you need to use the markup as
shown in the following example:
<configuration>
<connectionStrings>
<clear />
<add name="LocalSqlServer" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Integrated Security=SSPI;
Initial Catalog=aspnetdb" />
</connectionStrings>
...
</configuration>

The <clear/> element clears all the existing connection strings. After clearing the existing
connection strings, you can specify the new connection string.
Configuring Profile Properties
The properties that need to be stored in each user profile for an application can be configured
in the web.config file. You can configure the profile properties by using the markup shown in
the following example:
<system.web>
<profile>
<properties>
<add name="UserName" />
<add name="BirthDate" type="System.DateTime" />
</properties>
</profile>
<system.web>

In the preceding example, two profile properties, UserName and BirthDate, are defined. The
name attribute is used to define the name of the profile properties and the type attribute is

used to specify the data type. If the data type for a profile property is not defined, it takes the
default data type, which is String. Therefore, the data type of the UserName property is
String. The data type for the BirthDate property is defined as DateTime. The properties
UserName and BirthDate can be set only by the logged-on users. Anonymous users cannot
set these properties.
You can also create profile properties that can be set by all users including anonymous users.
To configure such profile properties, you need to use the markup as shown in the following
example:
<system.web>
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="UserName" type ="System.String" allowAnonymous=
"true"/>
<add name="BirthDate" type="System.DateTime" allowAnonymous=
"true"/>
</properties>
</profile>
<system.web>

Getting and Setting Profile Properties


After configuring the profile properties in the web.config file, you can access them by using
the Profile object. The value of the Profile property can be set, as shown in the following
code snippet:
Profile.UserName = TextBox1.Text;

In the preceding code snippet, the UserName profile property is set to the Text property of the
TextBox1 control. Similarly, the value of the profile property can be retrieved, as shown in
the following code snippet:
String uname = Profile.UserName;

The preceding code snippet returns the value of the Username profile property.

Note
When you store profile properties, ASP.NET identifies the user who has set the property.

Managing State by Using Cross-Page


Posting
By default, a Button control on a Web page submits the page back to itself. However,
sometimes, you may want to post one page to another. In such a case, you can set the
PostBackUrl property of the Button control to the URL of the target page. This posting of
information from one page to another page is called cross-page posting.
When the source page is posted to the target page, the target page must be able to access the
information stored in the controls on the source page. In addition, the target page must be
able to identify whether the page was loaded as a result of a cross-page postback.

Note
To make a control submit the page back to itself, you can set the AutoPostBack property of
the control to true.

Accessing Information Stored in Controls on the Source


Page
The Page class exposes a public property named PreviousPage. If the source and target
pages are in the same application, the PreviousPage property contains a reference to the
source page. However, if the pages are in different applications, or if the page is not the target
of a cross-page posting, the PreviousPage property is not initialized.
You can access the values in the controls on the source page by using the FindControl
method, as shown in the following example:
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl
("TextBox1");
if (t != null)
{

Response.Write(t.Text);
}
}

In the preceding example, the value of the TextBox1 control, which is on the source page, is
accessed in the target page.

Checking for Postbacks in the Target Page


In some cases, you need to execute some code on a page only if the page is running as a
result of a postback or a cross-page postback. Similarly, you may need to execute some code
only if the page is not running as a result of a postback or a cross-page postback. You can
check whether a page is running as a result of a postback by using the IsPostBack property
of the Page class. Similarly, you can check whether a page is running as a result of a crosspage postback by using the IsCrossPagePostBack property of the Page class.

Implementing Caching
Speed is a critical factor that judges the success or failure of any website. When multiple
users access a website simultaneously, slow access to Web pages is a common problem that
arises. The problem of slow access can be solved by using a technique called caching.
This technique improves the performance of any Web application by temporarily storing
frequently used Web objects, such as HTML pages, on local hard disks for later retrieval. As
a result, the Web server, on which the application resides, processes the requests for the
website only one time and caches the requests for future. Any subsequent request is
processed from the cache instead of the Web server. This leads to a considerable reduction in
the load on the server and a quicker response time. Caching enables you to improve the
performance of Web applications.
Caching is a very important and extensively used concept to enhance application
performance. The major benefits of using caching are:

Reduced access time: When most of the requests are processed by the cache itself and not
required to go to the Web server, the access time is reduced significantly.
Less bandwidth required: Cache location can be configured on the client computer. As a
result, most of the requests and responses do not require traveling the network between
the client and server, and this significantly reduces the bandwidth requirement.

Less load on server: Caching avoids executing the same ASP.NET code repetitively to create
the same result. This reduces the CPU usage at the server, and in the process, lowers the
load on the server.

ASP.NET supports three types of caching:

Output Caching
Fragment Caching
Data Caching

Output Caching
Output caching improves the performance of an ASP.NET application by caching the
rendered markup of an ASP.NET Web page. When the user requests the same page within a
specified period of time, instead of re-rendering the page, ASP.NET serves the cached page
to the user. Output caching is useful when the content of the Web page changes rarely.
For example, on an online shopping website, the products page gets the details of the
products from a database table. If output caching is not implemented, each time the products
page is accessed, a connection is made to the database, the table is queried, and the results are
returned to the requesting client. It takes a substantial amount of time affecting the
performance. Moreover, it is not required to fetch the product details from the database table
for every request because the product details rarely change.
With output caching, when the products page is first visited, the rendered HTML of the page
is cached for a specified duration. During the specified time period, if a user requests this
page, the cached markup is returned, thereby saving the database access and page rendering
time.
Implementing Output Caching
To implement output caching, you need to insert the @ OutputCache directive at the top of
your .aspx file, just below the @ Page directive, as shown in the following example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="20" VaryByParam="None" %>

In the preceding example, the @ OutputCache directive contains the two attributes,
Duration and VaryByParam. The Duration attribute instructs ASP.NET to cache the page
for the specified number of seconds. The VaryByParam attribute specifies how many copies
of the page need to be saved. In this example, the value of the VaryByParam attribute is set to
None, which indicates that only one copy of the page is to be cached.
However, there are situations when you want to save more than one cached copy of the page.
One such situation is when the page is requested with a query string. In this case the output of
the page differs, depending on the query string. In such a case, you want to use more than one
copy of the page. For this, you need to use the @ OutputCache directive as shown in the
following example:

<%@ OutputCache Duration="20" VaryByParam="*" %>

In the preceding example, the value * of the VaryByParam attribute instructs ASP.NET to
cache separate copies of the page for different query string arguments.

Fragment Caching
ASP.NET provides one more type of caching in which the data from some specific sections
of the page can be cached. This is called fragment caching. Sometimes it is also referred to as
partial page caching. Fragment caching is used in situations where you want to cache only a
portion of the Web page because it does not change frequently. The remaining content of the
page is loaded dynamically.
To implement fragment caching, the portion of the page that is to be cached is encapsulated
in a user control, and then the @ OutputCache directive is added to the control, as shown in
the following example:
<%@ Control Language="C#"%>
<%@ OutputCache Duration="120" VaryByParam="None" %>

Data Caching
Data caching is used to store frequently used data in the built-in collection object called
Cache. It is a property of the Page class, and it returns an instance of the
System.Web.Caching.Cache class. The Cache object works like the Application object.
The Cache object is globally available to all requests from all clients in the application.
The Cache object differs from the Application object in the following ways:

The Cache object does not need to be explicitly locked or unlocked.


Items in the Cache object are removed automatically.
Items in the Cache object can be linked to a file, a database table, or another type of
resource. If this resource changes, the cached object automatically becomes invalid
and is released.

Implementing Data Caching


Data caching can be implemented programmatically. The Cache class encapsulates data
caching and an object of the Cache class is created for implementing data caching. It stores
each item as a key-value pair.
For example, you can store a variable by the name, uname, in the Cache object, and assign it a
value, as shown in the following code snippet:
Cache ["uname"] = "Robert";

You can retrieve the value from the Cache object, as shown in the following code snippet:

TextBox1.Text = Cache["uname"];

The lifetime of the Cache object associated with an application is the same as the lifetime of
the application. Therefore, when an application stops, the information in the Cache object is
lost.

Summary
In this chapter, you learned that:

Client-side state management allows you to store information either on a Web page or
on a client computer.
The various options available to implement client-side state management are:
o
o
o
o
o

A hidden field is a control similar to a TextBox control but it does not render in a
Web browser.
Information in the form fields on a Web page is automatically added to the view state.
It can also be used to store some additional information.
Control state is used to store information that is specific to a control.
Cookies are used to store small pieces of information related to a users computer,
such as its IP address, browser type, and operating system.
Cookies can either be temporary or persistent.
A query string provides a simple way to pass information from one page to another.
ASP.NET provides the following options to manage state at the server side:
o
o
o

Hidden Fields
View State
Control State
Cookies
Query Strings

Application State
Session State
Profile Properties

Application state is used to store the application-specific information.


The information stored in the application state is shared among all the pages of the
Web application.
Session state is used to store session-specific information for a Web application.
The scope of session state is limited to the current browser session.
The profiles feature is used to implement personalization in Web applications.
Caching improves the performance of a Web application by temporarily storing
frequently used Web objects on local hard disks for later retrieval.
ASP.NET supports three types of caching:
o
o
o

Output Caching
Fragment Caching
Data Caching

Reference Reading

Implementing Client-Side State Management


Reference Reading: Books

Reference Reading: URLs

Microsoft ASP.NET: Fast


& Easy Web Development
by Nitin Pandey

http://dotnet.dzone.com/news/aspnet-client-side-state-manag-1
http://www.exforsys.com/tutorials/asp.net-2.0/statemanagement-in-asp.net-2.0.html

Implementing Server-Side State Management


Reference Reading: Books

Reference Reading: URLs

Pro ASP. Net 3. 5 Server


Controls and AJAX
Components by Rob
Cameron, Dale Michalk

http://articles.techrepublic.com.com/5100-10878_115030436.html
http://www.dotnetspider.com/resources/1472-STATEMANAGEMENT.aspx

Managing State by Using Cross-Page Posting


Reference Reading: Books

Reference Reading: URLs

Pro ASP.NET 3.5 in C#:


Create Next-generation
Web Applications by
Matthew MacDonald,
Mario Szpuszta

http://www.hotscripts.com/Detailed/74287.html

Implementing Caching
Reference Reading: Books

Reference Reading: URLs

Beginning ASP.NET 3.5


in VB 2005: From Novice
to Professional by
Matthew MacDonald

http://www.asp.net/learn/withpss/module7.aspx

Chapter 6

Working with Data


Accessing data from a data source is an important aspect of a Web application. Every Web
application that displays dynamic data needs to access data from a data source. Data from a
data source can be accessed either by implementing the data access logic directly into the
presentation layer or by separating the data access logic from the presentation layer by
creating a new logical layer known as Data Access Layer (DAL).
This chapter discusses the basics of accessing data in Web applications. It also discusses how
to access data from a database by using the presentation layer. In addition, it discusses how to
implement DAL to access data from a database.

Objectives
In this chapter, you will learn to:
Identify basics of data access in Web applications
Access data by using the presentation layer
Access data by using DAL

Identifying the Basics of Data Access in


Web Applications
Most Web applications are designed by using the multiple tier model known as the N-tier
model. Designing an application by using the N-tier model provides increased performance
and scalability. This is because the functioning of each layer is completely hidden from other
layers, and this makes it possible to change or update one layer without recompiling or
modifying the other layers. The following figure shows a basic N-tier model.

The Basic N-tier Model


The preceding figure shows three layers, which can further be divided into separate layers.

Presentation Layer
In a Web application, the presentation layer is the interface that appears when a user opens a
Web page in the browser. If you see the source code of the page, you would only see the code
such as HTML, Javascript, and Cascading Style Sheets. You would not be able to see the
database queries, loops, calls to classes, or any behind-the-scenes processing. This is due to
the fact that the presentation layer does not contain any data access code or program logic.
However, in case of small Web applications, you may find the database access layer merged
with the presentation layer.
Consider a situation where a developer has implemented the data source controls to access
data from the data source. In such a situation, the database access is merged with the
presentation layer. This approach tightly couples the data access logic with the presentation
layer. Therefore, this approach is not recommended because the data access logic, being
tightly coupled, cannot be implemented by any other application.

Business Rules Layer


The business rules layer is also known as the business logic tier or the application tier. It
contains all the classes and the source code of the Web application. The business rules layer
allows you to separate the application logic from the user interface of a Web page. It enables
the programmer to easily search for a specific code because the code is not cluttered with
HTML or Javascript. The business rules layer does not contain HTML or JavaScript code.

Data Access Layer

You can implement the data access logic in the presentation layer. However, this is not
recommended because it clutters the data access code with the HTML and Javascript code. In
addition, it tightly couples the data access logic with the presentation layer. This prevents the
data access logic to be reused in other Web applications.
All these limitations can be overcome by separating the data access logic from the
presentation layer. It can be done by creating a new layer and implementing the data access
logic in it. This separate layer is referred to as the Data Access Layer (DAL). DAL is
typically implemented as a separate class library.

Accessing Data by Using the Presentation


Layer
Most of the modern day Web applications need to manipulate data in databases. This can be
done by implementing data access logic in applications. If the data access logic is not to be
reused in any other application, it can be implemented in the presentation layer (ASP.NET
pages). This can be done by using:

Data source Controls


ADO.NET

Data Source Controls


Data source controls allow you to work with different types of data sources such as a
database, an XML file, or a middle-tier business object. Data source controls act as a bridge
between the application and the data sources. They can connect to the data sources and
retrieve data without requiring you to write any code. However, they do not provide the
interface to display data. To display the retrieved data, it is made available to the data
controls or data-aware controls.

Note
Data controls are the controls that are designed exclusively for use with data sources. Some
of the data controls are GridView, DataList, ListView, and FormView controls. Data-aware
controls are standard controls that can be used with databases, but are not exclusively for
that purpose. These controls can also be used without connecting them to a data source.
Examples of such controls include DropDownList and ListBox controls.
Data source controls perform the following tasks:

Retrieve data from a data source and supply it to the data controls or data aware
controls.
Update the data source when edits take place.

Data Source Controls in ASP.NET


ASP.NET provides various data source controls to access different types of data sources.
These controls are:

SqlDataSource
AccessDataSource
ObjectDataSource
XmlDataSource
SiteMapDataSource

SqlDataSource Control

The SqlDataSource control is generally used to access data from an SQL relational database.
However, it can be used to access any database product for which there is a managed
ADO.NET provider.

Note
A Provider is a class that communicates with a specific type of database or data store.
The SqlDataSource control is used in conjunction with data controls to retrieve data from a
relational database and to display or modify the data on a Web page with minimal coding.
The following table lists some properties of the SqlDataSource control.
Property

Description

ProviderName

Gets or sets the name of the ADO.NET provider


that is used to connect to an underlying data
source.

ConnectionString

Gets or sets the connection string that is used to


connect to an underlying data source.

SelectCommand

Gets or sets the SQL string that is used to retrieve


data from the underlying data source.

DeleteCommand

Gets or sets the SQL string that is used to delete


data from the underlying data source.

InsertCommand

Gets or sets the SQL string that is used to insert

data in the underlying data source.


UpdateCommand

Gets or sets the SQL string that is used to update


data in the underlying data source.

Properties of the SqlDataSource Control


You can retrieve data from a data source by using the SqlDataSource control, as shown in the
following example:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MusicConnectionString%>"
SelectCommand="SELECT [album_name] FROM [albums]"></asp:SqlDataSource>

In the preceding example, the ConnectionString attribute is used to connect to the


underlying data source and the SelectCommand attribute is used to retrieve the album_name
field values from the albums table.

Note
You can bind data controls to the SQLDataSource control by using the DataSourceID
property of the data controls.
AccessDataSource Control

The AccessDataSource control works with Microsoft Access databases. Like the
SqlDataSource control, the AccessDataSource control uses SQL queries to retrieve data.
However, unlike the SqlDataSource control, you do not set the ConnectionString property
in the AccessDataSource control. Instead of the ConnectionString property, you need to set
the location of the Access (.mdb) file in the DataFile property.
The Access database to be accessed should be placed in the App_Data directory of the
website and needs to be referenced by a relative path. Using relative path for referencing the
database provides security for data files because these files will not be served if requested
directly by the client Web browser.
You cannot access Access databases that are protected by a user name or password by using
the AccessDataSource control. This is because you cannot set the ConnectionString
property in the AccessDataSource control. If you need to access an Access database that is
protected by a user name or password, you need to use the SqlDataSource control because it
allows you to specify a complete connection string.

Note
You cannot set the ConnectionString property for the AccessDataSource control because it
is a read only property.
You can bind data-bound controls to an AccessDataSource by using the DataSourceID
property of the data-bound control. The following table lists some properties of the
AccessDataSource control.
Property

Description

ProviderName

Gets the name of the ADO.NET provider that is


used to connect to Microsoft Access.

DataFile

Gets or sets the location of the Microsoft Access


file.

SelectCommand

Gets or sets the SQL string that is used to retrieve


data from the underlying data source.

DeleteCommand

Gets or sets the SQL string that is used to delete


data from the underlying data source.

InsertCommand

Gets or sets the SQL string that is used to insert


data in the underlying data source.

UpdateCommand

Gets or sets the SQL string that is used to update


data in the underlying data source.

Properties of the AccessDataSource Control


You can retrieve data from an Access database by using the AccessDataSource control, as
shown in the following example:
<asp:AccessDataSource id="AccessDataSource1"
DataFile="~/App_Data/Northwind.mdb" runat="server"
SelectCommand="SELECT LastName, FirstName FROM Employees">
</asp:AccessDataSource>

In the preceding example, the DataFile attribute is used to specify the Access database file.
The SelectCommand attribute is used to specify the query that retrieves the LastName and
FirstName field values from the Employees table.
ObjectDataSource Control

The ObjectDataSource control represents a middle-tier object with data retrieval and update
capabilities. The ObjectDataSource control is used in conjunction with a data-bound control
to display or modify data on a Web page with minimal coding.
Most of the complex Web applications follow the three-tier architecture. In this architecture,
the presentation layer is separated from business logic, which is encapsulated in business
objects. These business objects form a distinct layer between the presentation layer and the
data layer. The ObjectDataSource control enables developers to access data from business
objects.
The following table lists some properties of the ObjectDataSource control.
Property

Description

TypeName

Identifies the name of the class that the


ObjectDataSource works with.

SelectMethod

Gets or sets the method or function that is


invoked to retrieve data.

SelectParameters

Gets the parameters collection that contains the


parameters used by the SelectMethod
property.

InsertMethod

Gets or sets the method or function that is


invoked to insert data.

InsertParameters

Gets the parameters collection that contains the


parameters used by the InsertMethod
property.

UpdateMethod

Gets or sets the method or function that is


invoked to update data.

UpdateParameters

Gets the parameters collection that contains the


parameters used by the UpdateMethod
property.

DeleteMethod

Gets or sets the method or function that is


invoked to delete data.

DeleteParameters

Gets the parameters collection that contains the


parameters used by the DeleteMethod
property.

Properties of the ObjectDataSource Control


You can retrieve data from business objects by using the ObjectDataSource control, as shown
in the following example:
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetEmployee"
typename="EmployeeLogic" >
<selectparameters>
<asp:querystringparameter name="EmployeeID"
querystringfield="empid"/>
</selectparameters>
</asp:objectdatasource>

In the preceding example, the SelectMethod attribute sets the method, GetEmployee, which
is invoked to retrieve data. The TypeName attribute defines the name of the class that the
ObjectDataSource is working with. The <SelectParameters> element passes the employee
ID as parameter because it is required by the GetEmployee method.
XmlDataSource

The XmlDataSource control presents XML data to data-bound controls. The XmlDataSource
control can be used by data-bound controls to display hierarchical as well as tabular data. The
XmlDataSource control loads data from an XML file that is specified by the DataFile
property. The XmlDataSource control can also load XML data in string form by using the
Data property. You can bind data-bound controls to an XmlDataSource control by using the
DataSourceID property of the data-bound control.
The following table lists some properties of the XmlDataSource control.

Property

Description

DataFile

Specifies the filename of the XML file that is to be


bound with the XmlDataSource control.

Data

Gets or sets the block of xml data that is to be


bound with the XmlDataSource control in string
form.

Properties of the XmlDataSource Control


You can retrieve data from an XML file by using the XmlDataSource control, as shown in
the following example:
<asp:xmldatasource id="XmlDataSource1" runat="server" datafile="books.xml"
/>

In the preceding example, the datafile attribute specifies the filename of the XML file that is
to be bound with the XmlDataSource control.
SiteMapDataSource Control

The SiteMapDataSource control provides navigation data to the navigational controls. It


obtains navigation data from a site map. The navigation data includes information about the
pages on your website, such as the URL, title, description, and location in the navigation
hierarchy. The SiteMapDataSource enables Web server controls that are not specifically site
navigation controls, such as the TreeView and Menu controls, to bind to site map data. These
controls can be used to display a site map to navigate a site. The SiteMapDataSource control
can be bound to the navigational controls by using the DataSourceID property of the
navigational controls. The following table lists some properties of the SiteMapDataSource
control.
Property

Description

SiteMapProvider

Gets or sets the name of the site map provider.

StartingUrlNode

Sets the URL in the sitemap that will be


considered as the root node.

ShowStartingNode

Indicates whether to show starting node or not. It


can only be set to True or False.

Properties of the SiteMapDataSource Control

You can retrieve data from a sitemap file by using the SiteMapDataSource control, as shown
in the following example:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

In the preceding example, the SiteMapProvider attribute is not defined. Therefore, the
default provider, XMLSiteMapProvider, will be used. When you use the default provider, the
SiteMapDataSource control will always look for the Web.sitemap file in the root folder of the
application. However, if your application has a sitemap file with a name other than the
default name, Web.sitemap, you need to use a custom provider for the SiteMapDataSource
control. You can use the custom provider by adding it in the web.config file, as shown in the
following example:
<siteMap>
<providers>
<add name="MusicManiaSiteMap"
type="System.Web.XMLSiteMapProvider"
siteMapFile="MyWeb.sitemap"/>
</providers>
</siteMap>

In addition to modifying the web.config file, you need to set the SiteMapProvider property
of the SiteMapDataSource control to the custom provider, as shown in the following
example:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
SiteMapProvider="MusicManiaSiteMap " />

Note
In addition to the preceding data source controls, ASP.NET provides the LinqDataSource
control that allows you to access data from wide variety of data sources such as a database,
data-source classes, and in-memory collections.
Displaying Data in Data-Bound Web Server Controls
Data-bound Web server controls are the controls that can be bound to a data source control to
display and modify data in a Web application. Data-bound Web server controls are composite
controls that combine other Web controls, such as Label and TextBox controls, into a single
unit. In addition to displaying and modifying data, data-bound controls enable you to

customize the layout of the control using templates. ASP.NET provides various data-bound
Web server controls. Some of them are:

GridView Control
DetailsView Control
FormView Control
ListView Control
DataList Control
Repeater Control
DataPager Control
DataGrid Control

GridView Control

When working with data in an application, it is required to display the data in tabular form.
To display data in a tabular form, ASP.NET provides a number of controls, one of which is
the GridView control. The GridView control allows you to display, edit, and delete data from
different kinds of data sources, such as databases, XML files, and business objects that
expose data. However, you cannot change the layout of the GridView control.
The GridView control provides various properties that can be set to display data in the
desired format. The following table lists some properties of the GridView control.
Property

Description

DataSource

Gets or sets the object from which the control


retrieves the items.

DataSourceID

Gets or sets the ID of the control from which the


GridView control retrieves the data items.

AllowPaging

Gets or sets the value indicating whether paging


is enabled.

AllowSorting

Gets or sets the value indicating whether sorting


is enabled.

AlternatingRowStyle

Gets the reference of the object that enables you


to set the appearance of the alternate rows.

SelectedIndex

Gets or sets the index of the selected row.

SelectedRow

Gets the reference of the object that represents


the selected row.

SelectedValue

Gets the data key value of the selected row.

Properties of the LinqDataSource Control

DetailsView Control

The DetailsView control allows you to display, edit, insert, or delete a single record at a time.
By default, the DetailsView control displays each field of a record in a new line. It can
display only one record at a time. It is generally used in a master/detail scenario. In such a
scenario, the DetailsView control is used to update or delete records that are selected in the
master control. The DetailsView control can also be used to add a new record.
The following table lists some properties of the DetailsView control.
Property

Description

DataSource

Gets or sets the object from which the control


retrieves the items.

DataSourceID

Gets or sets the ID of the control from which the


DetailsView control retrieves the data items.

AllowPaging

Gets or sets the value indicating whether paging


is enabled.

AlternatingRowStyle

Gets the reference of the object that enables you


to set the appearance of the alternate rows.

SelectedValue

Gets the data key value of the current record.

Properties of the DetailsView Control


FormView Control

Similar to the DetailsView control, the FormView control allows you to work with a single
record at a time. However, there is a difference between the FormView and the DetailsView
control. The DetailsView control displays the record in a tabular format with each field of the

record in a new row whereas the FormView control provides you with the flexibility to
modify the layout for displaying the record. You can modify the layout by creating a new
template or by modifying the existing template. The template can contain formatting,
controls, and binding expressions. The FormView control is also used in master/detail
scenarios.

Note
The FormView control provides various built-in templates such as ItemTemplate,
InsertItemTemplate, and EditItemTemplate that allow you to provide a different interface for
performing different operations such as view, insert, and edit. Similarly, the
EmptyDataTemplate enables you to specify a template to display when the data source
returns no data.
The following table lists some properties of the FormView control.
Property

Description

DataSource

Gets or sets the object from which the control


retrieves the items.

DataSourceID

Gets or sets the ID of the control from which the


FormView control retrieves the data items.

AllowPaging

Gets or sets the value indicating whether paging


is enabled.

SelectedValue

Gets the data key value of the current record.

Properties of the FormView Control


DataList Control

The DataList control allows you to display rows of database information in a customizable
format. You can create the format for displaying data by defining templates. You can create
templates for items, alternating items, selected items, and edit items.
The following table lists some properties of the DataList control.
Property

Description

DataSource

Gets or sets the source that contains the list of


values to be used to populate the items within
the control.

DataSourceID

Gets or sets the ID of the control from which the


list of values is to be retrieved.

SelectedValue

Gets or sets the value of the key field for the


selected item.

SelectedIndex

Gets and sets the index of the selected item.

SelectedItem

Gets the selected item.

Properties of the DataList Control


Repeater Control

A Repeater control displays data from different data sources by using customized layouts. A
Repeater control does not have a default layout. You need to create templates to provide a
layout to the Repeater control. You can create tables, grids, comma separated lists, and
bulleted or numbered lists to display data in a Repeater control. After adding the Repeater
control to a Web form, you can set its properties and then create different templates to
provide the layout to the Repeater control. The ItemTemplate template is mandatory as it
provides a basic layout to the Repeater control. Other templates can also be created to
enhance the layout. The Repeater control does not provide certain features such as editing,
updating, and paging.
The following table lists some properties of the Repeater control.
Property

Description

DataSource

Gets or sets the source that provides data for


populating the list.

DataSourceID

Gets or sets the ID of the control from which the


list of values is to be retrieved.

DataMember

Gets or sets the table with which the control is to


be bound.

Properties of the Repeater Control

ListView Control

The ListView control is similar to the GridView and Repeater controls. The GridView and
Repeater controls have some limitations. The GridView control does not allow a user to
change the layout of the data display. Similarly, the Repeater control does not provide
features such as editing, updating, and paging. Both these limitations are overcome in the
ListView control.
The ListView control enables you to display data in a format that is defined by using
templates and styles. In addition, it enables you to edit, insert, delete, and sort and page data
without writing code.

Note
The ListView control provides various layouts, templates, and styles that you can choose
according to your requirements.
The following table lists some properties of the ListView control.
Property

Description

DataSource

Gets or sets the object from which the control


retrieves the items.

DataSourceID

Gets or sets the ID of the control from which the


ListView control retrieves the data items.

SelectedValue

Gets the data key value of the selected item.

SelectedIndex

Gets and sets the index of the selected item.

Properties of the ListView Control


DataPager Control

The DataPager control is used to enable users to page through data in either a ListView
control or a control that implements the IPageableItemContainer interface. The DataPager
control can be inserted inside the LayoutTemplate template or on the page outside the
ListView control. It the DataPager control is inside the LayoutTemplate template, the
DataPager is a direct part of the generated output. If it is not in the ListView control, you
need to set the PagedControlID property of the DataPager control to the ID of the ListView
control.

The following table lists some properties of the DataPager control.


Property

Description

PagedControlID

Gets or sets the ID of the control that contains


data to be paged.

PageSize

Gets or sets the number of records that are to be


displayed for each page.

Properties of the DataPager Control


DataGrid Control

The DataGrid control is used to display data in a tabular layout. By default, it displays data in
the read-only mode. However, it is capable of automatically displaying the data in editable
controls at run-time. The DataGrid control supports paging.
To display data from a data source, you need to bind the DataGrid control to a data source
control by using its DataSourceID property. You can also bind the DataGrid control from a
data source such as the DataSet and data readers by using its DataSource property.
When binding a DataGrid control with data source such as the DataSet and data readers by
using its DataSource property, the DataGrid control generates a bound column for each field
in the data source. However, you can select which fields in the data source generate columns
in the grid. When using the DataSource property, you need to call the control's DataBind
method to load data in the control, as shown in the following code snippet:
DataGrid1.DataSource = ds;
DataGrid1.DataBind();

In the preceding example, ds is the object of type DataSet. The DataBind method is used to
load data in the DataGrid control. The DataBind method is also called to refresh the data in
the control, in case the data is modified in the data source.
The following table lists some properties of the DataGrid control.
Property

Description

DataSource

Gets or sets the source containing the values to


be displayed in the control.

DataSourceID

Gets or sets the ID of the control from which the

ListView control retrieves the data items.


AllowCustomPaging

Gets or sets a value indicating whether custom


paging is enabled.

AllowPaging

Gets or sets a value indicating whether paging is


enabled.

AllowSorting

Gets or sets a value indicating whether sorting is


enabled.

SelectedIndex

Gets or sets the index of the selected item in the


control.

Properties of the DataGrid Control

Note
The DataGrid control is not a standard control. Therefore, it is not present in the Toolbox. It
needs to be added to the Toolbox by right-clicking the Toolbox and selecting Choose Items.
You can find this control in the .NET Framework Components tab.
Binding Controls to Data by Using Data Binding Syntax
Data binding is a technique of linking data and user interface objects. Using data binding, you
can bind data in a data source to a user interface object. Any modifications to the data in
these user interface objects can be updated to the data source.
On the basis of the number of bound values that can be displayed through a user interface
object, binding can be classified into:

Single-Value Data Binding


Repeated-Value Data Binding

Single-Value Data Binding

Interactive Web pages are majorly designed by using controls such as TextBox, Label, and
RadioButton. These controls can display one data value at a time. For example, if you have to
register five friends of yours on a website by writing their names in a TextBox and clicking
the Submit button, you have to write the name and click the button five times. This is because
in controls such as a TextBox you can write only one value at a time. Such controls are

known as single-value controls. These controls can be bound to a data value by using singlevalue data binding.
Single-value data binding involves binding the controls that can display one data value at a
time to a data source. Single-value controls do not support any data binding properties, such
as the DataSource property or the DataMember property. Therefore, you need to bind a
single-value control by providing data as the value of its Text property. For example, you can
set the Text property of a TextBox control to display a data source value. This data source
value can be a property, a return value of a method, an expression, or a value from a database.
You can bind single-value controls to properties, such as page properties, public variables,
and the properties of other controls. Consider a case where you need to bind a Label control
to a public variable that displays the current date and time. For this, you can write the
following code in the .aspx.cs file:
public partial class _Default : System.Web.UI.Page
{
public string dt = DateTime.Now.ToString();
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();//binds the data source to the invoked server
//control and all its child controls
}
}

You can now use the variable dt to display date in a new Label control, as shown in the
following markup:
<asp:Label ID="Label1" runat="server"> <%# dt %></asp:Label>

Repeated-Value Data Binding

There are situations when you need to display a list of values from a data source on to a Web
page. One such situation is when you want to display a list of products on a Web page. This
can be done by using server controls, such as a ListBox, that can display multiple data values
at a time. Such controls are known as repeated-value server controls. These controls can be
bound to a data source by using repeated-value data binding.
Repeated-value data binding involves binding server controls to structures, such as ArrayList
and DataView objects, which implement the IEnumerable interface. The DataGrid,
DropDownList, and ListBox controls are some of the repeated-value server controls that can
display multiple data values. The following example shows how you can bind an ArrayList to
a ListBox control:

protected void Page_Load(object sender, EventArgs e)


{
ArrayList Month = new ArrayList();
Month.Add("Jan");
Month.Add("Feb");
Month.Add("Mar");
Month.Add("Apr");
ListBox1.DataSource = Month;
ListBox1.DataBind();
}

Using ADO.NET
Data source controls enable you to access data from a database without writing any data
access code. However, Data source controls do not provide the flexibility that can be
achieved by using ADO.NET. In addition, data source controls enable you to access data only
by using the connected environment. However, ADO.NET provides both the connected and
disconnected environments to access data.

Note
A connected environment requires a constant connection to transfer data between the client
application and the data source. However, a disconnected environment retrieves data and
performs modifications without being connected to the network all the time.
Accessing Data from a Database by Using ADO.NET
You can access data from various data sources such as MS Access, SQL Server, and Oracle
by using ADO.NET. To access data from a database by using ADO.NET, you need to use
certain objects. Some of the basic objects are:

Connection Objects
Command Objects
Data Reader Objects
Dataset Objects

Connection Objects

Before accessing data from a data source, you need to make a connection to the data source.
For this, you need to use the connection object. When creating a connection object, you need
to set the ConnectionString property. The ConnectionString property defines all the
information required to find the data source, log on, and choose an initial database. Consider
the following code snippet:
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=172.23.3.59;Initial
Catalog=Music;Integrated Security=SSPI; Persist Security Info=False";
myConnection.Open();

In the preceding example, a connection object myConnection is created. After creating the
connection object, the ConnectionString property of the myConnection object is set. The
connection string is a series of distinct pieces of information known as connection string
properties. When writing the code, the connection string properties are separated by
semicolons. The connection string can have various connection string properties. Some of the
important connection string properties are:

Data Source:

Indicates the name or the IP address of the server where the data
source is located.
Initial Catalog: Indicates the name of the database that this connection will be
accessing.
Integrated Security: Indicates that you want to connect to SQL Server using the
Windows user account. The value specified for this attribute is SSPI, which indicates
ASP.NET to use the credentials under which the Web application is executing to
authenticate with SQL Server.
Persist Security Info: Indicates whether the information such as the user Id and
password is discarded after it is used to open the connection. This information is
discarded when the value of the Persist Security Info is set to false. However,
if the value of this attribute is set to true, the security-sensitive information,
including the user ID and password, can be obtained from the connection after the
connection has been opened.

Note
In addition to windows authentication, you can use SQL server authentication. For SQL
server authentication, instead of the Integrated Security and Persist Security Info attribute,
you need to use the User ID and Password properties, as shown in the following example:
myConnection.ConnectionString = "Data Source=172.23.3.59;Initial Catalog=Music; User
ID=sa;Password=password@123";

After specifying the connection string, you need to open the connection. Then, the connection
object is ready to be used to access the data source.
You need to create the connection objects for all the Web pages in which you want to access
data from a data source. Generally, all the database code in an application uses the same
connection string. Therefore, it is not advisable to create separate connection objects for all
the Web pages because it makes an application slow. Moreover, you need to write the same
code again. These problems can be solved by storing the connection string in the web.config
file. If the connection string is stored in the web.config file, it can be accessed from any Web
page within the application. You can store the connection string in the
<connectionStrings> section of the web.config file, as shown in the following example:
<configuration>
<connectionStrings>
<add name="myMusic" connectionString=
"Data Source=172.23.3.59;Initial Catalog=Music;Integrated
Security=SSPI; Persist Security Info=True"
provideName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>

In the <ConnectionStrings> element the <add> sub tag is used to add a connection string.
The <add> sub tag contains the following attributes:

name: It is a required attribute that is used to retrieve the connection string.


connectionString: It is a required attribute that is used to define the connection

string value.

provideName:

It is an optional attribute that specifies a class that communicates with


a specific type of database.

To access the connection string that is defined in the web.config file, you need to use the
ConnectionStrings property of the ConfigurationManager class from any Web page
within the website. After accessing the connection string, you can use it in the Connection
object by writing code shown in the following example:
string connString =
ConfigurationManager.ConnectionStrings["myMusic"].ConnectionString;

SqlConnection myConnection = new SqlConnection();


myConnection.ConnectionString = connString;

myConnection.Open();

Command Objects

After a connection has been established with the data source, you can execute commands and
return results from the data source by using a command object.
To execute SQL statements, you need to create an instance of the SqlCommand class present
in the System.Data.SqlClient namespace. The command object specifies the SQL
statement that needs to be executed and the connection that needs to be used to execute the
statement. You can execute SQL statements or stored procedures through command objects.
The following code snippet demonstrates how to create a command object:
// Create an object of the SqlConnection class
SqlConnection connection = new SqlConnection();
// Create a connection string to the HR database
connection.ConnectionString = "Data Source=172.23.3.59;
Initial Catalog=HR; User ID=sa; Password=niit#1234";
connection.Open(); //opening the connection
// Create an object of the SqlCommand class
SqlCommand cmd = new SqlCommand("select * from
monthlysalary",connection);

In the preceding code snippet, the SqlCommand object cmd is initialized to the SQL statement
that needs to be executed.

Note
The SqlCommand object can also be used to specify insert, update, and delete queries.
DataReader Objects

After defining the command object, you need to execute it to get the data from the data
source. The data returned by executing the command object needs to be stored in another
object. The DataReader object can be used to store the data returned by executing the
command object. The DataReader object supports forward-only read-only access to the
results returned by executing the command object. Therefore, it can be used when you need

to retrieve information from a data source. The DataReader object works in a connected
environment. It requires an open connection for its working.
To create a DataReader object, you use the ExecuteReader() method of the command
object, as shown in the following code snippet:
//You don't need the new keyword, as the Command will create
the //DataReader.
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();

The preceding code snippet defines a variable myReader and then stores data in it by
executing the command. Once you have retrieved the data in the DataReader object, you can
view a single row at a time by using the Read() method, as shown in the following code
snippet:
myReader.Read(); // The first row in the result set is now available.

Note
The Command object can also execute a DML statement against a connection object and
returns the number of rows affected by using the ExecuteNonQuery method.
Dataset Objects

A dataset is a memory-based relational representation of data. A dataset is a disconnected,


cached set of records that are retrieved from a database. The dataset acts like a virtual
database containing tables, rows, and columns. Datasets are extensively used to retrieve data
from data sources in Web applications because they do not require the connection to be
opened all the time. Instead, they cache data from the database and after that the connection
can be closed. This improves the application performance because once cached the data is
retrieved from the dataset instead of the Web server. It also optimizes the use of server
resources because the connection is not used for a long time.
The dataset object requires the data adapter to retrieve data from the data source. You can
retrieve data from data source by using dataset by using the following code:
SqlConnection myConn = new SqlConnection("Data Source=SQLSERVER;Initial
Catalog=Music;User=sa; password=password@123");
DataSet ds = new DataSet();
myConn.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from albums", myConn);

da.Fill(ds, "albums");
GridView1.DataSource = ds;
GridView1.DataBind();

In the preceding example, the data from the data source is retrieved by the data adapter and
filled into the dataset. After that the data in the dataset is displayed by using the GridView
control.

Accessing Data by Using DAL


DAL is a layer of code that provides simplified access to the data stored in persistent storage
such as a database. This layer is used by other program modules to access and manipulate
data within the data source without dealing with the complexities involved in accessing the
data. When using DAL, an application calls the methods provided by DAL to access data
instead of writing complex queries.
DAL separates the data access code such as creating a connection to the database, issuing
SELECT, INSERT, UPDATE, and DELETE commands from the application logic.
Separating the data access code from the application logic makes it easy to debug. It also
makes the code reusable. Other applications can also use the code because it is not
application specific.

Advantages of Using DAL


DAL separates the data access code from the rest of the code. This provides the following
advantages:

It minimizes the impact of a change in the database provider.


It also minimizes the impact of a change in data representation such as a change in
database schema.
It simplifies testing and maintenance.
It increases code reusability because the data access code can be generalized to work
across applications.

Creating a DAL
You can create a DAL by creating a class library and writing all the data access functions in
that library. All the data access functions written in the class library should be generic. This is

because a DAL is created to separate the data access logic from the application layer. In
addition, the functions written in a DAL should be reusable. Consider the following example:
public void CreateConnection(String ConnString)
{
Sqlcon = new SqlConnection(ConnString);
}

In the preceding example, the function CreateConnection is created to set the connection
string to be used in the application. Instead of hard coding the connection string in the DAL,
the CreateConnection function creates the connection depending on the connection string
that is passed as a parameter by the user. This provides flexibility to the DAL and it can be
reused in any application that requires data access code.
Consider another example that demonstrates a function to retrieve data from a database table:
public class Class1
{
SqlConnection Sqlcon=null;
public void CreateConnection(String ConnString)
{
Sqlcon = new SqlConnection(ConnString);
}

public DataSet ExecuteQuery(String query)


{
SqlDataAdapter Sqlda = null;
DataSet dset = null;
try
{
Sqlcon.Open();
Sqlda = new SqlDataAdapter(query, Sqlcon);
dset = new DataSet();
Sqlda.Fill(dset);

return dset;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (Sqlcon.State == ConnectionState.Open)
{
Sqlcon.Close();
Sqlcon = null;
Sqlda = null;
dset = null;
}
}
}
}

In the preceding example, the function CreateConnection is defined for creating a


connection. This function takes the connection string as argument and creates the connection
according to the connection string. The function DisplayDetails is created to retrieve data
from a database table. Both the functions are generic.

Summary
In this chapter, you learned that:

The basic N-tier model consists of the following layers:


o
o
o

You can implement data access logic in the presentation layer (ASP.NET pages) by
using:
o
o

Data Source Controls: Allow you to work with different types of data sources by
acting as a bridge between the application and the data sources.
ADO.NET: Allows you to write flexible data access code.

The basic objects used to access data from a database by using ADO.NET are:
o
o
o

Presentation Layer
Business Rules Layer
Database Access Layer

Connection Objects
Command Objects
Data Reader Objects

DAL is a layer of code that provides simplified access to the data stored in persistent
storage such as a database.

Reference Reading
Identifying the Basics of Data Access in Web Applications
Reference Reading: Books

Reference Reading: URLs

Doug Lowe & Joel


Murach, murach's
ASP.NET 3.5 upgrader's
Guide

http://www.asp.net/learn/withpss/module5.aspx

Chapter 7

Manipulating Data Using LINQ


Any application that displays dynamic information has to retrieve data from various data
sources, such as a flat file, an XML file, or a database. To access data from these data
sources, programmers need to implement different techniques. This complicates the task of
programmers because they need to master all the techniques. However, the task of
programmers can be simplified by implementing a standard technique to access data from
various data sources. Such a standard technique is provided by Language-Integrated Query
(LINQ).
This chapter provides an overview of LINQ. In addition, it discusses how to access data from
disparate data sources.

Objectives
In this chapter, you will learn to:
Identify the basics of LINQ
Access data from disparate data sources by using LINQ

Identifying the Basics of LINQ


When creating a dynamic Web application, you need to retrieve data from various data
sources, such as a flat file, an XML file, or a database. To access data from these disparate
data sources, you need to learn and implement different techniques. For example, to access
data from files, you need to implement input/output streams and to access data from a
database, you need to implement SQL. This complicates your task as a programmer. This
task can be simplified by using LINQ.
LINQ provides a standard way to access data from disparate data sources. Using LINQ, you
can access data from disparate data sources by writing a standard query, LINQ query. This
eases your task because you need not learn different technologies to access data. In addition,
LINQ provides various facilities such as stronger typing, compile-time checking, and
improved debugger support.
The following figure shows a model of .NET LINQ.

Model of .NET LINQ


The .NET Language-Integrated Query model consists of all the languages in which you can
create your Web application. It includes the components such as LINQ to ADO.NET, LINQ
to XML, and LINQ to objects, using which you can access the data from data sources such as
database, an arraylist, and an XML.
To retrieve data from data sources, you need to write a LINQ query. Therefore, you need to
know the different components of a LINQ query.

Understanding the LINQ Query


A LINQ query is an expression that retrieves data from a data source. It enables you to write
a standard query expression to retrieve data form disparate data sources. It also allows you to
filter, sort, group, and join the results of the query by using additional clauses in the query.

Accessing Data by Using a Simple LINQ Query


To access data by using LINQ, you need to perform the following steps:
1. Specify the data source.
2. Create the query.
3. Execute the query.
Specifying the Data Source

In a LINQ query operation, the first step is to specify the data source. The data source in a
LINQ query can be an XML file, an array, a collection, or a database. If the data source that
you want to use is an array, you can specify the data source by using the following statement:
string[] customers = new string[2] {John, Mary};

In the preceding statement, the array, customers, is the data source.


Similarly, if the data source that you want to use is an XML file, you can specify the data
source by using the following statement:
XElement customers = XElement.Load(@"c:\myCustomerList.xml");

In the preceding statement, the XElement object, customers, is the data source.
After specifying the data source, you need to create a query expression to retrieve or
manipulate data from the specified data source.
Creating the Query

A query describes what information is to be retrieved from the specified data source. It must
include the from and select clauses to retrieve data. The from clause specifies the data
source from where the data is to be retrieved and the select clause specifies the type of the
returned elements. Consider the following query:
var query = from <type of the value returned> cus in customers
select cus;

The preceding query contains the from and select clauses. The from clause specifies the
range variable cus and the data source Customers, and the select clause specifies the type
of the values that will be returned by the query. The query is stored in a query variable,
query. It is initialized with a query expression.

Note

The range variable acts as an iteration variable in a foreach loop. When the query is
executed, the range variable is served as a reference of each item stored in the data source,
such as a database.

Note
The var keyword is a new keyword that can infer its data type from the resulting set. A var
type variable needs to be initialized at the time of declaration. The var keyword cannot be
used when declaring the member variables of a class. Consider the following examples:
var one = 1; //infers an int
var two = "2"; // infers a string
var five = null; // This results in a compilation error because //the data
type is not specified in the Right hand side.

Executing the Query

In LINQ, the query variable only stores the query. The actual execution of the query is
deferred until the query variable is iterated by using the foreach loop. The foreach loop is
the place where the query results are retrieved. Consider the following code snippet:
//Query execution
foreach (var cus in query)
{
Response.Write(cus);
}

In the preceding code snippet, the iteration variable cus holds each value, one at a time, in the
same sequence as returned by the query.
The query variable only stores the query that is to be executed. Therefore, you can execute
the query variable as many times as you want. It is useful in situations where the database is
constantly updated. In such a situation, you can create a query variable and execute it at some
interval to retrieve the updated data.
The execution of all the queries is not deferred till query variable is iterated by using the
foreach loop. The queries that perform aggregate functions such as Max and Count over a
range of source elements must first iterate over those elements. Such queries execute without
explicitly using the foreach loop. This is because such queries itself use the foreach loop in
order to return the result. These queries return a single value. Consider the following
example:

var evenNumbers = from num in numbers


where (num % 2) == 0
select num;
int Count = evenNumbers.Count();

In the preceding example, the foreach loop has not been used to execute the query. It gets
executed automatically when the Count function is used.
Consider the following example in which the LINQ query is used to retrieve data from an
ArrayList object:
public partial class Default : System.Web.UI.Page
{
public class customer
{
public string Name { get; set; }
public string City { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
ArrayList arrList = new ArrayList();
arrList.Add(
new customer
{
Name = "Svetlana", City = "London"
}
);
arrList.Add(
new customer
{
Name = "Claire", City="Paris"

}
);
arrList.Add(
new customer
{
Name = "Cesar",

City="New York"

}
);
var query = from customer cus in arrList
select cus;
foreach (var cus in query)
{
Response.Write (cus.Name + "

lives in

" + cus.City

+ "<br>");
}
}
}

In the preceding example, a class customer with two properties, Name and City, is created.
After creating the class, an object of the ArrayList class is created and three objects of the
type customer are added to the ArrayList object. The ArrayList object is the data source
from which the data is retrieved by using the LINQ query. The LINQ query retrieves all the
data from the data source.
Using LINQ Queries to Filter, Sort, Group, and Join Data
In addition to selecting data, a query can perform the following operations on data:

Filtering
Ordering
Grouping
Joining

Filtering

To retrieve data depending on certain criteria or condition, you need to filter the data.
Filtering causes the query to return only the data that matches with the specified condition.

The condition to retrieve data can be specified by using the where clause. For example, the
following code snippet returns the data of the customers who live in London:
var query = from <type of the value returned> cus in customers
where cus.City == "London"
select cus;

You can also use the logical operators in the where clause to apply two or more conditions.
For example, the following code snippet returns the data of the customers who live in London
and have last name as Darcy:
var query = from <type of the value returned> cus in customers
where cus.City == "London" && cust.Name == "Svetlana"
select cus;

Ordering

LINQ queries can also be used to retrieve data and display it in a sorted manner. This can be
done by using the orderby clause. The orderby clause enables a user to sort the retrieved
data in ascending or descending order. For example, the following code snippet returns the
data for the customers who live in London. The data is sorted by customer names in
alphabetical order:
var query =
from <type of the value returned> cus in customers
where cus.City == "London"
orderby cus.Name descending
select cus;

Note
The default value for the orderby clause is ascending.
Grouping

You can also retrieve data and group it by using the group clause. For example, the following
code snippet returns the data for all the customers, grouped on the basis of the cities they live
in:
var query = from <type of the value returned> cus in customers

group cus by cus.City;

When you end a query with a group clause, the results take the form of a list of lists. Each
element in the list is an object that has a Key member and a list of elements that are grouped
under that key. When you iterate over a query that produces a sequence of groups, you must
use a nested foreach loop. The outer loop iterates over each group, and the inner loop iterates
over each member of the group. For example, to execute the preceding query and to display
the results, you need to use nested foreach loops as shown in the following code snippet:
foreach (var cus in query)
{
foreach (var i in cus)
{
Response.Write(i.Name + "

lives in

" + i.City +

"<br>");
}
}

Joining

It is possible that the data you need to retrieve exists in more than one table/object. For
example, you need to retrieve information regarding the orders placed by a customer. The
information regarding the customers is stored in the customers table/object and the
information regarding the orders is stored in the orders table/object. Both the tables/objects
must have a common field, which is required to join the tables/objects. To retrieve the
required information, you need to join the data from both the tables/objects. This can be done
by using the join clause, as shown in the following code snippet:
var query = from <type of the value returned> cus in customers join
<type of the value returned> ord in Order on cus.order_id
equals ord.order_id
Select new {CustomerName=cus.Name,
OrderAmount=Order.Amount};

In the preceding code snippet, two ArrayList objects customers and Order are the data
sources. These ArrayList objects contain information about the cutomers and the orders
placed by them. Both the objects have a common field order_id, which is required to join
data from these objects. The data from the preceding query can be retrieved by using the
following foreach loop:
foreach (var cus in query)

{
Response.Write(cus.CustomerName + " has the order amount " +
cus.OrderAmount + "<br>");
}

Accessing Data from Disparate Data


Sources
In Web applications, the data that is to be displayed on the Web pages may exist in disparate
data sources. These data sources can be objects, databases, or XML files. You can access data
from these data sources either by using the LINQ queries or by using the LINQ data source
control.

Accessing Data by Using the LINQ Queries


LINQ provides a standard query for retrieving data from disparate data sources. These
queries can be used to access data from:

Objects
Databases
XML files

Accessing Data from Objects


Data from objects can be accessed by using LINQ to Objects. LINQ to Objects provides an
easy way to create a query for accessing data from an object collection such as an ArrayList
by writing foreach loops.
To use LINQ to query an object collection, you need to declare a range variable. The type of
the range variable should match the type of the objects in the collection. For example, if you
create an ArrayList that stores objects of type customers, the range variable should also be of
the customers type, as shown in the following code snippet:
var query = from customers cust in arrList
select cust;

In the preceding code snippet, a range variable cust is of the type customers. By declaring a
range variable, each item in the ArrayList is typecasted to a customers object.
The following example describes how to access data from a string array that contains the
names of students in a class:
string[] arr = new string[] { "Peter", "Sam" , "Philip"};
var query = from string person in arr

select person;
foreach (var p in query)
{
Response.Write(p + "<BR>");
}

Accessing Data from Databases


A Web application accesses most of the data from databases. To access data from a database,
you can use LINQ to ADO.NET. LINQ to ADO.NET includes the following technologies to
access data:

LINQ to dataset
LINQ to SQL

LINQ to Dataset

A Dataset is a collection of cached data presented in a tabular form. The data from a Dataset
can be retrieved by using LINQ. LINQ to Dataset is basically used in situations where you
have used ADO.NET for accessing data from a database. Now, you want to implement LINQ
queries in the application to get the benefits such as compile time checking of the query
syntax and better performance. However, you want minimal changes in the coding. In such a
situation, you can use LINQ to ADO.NET because by using LINQ to ADO.NET, you just
need to change the data retrieval code that was used to access data from the Dataset. The rest
of the code will remain the same.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection MyConn = new SqlConnection();
MyConn.ConnectionString = "Data Source=172.23.3.59;Initial
Catalog=Music;User Id=sa; Password=password@123";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from
albums",MyConn);
MyConn.Open();
da.Fill(ds);
DataTable album= ds.Tables[0];
var q = from d in album.AsEnumerable()

select d;
foreach (var i in q)
{
Response.Write(i.Field<string>("Album_Name") + "<br>");
}
}

In the preceding example, LINQ to Dataset is used to retrieve data from the Dataset and
display it on the Web page. Notice the use of the AsEnumerable() method. It changes the
compile time type of a query to IEnumerable<T>. This means that the type can be used in a
foreach loop.
LINQ to SQL

LINQ to SQL provides a run-time infrastructure for managing relational data as objects. In
LINQ to SQL, the data model of a relational database is mapped to an object model created
by the developer. While querying data by using LINQ to SQL, it translates the languageintegrated queries in the object model defined by the developer and sends the data to the
database for execution. The database returns the result, and LINQ to SQL translates the result
back into the form of objects that can be used in a programming language to query data. This
helps in integrating the object-oriented features such as classes and methods with SQL. The
methods written to query data can be reused in any application because these methods are
generic.
In addition, IDE such as Microsoft Visual Studio provides the Object Relational Designer
(O/R designer), which provides a visual designer surface for creating LINQ to SQL entity
classes and relationships that are based on objects in a database.

LINQ to SQL entity classes are also used by the ASP.NET Dynamic Data to determine the
user interface that is based on the LINQ to SQL data model. ASP.NET Dynamic Data is a
framework that enables a user to create data-driven ASP.NET Web applications with minimal
or no coding. ASP.NET Dynamic Data does this by automatically discovering data-model
metadata at run time and rendering the user interface according to it. The data-driven
ASP.NET Web applications created by using ASP.NET Dynamic Data provides:

Data access operations such as create, update, remove, and display, relational
operations, and data validation.
Built-in support for foreign-key relationships.

The ability to customize the user interface rendered to display and edit specific data
fields.
The ability to customize data field validation.

Accessing Data from XML Files


XML is widely used to exchange data between various applications. LINQ to XML is a
programming interface that enables you to access data stored in XML files. The following
example shows the code in an XML file, CustomersDetails.Xml:
CustomersDetails.Xml:
<?xml version="1.0" encoding="utf-8" ?>
<CustomersDetails>
<Customer>
<CustomerID>C001</CustomerID>
<Name>Svetlana</Name>
<City>London</City>
</Customer>
<Customer>
<CustomerID>C002</CustomerID>
<Name>Claire</Name>
<City >Paris</City>
</Customer>
<Customer>
<CustomerID>C003</CustomerID>
<Name>Cesar</Name>
<City>New York</City>
</Customer>
</CustomersDetails>

To access the data from the CustomersDetails.Xml by using LINQ, you need to write the
following code snippet:
XDocument xmlDoc = XDocument.Load("D:\\Website7\\XMLFile2.xml");
var q = from c in xmlDoc.Descendants("Customer")
select (string)c.Element("CustomerID") + "-" + (string)c.Element("Name")+"" + (string)c.Element("City")+"<br>";
foreach (string name in q)
{
Response.Write(name);
}

Accessing Data by Using the LINQ Data Source Control


The LinqDataSource control enables you to connect a data control to a wide variety of data
sources, such as a database, data-source classes, and in-memory collections. The
LinqDataSource control can be connected to any kind of data collection that is stored in a
public field or property. The declarative markup and code to perform data operations in a
LinqDataSource control are the same for all data sources. You can bind data-bound controls
to a LinqDataSource control by using the DataSourceID property of the data-bound control.
The following table lists some properties of the LinqDataSource control.
Property

Description

ContextTypeName

Gets or sets the name of the type that contains


the property whose value has the data that is to
be retrieved.

TableName

Gets or sets the name of the property or field in


the data context object that represents a data
collection.

DeleteParameters

Gets the collection of parameters that are used


during the delete operation.

Delete

Performs the delete operation.

InsertParameters

Gets the collection of parameters that are used


during the insert operation.

Insert

Performs the insert operation.

SelectParameters

Gets the collection of parameters that are used


during the data retrieval operation.

Select

Gets or sets the properties and the calculated


values included in the retrieved data.

UpdateParameters

Gets the collection of parameters that are used


during the update operation.

Update

Performs the insert operation.

Properties of the LinqDataSource Control


You can retrieve data by using the LinqDataSource control, as shown in the following
example:
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="MyMusicDataContext"
TableName="albums">
</asp:LinqDataSource>

In the preceding example, the ContextTypeName attribute sets the name of the type that
contains the property that provides the data. The TableName attribute sets the name of the
table in the data context object that represents a data collection.

Summary
In this chapter, you learned that:

LINQ provides a standard way to access data from disparate data sources.
When accessing data by using LINQ, you need to perform the following steps:
o
o
o

LINQ provides a standard query for retrieving data from disparate data sources.
LINQ queries can be used to access data from:
o
o
o

Specify the data source


Create the query
Execute the query

Objects
Databases
XML files

You can also use the LINQ data source control to access data from disparate data
sources.

Reference Reading
Identifying the Basics of LINQ
Reference Reading: Books

Reference Reading: URLs

Pro ASP.NET 3.5 in C#


2008 by Matthew
MacDonald, Mario
Szpuszta

http://www.develop.com/course/new-net3-net35-linq

Accessing Data from Disparate Data Sources


Reference Reading: Books

Reference Reading: URLs

Professional ASP.NET
3.5: In C# and VB by Bill
Evjen, Scott Hanselman,
Devin Rader

http://www.develop.com/course/new-net3-net35-linq

Chapter 8

Implementing Error Handling and


Debugging
While developing a Web application, you may come across several errors. These errors can
occur because of invalid data, unexpected circumstances, or even hardware failure. Whenever
an error occurs, the application ends abruptly. Being a professional Web developer, you need
to ensure that your application is able to handle errors. For this, you need to consider all the
possible cases of errors that can occur in an application.
ASP.NET provides several error-handling and debugging techniques that you can use to
secure your ASP.NET applications against common errors.
This chapter discusses how to implement error-handling techniques to capture errors in a
Web application. It also discusses how to add error messages to the event log. In addition, it
discusses how to debug Web applications.

Objectives
In this chapter, you will learn to:
Handle and log errors
Debug Web applications

Handling and Logging Errors


A Web application may contain various types of errors or bugs. Errors such as typing errors
and syntax errors are detected at compile time. However, run-time errors such as division by
zero and type mismatch cannot be detected at compile time. Such errors can be dealt with by
implementing effective error-handling and debugging techniques.
For implementing effective error-handling techniques, you should be able to classify errors
and identify situations where errors can occur in your Web applications. This is possible only
for the errors that can be anticipated, such as division by zero. However, there are errors such
as logical errors that cannot be anticipated. To secure your application against such types of
errors, you need to implement debugging techniques to identify and solve the error.
When an error occurs, details about the error can be added to an event log. This logging of
errors helps in debugging because the users can see the event log to know about the errors
that occurred previously in the application.

Handling Errors

ASP.NET allows you to handle errors at the following levels:

Page Level
Application Level

Page-Level Error Handling


Page-level error handling is used to handle errors that occur on ASP.NET pages. For
example, when you try to write to a non existing file, an error occurs on ASP.NET pages and
can be handled by using Page-level error handling. You can implement page-level error
handling either by using the try-catch block or by using the Page_Error subroutine.
Using the Try-Catch Block

You can place the statements susceptible to errors in a try-catch block. It is an error handling
feature provided by most of the languages. It enables you to programmatically handle the
errors that occur at runtime. The try block contains the code that may cause an exception. It
is followed by one or more catch blocks, which specify the code for handling the exception.
To handle errors properly, you need to retrieve information about the type and cause of the
error and then handle the error. You can retrieve error information by using a try block and
handle the error by using the catch block.
The exceptions that occur in a Web application are inherited from the Exception class. The
properties included in the Exception class help you handle errors easily and efficiently. You
can use the following properties of the Exception class to handle errors:

Message: Returns a string that represents the error message.


Source: Returns a string that represents the object or application that caused the error.
StackTrace: Returns a string that represents the methods called immediately before

the error occurred.


TargetSite: Returns a MethodBase object, which represents the method that caused
the error.

Consider the following example. It uses the preceding properties to handle an error that can
occur while opening a database connection:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat=server>
void Page_Load(Object sender , EventArgs e)
{
SqlConnection mycon;
SqlCommand mycommand;
mycon = new SqlConnection(

@"Server=localhost;Database=SimpleCon;Connection Timeout=15" );
mycommand = new SqlCommand( "select * from Products", mycon );
try {
mycon.Open();
dgrdProducts.DataSource = mycommand.ExecuteReader();
dgrdProducts.DataBind();
mycon.Close();
}
catch (Exception objException)
{
//Exception objException;
Response.Write("Sorry we are experiencing technical
problems...");
Response.Write("<hr>");
Response.Write("<li> Message: " + objException.Message);
Response.Write("<li> Source: " + objException.Source);
Response.Write("<li> Stack Trace: " +
objException.StackTrace );
Response.Write("<li> Target Site: " +
objException.TargetSite.Name);
}
}
</script>
<html>
<head><title>CatchException.aspx</title></head>
<body>
<asp:DataGrid

ID="dgrdProducts"
Runat="Server" />
</body>
</html>

In the preceding example, if an error occurs within the try block, statements in the catch
block are executed and detailed information about the error is displayed. The Exception
object used in the catch block represents a generic exception. The catch block can also be
used to capture particular exceptions such as InvalidArgumentException or
IndexOutOfRangeException. This is required if specific information on the cause of error is
needed.
You can include the finally block in a try-catch block for cleaning up the resources. The
finally block always executes, irrespective of whether or not an exception has occurred. For
example, you can use the finally block to close a database connection, as shown in the
following code snippet:
try
{
DgrdProducts.DataSource=mycommand.ExecuteReader();
DgrdProducts.DataBind();
}
catch(Exception objException)
{
Response.Write("Could Not Execute Statement");
}
finally
{
// closing the connection to the database
mycon.Close();
}

In the preceding code snippet, the finally block closes the database connection even if no
exception is caught.

Using the Page_Error Subroutine

It is not always possible to anticipate and handle all the errors that may occur on a page.
Many unexpected errors can occur while the application is running in a real-world
environment. To handle such errors, you should include the Page_Error subroutine in the .cs
file for the page. This subroutine executes in case an unhandled exception occurs on a page.
For example, you can use the Page_Error subroutine to display an error message, as shown
in the following code snippet:
void Page_Error (Object sender , EventArgs e) {
Response.Write( "Sorry, an error was encountered:" );
Response.Write( "<p>" );
Response.Write( Server.GetLastError().Message);
Server.ClearError();
}

In the preceding code snippet, the GetLastError() method of the Server object returns the
previous exception that had occurred in the page. The ClearError() method is used to clear
the error message. Clearing an error means that it has been handled. Once you have cleared
the error, it is not passed to any higher level error handler such as the Application_Error
event.
Application-Level Error Handling

Application-level error handling enables you to handle errors on ASP.NET pages,


irrespective of where the errors occur in the application. If an error is not handled at the page
level, it is passed to the application-level error handler.
Some errors, such as leaving a required field blank, are common on Web pages. Instead of
writing error handler code for the common errors on every Web page, you can use the
application-level error handling code to handle these errors.
You can implement application-level error handling either by using the <customErrors>
element in the web.config file or by using the Application_Error subroutine in the
global.asax file.
Using the <customErrors> Element

When a user accesses an ASP.NET Web application from a Web browser and an error
occurs, the default error message is displayed to the user. However, it is not a good
programming practice to display the default error message to the user. You can use the
<customErrors> element of the web.config file to control the details of the error information
made available to the users of ASP.NET applications.

By using the <customErrors> element, you can either completely hide the error information
from the users or display customized error messages. You can also redirect users to an
appropriate error page in case an unhandled error occurs.

Note
The <customErrors> element will work when you start the application without debugging
support.
Consider the following example in the web.config file:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx">
</customErrors>
</system.web>
</configuration>

In the preceding example, the following two attributes of the <customErrors> element have
been set:

mode:

Specifies the mode for handling custom errors. The mode attribute can be set to
any of the following values:
o
o

Off: Disables the display of custom error messages. The default error message is

displayed for both local and remote users in case of an error.


On: Enables the display of custom error messages. The user-defined custom error
messages are displayed instead of the default error message for both local and
remote users.
RemoteOnly: Enables the display of custom error messages for remote users only.
The local users are shown the default error message only. RemoteOnly is the
default value of the mode attribute.

Note
Local users are the developers who are working on the same computer on which the
Web application is deployed. Remote users are those users who are accessing the
Web application from a computer other than the one on which the website is
deployed.

defaultRedirect:

Specifies the URL of the customized error page that should be


displayed in case of an error. In the preceding example, the defaultRedirect
attribute is set to the Web form, Error.aspx, specifying that in the case of an
unhandled run-time error, the browser should be redirected to the Web form,
Error.aspx.

The preceding example displays a single error page for all types of errors. However, it is
possible to display different error pages for different types of errors by including <error>
elements within the customErrors section. Consider the following example:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="PageNotFound.aspx" />
<error statusCode="408" redirect="SessionTimeedOut.aspx" />
</customErrors>
</system.web>
</configuration>

In the preceding example, if an error with the status code 404 occurs, the user will be
redirected to the error page, PageNotFound.aspx. If an error with the status code 408 occurs,
the user will be redirected to the error page, SessionTimedOut.aspx. However, if an error
with any other status code occurs, the user will be redirected to the default error page,
Error.aspx.
Using the Application_Error Subroutine

Application-level errors can also be handled in the event handler for the Application.Error
event that occurs whenever an unhandled error occurs in an application. The event handler
for this event is written in the Global.asax file. You can use this event handler to capture the
errors for logging or notification.
This event handler is similar to the Page_Error event handler. The only difference is that it
operates at the application level.
Consider the following code snippet:
protected void Application_Error(Object sender, EventArgs e)
{
Response.Redirect("ErrorPage.aspx");
}

In the preceding code snippet, the Application_Error event handler redirects the user to the
ErrorPage.aspx page in case an error occurs anywhere in the Web application.

Logging Errors
It is possible that certain unexpected errors occur in a Web application while it is running in a
real-world environment. It would be easy to resolve such errors if a log of these errors is
maintained. ASP.NET enables you to log unhandled errors in an event log, database, or some
other file. These event logs, databases, or files can be used by the administrator to learn about
the errors that are occurring in a Web application. You can log information about all the
errors whether they occur at the page-level or at the application-level.
To log errors occurring in an application, you need to create a log for the application in the
event log. Whenever an unhandled error occurs in a Web application, the
Application_Error event handler, written in the Global.asax file, is executed. Therefore,
the event logging code can be written in the Application_Error event handler.
A log can be created by using the EventLog class of the .NET Framework. For using this
class, you need to import the System.Diagnostics namespace.
The following table describes the various properties of the EventLog class.
Property

Description

Entries

Retrieves the contents from an event log.

Log

Specifies the name of the log from where the log


information is to be read or written.

Source

Specifies the name by which the application


needs to be registered in the event log. The name
specified as the Source property should be
unique in an event log. A single event log can
contain content from multiple sources.

Properties of the EventLog Class


The following table describes the various methods of the EventLog class.
Method

Description

Exists

Determines whether the log to which the


information is to be written or read exists on the
specified computer. If the computer is not

specified, the existence of the log is checked on


the local computer.
SourceExists

Determines whether a particular source name


already exists on the specified computer. If the
computer is not specified, the existence of the
event source is checked on the local computer.

CreateEventSource

Establishes an application as a valid event source


for adding information to a log.

WriteEntry

Writes information to an event log.

Methods of the EventLog Class

Debugging Web Applications


Debugging is the process of finding and fixing errors in an application. An application may
contain syntax errors, logical errors, and run-time errors. The syntax errors are resolved
during the compilation of the Web application. However, logical errors and run-time errors
cannot be identified during compilation. Such errors require you to debug the code while it is
running.
There are various tools available that help you debug your Web application. One such tool is
Visual Debugger. It is available in Visual Studio IDE. These tools enable you to step line-byline through the statements in an application to ensure that the execution path and the data are
correct. Before using these tools, you need to configure your Web application for debugging.

Configuring Web Applications for Debugging


To enable debugging in an ASP.NET Web application, you must configure the application to
compile into a debug build. A debug build includes the information that the debugger needs
to debug the code. You can configure a Web application to compile into a debug build by
setting the debug attribute in the <compilation> element of the web.config file to true, as
shown in the following markup:
<configuration>

<system.web>
<compilation debug="true" />
</system.web>
</configuration>

However, if you want to debug only a single page in your Web application, you can add the
debug attribute and set its value to true in the @ Page directive of the page that you wish to
debug, as shown in the following markup:
<%@ Page debug="true" %>

Application execution becomes slow when debugging is turned on. For this reason,
debugging has to be turned off before the deployment of the Web application. To disable the
debug mode, set the debug attribute to false in the <compilation> element of the
web.config file, as shown in the following markup:
<compilation defaultLanguage="C#" debug="false" />

Features of Debugging
Debugging allows you to run your code line by line to monitor the program execution. You
can check the state of the application objects such as variables and database table values to
ensure that the application is running properly. A debugger includes the following features
that help you debug Web applications:

Breakpoints: Breakpoints are places in the code where the debugger stops the
execution of the Web application. This allows you to view the current state of data in
your Web application. You can step through each line of code when executing the
Web application.
Stepping: Once the execution of the Web application has been stopped at a
breakpoint, you can execute the code line by line, which is known as stepping through
the code.
Data Viewing: This feature allows you to view and track data while the Web
application is running. It also allows you to modify data while the execution of the
Web application is stopped at a breakpoint. You can then continue to run the
application with the modified data.

Debugging enables you to observe and change values of variables and objects in your
application code. You can get a close look at what your code does by using the debugger.

Summary
In this chapter, you learned that:

The errors can be handled at the following two levels:


o
o

The page-level error can be handled either by using the try-catch block or by using the
Page_Error subroutine.
Application-level error handling enables you to handle errors on ASP.NET pages,
irrespective of where they occur in the application.
The application-level error can be handled either by using the <customErrors>
element in the web.config file or by using the Application_Error subroutine in the
Global.asax file.
ASP.NET enables you to log unhandled errors in an event log, database, or some
other file.
An event log can be created by using the EventLog class of the .NET Framework.
Debugging is the process of finding and fixing errors in an application.
There are various tools available that help you debug your Web application. One such
tool is Visual Debugger, available in Visual Studio IDE.
The features of a debugger that help you debug Web applications are:
o
o
o

Page Level
Application Level

Breakpoints
Stepping
Data Viewing

The aspnet_wp.exe process is attached to the debugger to debug a running page.

Reference Reading
Handling and Logging Errors
Reference Reading: Books

Reference Reading: URLs

Beginning ASP.NET 3.5


http://wiki.asp.net/page.aspx/383/custom-error-logging/
in VB 9.0: From Novice to
Professional by Matthew
MacDonald
Debugging Web Applications

eference
Reading: Books

Reference Reading: URLs

Beginning
ASP.NET 3.5 in
VB 9.0: From
Novice to
Professional by
Matthew
MacDonald

http://www.informit.com/articles/article.aspx?p=29419

Chapter 9

Enhancing Web Applications by Using Web


Parts
Being a Web developer, you need to develop websites that appeal users. Users today want to
do much more than just viewing the content on the website. They want to personalize Web
pages according to their interest and preferences. You can implement personalization on your
websites by implementing Web parts. Users can use these Web parts to personalize Web
pages.
In addition to using Web parts, you can enhance a Web application by including commonlyused features such as information about astrology, latest news updates, cricket scores,
temperature of the day, or weather forecast. These features are common and are provided on
the Internet through Web services. You can easily include these features on your website by
consuming existing Web services.
This chapter discusses Web parts and their implementation. In addition, it discusses how to
consume Web services for providing various features in a Web application.

Objectives
In this chapter, you will learn to:
Implement Web parts in a Web application
Consume Web services in a Web application

Implementing Web Parts in a Web


Application
Today, a website may contain a wide variety of information regarding various domains, such
as entertainment, astrology, business, sports, and technology. However, users may be
interested in viewing only the information of their interest. Therefore, websites such as
MSN.com organize their data into discrete units. Each unit represents a standalone part of the
website and contains information about a specific domain. These units support a degree of
personalization. Users can rearrange or hide these units to suit their individual working styles.
These units can be developed by using ASP.NET and are known as Web parts.
A Web part is a modular unit that can contain any type of Web-based information. This
information could be a picture, static text, or database information. A Web part enables a user
to create a personalized user interface and enables you to present information in a better way.
It also enables you make your websites interactive.

Advantages of Using Web Parts


Web parts allow the information displayed on a website to be broken down into manageable
parts. Users can rearrange, move, or close the Web parts to suit their preferences. Users can
also save their preferences for future browser sessions.
The advantages of using Web parts on a website are:

Web parts enable users to personalize the content of a Web page. Users can move or
hide Web parts to customize the Web page. They can even add new Web parts to
change the layout of the page.
Web parts can be assigned role-based access, thereby, determining which Web part
can be shared by all users or which should be hidden for certain roles. This helps in
providing customized content based on security.
Web parts can be connected to each other. One of the connected Web parts is defined
as a provider and the other as a consumer. Consider the example of a Web parts page
that contains two Web parts, one displays a chart and another displays the stock
market data. These Web parts can be connected in such a way that the chart Web part
displays the chart for the stock market data present in the other Web part. In this
example, the Web part providing the stock market data is the provider and the Web
part displaying the chart is the consumer.

Web Part Modes


Personalization is one of the main advantages of using Web parts. You can implement
personalization by allowing a user to view a Web page in several display modes.
Display modes allow users to modify or personalize the Web page. Users can edit the Web
part controls, change the layout of the Web page, and add new Web part controls by using
different types of display modes. The different types of display modes available are:

Browse: This is the default mode. This mode allows users to view Web parts on the
Web page. It also allows users to minimize or close the Web part. If you close a Web
part, it cannot be restored from the Browse mode. However, you can restore it in
another mode called the Catalog mode. The following figure shows a Web part in the
Browse mode.

A Web Part in the Browse Mode

Edit: This mode allows users to edit Web parts on the Web page at runtime. Users
can set the title, color, or custom properties of the Web parts.
Design: This mode allows users to rearrange the order of Web parts on the Web page
by dragging and dropping them.
Catalog: This mode allows users to add new Web parts on the Web page. It also
allows users to rearrange or delete the existing Web parts from the Web page.
Connect: This mode allows users to connect two Web part controls on a Web page.

Note
A Web page can be displayed in only one display mode at a time.

Web Parts Control Set


ASP.NET provides you with the Web parts control set that are designed to implement Web
parts on your websites. A Web parts control set consists of a group of Web parts that work
together to enable users to create Web parts pages. A Web page that is composed of Web
parts is known as a Web parts page. A Web parts page is divided into zones that provide the
structure for placing Web parts. You can place Web parts in any of these zones according to
your requirements.
The following table describes some of the Web part controls available in ASP.NET.
Control

Description

WebPartManager

Manages all the Web part controls on a page.


Each Web parts page contains exactly one
WebPartManager control.

CatalogZone

Contains CatalogPart controls and is used to


create a catalog of Web part controls from

which a user can select a Web part control to


add to a page.
EditorZone

Contains EditorPart controls and is used to


enable a user to edit and personalize Web
part controls on a page.

WebPartZone

Contains the overall layout for the Web Part


controls that compose the main user interface
of a page.

ConnectionsZone

Contains Connection controls.

CatalogPart

Contains a list of available Web part controls


that a user can add to a page.

Connection

Creates a connection between two Web part


controls on a page.

EditorPart

Serves as the base class for specialized


controls that provide the functionality to edit
Web parts.

Some of the Web Part Controls Available in ASP.NET


To implement Web parts on your website, you first need to add a WebPartManager control
and one or more WebPartZone controls to the Web page. The WebPartManager control is
used to manage all the Web part controls on the Web page. The WebPartZone control serves
as a container for the Web part controls. After adding these controls, you need to add the
controls on your Web pages. These controls can be the existing Web server controls or Web
user controls.
Once you have created a Web parts page, you can allow users to change the appearance of the
user interface elements on the Web page. This can be done by changing the display mode of
the Web parts page.
To enable a user to switch between the various modes, you can include a drop-down list on
the Web page that allows a user to select the desired mode. After including the drop-down list
on the Web page, you can type the following code snippet in the SelectedIndexChanged
event of the DropDownList control:
WebPartManager wpm =
WebPartManager.GetCurrentWebPartManager(Page);
string selectedMode = DropDownList1.SelectedValue;
WebPartDisplayMode mode =
wpm.SupportedDisplayModes[selectedMode];
if (mode != null)

{
wpm.DisplayMode = mode;
}

The preceding code snippet, enables a user to change the mode of the Web parts present on
the Web page by selecting the edit mode from the DropDownList control.

Connecting Web Parts


There are situations where you need to connect sets of data from different data sources. For
example, a Web parts page contains two Web parts, one that contains details of senior
managers of a department and the other that displays their photographs, one at a time. You
can connect these Web parts in such a way that when you select the name of a manager in the
first Web part, the other Web part displays the photograph of the selected manager.
In the preceding example, the Web part containing the details of senior managers is the
provider and the Web part that displays the photograph of the selected senior manager is the
consumer.
Web part connections are based on a pull model, where the consumer pulls data from the
provider. To create a connection, the provider control defines a communication contract in
the form of an interface, indicating the data it can provide. The consumer control knows
about this contract and retrieves the data through the connection. The interface can contain
properties, events, or methods that the consumer control can use once the connection is
established.
To participate in a connection, a Web part needs to define a connection point. A connection
point contains the details necessary for a server control to connect to another control. These
details include information such as the type of the control itself, the type of data the control
recognizes, an ID for the connection point object, and whether the control can form multiple
connections. Connection points are of two types, provider connection points and consumer
connection points.
To create connected Web parts, you need to perform the following tasks:
1. Create the provider Web part as a custom control that derives from the WebPart class
and implements an interface that defines the communication contract. The provider
Web part defines a connection point in the form of a method to which the
ConnectionProvider attribute has been applied.

2. Create the consumer Web part as a custom control that derives from the WebPart
class and defines a connection point in the form of a method to which the
ConnectionConsumer attribute has been applied.
3. Add the Web parts to the Toolbox.
4. Add the Web part controls from the Toolbox to a Web parts page and assign an ID
and title to each of the two controls.
5. Add the connection information to the WebPartManager control by opening the Web
parts page in the Source view and adding a <staticConnections> element inside the
<asp:WebPartManager> element, as shown in the following example:
<StaticConnections>
<asp:WebPartConnection ID="wpCon" ProviderID="Provider1"
ProviderConnectionPointID="Color" ConsumerID="Consumer1"
ConsumerConnectionPointID="Color" />
</StaticConnections>

Consuming Web Services in a Web


Application
There are certain things that most websites require. For example, almost all websites provide
the searching functionality on their home pages. One way to provide this functionality on
your website is to write your own code. The other way is to use an existing code, and this can
be done by using Web services.
Web services are the application components that can be used by other Web applications.
You can create a Web service and publish it on a Web server, thereby, making it available for
other Web applications to use.

Invoking Web Services


A Web service is a self-describing Web component that exposes its functionality to the
consumers through open standards such as XML and Simple Object Access Protocol
(SOAP). It is a widely used method for implementing Service-Oriented Architecture (SOA).

Note
SOA is software architecture, which is essentially a collection of services communicating
with each other. It was developed for enabling the development of loosely-coupled distributed
applications.

Note
Coupling refers to the interrelatedness and interdependency between two or more
components of a Web application. In loosely-coupled distributed applications, it is possible to
change one component without affecting other components.
Web services allow integration of applications developed in different languages and running
on different platforms. This integration and interoperability in Web services is made possible
with the use of XML. Web services communicate by using a standard protocol called SOAP.
SOAP defines a standard way of passing the XML-encoded data.
Developing ASP.NET Web services starts by creating an .asmx file and hosting it on a Web
server, such as IIS. Once hosted or published on the server, a Web service can be consumed
by any client. The client can be a Web application, desktop application, console application,
or another Web service based on .NET or other platforms such as Java.
The client, who has to consume a Web service, locates the service by adding a Web
reference. This adds a proxy class on the client side, which exposes the methods, parameters,
and return types of the methods contained in the Web service. After adding the proxy class,
the client application creates an instance of the proxy class and accesses the methods
provided by the Web service through the instance.
The client requests are then handled by the proxy class. It transforms the method calls of the
client into the SOAP message format, which can be transmitted over HTTP to the server.
After processing the request, the response is also sent as a SOAP message to the proxy. The
proxy then converts this SOAP message into method return value, which is returned to the
client.

Invoking WCF Services


In distributed computing, Web services along with various other technologies, such as
COM+, .NET Remoting, Message Queues, and Web Service Enhancement (WSE) were used

to provide a wide range of functionality. Every technology is a discreet set of services


fulfilling a specific requirement of a distributed development. This restricts the developers to
make a choice of one of these technologies.
If a developer decides to use more than one technology, a lot of code needs to be written and
unification becomes tedious. In addition, developers need to learn different technologies to
cater to the different needs of distributed application development. For example, to provide
security to the Web services, WSE support needs to be separately added with the Web
service. Similarly, if there is a requirement to host a Web service on TCP and HTTP, separate
coding needs to be defined for both.
To overcome the complexity in the integration of applications developed by using different
technologies, Windows Communication Foundation (WCF) was introduced. WCF unifies
features of such discreet technologies under one single framework. It provides a unified
programming model used to build a secure, reliable, and robust Web service.
WCF aims at providing encoding, hosting, messaging patterns, networking, security, and
interoperability in a single infrastructure. This helps in simplifying the development of
distributed applications.
The following figure shows the WCF architecture.

The WCF Architecture


The following set of APIs is unified in the WCF architecture:

ASP.NET Web Services (ASMX): It provides support and interoperability with Web
services running on non-Windows platforms.
WSE: It provides end-to-end standards-based security for Web services.
System.Messaging: It is a namespace in the .NET Framework that provides managed
APIs to Microsoft Message Queues (MSMQ), enabling developers to build
asynchronous reliable distributed applications.
Enterprise Services: It provides managed APIs to COM+. COM+ provides
component-based programming for functionality such as transactions.
Remoting: It exposes the Common Language Runtime (CLR) type system remotely
and provides location transparency for objects. Remoting is designed for tightly

coupled .NET-to-.NET application communication. It provides seamless and simple


development experience for applications on the local network and the Internet.

Note
In tightly coupled applications, the components are interconnected with each other such that
any change in one component will lead to changes in other components as well.

Note
A WCF Service is a program that exposes a collection of Endpoints. An Endpoint is used for
communicating with other services and applications. An Endpoint has an Address, a Binding,
and a Contract. An Endpoint address is the address where the service listens. The Endpoint's
Binding specifies how the Endpoint communicates with other services and applications. The
Endpoint's Contract specifies what the Endpoint communicates. A WCF Endpoint can be
configured by using the <system.serviceModel> element.
The design goals for building WCF services are:

Unification: WCF increases productivity by bringing together various technologies


such as COM+ and .NET Enterprise services, Message Queues, .NET Remoting,
ASP.NET Web Services, and WSE for building distributed applications by using a
unified programming model.
Interoperability: WCF increases the interoperability options with .NET-to-.NET
applications by providing built-in support of .NET Remoting. It allows basic
communication with other applications running on other platforms.
Service orientation: WCF provides a highly productive programming model for
building distributed systems that involve developing loosely-coupled services. These
services can be independently managed, updated, and deployed.

Summary
In this chapter, you learned that:

A Web part is a modular unit that can contain any type of Web-based information.
The advantages of using Web parts on a website are:
o Web parts enable users to personalize the content of a Web page.
o Web parts can be assigned role-based access, thereby determining which Web
parts can be shared by all users or which should be hidden for certain roles.
o Web parts can be connected to each other.
The different types of display modes of a Web part are:
o Browse mode
o Edit mode
o Design mode
o Catalog mode
o Connect mode
A Web page that is composed of Web parts is known as a Web parts page.
A Web parts page is divided into zones that provide the structure for placing Web
parts.
A Web service is a self-describing Web component that exposes its functionality to
the consumers through open standards such as XML and Simple Object Access
Protocol (SOAP).
Windows Communication Foundation (WCF) aims at providing encoding, hosting,
messaging patterns, networking, security, and interoperability in a single
infrastructure.

Reference Reading
Implementing Web Parts in a Web Application
Refer Reference Reading: URLs
ence
Read
ing:
Book
s
Pro
ASP.
NET
3.5 in
C#
2008
by
Matt
hew
Mac
Dona
ld,
Mari

http://www.hotscripts.com/Detailed/79303.html
http://books.google.co.in/books?q=Implementing+Web+Parts+in+a+Web+Applicat
ions+in+ASP.NET+3.5&source=in&sa=X&oi=book_group&resnum=11&ct=title&
cad=bottom-3results

o
Szpus
zta
Consuming Web Services in a Web Application
Referenc Reference Reading: URLs
e
Reading:
Books
Beginnin
g
ASP.NET
3.5: In
C# and
VB by
Imar
Spaanjaa
rs

http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-webservices/
http://www.codedigest.com/Articles/ASPNET/52_ASPNET_35_AJAX_and_WebS
ervices__.aspx

Chapter 10

Creating Rich Internet Applications Using


AJAX
In a traditional Web application, when a user submits any data, it is transferred synchronously
to the Web server. This means that the user cannot interact with the application till the data
transfer activity is completed. Moreover, these applications always reload the complete Web
page even when a single component of a Web page is to be modified. This makes the Web
applications slow and less interactive. These limitations can be overcome by using
Asynchronous JavaScript and XML (AJAX).
This chapter provides an overview of AJAX. It further discusses the various AJAX server
controls provided by ASP.NET. In addition, it discusses the client life-cycle events and
explains how to consume Web services in AJAX-enabled applications.

Objectives
In this chapter, you will learn to:
Explain the AJAX framework
Identify the ASP.NET AJAX server controls
Identify the ASP.NET AJAX client life-cycle events
Consume Web services in AJAX-enabled applications

Explaining the AJAX Framework


In traditional Web applications, the client and the server interact synchronously. This means
that the processing of a Web application happens sequentially, one after the other. When the
client requests a page for the first time, the server sends the full page containing HTML and
Cascading Style Sheet (CSS) code at once. The client enters or updates the information on the
page and submits it to the server. The server then processes the information, rebuilds the page
with the updated information, and sends the full page back to the client. This leads to the
following drawbacks:

The user interaction with the application is interrupted every time a postback is made
by the server.
The user has to wait during each postback.
The full page is rendered and transferred to the client after each postback, which is
time consuming and traffic intensive.

To overcome these drawbacks, a technology called AJAX is implemented in Web


applications. By implementing AJAX in Web applications, the interaction between the client

and the server becomes asynchronous. This allows users to interact with the Web application
while waiting for a response from the server. In addition to this, AJAX implementation
enables partial updates in Web applications. This means that instead of sending the entire
page, only the portion that needs to be updated is sent to the server.

Understanding AJAX
AJAX is a Web development technique that is used to create dynamically interactive
applications. It enables Web applications to retrieve data from the server, asynchronously in
the background, without interfering with the display and behavior of the existing page. To
understand the concept of AJAX, you need to understand the relevance of the following
terms:

Asynchronous communication: Asynchronous communication is the ability of an


application to send multiple requests and receive responses from the server
simultaneously. This enables the users to work continuously on the application
without being affected by the responses received from the server.
JavaScript: JavaScript is the scripting language that is used to generate client-side
scripts. JavaScript forms an integral part of the AJAX-enabled Web applications
because these applications process most of the requests on the client side, unless there
is a need to connect to the Web server. The client-side processing of data is handled
by using JavaScript object support in AJAX. The XMLHttpRequest object is one of
the primary objects used by JavaScript because it enables asynchronous
communication between the client and the server.
XML: XML is the standard used for transferring data between applications. XML
forms the base for manipulating the data received from the server and presenting of
the data in the Web application.

To understand the behavior of a Web application that implements AJAX, you need to
understand the role of AJAX in a Web application and how it helps the server to quickly
respond to the client.

Working of an AJAX-Enabled Web Application


When AJAX is implemented in an application, a new layer, the AJAX engine, is added to the
communication model. The AJAX engine resides at the client side and consists of three
components: HTML, CSS code, and some JavaScript files.
In AJAX-enabled Web applications, the page is loaded for the first time when it is requested
by a user. After that whenever a user requests data from the server, the requests are sent as
JavaScript calls to the AJAX engine. The AJAX engine serves as a mediator that sends only
small page bits that are to be updated to the server as XML and subsequently processes server
response to update the relevant page elements without reloading the entire page.
The following figure illustrates the complete life cycle of an AJAX-enabled Web page.

Life Cycle of an AJAX-Enabled Web Page

Advantages and Limitations of AJAX-Enabled Web


Applications
AJAX-enabled Web applications provide various advantages over the Web applications that
are completely server-based. AJAX-enabled Web applications offer:

Quick response to a users request. This is due to partial-page updates feature that
refreshes only those parts of a Web page that have changed or updated. In addition,
partial-page updates feature enables an application to use less bandwidth because only
the those parts of a Web page that have changed or updated are sent to the server.
Asynchronous communication that allows a user to interact with the rest of the Web
page while the application is processing the changed or updated parts of the Web
page.
Auto-generated proxy classes that are used to call Web service methods from client
script such as JavaScript.
Support for the widely used Web browsers such as Microsoft Internet Explorer,
Mozilla Firefox, and Apple Safari.

AJAX-enabled Web applications also have a few limitations. Some of them are:

Browser Integration: The AJAX-enabled Web application does not register the
dynamically-created Web page in the Web browsers history engine. This restricts a
user to view the previous look of the page when he or she triggers the back button of
the Web browser. In addition, a user is not able to bookmark a particular state of the
Web application.

Dependency on JavaScript: The AJAX-enabled Web applications are based on


JavaScript. JavaScript may be interpreted differently by different Web browsers or
versions of a particular Web browser.

You can create AJAX-enabled Web applications by using the .NET Framework. The .NET
Framework enables you to create rich and intuitive websites by providing support for AJAX
features. It provides a set of extensions to ASP.NET for implementing AJAX functionality.
This set of extensions is known as ASP.NET AJAX. To create AJAX-enabled Web
applications by using the .NET Framework, you need to understand the ASP.NET AJAX
architecture.

Architecture of ASP.NET AJAX


The ASP.NET AJAX Web applications consist of client-side and server-side scripts.
Therefore, these applications use both, the client-side and the server-side functionality. The
client-side and the server-side functionality are provided by the two components of the
ASP.NET AJAX architecture, client-script libraries and server components. These
components together provide a strong development framework for developing AJAX-enabled
applications.
The following figure displays the ASP.NET AJAX architecture.

The ASP.NET AJAX Architecture


The preceding figure shows that the ASP.NET AJAX architecture consists of the following
components:

Client-based Microsoft AJAX library

Server-based AJAX features for ASP.NET

Client-Based Microsoft AJAX Library


The ASP.NET AJAX client architecture provides features that enable you to create rich,
intuitive, responsive, and interactive Web applications. This architecture includes the
ASP.NET AJAX library. This library includes:

Components
Browser compatibility
Networking
Core services

Components

The client components enable a Web application to render dynamic behavior to the Web
browser without requiring a postback to the Web server. There are various client components
such as non-visual objects and controls. Non-visual objects, such as a timer object,
encapsulate the code that needs to be repeated after a fixed interval.
Browser Compatibility

The browser compatibility feature provides compatibility for client scripts with major Web
browsers, such as Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari. This
feature makes your Web application browser-independent.
Networking

The ASP.NET AJAX client architecture provides the networking layer between the client and
the server. This layer is used to handle the communication of scripts with the Web services
and the application services. It is also used to handle asynchronous calls to the methods or
services at the remote locations.
The networking layer automatically handles partial-page updates for the UpdatePanel control
in your Web application. It also allows Web applications to access the server-based forms
authentication, role information, and profile information in a client script. The Web
applications that are not created by using ASP.NET can also use the networking layer if they
have access to the Microsoft AJAX library.
Core Services

The ASP.NET AJAX client architecture provides various core services, such as JavaScript
base class extensions, support for JavaScript libraries, debugging, error handling, and
globalization. The JavaScript libraries are either embedded in the assemblies or provided as
standalone JavaScript files with the .js extension.
The core services also include the Sys.Debug class to handle debugging in your Web
application. In addition to the Sys.Debug class, the core services also include the Error object
for handling errors in your Web application. The Error object provides support for the release
mode and the debug mode of the Web application.

Note
In the debug mode, the debug information is generated, which is used for rectifying the errors
in the code. It is used at the time of development of an application. In the release mode, the
debug information is not generated. It is used at the time of deployment of an application
because it is much faster than the debug mode.
Server-Based AJAX Features for ASP.NET
The ASP.NET AJAX server architecture provides the functionality for the following serverbased AJAX features:

Script support
Web services
Application services
Server controls

Script Support

AJAX features in an ASP.NET application can be implemented with the support of client
scripts. These client scripts are sent from the Web server to the Web browser when the
application is requested for the first time. These client scripts provide the following features:

Partial-page rendering: Enables you to update portions of the page by using an


asynchronous postback.
The Microsoft AJAX library: Provides a set of JavaScript extensions that provide
namespaces, inheritance, interfaces, enumerations, and reflection.

You can also create your own custom client scripts for the AJAX-enabled Web applications.
The custom client scripts can be saved as static files or can be embedded in an assembly with
.js extension.
Web Services

An AJAX-enabled Web application can call ASP.NET Web services (.asmx) and WCF
services (.svc) by using client scripts. An AJAX-enabled Web application can call the Web
services without a postback. When a user requests for a Web page for the first time, the proxy
class is automatically generated by the server and downloaded to the browser at the page-load
time. This proxy class can be used to call the corresponding Web service methods.
Application Services

The application services are the predefined Web services that are based on certain features
provided by ASP.NET such as forms authentication, roles, and user profiles. The ASP.NET
forms authentication is performed to verify credentials, such as login id and password, of the
users. The ASP.NET roles are used to group multiple users under one role, such as grouping

all the heads of each department in an administrator role. The profile of a user consists of the
information such as background and foreground colors of the application that is set when the
user logs on to the application.
The application services can be called by various clients, such as a client script in an AJAXenabled Web page, a WCF-compatible client, or a Windows application.
Server Controls

The ASP.NET AJAX server controls consist of server-side script as well as client-side script.
This allows a Web application to provide rich client behavior. A Web page that consists of
AJAX server controls sends supporting client script to a Web browser while it is rendered to
a user to provide AJAX functionality on the Web page. The AJAX functionality include
partial-refreshing of the Web page, asynchronous communication between the Web browser
and the Web server, and faster response to the user.

Identifying the ASP.NET AJAX Server


Controls
ASP.NET offers various AJAX server controls that implement AJAX functionality in a Web
application. Some of the controls offered by ASP.NET are:

ScriptManager control
ScriptManagerProxy control
UpdatePanel control
UpdateProgress control
Timer control

The ScriptManager Control


The ScriptManager control can be used to manage the client script for AJAX-enabled Web
applications. The ScriptManager control provides:

The custom scripts that you need to send to the Web browser to enable asynchronous
communication with the Web service and partial-page refreshes.
The JavaScript classes that are used to access the ASP.NET application services for
forms authentication, roles, and user profiles.
The JavaScript proxy classes that are used to call Web service methods from the
client script.

The ScriptManager control can be added to a Web page by using the following markup:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

The preceding markup adds a ScriptManager server control with a unique ID


ScriptManager1 to the Web page.

The following table describes some properties of the ScriptManager control.


Property

Description

AsyncPostBackErrorMessage

Sends error message to the client when an


unhandled server exception occurs during an
asynchronous postback.

AsyncPostBackTimeout

Gets or sets a value that indicates the period of


time, in seconds, before asynchronous postbacks
are timed out.

EnablePageMethods

Gets or sets a value that indicates whether static


page methods on an ASP.NET page can be called
from a client script. The default value is false.

EnablePartialRendering

Gets or sets a value that enables partial


rendering of a page, which in turn, enables you
to update regions of the page individually by
using the UpdatePanel server controls.

Properties of the ScriptManager Control

The ScriptManagerProxy Control


The ScriptManager control is used to manage the client script for AJAX-enabled Web
applications. The ScriptManager control provides features such as partial page updates.
However, there is a limitation in using the ScriptManager control. You can add only one
instance of the ScriptManager control to a Web page. A Web page can include the control
either directly or indirectly inside a nested component such as a user control or a content page
for a master page. This means that if a master page has a ScriptManager control, you cannot
add a ScriptManager control to the content page, which is using the master page.
This limitation can be overcome by using the ScriptManagerProxy Control. This means that
if a page that already contains a ScriptManager control needs another ScriptManager control
for a nested or parent component, the component can include a ScriptManagerProxy control.
The ScriptManagerProxy control enables you to add scripts and services that are specific to
nested components.
The following table describes some properties of the ScriptManagerProxy control.
Property

Description

Scripts

Gets a ScriptReferenceCollection object


that contains a ScriptReference object for
each script file that is explicitly registered with
the ScriptManagerProxy control.

Services

Gets a ScriptReferenceCollection object


that contains a ScriptReference object for
each service that is explicitly registered with the
ScriptManagerProxy control.

Properties of the ScriptManagerProxy Control

The UpdatePanel Control


The UpdatePanel server control is a container control that helps you create highly interactive
and responsive Web applications. The UpdatePanel control is used with the ScriptManager
control to enable partial-page rendering.
You can add more than one UpdatePanel controls to a Web page. The UpdatePanel control
can contain other Web server controls such as Label and TextBox controls. When the Web
page with multiple UpdatePanel controls is rendered for the first time, the content for the
controls present in the UpdatePanel controls is sent to the Web browser. For subsequent page
postbacks, the controls present in the UpdatePanel controls update independently.
For example, in your AJAX-enabled Web application, you have used three UpdatePanel
controls. In each UpdatePanel control, you have placed one GridView control. When the Web
page is loaded for the first time, the data for all the GridView controls is rendered by the Web
server. On subsequent partial-page refreshes, the data in the GridView controls is updated
independently when the user interacts with them.
You can use the UpdatePanel control on Master pages, content pages, and in the GridView or
Repeater controls.
You can add an UpdatePanel controls to a Web page by using the following markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> </asp:UpdatePanel>

The preceding markup adds an UpdatePanel server control with a unique ID UpdatePanel1 to
the Web page.
The following table describes some properties of the UpdatePanel control.
Property

Description

ChildrenAsTriggers

Gets or sets a value that indicates whether

postbacks from immediate child controls of an


UpdatePanel control update the panel's content.
The default value is false.
Triggers

Gets a collection of all the triggers that are


applied on the UpdatePanel control such as
AsyncPostBackTrigger and PostBackTrigger
objects.

UpdateMode

Gets or sets a value that indicates when an


UpdatePanel control's content is updated.

RenderMode

Gets or sets a value that indicates whether an


UpdatePanel control's content is enclosed in an
HTML <div> or <span> element.

Properties of the UpdatePanel Control

The UpdateProgress Control


The UpdateProgress control is used to provide information on the status of the partial-page
updates in the UpdatePanel controls. If the partial-page update is slow, you can use the
UpdateProgress control to provide a message about the status of the update. For example, you
can use the UpdateProgress control in situations where the client application has requested
for voluminous data that will take a substantial amount of time to load, such as retrieving
more than 500 records in a single request or request for a heavy video file from the server.
The UpdateProgress control can be customized. You can modify the default content and the
layout of the UpdateProgress control.
The UpdateProgress control can be added to a Web page by using the following markup:
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>

The preceding markup adds an UpdateProgress server control with a unique ID


UpdateProgress1 to the Web page.
The following table describes some properties of the UpdateProgress control.
Property

Description

AssociatedUpdatePanelID

Gets or sets the ID of the UpdatePanel control for


which the UpdateProgress control displays the

status of update.
DisplayAfter

Gets or sets the value (in milliseconds) before the


UpdateProgress control is displayed. The default
value is 500 milliseconds.

DynamicLayout

Gets or sets a value that determines whether the


progress template is rendered dynamically.

Properties of the UpdateProgress Control

The Timer Control


The Timer control is used with the UpdatePanel control to perform partial-page updates at a
predefined time interval. The Timer control can also be used to post the entire Web page at a
predefined time interval.
You can use the Timer control in your Web application to perform the following tasks:

Periodical updates of one or more UpdatePanel controls without refreshing the entire
Web page.
Execution of the code at the server each time the Timer control causes a postback.
When the tick event of the Timer control is raised, it causes a postback and the code
written under the tick event handler is executed. For example, a part of a website that
displays the score of a cricket match is updated after every one minute. The code for
updating the score can be written under the tick event handler of a timer control so
that it executes after the set time interval.
Synchronous postback of the entire Web page to the Web server at predefined time
intervals.

The Timer control embeds a JavaScript component into the Web page. The JavaScript
component initiates the postback from the Web browser to the Web server, every time the
predefined time interval has lapsed. When the postback is initiated, the Timer control raises
the Tick event on the server. To handle the Tick event, you can add an event handler that
performs certain predefined actions in response to the event.
You can place multiple Timer controls on a Web page. You can associate each Timer control
with a different UpdatePanel control. However, you can also place one Timer control on the
Web page and associate it with all the UpdatePanel controls.
You can add a Timer control to a Web page by using the following markup:
<asp:Timer ID="Timer1" runat="server"> </asp:Timer>

The preceding code adds a Timer server control with a unique ID Timer1 to the Web page.

The following table describes some properties of the Timer control.


Property

Description

Enabled

Gets or sets a value that indicates whether the


Timer control initiates a postback to the server
after the number of milliseconds specified in the
Interval property has elapsed.

Interval

Gets or sets the number of milliseconds to wait


before initiating a postback to the server. The
default value is 60,000 milliseconds.

Properties of the Timer Control


AJAX server controls raise some events when a client interacts with them. These events
describe how an AJAX-enabled Web application is loaded when requested for the first time
or how it behaves when a user sends a request to the Web server. To understand the events
raised by an AJAX-enabled Web application, you need to understand the client life-cycle
events of ASP.NET AJAX.

Identifying the ASP.NET AJAX Client LifeCycle Events


AJAX-enabled Web applications mainly consist of a client-side script that is processed by the
Web browser. When a user interacts with an ASP.NET AJAX-enabled application, it raises
some client events. These events are handled at the client side and are called client life-cycle
events.
The client events enable you to customize both synchronous and asynchronous (partial-page
updates) postbacks. These events also help you manage custom script components during the
lifetime of the Web page on the browser.
Client events are raised by the classes present in the Microsoft AJAX Library. The two main
Microsoft AJAX Library classes that raise events are Application and
PageRequestManager. These classes are automatically instantiated when an event is raised
on a Web page that contains AJAX server controls. These classes provide APIs that enable

you to bind the events to the controls and provide handlers for those events. For example,
when an UpdatePanel control is added to a Web page, the events of the
PageRequestManager class are raised. These events can be used to cancel postback or to
provide preference to one postback over the other. These events can also be used to animate
the UpdatePanel control when the content in the control is refreshed.

Client Events of the Application Class


The Application class of Microsoft AJAX Library is instantiated when a Web page
displayed on the Web browser contains a ScriptManger control. It inherits the
Sys.Component class.
The following table lists the client events of the Application class that are raised in AJAXenabled Web pages.
Event

Description

Sys.Application.init

Is raised after all scripts have been loaded on the


Web browser. You can use this event to add your
custom component to the Web page. This event
is raised only when the page is rendered for the
first time.

Sys.Application.load

Is raised after all scripts have been loaded on the


Web browser and all the objects in the
application are initialized. This event is raised for
all postbacks to the server, including the
asynchronous postbacks.

Sys.Application.unload

Is raised before all objects are disposed and


before the window.unload event of the Web
browser window occurs.

Sys.Component. propertyChanged

Is raised when a property of a component


changes. To raise this event, you need to call the
Sys.Component.raisePropertyChange

method in a set accessor.


Sys.Component.disposing

Client Events of the Application Class

Is raised when the Application instance is


disposed.

Client Events of the PageRequestManager Class


To enable a Web page to perform partial-page update, you need to add a ScriptManager
control and an UpdatePanel control. When such a page is displayed on the Web browser, an
instance of the PageRequestManager class is automatically instantiated on the browser. This
class raises client events that are specific to asynchronous postbacks (partial-page update).
The following table lists the client events of the PageRequestManager class that are raised
in the AJAX-enabled Web pages.
Event

Description

Sys.WebForms.PageRequestManagerintializeRequest Is raised before an asynchronous

request starts. You can use this


event to cancel a postback.
Sys.WebForms.PageRequestManagerbeginRequest

Is raised before an asynchronous


postback starts and till the
postback is sent to the server. If a
postback is already processing, the
other postback is stopped by using
the abortPostBack method. This
event can be used to begin an
animation on the page to indicate
that the request is in process.

Sys.WebForms.PageRequestManagerpageLoading

Is raised after the response from


the server to an asynchronous
postback is received by the Web
browser, but before any content on
the page is updated or displayed.
This event can be used to provide a
custom transition effect for
updated content.

Sys.WebForms.PageRequestManagerpageLoaded

Is raised after all content on the


page is refreshed, as a result of
either a synchronous or an
asynchronous postback. This event
can be used to manage a custom
transition effect for updated
content.

Sys.WebForms.PageRequestManagerendRequest

Is raised after the response for an


asynchronous postback is
processed and the page is updated,
or during the processing of the
response if there is an error. If an
error occurs, the page is not
updated. This event is used to
provide customized error
notification to users or to log
errors.

Client Events of the PageRequestManager Class

Consuming Web Services in AJAX-Enabled


Applications
In AJAX-enabled Web applications, the Web service is called by using client-side scripts. To
enable client scripts to communicate asynchronously with the server, ASP.NET AJAX
provides the asynchronous communication layer. This layer enables a client application to
call Web services by using JavaScript. The asynchronous communication layer acts as an
intermediary layer between the browser and the server. It uses the XMLHTTP object to
communicate asynchronously.

The Asynchronous Communication Layer


The ASP.NET AJAX architecture provides an asynchronous communication layer that
enables a Web browser to call the Web service methods by using JavaScript. JavaScript can
use the APIs that are exposed by the asynchronous communication layer. These APIs use the
asynchronous behavior provided by the browsers XMLHTTP object.
The asynchronous communication layer offers the following features:

It enables the JavaScript code to perform asynchronous calls to the server.


It can invoke methods in Web services that are implemented as .asmx or .svc files. It
makes Web service interactions easier by generating JavaScript proxies for Web
services that can be accessed from the client script.
It can invoke ASP.NET static page methods like a Web service method.
It supports a variety of serialization formats such as JavaScript Object Notation
(JSON), string data, and XML data for passing data between the browser and the
server.
It provides extensibility for client executors that are used by the proxy objects.

Note
An executor is a component that functions as an interface between a client Web request and
the network or other media. You can write your own executor that plugs into the
asynchronous communication layer.

JSON Support in Consuming Web Services


To call a Web service by using JavaScript, a Web browser interacts with a Web server
through asynchronous communication layer. While communicating, the asynchronous
communication layer exchanges data between the Web browser and the Web server. This
data is exchanged in a format named as JSON.
JSON is a standard and default format used for serialization by the asynchronous
communication layer. It makes the interaction between the client and the server easy by
eliminating the need for the client script to construct request.
Data that is formatted in the JSON format is lightweight and easy to be parsed by
implementing JavaScript. JSON is the ideal format for data exchange for AJAX-enabled Web
applications. It can also be used to exchange or store structured information as text. A JSON
object provides two methods, JSON.parse and JSON.stringify. The JSON.parse method
is used to serialize objects and arrays into JSON text format and the
JSON.stringify method is used to convert JSON text format to in-memory objects.

Creating and Registering Client Scripts


An AJAX-enabled Web application calls a Web service by using client script. There might be
a possibility that the built-in client scripts in an AJAX-enabled Web application does not
provide the functionality that you want when calling a Web service. To implement such
functionality, you need to create a custom client scripts and integrate it with an AJAXenabled ASP.NET application. A custom client script can be created and integrated with an
AJAX-enabled ASP.NET application as:

Inline script
External java script file
Script embedded as a resource in an assembly

Inline Script
An inline script can be created as a script block in a Web page. A script block is defined in a
Web page as an HTML markup. The following code snippet shows how you can define a
script block in a Web page:
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>

CodeFile="Default.aspx.cs"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script type="text/javascript" language="JavaScript">

function HelloWorld()
{
alert(Hello World!);
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Hello"
onclick="HelloWorld()" />
</div>
</form>
</body>
</html>

In the preceding code snippet, a script block is defined that consists of a function,
HelloWorld. When a user clicks the Hello button on the Web page, the HelloWorld
function is called and an alert box showing the Hello World! Message is displayed.
An inline script is not registered in an AJAX-enabled ASP.NET application because the
script block is defined in a Web page only.
External Java Script File

You can also add a reference of an external java script file in an AJAX-enabled ASP.NET
application. To add the reference, you need to add the java script file in your Web
application. After adding the java script file, you need to set the src attribute of the script
element of the Web page to the name of the java script file.
The following code snippet is written in a java script file, JScript.js:
function HelloWorld()
{
alert(Hello World!);
}

In the preceding code snippet, a function HelloWorld is created and an alert message, Hello
World!, is defined.
The highlighted part of the following code snippet shows how you can set the src attribute of
the script element of the Web page to a java script file:
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>

CodeFile="Default.aspx.cs"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script type="text/javascript" src="JScript.js" >


</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Hello"
onclick="HelloWorld()" />
</div>

</form>
</body>
</html>

In the preceding markup, a java script file, JScript.js is specified in the src attribute of
the script element of the Web page. When a user clicks the Hello button, the function
HelloWorld defined in the java script file is called and an alert message box showing the
message, Hello World!, is displayed.
Script Embedded as a Resource in an Assembly
You can also add a custom client script in a web page by using the ScriptManager control.
Such a client script consists of a java script file that is embedded as resources in an assembly.
The java script that is embedded in an assembly acts as a Web resource. For example, you are
creating a custom control that consists of a java script file. This file can be embedded as a
Web resource in the assembly of the custom control.
To access such a java script file, an HTTPhandler WebResource.axd is used by the ASP.NET
application. This handler retrieves assembly resources and serves them to a Web browser. To
access the assembly resources using a ScriptManager control, you need to add the reference
of the assembly and the java script file as shown in the following markup:
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<scripts>
<asp:ScriptReference Assembly="ClassLibrary"
Name="ClassLibrary.JScript1.js" />
</scripts>
</asp:ScriptManager>

In the preceding markup, a ScriptManager control is defined. A reference of the assembly and
the java script file is added in the scripts tag of the ScriptManager control.
Most client-side code is added at design time. However, it can also be generated and added in
the Web page at run time by using the System.Web.UI.ClientScriptManager class.
Consider the following code snippet:
protected void Page_Load(object sender, EventArgs e)
{
string str="return confirm(Do you want to submit the
page?)";
ClientScript.RegisterOnSubmitStatement(this.GetType(),"ABC",

str);
}

To manage, register, and add a script to a Web page, you need an object of the
ClientScriptManager class. In the preceding code snippet, the ClientScript property of
the Page object has been used to obtain a ClientScriptManager object. The
RegisterOnSubmitStatement method registers an OnSubmit statement with the Page
object.
In RegisterOnSubmitStatement (Type type, String key, String script) method:

The type parameter defines the type of the control that is registering the OnSubmit
statement.
The key parameter defines a key that uniquely identifies the script statement.
The script parameter defines the script literal for the OnSubmit statement.

Note
A custom client script can also be used to add AJAX functionality into a server control. To
provide AJAX functionality in a server control, you need to embed the JavaScript file as a
resource in the assembly that is created when the server control is precompiled.

Summary
In this chapter, you learned that:

AJAX is a Web development technique that is used to create dynamically interactive


applications.

AJAX enables Web applications to retrieve data from the server, asynchronously in
the background, without interfering with the display and behavior of the existing
page.
AJAX includes the following terms:
o
o
o

The advantages offered by AJAX-enabled Web applications are:


o
o
o
o

ScriptManager control
ScriptManagerProxy control
UpdatePanel control
UpdateProgress control
Timer control

Client events are raised when a user interacts with an ASP.NET AJAX-enabled
application.
Client events are raised by the classes present in the Microsoft AJAX Library.
The two main Microsoft AJAX Library classes that raise events are:
o
o

Client-based Microsoft AJAX library


Server-based AJAX features for ASP.NET

Some of the AJAX server controls offered by ASP.NET are:


o
o
o
o
o

Browser Integration
Dependency on JavaScript

The ASP.NET AJAX architecture consists of the following components:


o
o

They provide quick response to a users request.


They allow users to interact with the rest of the Web page while the application is
processing the changed or updated parts of the Web page.
They provide auto-generated proxy classes that are used to call Web service
methods from client script such as JavaScript.
They provide support for the widely used Web browsers such as Microsoft Internet
Explorer, Mozilla Firefox, and Apple.

The limitations of AJAX-enabled Web applications are:


o
o

Asynchronous communication
JavaScript
XML

Application
PageRequestManager

The ASP.NET AJAX architecture provides an asynchronous communication layer


that enables a Web browser to call the Web service methods by using JavaScript.
JSON is a standard and default format used for serialization by the asynchronous
communication layer.
A custom client script can be created and integrated with an AJAX-enabled ASP.NET
application as:
o
o
o

Inline script
External java script file
Script embedded as a resource in an assembly

Reference Reading
Explaining the AJAX Frameworkn

Reference
Reading:
Books

Reference Reading: URLs

ASP.NET
AJAX
Programmer
s Reference:
With
ASP.NET 2.0
Or ASP.NET
3.5 by
Shahram
Khosravi

http://blogs.sun.com/enterprisetechtips/entry/building_an_ajax_enabled_we
b

Identifying the ASP.NET AJAX Server Controls


Reference
Reading:
Books

Reference Reading: URLs

Pro ASP. http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRendering


Net 3. 5
Overview.aspx
Server
Controls
and AJAX
Compone
nts by Rob
Cameron,
Dale
Michalk
Identifying the ASP.NET AJAX Client Life-Cycle Events
Reference
Reading:
Books

Reference Reading: URLs

Pro
ASP.NET
3.5 in C#
2008 by
Matthew
MacDona
ld

http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRenderingO
verview.aspx
http://www.dcs-media.com/desdev/dotNet/aspnet-ajax-client-life-cycleevents.aspx

Chapter 11

Implementing Internationalization and


Accessibility
An organization that does business in the global marketplace must design applications to
accommodate users from a wide variety of cultures. Users in different parts of the world use
different languages and different formatting standards for numbers, currency, and dates.
Therefore, you need to enable your Web applications to represent information in the users
native language and formats. This functionality can be provided by implementing
internationalization.
Web applications may also be accessed by users with disabilities. These users may not be
able to interact with the user interface properly because of their disabilities. A Web
application should be designed in such a way that it is easily accessible to such users. This
can be achieved by implementing accessibility features.
This chapter discusses how to implement internationalization and accessibility features in a
Web application to make the application accessible to everyone.

Objectives
In this chapter, you will learn to:
Implement internationalization
Implement accessibility

Implementing Internationalization
Web applications are accessed by people from different countries, cultures, and regions.
These people may want the information on the websites to be in their native language and
formats. This would make it easy for them to understand the content given on the site. To
enable the people from different countries, cultures, and regions to access your Web
application, you need to implement internationalization in the application. The process of
making an application ready for international users is called internationalization.
Consider the scenario of an organization that has a chain of hotels in various countries. The
organization is maintaining the information about the hotels through a website. This website
is accessed by people from various countries.
The website has a limitation. The information provided by the website is in English and the
currency is set to United States Dollar (USD). This poses problems for the non-English
speaking people because they are unable to understand the information given on the website.
As a result, people from the countries where the currency is other than USD have to calculate

the fares according to their currency. These problems are affecting the popularity of the
website.
To accommodate users from different countries and enable them to use the website
efficiently, the organization decides to implement internationalization in the application.
Implementing internationalization on the website would enable people from various countries
to have the information on the website in their native language and formats. This would help
users to easily understand the information given on the website.
To target the wide range of audience and to enable them to browse through your website,
your Web application must be designed to accommodate users from various countries and
cultures. This can be done by implementing internationalization in the application.
International applications should be customizable according to the preferences of users
belonging to different nations, cultures, or regions. User preferences refer to the language,
currency, and formats. To make an international application customizable, you need to
understand the following phases that are involved in developing an internationalized
application:

Globalization: Globalization is the process of designing and developing a Web


application in such a way that it is culture-neutral and language-neutral. In this phase,
the executable code is separated from the data specific to a locale.
Localizability: Localizability is an intermediate process that ensures that a globalized
Web application is ready for implementing localization. The purpose of this step is to
test whether the application's executable code is independent of the culture and
language-specific data. This means that the culture and language-specific details
should not be hard-coded into the application code.
Localization: Localization is the process of customizing the globalized Web
application to a specific locale and culture. In this phase, various resources, such as
images and text, for the designated locale are created. For example, to localize an
application for French users, all text messages should be translated to French.

Note
Locale is a combination of a language and a country. It includes information about the
formats used for representing time and date, symbols, and conventions used for representing
currency, and the character encoding scheme being used.

Factors Related to Creating International Applications


Application developers need to attend to locale considerations when they develop
international applications because negligence of these considerations can lead to issues. The
factors that need to be considered while designing an internationalized application are:

Language issues
Formatting issues

String-related issues
User-interface issues

Language Issues
Languages around the world differ in display, alphabets, grammar, and syntactical rules. For
example, some languages such as Arabic are written from right-to-left, whereas other
languages are written from left-to-right. Some languages include uppercase and lowercase
characters, whereas others do not even have the concept of uppercase and lowercase.
Languages differ in the number of characters, storage requirements, keyboard layouts, and
code representations. This diversity makes it difficult to share data between cultures. It is
even more difficult to create a multilingual user interface.
Formatting Issues
Formatting is the main source of differences in applications designed for multiple languages
or cultures. Formatting differences may arise in the addresses, currency, dates, numerals,
telephone numbers, time, and units of measure of various languages.
String-Related Issues
When developing international applications, programmers must consider issues related to
strings. When strings are translated from one language to another, the translated strings may
be longer than the original strings. In strings, the order of alphabets varies in different
languages. This causes major problems in sorting and comparison of strings. Issues also arise
when strings are concatenated because these strings may convey different meanings in
different languages.
User-Interface Issues
Various user interfaces are associated with the design of an international application. The size
of user interface elements should be larger than that required for accommodating English
strings. This is because strings in other languages are usually longer than strings in the
English language. When messages grow in size as a result of translation to another language,
they should be allowed to wrap to subsequent lines. You should also ensure that all the
access-key and shortcut-key combinations are available on international keyboards. This is
because every language has a different keyboard layout, and some characters do not exist on
all keyboards.

Creating International Applications


The structure of an application that is created with internationalization in mind is divided into
the following two blocks:

Data block: Contains user-interface resources, such as the text on Label controls that
are to be translated into various languages. This block is locale-specific, and each
locale will have one data block.
Code block: Contains the application code or the executable part of an application
that is applicable to all cultures/locales. This block will remain same for all locales.

The separation of culture/locale specific and culture/locale independent parts allows a user to
dynamically switch the user interface to a localized version.
The data block of a Web application consists of a set of resource files. Each application has a
default resource file that contains the resources in the default language/culture. For each
additional language/culture that your website needs to support, you need to create a separate
resource file, called a localized resource file.
Information is stored in resource files as a set of key/value pairs. For example, if you want to
display a welcome message on a Web page, you can create a key named WelcomeText. The
resource files for each language/culture can then specify a different value to the key
depending on the language/culture.
The .NET Framework represents different cultures across the world by using a culture code.
A culture code consists of two parts, a two-letter language code and an optional two-letter
country/region code.
The general format of the culture code is:
<Language code>-<Country/Region code>

The following table lists some culture codes and their descriptions.
Culture Code

Description

En

Specifies English language, no region

en-CA

Specifies English language, Canada

fr-FR

Specifies French language, France

De

Specifies German language, no region

Zh-CN

Specifies Chinese language, China region

de-DE

Specifies German language, Germany region

Culture code snippets that only specify a language are called neutral cultures, whereas culture
code snippets that specify a language as well as a region are called specific cultures.
To implement globalization in an application, you need to include the
System.Gloablization namespace in your application. The System.Gloablization
namespace provides classes that define culture-related information, such as the language,
country, calendars, and formats. Two important classes included in the
System.Gloablization namespace are:

CultureInfo
RegionInfo

The CultureInfo Class

The CultureInfo class provides information about a specific culture. The information
includes details such as the name of the culture, the formatting styles used, and the calendar
used.
The following table lists some of the commonly used properties of the CultureInfo class.
Property

Description

CurrentCulture

Returns an instance of the CultureInfo


class that represents the culture for the
current thread.

CurrentUICulture

Returns an instance of the CultureInfo


class that represents the current culture used
by the Resource Manager to look for culturespecific resources at run time.

Name

Returns the name of the culture in the


<Language code>-<Country/Region
code> format.

IsNeutralCulture

Returns a Boolean value indicating whether


the culture represented by the CultureInfo
object is a neutral culture.

NumberFormat

Gets or sets a NumberFormatInfo object that


defines the appropriate format of displaying
numbers, currency, and percentage.

Properties of the CultureInfo Class


The following table lists some of the commonly used methods of the CultureInfo class.
Method

Description

CreateSpecificCulture

Creates a CultureInfo object that


represents the specific culture that is
associated with the specified name.

GetCultureInfo

Returns a read-only instance of a culture.

GetCultures

Gets a list of supported cultures filtered by


the specified type.

GetFormat

Returns an object that represents the format


of a specified type. For example, this method
will return an object representing the format
of the date when the specified type is
date/time.

Methods of the CultureInfo Class

You can set two culture values for an ASP.NET application, the Culture and UICulture
properties. These values determine the types of resources loaded for an application and the
formatting options for various fields like currency, numbers, and dates. The resources loaded
are determined by the UICulture property and the formatting options are determined by the
Culture property.
You can set the Culture and UICulture properties for all pages on a website by using the
globalization section of the web.config file, as shown in the following example:
<globalization UICulture=fr culture=fr-FR>

You can set the Culture and UICulture properties for individual pages by using the @Page
directive of the page, as shown in the following example:
<%@ Page UICulture=fr Culture=fr-FR>

If you want to set the UICulture and Culture values to the first language specified in the
current browser settings, you need to set the UICulture and Culture values to auto.
However, you should not rely exclusively on the browser settings to determine the UI culture
for a page because users frequently use browsers that are not set to their preferences.
Therefore, you must provide users a method to explicitly select a language/culture for their
page.
You can set the UICulture and Culture values for a page programmatically by overriding
the InitializeCulture method and using any of the following methods in the overridden
method:

Set the UICulture and Culture properties of the page to the desired values.
Set the CurrentUICulture and CurrentCulture properties of the current thread to
the desired UI culture and culture, respectively.

Consider the following example that demonstrates how to use both the methods:
protected override void InitializeCulture()
{
if (Request.Form["ListBox1"] != null)
{
String language = Request.Form["ListBox1"];
UICulture = language;
Culture = language;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(language);

Thread.CurrentThread.CurrentUICulture = new
CultureInfo(language);
}
base.InitializeCulture();
}

The code given in the preceding example allows users to select their preferred language from
a drop-down list and sets the UICulture and Culture properties accordingly.
The RegionInfo Class
The RegionInfo class contains information about a country/region. The following table lists
some properties of the RegionInfo class.
Property

Description

CurrencySymbol

Gets the currency symbol for the


country/region.

CurrentRegion

Gets a RegionInfo object that represent the


county/region used by the current thread.

IsMetric

Gets a value that indicates whether the


country/region uses the metric system for
measurement.

The following table lists some methods of the RegionInfo class.


Method

Description

Equals

Determines whether the specified object is


the same instance as the current RegionInfo
object.

GetType

Gets the type of the current instance.

Implementing Culture-Specific Formatting

The resource files allow you to specify the text appearing on a website in different languages.
However, if you want to change the format of date, time, or currency values depending on the
current culture, you need to specifically write code for implementing the same.
Suppose you want to use different formats for displaying a date on a Label control, depending
upon the current culture. Dates can be displayed in various formats. Each format has a format
character associated with it.
The following table lists some date formats, and their corresponding format characters.

Date Formats
The preceding table specifies the pattern of date/time in the en-US culture. Other cultures
may have slightly different patterns for each date format.
The following code snippet demonstrates how to use a different format for displaying a date
depending on the current culture:
protected void Page_Load(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
CultureInfo USCulture = new CultureInfo("en-US");
CultureInfo FrenchCulture = new CultureInfo("fr-FR");
if (CultureInfo.CurrentCulture.Equals (FrenchCulture))
Label2.Text = dt.ToString("d", FrenchCulture);

else
Label2.Text = dt.ToString("d", USCulture);
}

In the preceding code snippet, the ToString() method of the DateTime object is used to
convert the date to the Short Date format, as specified by the first parameter of the
ToString() method. The second parameter specifies the culture to be used for the short date
format.
At run time, if the users browser settings specify French (France) as the preferred language,
the date will be displayed in the format, dd/MM/yyyy. However, if the preferred language is
set to any other value, the date will be displayed in the US format, MM/dd/yyyy.

Implementing Accessibility
When you develop a Web application, you want the application to be used by as many users
as possible. Your Web application may be used by users with some disabilities. These users
may not be able to interact with your Web application properly because of their disabilities.
As a Web developer, you need to take care of all such issues and design the Web application
in such a way that it can be accessed easily by most of the users. This can be done by
implementing accessibility.
Accessibility refers to the degree of ease with which an application can be used by a variety
of people. Implementing accessibility in a Web application helps people having disabilities as
well as enables other users to interact with the application more efficiently. ASP.NET
provides some guidelines that you should consider while designing your Web application to
achieve high accessibility.

Fundamentals of Designing an Accessible Application


Creating an application that complies with all accessibility guidelines is not feasible because
it requires a substantial amount of time and money. Therefore, you need to select the suitable
accessibility features that would be implemented in an application. The selection of features
should depend upon the profile of the users accessing the application. For example, if you are
creating an application for retired people, most of the users will be over 60 years of age.
These users may be suffering from old age ailments such as diminished vision. Therefore,
your application should have accessibility features such as appropriate font size and
background color to enable the users to easily interact with the application.
The features of a Web application that are used frequently should have a high degree of
accessibility. For example, on an online shopping site, shopping cart feature is a frequentlyused feature. Therefore, a developer should strictly follow the accessibility guidelines while
designing this feature. The principles that should be followed while implementing
accessibility support in an application are:

Flexible user interface: Flexibility of a user interface refers to its capability to


change its presentation to adapt to changing user preferences.

Flexible input and output features: Flexible input features refer to numerous ways
in which a user can interact with an application. All features should be accessible
through keyboard with the same degree of ease as while using mouse. Three-click rule
should always be followed, which states that all functionality should be accessible in a
maximum of three clicks. Flexible output features refer to the numerous ways in
which a user can retrieve information from an application. It is a good accessibility
practice to keep a wide range of output options such as text, images, sound, and
graphics.
Simple and Intuitive: The user interface should be simple and easy to understand,
regardless of a user's experience, knowledge, language skills, or current concentration
level. Any unnecessary complexity should be eliminated. Each object on the screen
should be assigned a unique and descriptive label to assist users who cannot see its
context on the screen.

The application should interact with other applications in a standard manner. For example,
the application should provide a standard mechanism for importing data from and exporting
data to other applications.

Accessibility Design Guidelines for the Web


Accessibility makes an application user friendly. There are instances when people are not
able to access information just because of bad accessibility design, such as small font size of
the text given in an application or improper navigational structure. Some guidelines for
implementing accessibility in an application are:

Standardize font styles: While deciding the font style, you should keep in mind that
users having diminished eyesight may also access your website. Therefore, you need
to select the font style and the color for the background and foreground such that the
text is easily readable. Some of the important guidelines for designing a website that
can be used by the users having diminished eyesight are:
o Font size should be greater than 12 points. However, the font size may differ
depending upon the font style.
o Text should not be italicized.
o Important points should be in bold.
o Decorative fonts should be avoided.
o Text color and background color should be selected in such a way that the text
can be easily read.
Support keyboard navigation: Keyboard navigation in an application can be
provided by using the TAB key. The TAB key navigation direction should be from
top to bottom and left to right. The navigation order while using the TAB key should
be correct. All navigation links should have tool tip that explains the use of the link.
All controls should be assigned keyboard shortcuts. ASP.NET provides the following
properties that are set for the controls used in a Web page so as to enable a user to
navigate properly by using the Tab key:
o TabIndex: You can specify the TabIndex property of a control to set tab
order for proper navigation.
o DefaultButton: You can specify default button for a form or a panel by
setting its DefaultButton property. The DefaultButton property specifies

that a user can cause a postback by pressing the ENTER button in an input
control in the form such as a text box.
o AccessKey: Keyboard shortcuts can be assigned to each control by using the
AccessKey property of the control.
o ToolTip: Tool tips can be displayed for each control by using the ToolTip
property of the control.
o AssociatedControlID: You can associate a Label control to another control
by setting the AssociatedControlID property of the Label control to the ID of
the relevant control. You can then use the properties of the Label control to set
some properties of the associated control. For example, you can use the Text
and AccessKey properties of the Label control to provide the caption and
short-cut key for the associated control.
Standardize the use of images: When you use images in the form of buttons, links,
or image maps in your application, you should provide a meaningful text for the
images to enable user to understand its functionality. ASP.NET allows you to do this
by setting the following properties of controls:
o AlternateText property: You can specify the AlternateText property of the
image to provide a meaningful text to the image.
o GenerateEmptyAlternateText: You can specify the
GenerateEmptyAlternateText property to true if the image does not provide
any functionality or does not convey information relevant to the context of the
Web page and is used for enhancing the UI of a Web page.
In addition, controls such a TreeView and Menu controls display images or links. For
example, the TreeView control displays images for the expand and the collapse button
for each node in the TreeView control. The TreeView control generates alternate text
for these images based on the text of the node. By default, the alternate text for the
image of the expand button that has the text as Start is rendered as Expand Start on a
Web page. You can also specify your own alternate text by setting the
ExpandImageToolTip and CollapseImageToolTip properties for the TreeView
control.

Standardize the use of tables on a Web page: You use tables in your Web
application to place each control in a well-organized and structured manner. While
creating a table, you should specify the caption to help assistive technologies such as
screen readers to identify the purpose of the table by setting its caption property.
Minimize the use of style sheets: The layout of a form should not be affected when it
is displayed in a browser that does not support style sheets. For this, you need to
provide an alternate page that does not make use of style sheets for every page that
uses a style sheet.
Use controls properly: While using controls at the time of designing an application,
you should consider the following points:
o Do not use ActiveX controls as some browsers may not support them. If you
are using an ActiveX control on a Web page, it should have an alternate page
that does not contain the ActiveX control.
o Use either LABEL or TITLE tags to specify the name of each control.

Note
An ActiveX control can be automatically downloaded and executed by a Web browser.
ActiveX is a set of rules for how applications should share information. Programmers can
develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and
Java.

Assistive Technologies Used for Accessibility of the Web


People with disabilities use various assistive technologies for accessing a Web application.
These assistive technologies are the products used by them to access a Web application in an
easy way. You should develop a Web application that should support these technologies so as
to enable the maximum number of users to access your Web application. Some assistive
technologies used by people with disabilities are:

Braille and Refreshable Braille: Braille is a system using six to eight raised dots in
various patterns to represent letters and numbers that can be read by the fingertips.
Braille system is used by blind people. Braille consists of an 8-dot version that has
been developed to allow all ASCII characters to be represented on a Web browser.
Refreshable Braille offers mechanical display where the dots are raised and lowered
dynamically that allows a Braille character to be displayed on a Web browser.
Refreshable Braille displays can be incorporated into portable Braille devices with the
capabilities of small computers, which can also be used as interfaces to devices, such
as information kiosks.
Scanning Software: Scanning software is adaptive software used by individuals with
some physical or cognitive disabilities that highlights or announces selection choices
such as menu items, links, or phrases one at a time. A user selects a desired item by
hitting a switch when the desired item is highlighted or announced.
Screen Magnifiers: Screen magnifier is software used primarily by individuals with
low vision that magnifies a portion of the screen that allows them to easily view a
Web application on a Web browser. Screen magnifiers make presentations larger, and
reduce the area of the document that can be viewed by removing surrounding context.
Some screen magnifiers offer two views of the screen, one magnified and one default
size for navigation.
Screen Readers: Screen reader is software that is used by individuals who are blind
or who have dyslexia. It interprets what is displayed on a screen and directs it either to
speech synthesis for audio output or to refreshable Braille for tactile output. Some
screen readers use the document tree such as the parsed document code as their input.
In addition, the screen readers use linearization process for interpreting the text in
each column of each row of a table on your Web page. It reads all the text in the first
cell of row one, the second cell, the third, and so on until it runs out of cells. It then
moves on to the second row.
Speech Recognition: Speech recognition is used by people with physical disabilities
or temporary injuries to hands and forearms. It is used by them as an input method in
a voice browser that allows voice-driven navigation. Applications that have full
keyboard support can be used with speech recognition.
Visual Notifier: Visual notifier is an alternative feature of some operating systems
that allows hearing impaired users to receive a visual alert of a warning or error
message that might otherwise be issued by sound.

Summary
In this chapter, you learned that:

The process of making an application ready for international users is called


internationalization.
The phases that are involved in developing an internationalized application are:
o Globalization
o Localizability
o Localization
The factors that need to be considered while designing an internationalized
application are:
o Language issues
o Formatting issues
o String-related issues
o User-interface issues
The two blocks that make a structure of an internationalized application are:
o Data block
o Code block
The System.Gloablization namespace provides classes that define culture-related
information, such as the language, country, calendars, and formats.
The two important classes included in the System.Gloablization namespace are:
o
o

CultureInfo
RegionInfo

The principles that should be followed while implementing accessibility support in an


application are:
o Flexible user interface
o Flexible input and output features
o Simple and Intuitive
The guidelines to implement accessibility in an application are:
o Standardize font styles
o Support keyboard navigation
o Standardize the use of images
o Standardize the use of tables
o Minimize the use of style sheets
o Use controls properly

Reference Reading
Implementing Internationalization
Reference Reading:
Books

Reference Reading: URLs

Ethical and Social Issues


in Professional Education

http://wiki.asp.net/page.aspx/55/internationalization/

by Celeste M. Brody,
James Wallace
Managing Across
Cultures by Susan C.
Schneider, Jean-Louis
Barsoux
Implementing Accessibility
Referen Reference Reading: URLs
ce
Reading
: Books
Pro
http://www.globalknowledge.com/training/course.asp?pageid=9&courseid=1134
ASP.NE 5&catid=184&country=United+States
T 3.5 in
C# 2008
by
Matthe
w
MacDo
nald,
Mario
Szpuszta

Chapter 12

Securing Web Applications


Organizations use Web applications to share and access important data. As the Internet is a
majorly-used medium for sharing and accessing data, this data needs to be secured from
unauthorized users. Therefore, security has become one of the major aspects in developing a
Web application. ASP.NET provides a security model that enables developers to address
security-related issues in Web applications.
This chapter discusses about identifying the ASP.NET security process. In addition, it
explains how to configure ASP.NET Web applications for security.

Objectives
In this chapter, you will learn to:
Identify the ASP.NET security process
Configure an ASP.NET Web application for security

Identifying the ASP.NET Security Process


Most of the websites restrict access to some of its content. This is necessary to provide
different levels of access to different types of users. For example, on an online shopping
website, the product catalog is accessible to all the users accessing the website. However,
certain portions of the website such as status of customer's order or customer's payment
details should only be accessible to users with certain credentials, such as employees.
Controlling access to the content in a Web application helps you protect your application
from various security threats, such as tampering with data files and stealing passwords. The
ASP.NET security model allows you to deal with these security threats to help secure your
Web applications.

Introducing the ASP.NET Security Model


The ASP.NET security model allows you to implement security in your Web applications. It
provides restricted levels of access to secure website information from unauthorized access. It
also helps in maintaining data integrity and confidentiality. The following figure displays the
architecture of the ASP.NET security model.

IIS and ASP.NET Interaction


The preceding figure indicates that ASP.NET security works in conjunction with Internet
Information Services (IIS) to implement security in a Web application. The following steps
describe the working of the ASP.NET security model:
1. IIS receives a request from a Web client.
2. It attempts to authenticate the user. If the user is authenticated, the request is checked.
If the request is for a non ASP.NET Web page, the request is directly passed to the
operating system. The operating system performs its own security checks to verify
that the authenticated user is allowed to access the specified file and directory.
However, if the request is for an ASP.NET Web page, it is passed to ASP.NET with
additional information about the authenticated user. ASP.NET uses its own security
services, depending on the settings in the web.config file and the page that was
requested.
3. If ASP.NET authenticates the user, it allows requests to the specified Web page. Your
code can perform additional security checks such as manually asking for another
password by using the .NET Framework.
4. When the ASP.NET code requests resources, the operating system performs its own
security checks to verify that the authenticated user is allowed access to the specified
file and directory.
5. If access is granted, the requested resource is returned through IIS.
All Web users communicate with ASP.NET applications through IIS. Therefore, to
implement security in your Web applications, you need to first configure IIS.

Configuring IIS for Implementing Security

Whenever a user requests for a Web application, the request is received by IIS. After
receiving the request, IIS tries to authenticate the user who has requested for the application
by using a specific type of authentication. The type of authentication depends on how the
security for Web applications is configured on IIS. Therefore, you first need to configure
security on IIS to authenticate users before they are permitted access to a Web application.
IIS provides the following different types of authentications to control access to your Web
application:

Anonymous: In anonymous authentication, IIS uses a default logon name and


password to request for resources from a Web application. Therefore, this type of
authentication mechanism does not require the user to provide a user ID or password
to browse through a Web application.
Basic: In basic authentication, users access resources only after specifying a valid
user ID and password. However, in this type, the users password is transmitted over
the Internet in the form of plain text. It makes the method vulnerable to a sniffing
attack. This method should be used in conjunction with Secure Socket
Layer/Transport Layer Security (SSL/TLS). If a website is configured to use
SSL/TLS and basic authentication, all data including username and password are
encrypted before they are transmitted.
Digest: In digest authentication, the user password is transmitted as a hash value
rather than as plain text. This authentication is similar to the basic authentication
mechanism, but it is more secure. The major drawback of this method is that it is
supported by very few browsers and Web servers. For example, digest authentication
is only supported by IIS 5.0 and later versions.
Integrated Windows: In this type, IIS does not prompt the user to pass credentials.
Instead, it extracts the user credentials from the operating system by retrieving the
account information used by the user to log on to the machine. The user is granted
access only if the current account under which the user has logged on is a valid
account on the server.

Note
A sniffing attack is a security threat in which an attacker gains access to the network
communication. The attacker can extract the message transmitted over a network. This
increases the risk of private information being misused.
You can configure the preceding authentication types in IIS for a Web application by using
the Internet Services Manager.

Configuring an ASP.NET Application for


Security

The initial check for user authentication is done by IIS. After the user is authenticated, IIS
sends the Web request to ASP.NET to perform a second level checking. ASP.NET uses its
own security mechanism to authenticate the user.
ASP.NET first authenticates the user by using the authentication settings defined in the
web.config file of the application. If the user is authenticated, it checks whether the user has
the right to access the requested resource of the Web application. All this requires you to
configure the security settings in the web.config file of the Web application. These security
settings include configuring authentication, authorization, and impersonation for accessing
resources in your application.

Configuring Authentication
Authentication is the process of validating the identity of a user before granting access to a
restricted resource. When ASP.NET receives a Web request from IIS, it tries to authenticate
the user. This authentication is based on the settings defined in the web.config file of the Web
application. These settings enable ASP.NET to determine which user is authenticated to
access the Web application.
Authentication in a Web application can be configured by using the <authentication>
element in the web.config file. The <authentication> element specifies the authentication
type that is used by an application to authenticate the user. The authentication type can be
specified by using the mode attribute of the <authentication> element. The mode attribute
can have the following values:

Windows: This mode specifies that the authentication is performed by IIS by using
Basic, Digest, or Integrated Windows authentication.
Forms: This mode specifies that the user will be authenticated by using form-based
authentication method. This method displays a logon form to verify the users
credentials.
Passport: This mode specifies that the user will be authenticated by using Microsoft
Passport authentication method. Passport authentication relies on cookie-based
authentication and single signing authentication service provided by Microsoft.
None: This mode specifies that no authentication mechanism is set and that any
anonymous user can access the Web application.

Implementing Windows Authentication


If you choose windows as the authentication mode for your Web application, IIS takes care of
the authentication process. In this mode, ASP.NET uses the user credentials authenticated by
IIS for security checks.
To configure an ASP.NET Web application for Windows authentication, you need to change
the mode attribute of the <authentication> element to Windows, as shown in the following
markup:
<authentication mode="Windows" />

This type of authentication is best suited to an intranet environment where a set of known
users are already logged on to a network. For example, if you are creating a Web application
that is to be used within an organization, you can use the Windows authentication mode to
authenticate the users. This is because the existing users already have their accounts in the
database of the Web server. A Web application that implements Windows authentication
rejects a users request that is not an authenticated user or has an invalid user name or
password.
Implementing Forms Authentication
When you implement Forms authentication to a Web page, you have to create an HTMLbased Web page for collecting users credentials and then authenticate the user. When a user
enters his or her credentials and gets authenticated to view a Web page, ASP.NET generates a
cookie that is served as an authentication token to the user. The browser uses this cookie for
the future requests made by the user, allowing the application to validate the requests. This
cookie can be encrypted by a private key located on the Web server to identify that the
request is sent by the same user.
To authenticate users by using Forms authentication, you need to create and store the user
credentials in a data source. You can create and manage users in ASP.NET by using the
membership management service. The membership management service is used to
authenticate the users who require access to Web pages. This service provides an API suite
and some server controls such as CreateUserWizard to manage users in an ASP.NET Web
application.
To configure an ASP.NET Web application for forms authentication, you first need to change
the mode attribute of the <authentication> element to Forms, as shown in the following
markup:
<authentication mode="Forms" />

If a user tries to access a restricted page without first logging on, the user should be redirected
to the logon page. You are required to specify the settings to redirect anonymous users to the
logon page. These settings are specified by using the <forms> element in the web.config file.
The <forms> element has the following four attributes:

name:

It specifies the HTTP cookie that will be used for authentication. .ASPXAUTH is
the default value of this attribute.
loginUrl: It specifies the URL to which the user requests are redirected for logon
when no valid authentication cookie is found. The default value is default.aspx.
protection: It specifies the type of protection that a Web application uses to protect
the HTTP cookie. The valid values of this attribute are All, None, Encryption, and
Validation. The default value of this attribute is All.
timeout: It specifies the life span of the cookie that is used for authentication. After
the time specified in the timeout attribute, the cookie expires. The value of the
timeout attribute is specified in minutes.
path: It specifies the path of the cookie.

Note
When a user visits your website without logging in or providing his/her credentials, the user
is called anonymous user.
The following markup shows a web.config file that is configured for forms authentication:
<configuration>
<system.web>
<authentication mode="Forms">
<forms
name=".AuthenticationCookie"
loginUrl="~/mylogin.aspx"
timeout="5"/>
</authentication>
</system.web>
</configuration>

In the preceding markup, the name of the HTTP cookie is AuthenticationCookie and URL
to which the user will be directed for logon is mylogin.aspx. The life span of the cookie is 5
minutes.
After configuring the Web application for forms authentication, you are required to add users
to the ASP.NET membership management service. You can add users by using the following
methods:

Using the <credentials> element in the web.config file


Using the Membership API

When you add users to the membership management service by using either of the preceding
methods, the user information is stored in the ASPNETDB.MDF file. The user information stored
in the ASPNETDB.MDF file is made available to the membership management service by the
membership provider.
The membership provider specifies the type of database that will be used to store the
membership information. The default provider uses a Microsoft SQL Server database,
ASPNETDB. You can also choose to use Active Directory or specify a custom provider to store
membership information.

Note
In addition to the preceding methods, Visual Studio provides the following methods to add
users to the ASP.NET membership management service:

Using the CreateUserWizard Server Control provided by ASP.NET


Using the ASP.NET Website Administration Tool (WAT)

Adding Users by Using the <credentials> Element

The <credentials> element is defined within the <forms> tag in the web.config file. It
contains the <user> tag to specify the user credentials, as shown in the following markup:
<configuration>
<system.web>
<authentication mode="Forms">
<forms
name=".AuthenticationCookie"
loginUrl="/login.aspx"
protection="All"
timeout="60"
path="/">
<credentials passwordFormat="Clear">
<user name="John" password="P@ssw0rd"/>
<user name="Tom" password="123_P@ss"/>
</credentials>
</forms>
</authentication>
</system.web>
</configuration>

In the preceding markup, two username/password pairs John/P@ssw0rd and Tom/123_P@ss


are stored in the web.config file. The passwordFormat attribute of the <credentials> tag is

used to specify the format in which the password is stored in the web.config file. The
passwordFormat attribute is set to Clear which means the password is stored as plain text.
Other options available with passwordFormat attribute are MD5 and SHA both of which are
encryption algorithms.
After specifying the user credentials, you are now required to create the login form. You can
create the login form either manually or by using the login controls provided by ASP.NET. If
you use login controls, you are not required to write any code to validate users, the users are
validated automatically by using the credentials stored in the membership management
service. However, if you create the login form manually, you are required to perform the
validation programmatically. ASP.NET provides you with the FormsAuthentication class
that helps you validate the users programmatically.
The FormsAuthentication class is defined in the System.Web.Security namespace and is
used to implement form authentication when the configuration file is used to store user
credentials. The following table lists some commonly used methods of the
FormsAuthentication class.
Method

Description

Authenticate

Validates the user credentials passed to it and


returns a boolean value indicating whether the
authentication process was successful or not.

RedirectFromLoginPage

Redirects an authenticated user back to the


specified URL.

SignOut

Removes the authentication cookies created on


the computer of an authenticated user.

Methods of the FormsAuthentication Class


Consider a scenario wherein you have created a login form manually. To validate the user
credentials, you need to write code as shown in the following example:
protected void Button1_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(UserName.Text, Password.Text))
{
Response.Write("Welcome " + UserName.Text);
}

else
{
Response.Write("Sorry! Login failed");
}
}

In the preceding example, the user name and the password are authenticated by using the
Authenticate function of the FormsAuthentication class. If the user is authenticated, the
message Welcome <username> is displayed on the Web form. However, if the user is not
authenticated, the message Sorry! Login failed is displayed on the Web form.

Adding Users by Using the Membership API

When adding users by using the <credentials> element in the web.config file, you need to
add all the users at design time. In addition, if you want to modify or delete a user, you need
to manually remove or modify the users in the web.config file. However, if you want to add,
modify, or delete users at run time, you need to use the Membership class. To implement the
Membership class, you need to use the System.Web.Security namespace. The Membership
class has various static methods that allow you to manage users at run time. The following
table lists some useful static methods.
Method

Description

CreateUser

Adds a new user to the database.

DeleteUser

Deletes an existing user from the database. To


delete a user, you need to specify the user name.

GetUser

Gets information from the data source for the


membership users associated with the unique

identifier .
GetAllUsers

Gets a collection that represents all the users in


the database.

UpdateUser

Updates information for a specific user.

ValidateUser

Validates the supplied user name and password.

Static Methods of the Membership Class


Consider the following example:
protected void AddUser_Click(object sender, EventArgs e)
{
MembershipCreateStatus result;
try
{
MembershipUser newUser =
Membership.CreateUser(UserName.Text,
Password.Text, Email.Text, passwordQuestion.Text,
passwordAnswer.Text, true, out result);
if (result==MembershipCreateStatus.Success)
{
Response.Write("User Successfully Created");
ShowAllUsers();
}
else
{
Response.Write("Sorry cannot create the user");
}
}

catch (Exception err)


{
Response.Write(err.Message);
}
}

public void ShowAllUsers()


{
GridView1.DataSource = Membership.GetAllUsers();
GridView1.DataBind();
}

In the preceding example, the code within the AddUser_Click event handler is written to
create a user. If the user gets created successfully, the method ShowAllUsers is invoked. This
method is used to retrieve all the users and display them in the GridView control. However, if
any exception is thrown by the code, the error message is displayed on the Web form.
Once created, you can change the user details by using the methods of the Membership class.
For example, you have created a user with the name user1. Now, you want to change the
password for the user. For this, you need to write the following code snippet:
MembershipUser currentUser = Membership.GetUser("user1");
if (currentUser.ChangePassword("OldPassword", "NewPassword"))
{
Label1.Text = "Your password is successfully changed";
}
else
{
Label1.Text = "Your password could not be changed";
}

Note
When you modify user details such as the e-mail address, you need to use the UpdateUser
method of the Membership class after modifying the details. The UpdateUser method takes
the MembershipUser class object as an argument.
You can customize the membership settings, if required, by configuring the membership
provider.
Configuring Membership Provider
You can configure the membership provider to customize the membership settings, such as
specify the database for storing the user credentials and change the default password policy.
To configure the membership provider, you need to add the <membership> element to the
web.config file. All the custom settings are defined inside the <membership> element as
shown in the following example:
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add
name="CustomMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlServer"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0"
passwordFormat="Hashed"/>
</providers>
</membership>

In the preceding example, the membership provider is configured. The <add> element in the
preceding example contains the following attributes:

Name:
type:

Specifies a name for the membership provider. It is mandatory.


Specifies the type of membership provider. It is mandatory.

connectionStringName:

Specifies the name of the connection string setting. The


name must correspond to the connection string defined in the <connectionStrings>
section. It is mandatory.
enablePasswordRetrieval: Determines whether a password can be retrieved in case
the user forgets it.
enablePasswordReset: Determines whether a password can be reset.
requiresQuestionAndAnswer: Determines whether the membership security answer
will be required when requesting or resetting the password. It is optional.
minRequiredPasswordLength: Specifies the minimum length of a password.
minRequiredNonalphanumericCharacters: Specifies minimum number of
nonalphanumeric characters that the password should contain. It is optional.
passwordFormat: Specifies the way passwords are stored in the database. The values
that this attribute can hold are Clear, Encypted, and Hashed.

Configuring Authorization
Authorization is the process of verifying whether an authenticated user has the privilege to
access a requested resource. After creating users that can access your Web application by
using the membership management service, you need to specify authorization rules for the
users.
You need to grant different permissions to different users to provide accessibility to the Web
pages on your website. For example, on an online shopping website, the users are able to
view the product catalog. They cannot make changes to the products being displayed on the
website. However, the administrator of the website can add or remove any product from the
website. This requires providing different levels of permission to different users of the
website.
Maintaining a different set of settings for each user is a complex task. Therefore, the users are
assembled into groups called roles and the permissions are defined on these roles. In
ASP.Net, you can provide authorization by using the role management service. The role
management service enables you to create roles, assign users to each role, and then restrict
user access based on these roles.
To use role-based authorization in your Web application, you need to enable it by using the
<roleManager> element in the web.config file, as shown in the following markup:
<configuration>
<system.web>
<roleManager enabled="true" />
...
</system.web>
...
</configuration>

In the preceding markup, setting the value of the enabled attribute to true will enable rolebased authorization for the Web application.
Creating and Assigning Roles
After you have enabled the role management service, you need to create roles, such as Users,
Administrator, and Guest. You can then assign users to one or more roles.
ASP.NET provides you with the Roles class to help you create roles. The Roles class
contains a number of methods that help you modify role information. The following table
lists the various methods of the Roles class and their description.
Methos

Description

CreateRole

Adds a new role to the data source.

DeleteCookie

Deletes the cookie where role names are cached.

DeleteRole

Removes a role from the data source.

FindUsersInRole

Gets a list of users in a specified role where the


user name contains the specified user name to
match.

GetRolesForUser

Gets a list of the roles that has been assigned to


a user.

Methods of the Role Class


You can create roles by using the CreateRole method as shown in the following code
snippet:
Roles.CreateRole(Admin);

In the preceding code snippet, the role Admin is created.


You can add a user to a role by using the AddUserToRole method as shown in the following
code snippet:
Roles.AddUserToRole(Peter, Admin);

In the preceding code snippet, the user Peter is added to the Admin role. You can get a list of
all the users in a particular role. For this you need to write the code as shown in the following
example:

protected void Button1_Click(object sender, EventArgs e)


{
MembershipUserCollection users = Membership.GetAllUsers();
foreach (MembershipUser MyUser in users)
{
if (Roles.IsUserInRole(MyUser.UserName, "Manager"))
{
Label1.Text += MyUser.UserName + "<br>";
}
}
}

In the preceding example, all the users are retrieved and the names of those users who have
assigned the Manager role are displayed on the label control.

Restricting User Access


Once you have created and assigned users to roles, you can restrict the access of users. You
can specify the list of users who are allowed to access a website in the <authorization>
element. The <authorization> element is specified in the web.config file. The
<authorization> element includes two child elements, <allow> and <deny>. You can
specify the list of users who are allowed to access the website in the <allow> element and the
list of users who should not be allowed to access the website in the <deny> element.
Some attributes of the <allow> and <deny> elements are:

users:

It enables you to assign a list of users to be granted or denied access. The


symbol ? is used to denote anonymous users and the symbol * is used to denote all
users.
roles: It enables you to assign a list of roles to be granted or denied access.

A Web application contains certain Web pages that can be accessed only by specific users.
For example, there are certain Web pages that should be accessed only by the administrator.
For restricting access to such Web pages, these Web pages need to be stored in a separate
subdirectory. After storing the Web pages in the subdirectory, you need to add a Web.config

file to that subdirectory. Then, you need to use the following markup in the web.config file to
restrict users having roles other than Admin to access the Web pages:
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>

The preceding markup specifies that the users who have been assigned to the Admin role are
allowed to access the Web pages stored in the subdirectory. All users having roles other than
the Admin role are denied access on these Web pages.

Configuring Impersonation
When a user requests an ASP.NET application, the request goes to IIS. IIS authenticates the
user and forwards the request to ASP.NET. If ASP.NET impersonation is disabled,
irrespective of the user who has logged on, the ASP.NET application will be executed by
using a fixed machine-specific account. In Windows XP, this account is automatically created
by ASP.NET and is named as ASPNET.
The ASPNET account has permissions such as code compilation and viewing information in
any database or files in your application that you would not want to grant to a user. For
example, if a user visits the current account page, you need to make sure that the user is able
to view the information only for his\her account. To allow users to access the ASP.NET
application according to the permissions granted to them, you need to use impersonation.
Impersonation is the process of executing code under the authenticated user identity and not
under the ASPNET account. When a user tries to access a Web application, the first step is to
check whether impersonation is enabled for the application.
Impersonation involves the following steps:
1. When a request from a remote client is received, IIS carries out authentication. If the
client is authenticated, it passes the request to the ASP.NET application.
2. The application impersonates the client and uses the authentication given by IIS to
access the restricted resources.
3. If authorized to access resources, the ASP.NET application returns the requested
resources to the client through IIS.
By default, impersonation is disabled in ASP.NET and unless overridden, all applications
inherit this setting. When impersonation is disabled, the account used for executing ASP.NET
resources is controlled by the <processModel> element in the machine.config file. However,
you can enable impersonation in an ASP.NET application by adding the following markup in
the <system.web> section of the web.config file:
<identity impersonate="true" />

In the preceding markup, impersonation is enabled for the Web application. Therefore, the
application uses the user credentials authenticated by IIS to provide access to the requested
resources.
You can also enable your Web application to run under a specific users identity. For this,
you need to specify the user credentials for that specific user in the web.config file, as shown
in the following markup:
<identity impersonate="true" userName="user1" password="Password" />

In the preceding markup, impersonation defines a single specific user account, user1.
Therefore, no matter which user accesses the application, all the Web requests will be granted
access according to the permissions of the user1 account.

Summary
In this chapter, you learned that:

The ASP.NET security model provides restricted levels of access to secure website
information from unauthorized access.
IIS provides the following different types of authentication to control access to your
Web application:
o
o
o
o

Anonymous
Basic
Digest
Integrated Windows

Authentication is the process of validating the identity of a user before granting access
to a restricted resource.
Authentication in a Web application can be configured by using the
<authentication> element in the web.config file.
Authorization is the process of verifying whether an authenticated user has the
privilege to access a requested resource.
Impersonation is the process of executing code under the authenticated user identity
and not under the ASPNET account.

Reference Reading
Identifying the ASP.NET Security Process

Reference Reading: Books

Reference Reading: URLs

Pro ASP.NET 3.5 in C#


2008 by Matthew
MacDonald, Mario
Szpuszta

http://msdn.microsoft.com/en-us/magazine/cc301387.aspx
http://www.springerlink.com/content/q6w220jt19065733/

Chapter 13

Deploying an ASP.NET Application


After creating a Web application, you need to make it available to the users to enable them to
access the application through the Internet. To make a Web application available to the users,
you need to deploy it on a Web server.
This chapter explains how to configure a Web server for deploying a Web application. In
addition, it discusses about how to deploy a Web application.

Objectives
In this chapter, you will learn to:
Configure a Web server for deployment
Deploy a Web application

Configuring a Web Server for Deployment


Web servers accept requests from Web browsers and respond accordingly. To enable a Web
server to respond to a browser, you need to configure it. The configuration of a Web server
involves performing the following tasks:
1. Creating a virtual directory
2. Defining Web application URLs
3. Registering ASP.NET file mappings

The Virtual Directory


During the development phase, a Web application is saved in a folder on the computer on
which it is developed. However, once the application is developed, it needs to be deployed on
a Web server. When you deploy the application on a Web server such as IIS, you need to
create a directory on the Web server that contains all the components such as the Web pages,

images, user controls, and data source files of your application. This directory is known as a
virtual directory.
A virtual directory is created so that the user does not get direct access to the Web application
folder residing on the host computer. This helps in maintaining the security of the Web
application and the host computer because a remote user or a client cannot manipulate any
data.
A virtual directory exposes the components of a Web application to the remote clients and
allows them to access your Web application through Web browsers. When a client requests a
Web page in a virtual directory, the Web server searches the page in the corresponding
physical directory that exists on the host computer. After locating the page, the server sends it
back to the client.
For example, your Web application exists in a directory named D:\MusicMania on the host
computer. To allow remote users to access the application through their browsers, you need
to deploy it on a Web server as a virtual directory. The virtual directory can either have the
same name as the name of the Web application or a different name. When the user requests a
page in a virtual directory, for example, http://172.23.3.203/MusicMania/AboutUs.aspx, the
Web server searches for the file in the corresponding physical directory, D:\MusicMania\
AboutUs.aspx and renders it to the user.

Configuring Application Pools


After creating the virtual directory, you can configure the application pool for your
application. An Application pool can contain one or more applications and allows you to
configure the level of isolation between different Web applications. For example, if you want
to isolate your Web applications running on the same computer, you need to create a separate
application pool for every Web application and place the applications in the corresponding
application pool. When the applications are placed in separate application pools, errors in one
application pool will not affect the applications running in other application pools.
You can configure application pools for your Web applications by using the IIS manager. For
this, you need to right-click the virtual directory that is created for the Web application and
select the Properties option. You can set the isolation for your application by selecting the
appropriate option from the Application Protection drop-down list, as shown in the following
figure.

The Virtual Directory Properties Dialog Box


The Properties dialog box provides the following application protection options:

Low (IIS Process): The applications that are configured to run under this application
protection run in Inetinfo.exe. The Inetinfo.exe hosts IIS core processes. Therefore, if
the application fails, it might stop the functioning of the Web server.
Medium (Pooled): The applications that are configured to run under this application
protection share an instance of dllhost.exe and do not run in Inetinfo.exe. If the
applications fail, the Web server does not get affected. However, other application
running under this application protection share may get affected. It is the default
option.
High (Isolated): The applications that are configured to run under this application
protection are isolated from both the Inetinfo.exe and dllhost.exe. Therefore, if the
application fails, it will not affect any other application or the Web server.

Web Application URLs


Users access a Web application by using an easy-to-remember address in the address bar of a
Web browser. This easy-to-remember address is known as the Uniform Resource Locator
(URL).

A URL is the location of a file on the Web. It is unique for every application. To access a
Web application, users type the URL for that application in the address bar of a Web browser.
The Web browser sends this request to the Web server. The Web server searches for the
application mapped to that URL and sends it back to the browser.
Consider a scenario where an airline company sells airline tickets through their Web
application. The passengers can book their tickets, check the booking status, and see the
flight schedules through the airline website. Users can access the website by using the
following URL:
http://172.23.3.203/MyWebApp/default.aspx
In the preceding URL, 172.23.3.203 is the IP address of the Web server and MyWebApp is
the virtual directory residing on the Web server. To access the Web application through its IP
address, users need to remember the IP address. However, it is difficult to remember IP
addresses. Therefore, instead of using an IP address, Web applications are accessed by using
a unique name known as the domain name. For example, the airlines Web application can be
accessed by using the domain name, as specified in the following URL:
http://www.MyFlight.com/MyWebApp/default.aspx
In the preceding statement, www.MyFlight.com is the domain name for the airline website.

Note
IP address is a unique 32-bit number and is typically written as four numbers in the range of
0 to 255 separated by periods (as in 172.23.3.203).

Note
A domain name is the address that is used by users to access a Web application. A domain
name is registered by companies so that it can be used by its users to access the companys
website.

Registering ASP.NET File Mappings


When multiple versions of .NET Framework are installed on the same computer, each
version installs an ASP.NET Internet Server Application Programming Interface (ISAPI)
extension version associated with it. This extension version determines which version of the
Common Language Runtime (CLR) will be used by a particular Web application.

A Web application can be configured to use any version of the .NET Framework that is
installed on the computer. To configure a Web application to use a particular version, you
need to register a script map in the Internet Information Services (IIS). A script map is a path
to the ASP.NET ISAPI version used by the application. It associates a file extension and
HTTP verb with the appropriate ISAPI for script handling.
When a user requests for a particular Web page, the script map for the application directs IIS
to forward the requested file to the ASP.NET ISAPI for processing. Therefore, when you
need to use a particular version of the .NET Framework, you need to update the script maps
so that they direct the request for a Web page to the appropriate version of the ASP.NET
ISAPI.
To update the script map, you need to use the ASP.NET registration tool called
aspnet_regiis.exe, as shown in the following figure.

Note
The aspnet_regiis command can be used with several options. You can check all the available
options by typing aspnet_regiis/? at the command prompt.

Deploying a Web Application


In todays scenario, the Internet is the best and the most used medium for getting information
on any topic. The information, available on the Internet, is contained in different Web
applications. To enable users to access the information contained in Web applications, these
applications need to be installed on a Web server. The process of installing a Web application
on a Web server is known as deployment.
The most basic technique for deployment is to copy the application components to the hard
drive of the Web server. In this technique, the various application components are deployed
to the Web server in their un-compiled form. This type of deployment has the following
issues:

The application is deployed even if it contains compilation errors.


The source code of the application is exposed.

The application loads slowly initially because it is compiled when it is accessed for
the first time.

These problems can be resolved by precompiling an application before deploying it to a Web


server.

Precompiling a Web Application


Precompiling a Web application involves compilation of the source code into DLL
assemblies before deployment. Precompiling a Web application provides the following
advantages:

It provides faster response time because the Web application does not need to be
compiled the first time it is accessed.
It helps in identifying the bugs that can occur when a Web page is requested. These
bugs are rectified at the time of compiling the Web application. Then, the compiled
and error-free Web application is deployed on to the server and is rendered to a user.
It hides and secures the source code of a Web application from the users accessing the
application.

You can precompile a Web application by using the aspnet_compiler.exe command-line tool.
This tool compiles source files such as Web pages, user controls, resources, and utility
classes into assemblies and creates output in the form of an executable version of the
application. The compiler removes all source and markup from the output. The output
consists of the compiled files of each of the .aspx file with the .compiled extension. These
compiled files contain pointers to the appropriate assembly for that page. Assemblies are the
.dll files that contain the compiled version of .aspx.cs file.

Note
All source code on an ASP.NET Web form is dynamically compiled into intermediate
language. When the intermediate language code is executed on a machine it gets compiled
just-in-time (JIT) into native machine code and then executes.
To compile a website, you need to execute the aspnet_complier command, as shown in the
following figure.

Using the aspnet_compiler Tool


In the preceding example, the path, E:\MyWebSite specifies the physical directory containing
the source code, and the path, E:\TargetSite specifies the location where the compiled project
needs to be saved.
The following table lists some options that can be used with aspnet_compiler.exe tool.
Option

Description

-v

Specifies the virtual path of the application to


be compiled. For example, if the application
is hosted in the virtual directory, MyWebApp,
the virtual path can be specified as
/MyWebApp. If the application to be
compiled is not stored in a virtual path, the -v
parameter can specify / as the virtual
directory.

-p

Specifies the physical path of the application


to be compiled.

-u

Specifies that aspnet_compiler.exe should


create a precompiled application that allows
subsequent updates of contents such as .aspx
pages.
If this option is omitted, the resulting
application contains only compiled files and
cannot be updated on the deployment server.
You can update the application only by
changing the source markup files and
recompiling.

-c

Specifies that the application to be compiled


should be fully rebuilt. Components that have
already been compiled are compiled again. If
this option is omitted, the tool builds only
those parts of the application that have been
modified since compilation was last

performed.
Options Used with aspnet_compiler.exe

Managing ASP.NET Precompiled Output for Deployment


The compilation tool of ASP.NET, aspnet_compiler.exe, compiles the source files and
creates separate assemblies for each source file. These assemblies are then combined and
managed by using the ASP.NET merge tool, aspnet_merge.exe. The ASP.NET merge tool
merges all the assemblies produced by the compilation tool to create a single assembly for the
entire application. The merged assembly helps in making the deployment process fairly
simple.
The ASP.NET merge tool can be used to combine:

All assemblies on a precompiled website into a single assembly.


All Web user interface content assemblies into a single assembly.
All Web user interface content assemblies into an assembly for each folder on the
website.

When you use the aspnet_merge tool, without any options, and only specify the target folder
name, as shown in the following figure, output assemblies are created for each Web user
interface content folder.

Using the aspnet_merge Tool Without Specifying any Option


To create a single assembly that combines all Web user interface content assemblies, you
need to use the -w switch with the aspnet_merge tool and specify a name for the merged
assembly, as shown in the following figure.

Using the aspnet_merge Tool with the -w Switch

To create a single assembly that combines all assemblies on a precompiled website, you need
to use the -o switch with the aspnet_merge tool and specify a name for the merged assembly,
as shown in the following figure.

Using the aspnet_merge Tool with the -o Switch

Summary
In this chapter, you learned that:

The configuration of a Web server involves performing the following tasks:


o Creating a virtual directory
o Defining Web application URLs
o Registering ASP.NET file mappings
A virtual directory is created so that the user does not get direct access to the Web
application folder residing on the host computer.

A virtual directory exposes the components of a Web application to the remote clients
and allows them to access your Web application through Web browsers.
An Application pool can contain one or more applications and allows you to
configure the level of isolation between different Web applications.
A URL is the location of a file on the Web. It is unique for every application.
Precompilation involves compilation of the source code of the Web application into
DLL assemblies before deployment. Precompiling a Web application provides the
following advantages:
o It provides faster response time because the Web application does not need to
be compiled the first time it is accessed.
o It helps in identifying the bugs that can occur when a Web page is requested.
These bugs are rectified at the time of compiling the Web application. Then,
the compiled and error-free Web application is deployed on to the server and
is rendered to a user.
o It hides and secures the source code of a Web application from the users
accessing the application.
The compilation tool of ASP.NET, aspnet_compiler.exe, compiles the source files and
creates separate assemblies for each source file.

Reference Reading
Configuring a Web Server for Deployment
Reference Reading:
Books

Reference Reading: URLs

Beginning ASP.NET 3.5:


In C# and VB by Imar
Spaanjaars

http://msdn.microsoft.com/en-us/library/aa244279(VS.60).aspx

Deploying a Web Application


Reference Reading:
Books

Reference Reading: URLs

ASP.NET 3.5 For


Dummies by Ken Cox

http://e-docs.bea.com/wls/docs81/webapp/deployment.html
http://www.beansoftware.com/ASP.NET-Tutorials/DeployASP.NET.aspx

Chapter 14

Tracing and Monitoring Web Applications


After you have deployed a Web application, you need to make sure that it is running
properly. The errors occurring while the application is running need to be diagnosed and
fixed. You also need to ensure that there are not any performance related issues with your
Web application.
ASP.NET provides you with the tracing and health monitoring features that can be used to
troubleshoot and diagnose problems with your Web application. By using these features, you
can constantly monitor the application while it is running for any issues that could affect its
performance.
This chapter discusses how to implement tracing in Web applications. In addition, it
discusses how to monitor the health and performance of Web applications.

Objectives
In this chapter, you will learn to:
Implement tracing in Web applications
Monitor Web applications

Implementing Tracing in Web Applications


As a developer, you are focused on creating a Web application that runs smoothly after its
deployment. Once an application is deployed, you need to ensure that the application is
working properly and is not giving unexpected results. For this, you need to keep track of the
execution of your Web application. This will enable you to track any errors or performancerelated issues in your application.
ASP.NET provides you with the tracing feature that enables you to track the program
execution, thereby ensuring that your Web application runs properly. You can use this feature
to view diagnostic information about a particular Web page. This information includes the
execution time of page methods, the time spent rendering page controls, and the contents of
various collections, such as the query string, HTTP header, and session state.
In addition to the standard diagnostic information, tracing can also be used to display custom
tracing information about the execution of an application. Tracing information can also be
written to an event log or a text file by using trace listeners.

Implementing Tracing

Tracing can be implemented at any of the following levels:

Page Level
Application Level

Page-Level Tracing
Page-level tracing is used to generate diagnostic information at the end of page rendering.
This diagnostic information includes all the information about the requests made to the page
and their responses. This information is used to diagnose problems on the page. For example,
suppose the processing of your Web page is taking too long. You can use the trace
information to check which of the Web page methods or events are taking too long to
execute. Once you are able to determine the reason for delayed processing of your Web page,
you can easily resolve the problem.
To enable page-level tracing, you need to perform the following steps:
1. Include the following directive at the top of the page:
2.

<%@ Page Trace="True" %>


Include the TraceMode attribute in

the @ Page directive to specify the sort order for


your trace messages. You can sort the trace messages either by time or category. For
example, you can sort the trace messages on the basis of category, as shown in the
following code snippet:
<%@ Page Language="C#" Trace="True" TraceMode="SortByCategory" %>

If you enable tracing on a Web page of your Web application, the tracing information is
displayed at the end of the Web page, as shown in the following figure.

The Tracing Information of a Web Page


The following information is displayed when page-level tracing is enabled:

Request Details: It displays some basic information, such as current session ID, the
time when the request for the Web page was made, the request and response
encodings, the request type, and the return status code.
Trace Information: It displays performance-related information about the Web page
life-cycle events. The events are displayed under the Message column. The Category
column displays the category of the message. The From First(s) column displays the
running time from the instant when the page request started. The From Last(s) column
shows the elapsed time since the previous event. You can use this information to
determine which of the Web page events are taking too long to execute.

Control Tree: It displays information about each control on the Web page, such as
the size of the rendered controls. You can use this information to be aware of the
number of bytes that each control on the Web page uses. This will help you keep a
check on the overall weight of the Web page.
Session State: It displays information about all the session variables, their types, and
values.
Application State: It displays information about all the application variables, their
types, and values.
Request Cookies Collection: It displays information about all the cookies that were
sent by the Web browser with the request for this Web page.
Response Cookies Collection: It displays information about all the cookies that were
returned by the Web server with the response.
Headers Collection: It displays information about all the headers that are sent to the
Web server as part of the request from the Web browser. It includes information about
the browser making the request, the types of content it supports, and the language it
uses.
Response Headers Collection: It displays information about all the headers that are
sent to the client as part of a response from the Web server. It includes details such as
the version of ASP.NET and the type of content being sent (text/html for Web pages).
Form Collection: It displays the list of values that are posted back to the Web server.
It includes all the values that are submitted by Web controls, such as hidden field
values, the text in a textbox, and the current selection in a list box.
Querystring Collection: It displays the list of values included in the query string.
You can also view this information in the Web page URL. However, if the query
string contains a lot of information, it is easier to review the individual items in the
trace display.
Server Variables: It displays all the server variables and their values at the time of
Web page request.

Application-Level Tracing
When you enable tracing at the page-level, the tracing information is displayed at the end of
the Web page. As a result, every visitor to the website will see the tracing output at the
bottom of the Web page. This is not a good approach to display Web pages on a website. To
view the tracing output for all the Web pages on the website, you need to enable tracing for
every Web page if you are using page-level tracing. These limitations can be overcome by
enabling tracing for the entire Web application.
Application-level tracing is used to trace information for every Web page in a Web
application. A special page named trace.axd is used to view this trace information. This page
should ideally be accessible to the website administrator only. To use the trace.axd page, you
have to first enable application-level tracing within the Web.config file for your application.
You can use the following attributes of the <trace> element to change the tracing settings of
your website:

enabled: Indicates whether tracing is enabled for the application. The default value is
false.
requestLimit: Stores tracing information for a maximum number of HTTP requests.

The default value is 10.

pageOutput:

Indicates whether trace information is displayed at the bottom of every


page in the application. The default value is false.
traceMode: Indicates the order in which trace messages are displayed. The possible
values are SortByTime and SortByCategory. The default value is SortByTime.
localOnly: Indicates whether the tracing information should be displayed only on the
local computer (computer on which the Web application is hosted) and not on remote
computers. The default value is true, which means that remote clients cannot see the
tracing information.
mostRecent: Stores only the most recent trace messages if set to true. When the
maximum limit specified by the requestLimit attribute is reached, the information
for the oldest request is discarded every time a new request is received. If the
mostRecent attribute is set to false, which is the default value, ASP.NET stops
collecting new trace messages when the maximum number of requests has been
received.

For example, you can make the necessary settings to enable application-level tracing in the
web.config file, as shown in the following code snippet:
<configuration>
<system.web>
<trace
enabled="true"
requestLimit="100"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
mostRecent="false" />
</system.web>
</configuration>

In the preceding code snippet, the trace information will be displayed for the first 100 Web
requests as specified by the requestLimit and mostRecent attributes. The trace information
will be sorted by time as specified by the traceMode attribute. It is only available to the local
clients as specified by the localOnly attribute.
You can open the trace.axd page in the Web browser just by replacing the page name in the
URL with trace.axd, as shown in the following figure.

The Trace.axd Page


The preceding figure shows that three requests have been made to this application and the
right side of the header indicates "Remaining: 97". The page displays tracing information for
only three requests. Therefore, there are 97 more requests remaining before tracing stops for
this application. After all the 100 requests have been made to the application, tracing data is
not displayed for further requests. You need to click the "clear current trace" hyperlink on the
trace.axd page to start displaying tracing data for further requests. You can click the View
Details link to see the detailed information for any request. This detailed information is
similar to the information that you see for a Web page when you implement page-level
tracing.
Application-level tracing gathers and processes the trace information for each page in the
application. If you need to disable tracing for a particular page, you have to set the Trace
attribute of the @Page directive to false. The trace settings made at the application-level are
overridden by the page-level settings.

Writing Trace Information

When a Web application is in the development stage, you often use several Response.Write
statements in the program code to display debugging information. This information is used to
troubleshoot the application. However, these statements need to be removed once your
application is ready for deployment because the messages displayed using Response.Write
statements are required for debugging and should not be displayed to an end user.
Tracing resolves this problem by allowing you to insert debugging code within an application
such that the debugging code does not need to be removed at the time of deployment. This is
because you can disable tracing to prevent the debug information from being displayed as
trace information.
The Trace property of the Page class returns a Trace object, which can be used to write
custom trace statements. The Trace object is an instance of the TraceContext class. The
Trace object provides a set of methods and properties that help you trace the execution of
your application.
The properties of the Trace object are:

IsEnabled:
TraceMode:

Denotes whether tracing is enabled for the current request


Sets the trace modes such as sortByCategory or sortByTime

Some of the methods of the Trace object are:

Warn: Displays the trace information in red color


Write: Displays the trace information in black color

You can use the Trace object to write custom trace statements when tracing is enabled for a
page or an application. You can use the Write and Warn methods of the TraceContext class
to write trace statements to the trace log. The only difference between these two methods is
that the Warn method displays the statements in red while the Write method displays the
statements in black color. The Write and Warn methods are overloaded methods and have
three versions. These three versions differ in the number of arguments passed to them. The
syntax of the overloaded methods of the Write and Warn methods are:
public void [Warn | Write](String message)
public void [Warn | Write](String category, String message)
public void [Warn | Write](String category, String message, Exception
errorInfo)

The arguments used in the preceding versions of the Write and Warn methods are:

message:

This argument refers to the message displayed in the Trace Information

section.

category:

This argument refers to an arbitrary string that is basically used to group


similar kinds of messages. It helps sort and display the messages category-wise in the
Trace Information section.
errorInfo: This argument refers to an object of the Exception class that contains the
exception details associated with the request.

For example, you can write the following code in the Page_Load event of your Web page:
int i = 30;
int j = 0;
try
{
int z = i / j;
Response.Write(z);
}
catch(DivideByZeroException exp)
{
Trace.Write("Errors","Testing the limits of infinity?",exp);
Response.Write("A numeric value divided by zero gives result as
infinity.");
}

In the preceding code snippet, an exception is raised in the try block. This exception is caught
in the catch block. Then, a message, A numeric value divided by zero gives result as infinity,
is displayed to a user. The information of the execption caught in the catch block is displayed
in the Trace.axd file in the browser, as shown in the following figure.

Displaying Custom Trace Information


In the preceding figure, the trace messages are sorted and displayed as per the execution time.
Therefore, the trace messages are being displayed between the Begin Load and End Load
events. However, if you sort the trace messages as per the category, the tracing information is
displayed in the browser, as shown in the following figure.

Sorting of Trace Information Category-Wise

Using Trace Listeners


Trace listeners are used to collect, store, and route tracing messages. You can also use trace
listeners to redirect the tracing information to logs, windows, or text files.
ASP.NET provides the following three types of predefined trace listeners:

TextWriterTraceListener: Used to redirect the trace output to a file or console.


EventLogTraceListener: Used to redirect the trace output to an event log.
DefaultTraceListener: Used to redirect the trace output to OutputDebugString API
function and the Debugger.Log method.

To enable a trace listener, you need to add it to the Listeners collection. All the three types
of trace listeners receive the same trace output when included in the Listeners collection but
each of them then redirects this output to a different target.
Adding a Trace Listener
A trace listener is added in the web.config file within the <listeners> tag of the trace
element. The <listeners> tag is a collection of all the trace listeners. To add a trace listener
in the web.config file, you need to include the following code snippet in the web.config file:
<configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="MyListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="D:\myListener.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>

In the preceding code snippet, a listener, MyListener is added to the <listeners> tag. The
MyListener listener writes the trace information to a file, myListener.txt. The
autoflush attribute of trace element specifies whether the trace listener automatically
flushes the output buffer each time it writes to a text file.
To enable ASP.NET to route tracing information to a System.Diagnostics listener, you
need to include the following entry in the web.config file:
<system.web>
<trace writeToDiagnosticsTrace = "true" />
<customErrors mode="off" />
</system.web>

Removing a Trace Listener


To remove a trace listener from the Listeners collection, you need to include the following
code snippet in the web.config file:

<configuration>
<system.diagnostics>
<trace>
<listeners>
<remove name="MyListener"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>

In the preceding code snippet, the trace listener, MyListener is removed by using the
<remove> element within the <listeners> element.

Trace Switches
Trace switches allow you to enable, disable, and filter tracing output even after the
application has been deployed on the server. This can be done by configuring the trace
switches through the web.config file. The .NET Framework provides the following types of
switches:

BooleanSwitch:

It is a toggle switch that allows you to enable and disable trace


statements. It is useful when you want to receive only a specific set of trace
statements. It offers two levels of configuration, On and Off.
TraceSwitch: It allows you to set the level from which you want to receive trace
statements. By configuring TraceSwitch to the appropriate level, you can control the
type of tracing output you want to receive. To use trace switches to filter the tracing
output, you need to initialize and configure the trace switches.
SourceSwitch: It provides multilevel switch to control tracing and debug output
without recompiling the code. It provides a Level property to test the event level of
the switch. The Level property gets or sets the switch's TraceLevel value.

Initializing Trace Switches


To initialize a TraceSwitch, you need to first create its object. The following code snippet
shows how you can create and initialize a TraceSwitch object:
System.Diagnostics.TraceSwitch MyTraceSwitch =
new System.Diagnostics.TraceSwitch("MySwitch", "Entire application");

In the preceding code snippet, an object of TraceSwitch class is created and initialized. The
System.Diagnostics.TraceSwitch class takes two parameters, name and description of
trace switch.

Configuring Trace Switches


You can configure a trace switch to trace a Web application at different levels. These levels
enable you to trace various types of messages such as error messages, warning messages,
informational messages, and detailed messages.
The following table lists the levels of the TraceLevel enumeration and their integer values.

The Levels of the TraceLevel Enumeration and Their Integer Values


You can configure a trace switch by setting it to any of the values in the TraceLevel
enumeration. The following code snippet shows how you can configure a trace switch:
<system.diagnostics>
<switches>
<add name="MySwitch" value="2" />
</switches>
</system.diagnostics>

In the preceding code snippet, the value attribute of the switch MySwitch is set to 2 to
display the warning and error messages.

Monitoring Web Applications


After deploying a Web application, you, as a system administrator, need to constantly
monitor it for its proper functioning. Many unexpected problems, such as website
experiencing heavy load, may occur while the application is running in the real-world
environment. By monitoring a Web application, you can detect the problems occurring in the
application and troubleshoot them.
Monitoring and troubleshooting is required to improve the performance of a Web application.
To help you track and monitor a Web application, ASP.NET provides you with the following
two features:

Health Monitoring
Performance Monitoring

Health Monitoring
ASP.NET health monitoring system enables you to monitor the status of the deployed Web
applications. It is used to track system events and errors, which can hamper the performance
of a Web application.
Health monitoring system enables you to get the detailed run-time information about
ASP.NET resources used by a Web application. It is useful in scenarios where you want to
monitor an application and be notified when a critical error occurs. For example, you can use
health monitoring system to monitor events such as start and end of an application, successful
and failed logons, and unhandled exceptions. If you detect any unhandled exception in your
Web application, you can make appropriate changes so that it does not occur again.
The ASP.NET health monitoring system is implemented by using the
System.Web.Management namespace. This namespace contains classes and interfaces for
managing and monitoring the health of Web applications. This namespace includes Web
events responsible for packaging health-status data of the Web application. You can capture
Web events by using built-in event providers. For example, there is a provider to capture
events and send e-mail notifications, a provider to log events to SQL Server, and a provider
to drop events into an event log.
Configuring Health Monitoring
You can configure applications to use built-in or customized monitoring providers. These
providers process the health-monitoring information and report on the health status and the
performance characteristics of a Web application. To use the health monitoring system, you
need to perform the following configuration jobs:

Configure and enable Web events to be monitored.


Configure and enable event providers that listen for and process various Web events.

The following code snippet shows how you can configure health monitoring by using the
<healthMonitoring> element in the web.config file:

<healthMonitoring
enabled="true|false"
heartbeatInterval="time interval">
<bufferModes>...</bufferModes>
<providers>...</providers>
<eventMappings>...</eventMappings>
<profiles>...</profiles>
<rules>...</rules>
</healthMonitoring>

The following table lists the attributes of the <healthMonitoring> element.


Attribute

Description

enabled

Specifies whether health monitoring is enabled.

heartbeatInterval

Specifies the interval, in seconds, that indicates


how often the WebHeartbeatEvent event is
raised.

The Attributes of the <healthMonitoring> Element


The following table lists the child elements of the <healthMonitoring> element.
Element

Description

bufferModes

Specifies the buffering capabilities for a provider.

eventMappings

Maps friendly event names to the related event


types.

profiles

Defines a collection of parameter sets to use


when configuring events.

providers

Defines the health monitoring providers that


process events.

rules

Maps events to providers.

The Child Elements of the <healthMonitoring> Element


Web Events
Web events contain information about the health of a Web application. These events need to
be trapped to report the status of the applications health. Each Web event is defined by a
class. When a Web event is raised, an instance of the associated event class is created. This
instance stores the event data, which is processed by the event providers.
There are several events that you can trap to monitor the health of a Web application. Some
of the important events are:

WebBaseEvent: It acts as a base class for all the other Web events.
WebBaseErrorEvent: It acts as a base class for all Web events related

to errors in the

system.

WebHeartbeatEvent: It records Web events after a predefined interval of time.


WebRequestEvent: It occurs when a user sends a request to a Web server.
WebErrorEvent: It represents the errors that occurred at the configuration or

compilation time.

WebApplicationLifetimeEvent: It is raised when an application starts or stops.


WebRequestErrorEvent: It is raised when any unhandled exception occurs or an

error related to a users request is generated.


WebAuditEvent: It represents a base class for Web events that are raised when a user
attempts to log on.
WebSuccessAuditEvent: It is raised when a logon attempt by a user is successful.
WebFailureAuditEvent: It is raised when a logon attempt by a user fails.

You need to enable the Web events by connecting them to the event providers.
Event Providers
The event providers are used to listen for Web events that are raised by a Web application.
These providers process the event information either by logging the information or by
notifying the system administrator. ASP.NET provides you with several built-in event
providers that you can use to capture Web events raised by the Web application. Some of the
built-in providers are:

EventLogWebEventProvider: It logs Web events in the Windows event log.


SqlWebEventProvider: It is a Web event provider for SQL Server databases. It logs
Web events in the SQL Server and the SQL Server Express databases.
SimpleMailWebEventProvider and TemplatedMailWebEventProvider: These
providers respond to Web events by sending an e-mail message.
TraceWebEventProvider: It sends Web events to the diagnostics trace.
WmiWebEventProvider: It sends Web events to the Microsoft Windows
Management Instrumentation (WMI) subsystem.

The following example shows how to use the EventLogWebEventProvider in the web.config
file to log Web events in the Windows event log:
<healthMonitoring enabled="true" heartbeatInterval="0">
<rules>
<add name="Default Success Audits" eventName="Success Audits"
provider="EventLogProvider" profile="Default"
minInterval="00:02:00"/>
</rules>
</healthMonitoring>

In the preceding example, a <rule> child element is created under the <healthmonitoring>
element of the web.config file. Then, a rule, Default Success Audits, is created to handle
success audit events.

Performance Monitoring
Performance is an important factor in making a Web application or project successful. You
need to monitor a Web application to troubleshoot any performance-related issues. For
example, a user request may not be processed because of insufficient server resources. You
need to keep track of such errors to improve the performance of your Web application.
ASP.NET provides you with several performance counters, such as Application Restarts,
Requests Queued, and Errors Total to help you keep track of the execution of your Web
application. These performance counters are valuable in determining the performance-related
problems in Web applications.
For example, you can determine the number of requests that are in queue for your Web
application. A large number of Web requests in the queue may indicate that the application is
not efficient enough and needs to be tuned. By monitoring the Requests Queued performance
counter, you can track the number of requests waiting for service in the queue. If it is
affecting the performance of the application, you can make the necessary changes in the
configuration file of the application to improve its performance. You can use the System
Monitor (PerfMon) with ASP.NET applications to track the performance counters affecting
the performance of applications.
Performance Counters for ASP.NET
ASP.NET supports the following groups of performance counters:

System performance counters


Application performance counters

System Performance Counters

System performance counters are displayed in the Windows Performance monitor in the form
of the ASP.NET performance counter object.
The following table lists some of the system performance counters.
System Performance Counter

Description

Application Running

Represents the number of applications running


simultaneously on a Web server.

Requests Disconnected

Represents the number of requests that have


been disconnected due to communication failure.

Request Wait Time

Represents the number of milliseconds that the


most recent request waited in the queue for
being processed by the server.

State Server Sessions Active

Represents the number of user sessions that have


become inactive because of some user action.
This counter is available only on the computer
where the state server service, aspnet_state is
running.

Worker Process Running

Represents the number of worker processes


running on a Web server.

The System Performance Counters


Application Performance Counters

Application performance counters are displayed as the ASP.NET application performance


object. These counters enable you to monitor the performance of a single instance of an
ASP.NET Web application.
A unique instance of each ASP.NET application collects all the counters of each application.
These counters will display a value of zero when no application is running on a Web server.
The following table lists some of the application performance counters.
Application Performance Counter

Description

Anonymous Requests

Represents the number of requests that are using


anonymous authentication.

Anonymous Requests/Sec

Represents the number of requests per second


that are using anonymous authentication.

Cache Total Entries

Represents the total number of entries in the


cache.

Cache Total Hits

Represents the total number of hits from the


cache.

Debugging Requests

Represents the number of requests that occur


while debugging is enabled.

The Application Performance Counters

Summary
In this chapter, you learned that:

Tracing can be implemented at any of the following levels:


o
o

The properties of the Trace object are:


o
o

TextWriterTraceListener
EventLogTraceListener
DefaultTraceListener

ASP.NET provides you with the following features for monitoring a Web application:
o
o

Warn
Write

ASP.NET provides three types of predefined trace listeners:


o
o
o

IsEnabled
TraceMode

Some of the methods of the Trace object are:


o
o

Page Level
Application Level

Health Monitoring
Performance Monitoring

ASP.NET supports the following groups of performance counters:

o
o

System performance counters


Application performance counters

Reference Reading
Monitoring Web Applications
Reference Reading: Books

Reference Reading: URLs

Pro ASP.NET 3.5 in C#


2008 by Matthew
MacDonald, Mario
Szpuszta

http://www.mailarchive.com/mumbaiusergroup@groups.msn.com/msg15921.html
http://www.ajaxline.com/health-monitoring-in-asp-net-3-5

Chapter 15

Creating Web Applications for Mobile


Devices
Web applications enable users to access information on a 24x7 basis. Users may need to
access Web applications even while they are on the move. This is possible by using mobile
devices such as PDAs and cellular phones. However, accessing information by using such
devices requires you to make the Web pages available in a format that can be viewed on
mobile devices. ASP.NET allows you to create Web applications having Web pages that can
run on a variety of mobile devices.
This chapter discusses about how to create mobile Web pages. In addition, it discusses about
rendering content on mobile Web pages.

Objectives
In this chapter, you will learn to:
Create mobile Web pages
Render content on mobile Web pages

Creating Mobile Web Pages


Mobile devices have many limitations such as small display area and low bandwidth. Due to
these limitations, a Web page created for desktop browsers cannot be properly displayed on
mobile devices. For example, you can create a Web page that contains a header, a navigation
bar at the left side of the page, and content in the rest of the page. This Web page can be
rendered on desktop browsers. However, this layout of the Web page may not be suitable for
mobile device browsers because mobile devices have a smaller display area than desktop
monitors. Therefore, you need to create specifically designed Web pages for mobile devices.
ASP.NET provides you with the System.Web.Mobile namespace that is used specifically for
mobile Web development. The System.Web.Mobile namespace contains the core capabilities
such as authentication and error handling, required for building ASP.NET mobile Web
applications.

Working with Mobile Web Controls


ASP.NET provides you with mobile Web controls that can be used to create a mobile Web
page. Some of these controls are similar to the controls used for creating Web pages for
desktop browsers. The ASP.NET mobile Web controls are contained in the
System.Web.UI.MobileControls namespace that provides the user interface elements for
rendering mobile Web applications. Most of the mobile Web controls are similar to the
normal Web server controls. However, there are some specific controls that are specific to the
mobile Web pages. These controls are:

Form
Command
PhoneCall
List and ObjectList
DeviceSpecific
SelectionList
StyleSheet
TextView

Form Control
Mobile devices have small display areas. Therefore, it is difficult to display complex Web
pages, containing multiple controls, on a mobile device. To display such complex Web pages
on a mobile device, you can break these pages into a collection of forms by using the Form
control. A Form control is a container control that provides the capability to group controls
together. Each Form control can hold a group of logically related controls. These Form
controls can be displayed by setting the ActiveForm property of the Web page, as shown in
the following example:
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<mobile:Form id="Form1" runat="server">

<mobile:Label text="Welcome the

mobile application" ID="Label1"

runat="server" />
<mobile:Command ID="Button1" text="Click Me" runat="server"
OnClick="Button1_Click" />
</mobile:Form>

<mobile:Form id="Form2" runat="server">


<mobile:Label text="Welcome the second page" ID="Label2"
runat="server" />
</mobile:Form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
this.ActiveForm=Form2; //Form2 is the name of the Form control
}

In the preceding example, when the application starts, the default form control Form1 is
displayed. When the user clicks the Button1 button control in the Form1 control, the Form2
Form control is displayed.
ASP.NET Web pages can contain more than one Form controls. However, a mobile Web
application can display only one Form control at a time. When a user browses a mobile Web
page, by default, the first form appears on the page.

Note
A mobile Web page must contain at least one Form control. Form controls cannot be nested.
Command Control
The Command control is similar to the Button Web server control. It combines the
functionality of the normal Button, ImageButton, and LinkButton controls. The Command

control can be added to a mobile page by using the <Command> element, as shown in the
following example:
<mobile:Command ID="Button1" text="Click Me" runat="server"
OnClick="Button1_Click" />

In the preceding example, a Command control, Button1, is added to a Form control. The
Text property of the Command control is set to Click Me and the event handler
Button1_Click is attached with the Click event of the Command button.
PhoneCall Control
A PhoneCall control is used to enable applications to initiate telephone calls if the user's
mobile device supports that capability. If the mobile supports the capability, the phone
number specified by using PhoneNumber property of the PhoneCall Control is displayed as
hyperlink, selecting which a user can initiate a telephone call.
However, if the mobile device does not support the capability of placing phone calls, the
PhoneCall control displays the phone number as text. The PhoneCall control can be added to
a mobile page by using the <PhoneCall> element, as shown in the following example:
<mobile:PhoneCall ID="Phone1" PhoneNumber="9999037202" runat="server"/>

In the preceding example, a PhoneCall control with the PhoneNumber property set to
9999037202 is added to a Form control.
To use a PhoneCall control, you need to add the control onto a Form or Panel control or
inside a control's template on an ASP.NET mobile Web page. After adding the control, you
need to specify the Text and the PhoneNumber properties. You can optionally use the
AlternateUrl property, which is set to the URL of the page that the application will
navigate to when running on devices that cannot initiate phone calls.

Note
The PhoneNumber property must be set, to use the PhoneCall control. If the PhoneNumber
property is not set, the application will throw an error.
List and ObjectList Controls
Mobile Web controls do not include the DataList and Repeater controls. Instead of these
controls, the mobile Web controls include the List control. The List control includes the
functionality that is provided by the DataList and Repeater controls. The List control can be
added to a mobile page by using the <List>> element, as shown in the following example:
<mobile:List ID="List1" Runat="server">
<Item Text="Sam" />

<Item Text="Peter" />


<Item Text="Jack" />
</mobile:List>

In the preceding example, a List control, List1, is added to a form control. The list control
has three items.
Similarly, in place of the DataGrid control, the mobile Web controls include the ObjectList
control. The ObjectList control includes the functionality that is provided by the DataGrid
control. The ObjectList control can be added to a mobile page by using the <ObjectList>>
element, as shown in the following example:
<mobile:ObjectList ID="ObjectList1" Runat="server"/>

The following code nippet binds the ObjectList control with a dataset:
ObjectList1.DataSource = ds;
ObjectList1.DataBind();

DeviceSpecific Control
The DeviceSpecific control is used to specify a choice among multiple content alternatives.
The DeviceSpecific control allows you to specify one or more choices, each containing
attributes that specify how to evaluate the choice against target device capabilities. During
run time, each choice specified in the DeviceSpecific control is evaluated in order, and the
first choice that is successfully evaluated is used.
The DeviceSpecific control is used to specify template sets and override properties. For
example, you can use the DeviceSpecific control to specify device-specific images for the
Image control, as shown in the following example:
<mobile:Image runat=server>
<DeviceSpecific>
<Choice Filter="isColor" ImageURL="colorImg.gif" />
<Choice Filter="isWML11" ImageURL="myImage.wbmp" />
</DeviceSpecific>
</mobile:Image>

In the preceding example, if the device is colored as specified by the isColor value of the
Filter attribute, the colorImg.gif image will be displayed. For WML device,
myImage.wbmp image will be displayed.
SelectionList Control

The SelectionList control provides different visual representations for a list of selectable
items. It combines the functionality of the CheckBox, CheckBoxList, DropDownList,
ListBox, RadioButton, and the RadioButton Web server controls. You can use the
SelectType property of the SelectionList control to define the type of selection list button to
render.
For example, if you set the SelectType property of the SelectionList control to CheckBox,
the item passed to the control as the value of its DataSource property are displayed as check
boxes. You can set the SelectType property of the SelectionList control as shown in the
following code snippet:
SelectionList sl = new SelectionList();
sl.SelectType = ListSelectType.DropDown;

StyleSheet Control
The StyleSheet control enables you to use styles in the ASP.NET mobile Web Forms. It has
no visual representation. The StyleSheet control can only be attached to ASP.NET mobile
Web forms or to mobile user controls. There can be only one style sheet for a page or a
control.
Each style sheet can contain one or more styles. A control can use the styles defined in the
StyleSheet control by using the StyleReference property. The following example shows
how to define styles by using the StyleSheet control:
<mobile:StyleSheet ID="MyStyle" Runat="server">
<mobile:Style Name="Style1" ForeColor="#ff0066"
Font-Size="Large"/>
<mobile:Style Name="Style2" ForeColor="#009900"
Font-Size="Normal"/>
</mobile:StyleSheet>

The preceding example defines two styles, Style1 and Style2. To use these styles for a
control, you need to set the StyleReference property of the control as shown in the
following example:
Label1.StyleReference = "Style1";

TextView Control
The TextView control is used to display large quantities of text. The TextView control
supports device filters for overriding property values. This enables the TextView control to
customize its appearance according to the capabilities of the device on which it is rendered.
The TextView control can be added to a mobile page by using the <TextView> element, as
shown in the following example:

<mobile:TextView ID="TextView1" Wrapping="Wrap"/>

Working with Device Emulators


After developing a mobile Web application, you need to test it on a mobile device. Although,
you can test the mobile Web application in a standard Web browser, it will not give a realistic
view of how the application would appear on a mobile device. To have a realistic view of the
mobile Web application, you can use device emulators. Device emulators are software
programs that simulate the environment of a cell phone or Personal Digital Assistant (PDA)
on the desktop of your computer. Device emulators are treated as virtual mobile devices.
Device emulators for most mobile devices are available to simulate the behavior of the
hardware and browsers of the mobiles. These emulators allow you to view mobile Web forms
as they would appear on the actual mobile devices. They enable you test your mobile Web
applications before deploying.

Rendering Content on Mobile Web Pages


There are various mobile devices available in the market. These devices have different
capabilities and they differ from each other in terms of screen size, color combination,
browser type, and many other features. Due to these differences, a Web control is rendered
differently on different mobile devices. Therefore, if you want to create a Web application
that can run on multiple mobile devices, you need to create a separate user interface for each
device. It is a tedious and complex task. This task can be simplified by using control adapters
and device filters provided by ASP.NET.

Implementing Control Adapters


Mobile devices have different screen sizes and capabilities. When a mobile device requests a
Web page, the server first checks the capabilities of the browser that has made the request.
Based on the browser capabilities, the controls are rendered on the Web page. For example,
consider that a mobile device requests for a Web page that displays a calendar control. Since
a mobile device does not have enough space on the screen, the calendar control is rendered as
a hyperlink, as shown in the following figure.

Rendering of a Calendar Control on a Mobile Device


When a user clicks the Calendar hyperlink, a menu appears. This menu prompts the users to
enter a date. However, if the request for the same Web page comes from Internet Explorer,
the Calendar control is rendered as shown in the following figure.

Rendering of a Calendar Control on Internet Explorer


This type of browser-based rendering of controls is known as adaptive rendering and can be
implemented by using control adapters.
A control adapter is used for device-specific rendering of mobile Web controls instead of
using the control's default rendering logic. To customize the behavior of Web controls, you
need to specify an object of the ControlAdapter class. The ControlAdapter class is an
abstract class that defines the basic functionality for all adapters. It overrides certain methods
and events of the Control class to allow browser or markup-specific handling.
When a control is rendered on a Web page, the Control base class first checks whether a
control adapter is currently associated with the control. If an adapter is associated with the
control, the Render() method of the adapter is invoked. Otherwise, the standard Render()
method of the control is invoked.

You need to map the mobile Web control with its adapter through the browser definition
files. The browser definition files have a .browser extension. It contains information about the
browser capabilities. ASP.NET uses the .browser files to determine the capabilities of the
browser, and to decide how to render markup to that browser.
The browser definition file, in addition to the mapping control adapters, is used to populate
the HttpBrowserCapabilities class. This class contains information about the capabilities
of the browser, such as name, type, and version of the browser. You can determine the
capabilities of the browser by accessing the HttpBrowserCapabilities class through the
Request.Browser property.
The following table lists some commonly used Request.Browser properties with their
description.
Property

Description

Request.Browser.Browser

Gets the name of the browser

Request.Browser.Version

Gets the full version number of the browser


as string

Request.Browser.Type

Gets the name and major version number of


the browser

Request.Browser.IsColor

Gets a boolean value that indicates whether


the browser has a color display

Request.Browser.IsMobileDevice

Gets a boolean value that indicates whether


the browser is a mobile device

Request.Browser.CanInitiateVoiceCall

Gets a boolean value that indicates whether


the browser is capable of initiating a voice
call

Some Commonly Used Request.Browser Properties


Consider an example wherein you have created separate home pages for desktop computers
and mobile computers. You want to render the home pages depending upon the type of the
computer that has requested the page. For this, you need to check the browser capabilities.
This can be done by using the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice)
{
Response.Redirect("Mobile/Home.aspx");
}

The preceding code is written within the Page_Load event handler of the home page that is
created for the desktop computers. It is the default startup page for the application. When the
page is requested by any computer, the type of the device is checked. If the request is from a
desktop computer, the default home page is returned. However, if the request comes from a
mobile device, the Mobile/Home.aspx page is returned.

Note
You can check the browser capabilities by declaring a HttpBrowserCapabilities type
variable as shown in the following code snippet:
HttpBrowserCapabilities browser = Request.Browser;
Response.Write(browser.ActiveXControls);

Note
Some mobile controls require you to use fully qualified redirects. For converting relative
paths into fully qualified paths, you need to use the <httpRuntime> element as shown in the
following example:
<system.web>
<httpRuntime useFullyQualifiedRedirectUrl="true" />
</system.web>

Implementing Device-Specific Rendering


Different mobile devices have different capabilities. Some devices can access the Internet and
send e-mail messages while others cannot. Similarly, some devices have color screens,
whereas others have gray-scale screens. When you design a Web page for mobile devices,
you do not know which device will be used by the user to access that page. Therefore, you
should design a Web page that caters to all the possible types of mobile devices.
For example, you may want to display a colored image on your mobile Web page. However,
there are mobile devices that do not support colored images. Therefore, you need to design
your Web page in such a way that it can be used by both types of mobile devices. For this,
you need to design the Web page in such a way that it displays a gray image on devices that
do not support colored images and a colored image on the rest of the devices.

The ability to render a control based on the type of the device is known as device-specific
rendering. This requires you to set the properties of the controls based on the capabilities of
the mobile devices by using device filters. You can customize a mobile Web page for specific
types of devices by defining a set of device filters for the page.
ASP.NET allows you to specify device filters for each type of device by using the
<DeviceSpecific><Choice> tags. You can insert the <DeviceSpecific> tag as a child
element of any mobile control on the Web page. This tag acts as an outer container for
holding a number of choices defined by the <Choice> tag.
The <Choice> tag represents device characteristic/value pairs, where the device characteristic
is drawn from a number of sources. A control can contain only one <DeviceSpecific> tag.
However, it can contain many <Choice> tags. Choices are evaluated in the order in which
they appear in the DeviceSpecific/Choice construct. Each <Choice> tag contains:

A Filter attribute that specifies the devices that this choice applies to.
Additional property values that override the properties of the original control when
the device specified by the Filter attribute is used.

Consider a scenario wherein you need to control the display of an image by using the
<DeviceSpecific><Choice> tags. For this, you need to use the
<DeviceSpecific><Choice> tags as shown in the following example:
<mobile:Image runat=server>
<DeviceSpecific>
<Choice Filter="isColor" ImageURL="colorImg.gif" />
<Choice Filter="isWML11" ImageURL="myImage.wbmp" />
<Choice ImageURL="monoImage.gif" />
</DeviceSpecific>
</mobile:Image>

In the preceding example, if the device is colored as specified by the isColor value of the
Filter attribute, the colorImg.gif image will be displayed. For WML device,
myImage.wbmp image will be displayed. The third <Choice> tag does not have any Filter
attribute. Therefore, it is the default choice and will be evaluated if the preceding two choices
are not matched.

Note

WML devices are those devices that support Wireless Markup Language (WML) intended for
displaying Web pages on mobile devices. Currently, in place of WML, Extensible HyperText
Markup Language (XHTML) is used in mobile devices.
The Filter attribute in each <Choice> tag either specifies the name of a method on the
mobile form or associated .ascx file, or the name of a device filter defined in the
<deviceFilters> element of the web.config file.
Using the Name of a Method as Filters
When the name of a method is used as a filter, the choice is applied on the basis of the
Boolean value returned by the method.
The filter method must conform to the following signature:
public bool methodName(
System.Web.Mobile.MobileCapabilities capabilities,
string optionalArgument);

Using Device Filters in the Web.config File


The Filter attribute can also specify the name of a filter defined in the web.config file.
These filters can be of two types:

Comparison filter: Comparison filters make comparisons that are generally based on
a Boolean argument. In comparison filter, you need to provide the name of a
capability and the value that you want the filter to compare. The following markup
shows a comparison filter:
<system.web>
<deviceFilters>
<filter name="TestIsColor" compare="IsColor" argument="true" />
</deviceFilters>
</system.web>
In the preceding markup, TestIsColor is the name of the filter and
IsColor is the capability that is to be compared against the value,
true.

Evaluator-delegate filter: The evaluator-delegate filter is used for more complex


evaluation. In evaluator-delegate filter, you need to specify an evaluator-delegate
filter by providing the class and the name of a method. The following markup shows a
evaluator-delegate filter:
<system.web>

<deviceFilters>
<filter
name="TestIsColor"
type="CustomFilter"
method="checkColor" />
</deviceFilters>
</system.web>

In the preceding markup, TestIsColor is the name of the filter, CustomFilter is the
name of the class, and checkColor is the method that is called at run time to test the
evaluator. You need to write and compile the class containing the method that is used
to test the evaluator.

Note
In addition to device-specific rendering by using the <DeviceSpecific> element, you can
use the XhtmlTextWriter and ChtmlTextWriter classes to provide additional adaptive
rendering capabilities to the controls.

Summary
In this chapter, you learned that:

A Web page created for desktop browsers cannot be properly displayed on mobile
devices because mobile devices have small display area and low bandwidth.
ASP.NET provides you with the System.Web.Mobile namespace that is used
specifically for mobile Web development.
Mobile Web pages have some specific controls. These are:
o Form
o Command
o PhoneCall
o List and ObjectList
o DeviceSpecific

o
o
o

SelectionList
StyleSheet
TextView
Device emulators are software programs that simulate the environment of a cell phone
or PDA on the desktop of your PC.
A control adapter is used for device-specific rendering of mobile Web controls instead
of using the control's default rendering logic.
To customize the behavior of Web controls, you need to specify an object of the
ControlAdapter class.
The ControlAdapter class is an abstract class that defines the basic functionality for
all adapters.
The ability to render a control based on the type of the device is known as devicespecific rendering.

Reference Reading
Creating Mobile Web Pages
Reference Reading:
Books

Reference Reading: URLs

Pro ASP.NET 3.5 in C#


2008 by Matthew
MacDonald, Mario
Szpuszta

http://msdn.microsoft.com/en-us/library/8htez1ds.aspx

Rendering Content on Mobile Web Pages


Reference Reading:
Books

Reference Reading: URLs

Pro ASP. Net 3. 5 Server


Controls and AJAX
Components by Rob
Cameron, Dale Michalk

http://en.wikipedia.org/wiki/Mobile_browser
http://msdn.microsoft.com/en-us/library/7s9fybz5.aspx

You might also like