You are on page 1of 161

This product or document is protected by copyright

and distributed under licenses restricting its use,


copying, distribution and decompilation. Please view ASP.NET/SG/Q6M2/09-M1-V01
"Mark of Authenticity" label to establish proper Copyright ©NIIT. All rights reserved.
licensed usage. No part of this document may be
copied, reproduced, printed, distributed, modified,
removed, amended in any form by any means
whether electronic, mechanical, digital, optical,
photographic or otherwise without prior written
authorization of NIIT and its authorized licensors, if
any.
Information in this document is subject to change by
NIIT without notice. The names of companies,
products, people, characters, and/or data mentioned
herein are fictitious and are in no way intended to
represent any real individual, company, entity,
services, product or event, unless otherwise noted.
All products are registered trademarks of their
respective organizations.
All software is used for educational purposes only.
Disclaimer: The documents and graphics on this
courseware could include technical inaccuracies or
typographical errors/translation errors. Changes are
periodically added to the information herein. NIIT
may make improvements and/or changes herein at
any time. NIIT makes no representations about the
accuracy of the information contained in the
courseware and graphics in this courseware for any
purpose. All documents and graphics are provided
"as is". NIIT hereby disclaims all warranties and
conditions with regard to this information, including
all implied warranties and conditions of
merchantability, fitness for any particular purpose,
title and non-infringement. In any event, NIIT and/or
its licensor(s)/supplier(s) shall not be liable to any
party for any direct, indirect, special or other
consequential damages for any use of the
courseware/translated courseware, the information,
or on any other hyper linked web site, including,
without limitation, any lost profits, business
interruption, loss of programs or other data on your
information handling system or otherwise, even if
NIIT is expressly advised of the possibility of such
damages.
Due to the dynamic nature of the internet, the URLs
and web references mentioned in this document may
be (are) subject to changes, for which NIIT shall not
hold any responsibility.
q Work with data
q Manipulate data using LINQ
q Implement error handling and debugging
ABOUT THIS COURSE q Use Web parts
q Create Rich Internet Applications using AJAX
q Implement internationalization and
Prologue accessibility
q Secure a Web application
q Deploy an ASP.NET application
q Trace and Monitor Web Applications
Description q Create Web applications for mobile devices
ASP.NET provides a unified Web development model,
which includes the services for creating websites
easily and quickly. This module discusses features Entry Profile
such as master pages and themes, which enable the The students who want to take this course should
developers to create pages that are more consistent have knowledge of:
and offer a richer experience to the users. It also q SQL Server 2005
discusses how to implement AJAX functionality in the q C# and Microsoft Visual Studio
websites to enable partial page rendering. It also q HTML and javascript
discusses how to implement LINQ to write standard q ADO.NET
queries that enables a programmer to use the same q Extensible Markup Language (XML)
queries to retrieve data from disparate data sources.
In addition, it discusses how to create device-specific
Web applications, such as applications for mobile Exit Profile
devices.
At the end of this module, the students will be able
to develop Web-based applications by using
Rationale ASP.NET.

With the increased use of the Internet and advances


in information technology, application developers Methodology
need to quickly create applications that are
accessible over the Web or a corporate intranet. The
applications should also be efficient and effective. Learning Architecture Based on
ASP.NET provides developers with various time Collaborative Constructivism
saving and code saving features. One of its key
design goals is to make programming easier and
(LACC)
quicker by reducing the amount of code. In addition,
it contains several new server controls, which
Introduction
Broadly, almost all teaching-learning interactions/
eliminate the need for writing voluminous code.
modes can be classified as one of the following:
q Interactions, where the teacher or external
Objectives resource creates the learning experience.
q Interactions, where the teacher or external
After completing this module, the students will be resource creates or constructs the learning,
able to: in collaboration with the learners.
q Identify the basic features of Web q Situations, where the learners create their
development own learning experiences.
q Create a Web application Any learning architecture, which can suitably
q Work with controls integrate all of the above modes, would be ideal.
q Implement styles, themes, and master pages Methodologies, in the past, have mainly focused on
q Implement navigation in a Web application the first mode of interaction. The last two of these
q Manage state of a Web application possible modes, which encompass the theory of
situated cognition and collaborative constructivism, components:
provide the most challenging task for the design of a q CONSTRUCT: The learning begins with this
new methodology. component. An instructor who is a subject
NIIT’s breakthrough LACC methodology builds in matter expert is required to lead the
learning components that enable all of the above students here. This component introduces
interactions, to address the various stages of the learner to new concepts and thereby
experiential learning and catering to multiple learner constructing his/her knowledge base. The
types. instructor brings in concrete experiences for
Stages in Experiential Learning the learner through explanations and
demonstrations. These two sessions are
According to David A Kolb*, experiential learning
meant to provide the required foundation for
involves four principal stages:
the student to be able to move to the
q Concrete Experiences- (CE) - Learner’s
subsequent stages of learning.
personal involvement through concrete
q COLLABORATE: The next learning
experiences.
component makes it possible for the learner
q Reflective Observation- (RO) - Learner
to have contextual familiarity on the subject
reflects on experience and looks for
through collaborative learning. Here the
meaning.
learner is provided with a mentor/direction/
q Active Experimentation- (AE) - Learner
and stimulus for reflective observation. The
applies this meaning to form a logical
learner is provided with a rich choice of tools
conclusion; experiments with similar
like case studies, scenario/problem
problems, which leads to new concrete
statements and best practices to reflect on
experience.
the concepts learnt in the previous sessions
q Abstract Conceptualization- (AC) - Learner
and apply his/her understanding in the
experiments with similar problems, which
larger context.
leads to new concrete experience.
q EXPERIMENT: Here, the learner is exposed
Learner Types to active experimentation. The learner
The CE/AC and AE/RO dimensions are polar experiments his/her understanding of the
opposites as far as learning styles are concerned and concepts and observations to form a logical
depending on the preference of an individual’s conclusion leading to better learning
learning styles/stages, four distinct types of learners effectiveness and experience.
are possible. q APPLY: This learning component provides
the environment for learners to develop
conceptual clarity. Here the learner learns,
refers, compares, thinks and applies their
entire knowledge spectrum and create
solutions for a real life case study. The tools
used to provide such learning are project,
Information Search and Analysis Skills (ISAS)
and Reference Reading (RR).

q Divergers or the imaginative learners


q Assimilators or the analytic learners
q Convergers or the precision learners and
q Accommodators or the dynamic learners
NIIT’s LACC methodology has Learning Components,
that are oriented towards the four stages of
experiential learning and hence is highly suitable to
all possible types/profiles of learners.
Learning Components
NIIT’s LACC methodology has the following learning Required Resources
This methodology requires the following resources
for delivery:
q Online Classroom: Room having networked
computer nodes for all students: Learning
Components like CONSTRUCT, EXPERIMENT
and APPLY (Projects) are executed in such a
resource.
q Adequate Environment: To execute
components like COLLABORATE and APPLY
(RR and ISAS).

Conventions
intranets. This information can be accessed from
anywhere and at any time. In addition, Web
applications can support online commercial
Chapter 1 transactions popularly known as e-commerce. An
online store accessed through a Web browser is an
Introducing ASP.NET example of a Web application.
A Web application consists of Web pages. Web
Web applications have revolutionized the way pages can be of the following types:
business is conducted. These applications enable q Static Web Page: A Web page that consists
organizations to share and access information from of only Hyper Text Markup Language (HTML)
anywhere and at anytime. This has majorly moved is a static Web page. A static Web page does
the focus of application development from desktop not respond dynamically to the actions
applications to Web applications. One of the most performed by a user.
popular server-side technologies used today for q Dynamic Web Page: A Web page that
developing Web applications is ASP.NET. responds dynamically to the actions
This chapter introduces the basics of Web performed by a user is a dynamic Web page
development. It also discusses the architecture, and an application that consists of dynamic
functioning, and features of ASP.NET. In addition, it Web pages is a dynamic Web application.
explains how to develop ASP.NET applications. Such an application can be created by using
server-side scripts, client-side scripts, or both
Objectives in addition to HTML pages.
In this chapter, you will learn to:
Identify the basics of Web development Server-Side Scripting
Explore ASP.NET
With the increase in the usage of the Internet as the
Develop ASP.NET applications
information medium, organizations are creating
dynamic Web applications. Dynamic Web
Introducing Web Development applications enable a user to:
q Retrieve data from a database that may not
Among all technologies, the Internet has been the reside on the computer where the Web
fastest growing technology. Ever since its inception, server is located.
the Internet has evolved exponentially. In the recent q Submit data from HTML forms.
years, it has changed the way business is conducted. q Get information based on the input.
Prior to the evolution of the Internet, organizations To incorporate these features in a Web application,
were unable to create awareness about themselves you need to implement server-side scripting. Server-
because the communication media were limited. side scripting provides users with dynamic content
Moreover, the organizations could deliver only that is based on the information stored at a remote
limited information by using the existing location, such as a back-end database. Server-side
communication media such as television and radio. scripting includes code written in server-side
However, with the inception of the Internet, scripting languages, such as Active Server Pages
organizations found a new medium through which (ASP) and Java Server Pages (JSP). A server-side script
they could reach a larger range of people irrespective is executed on the Web server.
of their geographical locations. Therefore, When a browser requests for information on a
organizations increasingly became dependent on the website that is created by using server-side
Internet for sharing and accessing information. This technology, the Web server to which the request is
resulted in changing the focus of application sent, first processes the script and then sends the
development from desktop applications to Web results back to the browser. For example, if a Web
applications. page includes a server-side script to display the
Web applications are programs that are executed on current time of the system on which the website is
a Web server and accessed from a Web browser. hosted, the script will be processed at the server and
These applications enable organizations to share and the current system time will be sent back to the
access information on the Internet and corporate browser.
The following figure shows the working of server- has some major limitations. These limitations are:
side scripts. q Browser support: Client-side scripting is not
supported equally by all browsers and
operating systems.
q 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.
q Security: Client-side scripts are visible to the
end users. Therefore, they can be tampered
by malicious users.
Working of Server-Side Scripts q Thin clients: Web-enabled devices such as
mobile phones, palmtop computers, and
Personal Digital Assistants (PDAs) can
Client-Side Scripting communicate with Web servers. These
devices act as thin clients that can use Web
Client-side scripting enables you to develop Web
applications containing server-side scripting.
pages that can dynamically respond to user input
However, these devices do not support
without having to interact with a Web server.
client-side scripting such as JavaScript or
Suppose, you have a Web application that requires
VBScript.
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-
In spite of all the limitations, client-side
side scripts.
scripting is still in use. ASP.NET allows you
In addition to providing dynamic content, a client-
side script helps reduce network traffic because it
to use client-side scripting in addition to
does not need to interact with a Web server to the server-side scripting to create rich and
provide dynamic response to the user input. Client- responsive Web applications.
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, Exploring ASP.NET
such as VBScript and JavaScript, are used to write ASP.NET is a server-side technology that enables
client-side scripts. programmers to create dynamic Web applications. It
The following figure shows the working of client-side has a number of advanced features such as
scripts. 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.
Working of Client-Side Scripts The following figure displays the elements of an
Limitations of Client-Side Scripting ASP.NET application and how the elements fit in the
In spite of the all the advantages, client-side scripting broader context of the .NET Framework.
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
Elements of an ASP.NET Application in the .NET are:
Framework 1. A Web browser sends a request for an
The preceding figure indicates that an ASP.NET ASP.NET file to a Web server by using a
application has the following elements: Uniform Resource Locator (URL).
q Web Form Pages: Enable you to include 2. The Web server, such as IIS, receives the
user interfaces, such as Text box control, List request and retrieves the appropriate
box control, and the application logic of Web ASP.NET file from the disk or memory.
applications. 3. The Web server forwards the ASP.NET file to
q Configuration Files: Enable you to store the the ASP.NET script engine for processing.
configuration settings of an ASP.NET 4. The ASP.NET script engine reads the file and
application. executes any server-side script it encounters.
q XML Web Service Files: Define a Web 5. The processed ASP.NET file is generated as
service that can be called by an ASPX file an HTML page.
over the Internet or from a local network. 6. The Web server then sends the HTML page
Web forms and the state management feature of to the client.
ASP.NET constitute the ASP.NET Page Framework. 7. The Web browser interprets the output and
There are also a number of runtime services available displays it.
in ASP.NET. The ASP.NET runtime services include A Web server generates and sends only the HTML
view state, session state, and application state output to the client. As a result, it helps to hide the
management, Web security, and the caching code of the ASP.NET file from the users who access
mechanism of ASP.NET applications. The runtime an ASP.NET Web page.
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.
ASP.NET script engine is the engine that
processes the server-side scripts contained
Working of an ASP.NET in an ASP.NET application. After processing
Application the scripts, the engine renders the result as
an HTML document and sends it back to
After creating an ASP.NET application, the ASP.NET the browser.
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 Features of ASP.NET
the scripts. Finally, the results are sent to the Web
browser that requested the ASP.NET file. In addition to hiding the code of the ASP.NET file
from the users, ASP.NET has the following advanced
The following figure depicts how a Web server
features that help develop robust Web applications: responses. It improves the page loading
q Compiled code: The code written in time.
ASP.NET is compiled and not interpreted.
This makes ASP.NET applications faster to
execute than other server-side scripts, such Developing ASP.NET Applications
as the scripts written in a previous version of You can create ASP.NET applications by using any
ASP that are interpreted. text editor. However, this will take a substantial
q Power and flexibility: ASP.NET applications amount of time because you will have to create the
are based on CLR. As a result, the power and applications by creating all the Web page classes and
flexibility of the .NET platform is available to coding the Web page controls manually. In addition
ASP.NET applications. ASP.NET applications to being time-consuming, this process increases the
enable you to ensure that the .NET possibility of inducing errors that could otherwise be
Framework class library, messaging, and data avoided by using a design tool. A design and
access solutions are seamlessly accessible on productivity tool, such as Visual Studio, provides
the Web. ASP.NET is also language- various features that enable the developers to quickly
independent. As a result, you can choose create robust ASP.NET applications. Some of the
any .NET language to develop your Visual Studio IDE features are:
application.
q Integrated error checking: Visual Studio
q Simplicity: ASP.NET enables you to build
can detect various problems such as data
user interfaces that separate application
type conversion errors, missing namespaces
logic from the presentation content. In
or classes, and undefined variables. When
addition, CLR simplifies application
you type code, Visual Studio detects and
development by using managed code
underlines these problems.
services, such as automatic reference
q The Web form designer: Visual Studio
counting and garbage collection. Therefore,
provides the Web form designer that enables
ASP.NET makes it easy to perform common
you to create a Web page by simply
tasks ranging from form submission and
dragging the ASP.NET controls to the
client authentication to website
appropriate location and configuring their
configuration and deployment.
properties. The actual Web page markup is
q Manageability: ASP.NET enables you to
created automatically.
manage Web applications by storing the
q An integrated Web server: Web
configuration information in an Extensible
applications need to be hosted on a Web
Markup Language (XML) file. You can open
server such as IIS to be accessible for the
the XML file and modify it.
users. Therefore, you need to install IIS on
q Scalability: ASP.NET has been designed with
the development computer to test the
scalability in mind. It has features that help
applications. However, if you are creating a
improve performance in a multiprocessor
Web application by using Visual Studio, you
environment.
need not install IIS on the computer. This is
q Security: ASP.NET provides a number of
because Visual Studio has an integrated
options for implementing security and
development Web server that enables you to
restricting user access to a Web application.
run a Web application directly from the
All these options are configured within the
design environment.
configuration file.
q Developer productivity enhancements:
q Extensibility: ASP.NET provides a number of
Visual Studio provides features such as
options to create an extensible Web
automatic statement completion and color-
application. For example, you can create
coded syntax that makes coding quick and
custom controls and extend the default
efficient. In addition, Visual Studio has an
Hypertext Transfer Protocol (HTTP) pipeline.
integrated debugger that allows you to
The path through which the data flows from
watch code execution, pause your program
the client to the server is called the HTTP
at any point, and inspect the contents of any
pipeline. It is a technique in which multiple
variable. This helps in debugging the code
HTTP requests are written out to a single
quickly and efficiently.
socket without waiting for the corresponding
q Complete extensibility: Visual Studio allows hosting four Web applications.
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 A Web Server Hosting Four Web Applications
Object Access Protocol (SOAP). A Web service does
not have a user interface.

A virtual directory is a directory that is


exposed to the public on a Web server.

Anatomy of an ASP.NET Directories Used in ASP.NET Web


Application Applications
An ASP.NET application uses some specialized
ASP.NET applications are generally divided into directories. The following table lists these directories
multiple Web pages. Every Web page in an ASP.NET with their descriptions.
application shares a common set of resources and
configuration settings. These resources and
configuration settings cannot be shared by the Web Bin Stores all the
pages from any other ASP.NET application, even if compiled .NET
they are on the same Web server. components (DLLs) that an
Every ASP.NET application is executed inside a ASP.NET Web application
separate application domain. These application uses. For example, if you
domains ensure that even if a Web application create a custom
causes a fatal error, it does not affect other component, you need to
applications that are currently running on the same place the component in
computer. Application domains also restrict a Web this directory. Once placed
page in one application from accessing the in- in the Bin directory, the
memory information of another application. Each component can be used by
Web application is a separate entity that has its own any ASP.NET application.
set of data. It can be described as a combination of App_Code Stores source code files
files, pages, handlers, modules, and executable code that are dynamically
that can be invoked from a virtual directory on a Web compiled to be used in the
server. Web application. It is
The following figure shows a Web server that is similar to the Bin directory
except for one difference. important file types with their descriptions.
It contains source code
files whereas the Bin
directory contains Ends with .aspx These are ASP.NET Web
compiled assemblies. pages that contain the
App_Browsers Stores browser definition user interface and,
files. Browser definition optionally, the underlying
files are XML files that application code. Users
define a browser with its request or navigate
properties, capabilities, directly to one of these
and features. This pages to start a Web
information is used by application.
ASP.NET server controls to Ends with .ascx These are ASP.NET user
determine the browser controls. These controls
that has requested the are similar to Web pages,
page and render the except that the user
appropriate markup for cannot access these files
that browser. directly. Instead, they must
App_GlobalResources Stores global resources be hosted inside an
that are accessible to ASP.NET Web page. User
every page in the Web controls allow you to
application. It is used for develop a small piece of
localization purposes user interface and reuse it
where you want a website in as many Web forms as
to display content in more you want without
than one language. repeating code.
App_LocalResources Stores .resx files that are Ends with .asmx These are ASP.NET Web
accessible to a specific services. Web services are
page only. collections of methods
App_WebReferences Stores references to Web that can be called over the
services that are used by Internet. Web services
the Web application. work differently than Web
App_Data Stores data such as pages. However, they still
database files and XML share the same
files that are used by the application resources,
application. It is not configuration settings, and
mandatory to store data memory.
files in this directory. web.config This is the XML-based
App_Themes Stores the themes that are configuration file for
used in the Web ASP.NET applications. It
application. includes settings for
customizing features such
Directories Used in an ASP.NET Application as security, state
Some of the subdirectories given in the preceding management, and
table are created in specific applications. For memory management.
example, the App_Themes directory is created when Global.asax This is the global
you use themes in your application. application file. You can
use this file to define
Files Used in ASP.NET Web global variables (variables
Applications that can be accessed from
The ASP.NET Web applications can include different any Web page in the Web
types of files. The following table lists some of the application). It is mostly
used for defining the levels.
overall application events The following table lists the levels, the corresponding
related to the Application configuration files, and their description.
& 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@
WebHandlerdirective.
Configuration Files with Their Levels and
Files Used in an ASP.NET Application Descriptions
Configuration Files Used in ASP.NET The two files included in the hierarchy of
configuration files are machine.config and
Web Applications web.config. The machine.config file always resides at
ASP.NET uses a hierarchy of configuration files to the root of the configuration hierarchy and contains
keep application configuration settings separate from the global and default settings for all .NET
the application code. A configuration file is an XML Framework applications on the server. The
file that contains configuration settings for an web.config file can reside at multiple levels in the
application and has a .config extension. hierarchy. In case two versions of the same
It provides the following benefits: configuration setting exist at different hierarchal
q Provides control and flexibility over the way levels, local settings will take precedence over global
you run applications. settings.
q Eliminates the need to recompile the
application every time a setting changes.
q Controls access to protected resources, and ASP.NET Web Page Code Model
the location of remote applications and
objects by defining configuration settings. A Web page is made up of the following two
To understand the benefits of configuration files, components:
consider an example. Suppose, your Web application q The visual portion: Refers to the static
includes a number of forms that are required to HTML and ASP.NET server controls that
connect to an SQL Server database. You have written define the layout of a Web page.
the code to create the connection on each of these q The programming logic: Refers to the code
forms. However, if the location of the database is that is required to interact with the Web
modified, you will have to update the code for page.
connecting to the database in each form. A better ASP.NET provides two models for managing the
option is to store the details of the connection string visual elements and code:
in a configuration file for the Web application and q Single-file page model
refer to the connection string from within the code. q Code-behind page model
As a result of this, even if the database location is The Single-File Page Model
changed, only the connection string in the In the single-file page model, HTML markup of the
configuration file needs to be updated. page and its programming code are in the same
ASP.NET allows you to easily edit the configuration physical .aspx file. The programming code is
data before, or after an application is deployed on contained in a <script> block that specifies the
the server. The files in the configuration hierarchy attribute runat="server".
allow you to make configuration settings at different The first line in the .aspx file contains the @Page
directive. Every .aspx file should include the @Page the page to inherit. This class can be any
directive. The @Page directive provides ASP.NET with class that is derived from the Page class. This
the basic information about how to compile the Web attribute is used with the CodeFile
page. It also indicates the language that will be used attribute, which contains the path to the
for coding and the way to connect the event source file for the code-behind class.
handlers. The syntax of the page directive is: When the page is compiled, ASP.NET creates a new
<%@ Page Language="C#"%> partial class for the .aspx file. This class is a peer of
At run time, the compiler converts a single-file page the code-behind partial class file and contains the
into a class that derives from the declarations for the controls of the page. Finally,
System.Web.UI.Page class. ASP.NET generates a class that inherits from the
The single-file page model provides the following partial class created from the .aspx file and the code-
advantages: behind partial class. The generated class is compiled
q In pages with less code, keeping the into an assembly that runs in order to render output
programming code and the HTML markup in to the browser.
a single file proves to be very convenient The code-behind model provides the following
while studying the file. advantages:
q Pages written by using the single-file model q It allows a developer to separate the UI
are slightly easier to deploy or to send to display from the UI processing, thereby
another programmer because there is only enabling the programmer to reuse the
one file. programming logic.
q A single-file page is easier to rename q It enables a developer to quickly debug the
because there is no dependency between code because the code is not clubbed with
files. the UI.
q Managing files in a source code control q It enables developers to quickly create a
system is slightly easier because the page is Web application by separating the design
self-contained in a single file. and development functions. For example,
designers can work on the .aspx file and at
The Code-Behind Page Model
the same time programmers can implement
In the code-behind page model, HTML markup is
logics in the code-behind file.
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 The Page Class
(either System.Web.UI.Page or a class derived All Web forms are instances of the ASP.NET Page
from System.Web.UI.Page). class, which is defined in the System.Web.UI
There are two differences in the .aspx page between namespace. The Page class inherits the
the single-file and the code-behind models: TemplateControl class, which, in turn, inherits the
1. In the code-behind model, there is no Control class. As a result, the Page class provides
<script> block with the runat="server" useful events that can be used in the code.
attribute.
2. In the code-behind model, the @Page Page Events
directive contains attributes that reference an ASP.NET uses an event-driven model of
external file and a class, as shown in the programming. This model of ASP.NET defines a
following example: sequence of events that are raised during the
<%@ Page Language="C#" lifecycle of a Web page. The following table lists
CodeFile="Default.aspx.cs" some of the page events.
Inherits="_Default" %>
In the preceding example, the CodeFile
attribute specifies the code-behind file with Init It is the first event that
which the page is associated, and the Inherits occurs when the server
attribute specifies a code-behind class for executes an ASP.NET
page. It occurs only once
in the entire lifecycle of an Count Returns the number of
ASP.NET page. objects in the
Load It is fired after the Init HttpApplicationState
event, when the page is collection.
requested for the first time Item Provides access to an
and whenever the page is object in the
reloaded. This event can HttpApplicationState
be used to initialize the collection.
variables and the state of
the controls that are used
Application Object’s Properties with Description
in the page.
The Application object provides various methods
Unload It represents the last event and properties. The following table describes some
that occurs in the lifecycle of the methods of the Application object.
of an ASP.NET page. This
event is used to perform
final cleanup work, such
public void Lock() Blocks the access to an
as the closing of open
database connections, Application variable or
discarding objects, or object. The Lock()
closing files. method enables access
synchronization when
more than one process is
Page Events and Their Description
accessing a particular
variable or object.
public void UnLock Releases the lock procured
Intrinsic Objects of ASP.NET () on an
ASP.NET has a number of built-in objects that are Application variable
programmed using methods, properties, and or object.
collections. These objects are made available to the
Page object, which is an instance of the Application Object’s Methods with Description
System.Web.UI.Page class from which all
ASP.NET pages are inherited.
Request
The Request object provides a reference to an
ASP.NET provides the following built-in objects:
object of the HttpRequest class. The object enables
q Application
q Request ASP.NET applications to access information sent by
q Response the client during a Web request. The following table
q Server describes some of the properties of the Request
q Session object.
q HttpContext
Application
The Application object provides a reference to an ApplicationPath Returns the application
object of the HttpApplicationState class. The root path of ASP.NET on
Application object is used to store information the server. This is a read-
that is defined for the entire Web application. For only property.
example, the connection string, which is used to Url Returns a URI object,
connect to the database server, is defined for the which will contain the
entire Web application. Therefore, the connection complete address of the
string can be stored in the Application object. The requested page. This is a
following table describes some of the properties of read-only property.
the Application object. UserHostAddress Returns the IP host
address of the requesting
client.
UserLanguage Returns a sorted string Cache Provides access to the
array containing the caching policy, such as the
language preferences of expiration time and
the client. privacy settings of the
Browser Returns the Web page. This is a read-
HttpBrowserCapabili only property.
ties object, which ContentType Sets or gets the type of
contains information data that is sent to the
about the browser client through the
capability of the client. Response object.
Cookies Returns the Cookies Sets a cookie to the client
HttpCookieCollectio browser.
n object, which provides IsClientConnected Returns a Boolean value
access to the cookie indicating whether the
variables of the client. client is connected or
QueryString Provides access to the disconnected.
parameters passed from
the client to the server Response Object’s Properties with Description
along with a GET request. The following table describes some of the methods
of the Response object.
Request Object’s Properties with Description
The following table describes an important method
of the Request object. public void Clear() Clears the content in the
buffer of the Response
object.
byte[] BinaryRead Helps retrieve the data public void Close() Closes the connection to
(int) sent to the server from the the client.
client as part of a post public void End() Sends the buffered data to
request and stores it in an the client and closes the
array. connection to the client.
The End() method will
Request Object’s Method with Description raise an
Response Application_EndRequ
The Response object provides a reference to an est event.
object of the HttpResponse class. The object public void Flush() Sends the data in the
enables ASP.NET applications to send information to buffer to the client but
the client. The following table describes some of the does not close the
properties of the Response object. connection to the client.
public void Redirects the new URL
Redirect(string) specified in the string
Buffer Sets the buffer feature of parameter to the client.
the Response object. public void Write Writes a string on the
When the Buffer property (string) form. It is an overloaded
is set to true, the method.
Response object buffers
the responses together. Response Object’s Methods with Description
When the Buffer property
is set to false, the
Response object sends
the response as it receives.
Server
The Server object provides a reference to an object
The default value is true.
of the HttpServerUtility class. The Server
object provides methods that can be used to access
the methods and properties of the Web server. The Count Returns the number of
following table describes some of the properties of items in the session-state
the Server object. collection.
SessionID Returns the unique session
ID assigned for a session.
MachineName Returns the name of the Timeout Enables to get and set the
server machine. period in minutes that is
ScriptTimeout Helps get and set the allowed between requests
request timeout in seconds by the client before the
for the Web server. session-state provider
terminates the session.
Server Object’s Properties with Description
The following table describes some of the methods Session Object’s Properties with Description
of the Server object. The following table describes some of the methods
of the Session object.

public void Clears the last error that


ClearError() has occurred on the server. public void Add Adds a new item to the
public object Creates the server instance (string session-state collection.
CreateObject of a COM object. name, object value)
(String) public void Clear() Clears all the values
public Exception Returns an Exception stored in the session-state
GetLastError() object, which represents collection.
the last error that occurred public void Remove Deletes an item from the
on the server. (string name) session-state collection.
public string Returns the physical file
MapPath(string path on the Web server Session Object’s Methods with Description
path) that corresponds to the
specified virtual path. HttpContext
public void Terminates the processing The HttpContext object holds information about
Transfer(string) the current HTTP request. A new HttpContext
of the current page and
object is created for every request sent to an
loads the page specified in
ASP.NET application. The new object is created at the
the string format.
beginning of a request and destroyed when the
request is completed. The HttpContext object
Server Object’s Methods with Description holds current request-specific information such as
Session Request, Response, Server, and Session. The
The Session object provides a reference to an following table describes some of the properties of
object of the HttpSessionState class. The the HttpContext object.
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 AllErrors Gets an array of errors
session wide cache, which can be used to store that are accumulated
information pertaining to the client. while processing an HTTP
A session starts when a client logs on to a website request.
and ends when he/she logs off from the website. The ApplicationInstance Gets or sets the
session is also terminated if the client remains HttpApplication
inactive for a specific period. The default timeout object for the current
period is 20 minutes. The following table describes HTTP request.
some of the properties of the Session object. Timestamp Gets the initial timestamp
of the current HTTP
request. components:
Users Gets or sets security The visual portion
information for the current The programming logic
HTTP request. q ASP.NET provides two models for managing
the visual elements and code:
HTTPContext Object’s Properties with Description Single-file page model
The following table describes some of the methods Code-behind page model
of the HttpContext object. q ASP.NET provides the following built-in
objects:
Application
Request
public void Adds an exception to the Response
AddError(Exception exception collection for Server
errorInfo) the current HTTP request. Session
public void Clears all errors for the HttpContext
ClearError() current HTTP request.
public object Returns requested
GetConfig(string configuration information Reference Reading
name) for the current HTTP
request. Introducing Web Development

HttpContext Object’s Methods with Description


Mastering Web http://en.wikipedia.org/
Development with wiki/Server-side_scripting
Summary Microsoft Visual Studio
2005 by John Paul Mueller http://
In this chapter, you learned that: Beginning ASP.NET 3.5 in www.eggheadcafe.com/
q Web pages can be of the following types: VB: by Matthew articles/20041016.asp
Static Web Page MacDonald
Dynamic Web Page
q Server-side scripting provides users with
dynamic content that is based on the
Exploring ASP.NET
information stored at a remote location.
q Client-side scripting enables you to develop
Web pages that can dynamically respond to Programming ASP.NET: http://en.wikipedia.org/
user input without having to interact with a Building Web Applications wiki/.NET_Framework
Web server. and Services with ASP.NET
q An ASP.NET application has the following 3.5 by Jesse Liberty, Dan http://en.wikipedia.org/
elements: Hurwitz Essential ASP. wiki/ASP.NET
Web Form Pages NET with Examples in C#:
Configuration Files by Fritz Onion http://
XML Web Service Files articles.techrepublic.com.c
q ASP.NET has the following advanced features om/5100-10878_11-5771
that help develop robust Web applications: 721.html
Compiled code
Enriched tool support Developing ASP.NET Applications
Power and flexibility
Simplicity
Manageability ASP.NET in a Nutshell: by http://www.asp.net/
Scalability G. Andrew Duthie,
Security Matthew MacDonald http://
Extensibility Developing Web www.microsoft.com/
q A Web form is made up of the following two Applications with Visual learning/en/us/
Basic.NET and ASP.NET by syllabi/2310Bfinal.mspx
John Alexander, Billy
Hollis
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
Chapter 2 in the HTML format, thus, hiding the program logic
from the user.
Working with Controls Each server control provides an object-oriented
programmable interface. Therefore, each server
The success of an application largely depends upon control is an object with methods, properties, and
its user interface. For an application to be successful, events associated with it.
its interface needs to be attractive and easy-to-use. Server controls can be viewed as special HTML tags,
Such a user interface can be designed by using which are processed by the server. The advantages of
various types of controls provided in ASP.NET. using server controls are:
ASP.NET provides various types of controls that can q Automatic state maintenance: ASP.NET
be added to a Web form to make it interactive. server controls provide a property called
However, while developing an application, you may EnableViewState, which can be set to true
face a situation where the built-in controls do not to enable the server controls to maintain
fulfill your requirements. In such a situation, you their state after a postback.
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. Postback is the process by which a
browser posts information back to
Objectives itself. It can also be defined as the
In this chapter, you will learn to: process by which a browser posts
Use ASP.NET Web Server controls information back to the server by
Create custom controls requesting the same page.

q Browser independent rendering: When an


Using ASP.NET Web Server ASP.NET page is requested, the server
generates the corresponding HTML code for
Controls all the server controls in the page. The HTML
In the earlier days of Web development, the code generated is specific to the Web
programmers had to use HTML controls to design a browsers used by the clients. This feature
Web application because there were no other saves programmers from developing
controls available. The HTML controls do not provide different versions of the page for different
any built-in methods and events. Programmers had Web browsers.
to manually write the methods and events by using q Easily programmable model: Server
client-side scripts to create a dynamic Web page. controls are implemented as objects in
This is a time-consuming process. In addition, it is ASP.NET. This makes the server control
insecure because the client-side scripts are visible to programming model similar to the
the users when they view the source for the Web traditional object-oriented programming
page. model, making it easy to program server
ASP.NET solves this problem by providing server controls.
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 In addition to the server controls, ASP.NET
logic on the server. Server controls also provide built- provides HTML controls. Most HTML
in methods and events. This eliminates the need for controls are similar to server controls.
writing the events and methods manually. In However, there is a major difference. Unlike
server controls, HTML controls are 4. Loading the postback data: The server
processed by the Web browser. searches any data corresponding to the
control that is loaded in the data posted by
To understand the processing of the server controls the client.
in a Web page, you need to understand the 5. PreRendering: The control is updated with
sequence of their processing and how they are the changes made in it by the user. This is
rendered on a Web page. done in preparation for rendering.
6. Saving: The change in the state of the
controls between the current request and the
Processing of Server Controls on previous request of the page is saved. For
each change, the corresponding event is
a Web Page raised. For example, if the text of a textbox is
The processing of a server control depends on two changed, the new text is saved and a
situations, whether the page is requested for the first TextChanged event is raised.
time by the client or it is posted back to the Web 7. Rendering: The server creates the
server when the user interacts with the Web page. corresponding HTML tag for the control.
When a page is requested for the first time, the 8. Disposing: All cleanup tasks, such as closing
server controls are processed in the following files and database connections opened by
sequence: the control are performed.
1. Initializing: The server creates an instance of 9. Unloading: All cleanup tasks like destroying
the server control. the instances of server control are
2. Loading: The instance of the control is performed. This is the final event in the life
loaded onto the page object in which it is cycle of a server control.
defined. The following figure illustrates the processing of a
3. PreRendering: The control is updated with server control.
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. Processing of a Server Control
3. Loading control instance: The instance of
the control is loaded onto the page object in
which it is defined.
HtmlAnchor control for
In ASP.NET, Web page refers to an instance reference at the client side.
of thePage class and a Web form refers to Target Gets or sets the frame or
the Web page and all the controls on it. window in which the page
specified in the Href
property will load. The
default value is _self. As a
Types of Server Controls result the linked page will
be loaded in the same
ASP.NET provides various types of server controls. window.
These controls can be classified into the following Title Gets or sets the value of
categories: the tooltip attribute of the
q HTML Server Controls <a> tag that is displayed
q Web Server Controls when the mouse pauses
q Validation Controls over the control.
HTML Server Controls
In traditional websites, HTML controls were used to Properties of the HtmlAnchor Control
enable users to interact with the website. Developers When you click the HtmlAnchor control, the
had to write the methods and events for these ServerClick event is raised. Consider the following
controls manually to provide functionality to them. markup:
This was a very tedious task. In addition, these <a id="myAnchor1"
controls were processed by the Web browser that is href="URLLocation"
on the client-side, which does not provide the runat="server">Click here</a>
functionality for validating the user input or <a id="myAnchor2"
managing the state. OnServerClick="myFunction"
To overcome these limitations, ASP.NET provides the runat="server">Click here</a>
HTML server controls, which are processed by the The preceding markup illustrates the HTML code of
Web server and make full use of the .NET Framework two HtmlAnchor server controls with the name
utilities such as validation. Some of the common myAnchor1 and myAnchor2, as specified by the id
HTML server controls are: attribute. When myAnchor1 is clicked, the browser
q HtmlAnchor Control navigates to the new location, URLLocation, as
q HtmlInputText Control specified in the href attribute. When myAnchor2 is
q HtmlInputCheckBox Control clicked, the function, myFunction, attached to the
q HtmlInputRadioButton Control ServerClick event is invoked. The
q HtmlSelect Control OnServerClick attribute is used to attach an event
HtmlAnchor Control handler to the ServerClick event.
The HtmlAnchor control works like the HTML <a> tag HtmlInputText Control
but runs on the server. It is used to direct the user The HtmlInputText control works like the HTML
from one page to another. The following table lists <input type="text"> tag but runs on the server.
some properties of the HtmlAnchor control. The HtmlInputText server control is used to gather
information from the user. The following table lists
some properties of the HtmlInputText control.
ID Gets or sets a unique
identifier to the
HtmlAnchor control for ID Gets or sets a unique
reference at the server. identifier to the
Href Gets or sets the URL of the HtmlInputText control for
page to which the control reference at the server.
is linked. Type SetsType="Text"orType
Name Gets or sets a unique ="Password"to specify
identifier to the the mode of work.
Name Gets or sets a unique Name Gets or sets a unique
identifier to the identifier to the
HtmlInputText control for HtmlInputCheckBox
reference at the client side. control for reference at the
Size Gets or sets the width of client side.
the control. Checked Checks whether the check
MaxLength Gets or sets the value for box is selected or not.
the maximum characters Value Gets or sets the value of
that can be entered in the the HtmlInputCheckBox
textbox. control.
Value Gets or sets the value of
the textbox or password Properties of the HtmlInputCheckBox Control
box. When you select or clear a check box, the
ServerChange event is raised. The ServerChange
Properties of the HtmlInputText Control event triggers the associated event handler when the
The commonly used method of the HtmlInputText page consisting the check box is submitted to the
control is OnServerChange. The OnServerChange server. The following markup illustrates the HTML
method is invoked in response to the code for the HtmlInputCheckBox control:
ServerChange event. The ServerChange event is <input type="checkbox"
triggered when either a new text message is entered id="MyCheckBox1"
or a change is made to the existing text in the OnServerChange="FunctionCheckBox"
HtmlInputText control. The following markup runat="server">
illustrates the HTML code of two HtmlInputText The preceding markup uses an HtmlInputCheckBox
controls: control named MyCheckBox1, as specified by the id
<input type="text" id="txtName1" attribute. The OnServerChange attribute is used to
maxlength="12" runat="server"> attach an event handler to the ServerChange
<input type="text" id="txtName2" event. When the MyCheckBox1 HtmlInputCheckBox
maxlength="15" runat="server"> control is selected or cleared, the
The preceding markup illustrates the HTML code of FunctionCheckBox method attached to its
two HtmlInputText server controls with the names ServerChange event is invoked.
txtName1 and txtName2, as specified by the id HTMLInputRadioButton Control
attributes. The txtName1 can accommodate a The HtmlInputRadioButton control works as the
maximum of 12 characters whereas txtName2 can HTML <input type="radio"> tag but runs on
accommodate a maximum of 15 characters, as the server. You can use the HtmlInputRadioButton
specified by the maxlength attribute. control to implement multiple-choice questions,
HtmlInputCheckBox Control where a user can select only one option.
The HtmlInputCheckBox control works as the HTML The following table lists some properties of the
<input type="checkbox"> tag but runs on the HtmlInputRadioButton control.
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 ID Gets or sets a unique
Coffee? The answer is either yes or no. identifier to the
The following table lists some properties of the HtmlInputRadioButton
HtmlInputCheckBox control. control for reference at the
server.
Checked Gets or sets the status of
ID Gets or sets a unique the radio button. This
identifier to the property will return true if
HtmlInputCheckBox the radio button is
control for reference at the selected.
server. Name Sets the name of the
option button group. selected item.
Value Gets or sets the value of
the HtmlInputRadioButton Properties of the HtmlSelect Control
control. When an item is selected in the HtmlSelect control,
the ServerChange event is generated. The
Properties of the HtmlInputRadioButton Control following markup illustrates how to implement the
When the HtmlInputRadioButton control changes its HtmlSelect control:
state from the previous state on the server, the <select Runat="Server" size=4>
ServerChange event is generated. You can use the <option>Titanic</option>
following markup to implement the <option>The Lords of the Ring</
HtmlInputRadioButton control: option>
<input type="radio" <option>Matrix Reloaded</
id="MyRadioButton" option>
name="GroupRadio" value="Titanic" <option>Harry Potter</option>
OnServerChange="FunctionRadio" </select>
runat="server"> Titanic The preceding markup creates a list box containing
The preceding markup uses an four movie names as list items. Out of these movie
HtmlInputRadioButton control named names only one can be selected at a time.
MyRadioButton, as specified by the id attribute. Web Server Controls
The MyRadioButton HtmlInputRadioButton control Web server controls are created on the server and
belongs to a group GroupRadio as specified by the require a runat="server" attribute to work. This
name attribute. When MyRadioButton is selected attribute indicates that the element should be
or cleared, the FunctionRadio method attached to treated as a server control and will be processed at
its ServerChange event is invoked. The the server. However, unlike the HTML server controls,
OnServerChange attribute is used to attach an Web server controls do not necessarily map to any
event handler to the ServerChange event. existing HTML elements and may represent more
HtmlSelect Control complex elements. Some of the most commonly
The HtmlSelect control is same as the HTML used Web server controls are:
<select> element but it runs on the server. This q TextBox Control
control is used to create a list box. The HtmlSelect q Label Control
control is used when a user has to select an option q ListBox Control
from a list of options. The following table lists some q CheckBox and CheckBoxList Control
properties of the HtmlSelect control. q RadioButton and RadioButtonList Control
q AdRotator Control
q Calendar Control
ID Gets or sets a unique q DropDownList Control
identifier to the HtmlSelect q ImageButton Control
control for reference at the q Button Control
server. q Wizard Control
Name Gets or sets a unique q MultiView Control
identifier to the HtmlSelect q HyperLink Control
control for reference at the q FileUpload Control
client side. q XML Control
Items Gets the list of items. q Substitution Control
Multiple Specifies whether multiple TextBox Control
items can be selected. The TextBox control is used to obtain information,
SelectedIndex Gets the Index of the such as text, numbers, and dates from users in a Web
selected item. form. You can set a TextBox control as single-line,
Size Sets the number of visible password, or multi-line TextBox control. By default, a
items in the list. TextBox control is single-line that allows users to
type characters in a single line only. A password
Value Gets the value of the
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 Items Represents the collection
displays multiple lines and allows text wrapping. of list items in the ListBox
The properties of a TextBox control determine the control.
appearance of the TextBox control. The following Rows Sets the vertical size of the
table lists some properties of the TextBox control. ListBox control and takes a
value in number of rows. If
the control contains more
Text Gets and sets the text in a than the specified number
TextBox control. of items, a vertical
Height Gets and sets the height of scrollbar is displayed. If
the control. you set both the Height
Rows Allows you to set the and Rows properties, the
vertical size of the TextBox Height property takes
control and takes a value precedence.
in number of rows. If you SelectionMode Sets the number of items
set both the Height and that can be selected. To
Rows properties, the allow users to select only
Height property takes one item, you need to set
precedence. the SelectionMode
Wrap Allows you to set the word property to Single. To
wrap behavior in a multi- allow users to select
line TextBox control. The multiple items, you need
text wraps automatically if to set the
the value is set to True. SelectionMode
However, if the value is set property to Multiple. To
to False, the user has to select more than one item,
press the carriage return users can hold the or
key to move to the next key while selecting
line. the items.

Properties of the TextBox Control Properties of the ListBox Control


Label Control The items can be added to a ListBox control by using:
The Label control is used to display static text in a q Static item addition method: In this
Web form that cannot be edited by the user. The method, the items are added during the
Text property of the Label control can be set to design phase.
modify the control’s caption. The following table lists q Dynamic item addition method: In this
some properties of the Label control. method, the items are added during run
time.
CheckBox and CheckBoxList Controls
Text Gets or sets the text of the A check box provides you with independent choices
Label control. or options that you can select. You can add check
Visible Displays or hides the Label boxes to a Web form by using either the CheckBox
control. control or the CheckBoxList control. The CheckBox
control provides you with a single check box whereas
the CheckBoxList control is a collection of several
Properties of the Label Control check boxes. The choice between using the CheckBox
ListBox Control control and using the CheckBoxList control depends
The ListBox control is a collection of list items. It on the requirement. The CheckBox control provides
allows users to select one or more items from the list. more control over the layout of the check boxes on a
The following table lists some properties of the page. For instance, you can set the font and color of
ListBox control. 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 RadioButton and RadioButtonList


Controls

Properties of the CheckBox and CheckBoxList The methods for adding items to a
Controls RadioButtonList control are similar to the
methods for adding items to the ListBox
control.

AdRotator Control
Methods for adding items to a CheckBoxList The AdRotator control is used to display flashing
control are similar to the methods used to banner advertisements on Web pages. This control is
add items to the ListBox control. capable of displaying advertisements randomly.
AdRotator is one of the rich Web controls available in
RadioButton and RadioButtonList ASP.NET. The following table lists some properties of
Controls the AdRotator control.
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 AdvertisementFile Sets the path to an XML
the RadioButtonList control. The RadioButton control file that contains a list of
is a single radio button that you can work with banner advertisements to
whereas the RadioButtonList control is a collection of display. The XML file
radio buttons. Usually, you use radio buttons in a contains
group. A group of radio buttons provides a set of multiple<Ad>elements,
mutually exclusive options. You can select only one one for each
radio button in a group. advertisement that you
You can group a set of radio buttons in the following want to display.
ways: Each<Ad>element
q Place a set of RadioButton controls in a page contains
and assign them manually to a group by an<ImageUrl>element
using the GroupName property. that specifies the URL of
q Place a RadioButtonList control in a page. the image and
The radio buttons in this control are grouped an<Impressions>eleme
by default. nt that specifies weights
After you add a RadioButtonList control, you need to for each image. These
add individual radio buttons. You can do so by using weights define the relative
the Items property in the same way as you do for the probability of an image
CheckBoxList control. Similar to the CheckBox and being displayed.
CheckBoxList controls, the RadioButton control offers KeywordFilter Specifies the filter criteria
more control over the layout of the radio buttons on based on which
the page. advertisements of specific
The following table lists some properties of the categories will be
RadioButton and RadioButtonList controls. displayed on a Web page.
Target Specifies the name of the SelectionMode Specifies whether a user
Web browser window that can select a day, a week,
will display the contents of or a month. The default
the linked Web page when value of this property is
the AdRotator control is Day.
clicked. This parameter
can also take any of the Properties of the Calendar Control
following HTML frame-
DropDownList Control
related keywords:
The DropDownList control allows users to select an
item from a set of predefined items, where each item
_top: Loads the linked
is a separate object with its own properties, such as
page into the topmost
Text, Value, and Selected. You can add items to a
window
DropDownList control by using the Items property.
Unlike the ListBox control, you can select only one
_blank: Loads the linked
item at a time and the list of items remains hidden
page into a new browser
until the user clicks the drop-down button. The
window
following table lists some properties of the
DropDownList control.
_self: Loads the linked
page in the same window

_parent: Loads the Items Represents the collection


linked page in the parent of list items in the
window of the window DropDownList control.
that contains the link Width Gets or sets the width of
the DropDownList control
and takes the value in
Properties of the AdRotator Control
pixels.
Calendar Control Height Gets or sets the vertical
The Calendar control is used to display a one-month
size of the DropDownList
calendar. Users can use this control to view dates or
control and takes the
select a specific day, week, or month. Calendar is one
value in pixels.
of the rich web controls available in ASP.NET. The
following table lists some properties of the Calendar
control. Properties of the DropDownList Control
ImageButton Control
The ImageButton control is similar to a button
DayNameFormat Specifies the name format control but unlike the button control, it can also
of the days of a week. display an image. The ImageButton control has a few
properties that are identical to the Image control. It
VisibleDate Specifies the month to be
inherits these properties from the Image control. It
displayed in the Calendar
also has a few properties that are identical to the
control. This property is
Button control. The following table lists some
updated after the
properties of the ImageButton control.
VisibleMonthChanged
event is raised.
FirstDayOfWeek Specifies the day of the
week to be displayed in AlternativeText Gets or sets the alternative
the first column of the text that is displayed in
Calendar control. the Image control when a
Web browser does not
SelectedDate Represents the date
support images.
selected in the Calendar
control. CausesValidation Specifies whether
validation will be
performed when the graphic button. It is used
Button control is clicked. If for presenting a rich
the value is False, the form button appearance.
submitted by the button is
not validated. The default Types of Button Control
value of this property is The following table lists some common properties of
True. all the three Button controls.
CommandArgument Passes a value to the
Command event along
with the associated ID Gets or sets the unique
command name when the identifier assigned to the
button is clicked. button control.
ImageAlign Gets or sets the alignment Text Gets or sets the text that is
of the image. The possible displayed on the Button
values for this property are control.
Top, Left, Right, Middle, PostBackURL Gets or sets the URL of the
Bottom, AbsBottom,
Web page to which the
AbsMiddle, Baseline,
data is posted.
Middle, NotSet, and
Enabled Gets or sets a value
TextTop.
indicating whether the
ImageURL Specifies the URL of the
button control is enabled.
image to be displayed.
ToolTip Gets or sets the text
CommandName Gets or sets the command
displayed when the mouse
name associated with the
pointer hovers over the
Button control that is
button control.
passed to the Command
event.
Common Properties of Button Controls
Properties of the ImageButton Control Wizard Control
A wizard is a group of forms used to accomplish a
Button Control particular task. ASP.NET provides a Wizard control
The Button control is generally used to submit the
that is used to enable a user to perform a task step-
data that is entered by a user as an input in a Web
by-step or to collect user input related to the task. A
application. When the user clicks a button control on
Wizard control contains a series of forms that
a Web page, the page is posted back to the Web
describe the whole task. It provides an easy
server, and the click event is triggered. ASP.NET
mechanism that allows you to build steps, add a new
provides three types of button controls; Button,
step, or reorder the steps.
LinkButton, and ImageButton.
With the help of the Wizard control, a user can move
The following table describes how these buttons
between steps, which create a simple user experience
appear on a Web page.
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
Button Rendered as a standard performs the various steps of the wizard.
command button that is The following table lists some properties of the
rendered as an HTML Wizard control.
input element.
LinkButton Rendered as a hyperlink
on a Web page. It contains ID Gets or sets the unique
client-side script that identifier assigned to the
causes the form to be Wizard control.
posted back to the server.
WizardSteps Gets a collection of all
ImageButton Rendered in the form of a theWizardStepBaseobj
ects that are defined for lists some properties of the HyperLink control.
the control.
EnableViewState Gets or sets a value
indicating whether the Text Specifies the text displayed
Wizard control persists its as a hyperlink on a Web
view state, and the view browser.
state of any child controls ImageUrl Creates a graphical link
it contains. when you set the URL
Enabled Gets or sets a value property of the control to
indicating whether the a .gif, .jpg, or other Web
Wizard control is enabled. graphic file.
ToolTip Gets or sets the text NavigateUrl Specifies the URL of the
displayed when the mouse page to which you want to
pointer hovers over the link.
Wizard control. Target Indicates the ID of a target
window or frame in which
Properties of the Wizard Control you want to display as a
MultiView Control linked page.
A Multiview control is a set of View controls. These
View controls, in turn, contain child controls such as Properties of the HyperLink Control
buttons and textboxes. A Web application FileUpload Control
dynamically displays a View control to a user based The FileUpload control enables users to send a file
on certain criteria such as user identity, preferences, from their computer to the server. It is useful for
or information passed in a query string parameter. It allowing users to upload various types of files such as
is used to present alternate views of information. pictures, text files, or other files. The files that are to
The following table lists some properties of the be uploaded are submitted to the server as part of
MultiView control. 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.
ID Gets or sets the unique It also displays a Browse button that that can be used
identifier assigned to the to browse for the file. The following table lists some
MultiView control. properties of the FileUpload control.
Views Gets the collection of View
controls in the MultiView
control. Filename Gets the name of the file
Visible Gets or sets a value that on the client computer to
indicates whether a be uploaded.
MultiView control is HasFile Gets a value that indicates
rendered as UI on the whether the control
page. contains a file.

Properties of the MultiView Control Properties of the FileUpload Control


HyperLink Control XML Control
A HyperLink control is used to link all the Web pages The XML control is used to write the output of an
in a Web application. By using a HyperLink control, a XML document on a Web page. The XML output
user can easily move between the Web pages. It is appears at the location of the control on the Web
rendered as a clickable text or an image on a Web page. The following table lists some properties of the
page. A HyperLink control does not raise an event in XML control.
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 Document Gets or sets the XML
document to be displayed. q RequiredFieldValidator Control
DocumentContent Sets a string that contains q RegularExpressionValidator Control
the XML document to q CompareValidator Control
display. q RangeValidator Control
DocumentSource Gets or sets the path of q ValidationSummary Control
the XML document whose q CustomValidator Control
output is to be displayed. RequiredFieldValidator Control
The RequiredFieldValidator control is used to check
Properties of the XML Control whether a server control, added to a Web form, has a
value or not. For example, you can use this validation
Substitution Control
control to check whether a user has entered any
The Substitution control is used on the Web pages
value in the password textbox.
that are configured to be cached. It allows you to
create areas on the page that can be updated The following table lists some properties of the
dynamically and integrated into the cached page. RequiredFieldValidator control.
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 ControlToValidate Specifies the ID of the
selected portions of the page on each request. For control to be validated.
updating the selected portions in a cached page, you ErrorMessage Specifies the error
can place the Substitution control in the cached page message to be displayed
and insert dynamic content into the Substitution when the validation
control. The following table lists some properties of condition fails.
the Substitution control. Text Specifies the error
message displayed by the
control.
MethodName Gets or sets the name of
the method to be invoked Properties of the RequiredFieldValidator Control
when the Substitution RegularExpressionValidator Control
control executes. The RegularExpressionValidator control is used to
Site Gets information about check whether the server control added to a Web
the container that hosts form matches with a specific regular expression or
the current control when not. The regular expression can be the format of a
rendered on a design telephone number or an e-mail address.
surface. The following table lists some properties of the
RegularExpressionValidator control.
Properties of the Substitution Control
Validation Controls
Validation is the process of checking something ControlToValidate Specifies the ID of the
against a certain criterion. There are various control to be validated.
situations where validation is required. One such ErrorMessage Specifies the error
situation is when a user fills out a form for which the message to be displayed
minimum age required is 18 years. In such a when the validation
situation, when the user submits the form, the age condition fails.
must be validated against the criterion. If the ValidationExpressio Specifies the regular
criterion is satisfied, the form is accepted, otherwise it n expression, when
is rejected. Such type of validation can be performing validation.
implemented on a website by using the ASP.NET
validation controls. Properties of the RegularExpressionValidator
ASP.NET provides the following validation controls Control
that can be attached to input controls to validate the
CompareValidator Control
values that are entered by the user:
The CompareValidator control is used to compare
the entered value with another value. The other value HeadText Gets or sets the text to be
can be a number or a value entered into another displayed at the top of the
control. The following table lists some properties of summary.
the CompareValidator control. ShowMessageBox Displays the error
message in a pop-up
message box when the
ControlToCompare Specifies the ID of the value of this property is
control that will be used to True.
compare values. ShowSummary Enables or disables the
ControlToValidate Specifies the ID of the summary of error
control to be validated. messages.
ErrorMessage Specifies the error
message to be displayed Properties of the ValidationSummary Control
when the validation
condition fails.
CustomValidator Control
The CustomValidator control is used to perform user-
ValueToCompare Specifies the ID of the defined validations that cannot be performed by
control to be compared. standard validation controls. The following table lists
some properties of the CustomValidator control.
Properties of the CompareValidator Control
RangeValidator Control
The RangeValidator control is used to check whether ControlToValidate Specifies the ID of the
the value of a particular Web form field is within the control that is to be
range specified by the RangeValidator control’s validated.
MinimumValue and the MaximumValue properties. ErrorMessage Specifies the error
The MinimumValue and MaximumValue properties message to be displayed
can contain dates, numbers, currency amounts, or when validation condition
strings. fails.
The following table lists some properties of the
RangeValidator control. Properties of the CustomValidator Control

ControlToValidate Specifies the ID of the Server Control Events


control to be validated.
ErrorMessage Specifies the error Every server control has some events associated with
message to be displayed it. An event is a message that contains details about
when the validation the user action, such as the cause of the event and
condition fails. the control on which the event occurred.
When a user interacts with a server control, its
MaximumValue Specifies the maximum
corresponding event is invoked and the code written
value.
on the event is executed. For example, when a user
MinimumValue Specifies the minimum
clicks a button, the Click event of the button
value.
control is invoked and the code written on the event
is executed.
Properties of the RangeValidator Control Most of the ASP.NET events pass the following two
ValidationSummary Control arguments:
The ValidationSummary control is used to summarize q Sender Object: This is the first argument and
all errors and display the error list at a location is an instance of System.Object class. This
specified by the user on the Web page. The following represents the control that raised the event.
table lists some properties of the ValidationSummary q Event Object: This is an instance of
control. System.EventArgs class. This contains
information about the event that is In addition to the default event, each control exposes
generated. other events, called non-default events. For example,
ASP.NET Server Control Event Model the Command event is a non-default event of a
Button control. Non-default events are handled by
In traditional client-based Web applications, the
non-default event handlers.
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 Using the AutoEventWireup Capabilities
server. ASP.NET supports two types of events: of a Web Form
q Postback events: In postback events, a Web ASP.NET provides the event wire-up capability to a
page is sent back to the server for Web form using which events can be automatically
processing. When a user clicks a button, the associated with event-handling procedures having
click event of the button causes a Web page well-defined names and signatures. Event wire-ups
to be posted back to the server. When a Web determine the procedures that need to be called
page is posted back to the server, the server when objects raise events. To enable the event wire-
processes the page and sends it back to the up capability of a Web form, you need to set the
user. AutoEventWireUp attribute of the .aspx page to
q Nonpostback events: In nonpostback true. By default, the AutoEventWireUp attribute of
events, a Web page does not immediately the .aspx pages is set to true, as shown in the
cause a postback. For example, change following markup:
events in HTML server controls and Web <%@ Page Language="C#"
server controls, such as the TextBox control, AutoEventWireup="true"%>
are captured but do not immediately cause a The AutoEventWireup attribute can have two
post. These events are cached by the control values, true or false. When the value is set to true, the
until the next time a post occurs. When a ASP.NET runtime does not require events to specify
post occurs, the page is processed on the event handlers, such as Page_Load and Page_Init.
server and all the pending events are raised This means that in Visual C#, you do not have to
and processed. initialize and create the delegate structures. However,
Event Handlers when the value is set to false, the events need to
When an event is raised, the corresponding event specify event handlers explicitly.
handler is searched and the code written in the event Creating Centralized Event-Handlers
handler is executed. If you want your application to There are situations when you want to associate the
perform some action when an event is raised, you same event handler with different controls. Such
need to add an event handler for that event. situations can be handled by using a centralized
The various approaches that can be used to work event handler. A centralized event handler eliminates
with event handlers include: the need for declaring separate event handlers for
q Using default events different ASP.NET objects. You can create one
q Using non-default events centralized event handler that can perform
q Using the AutoEventWireup capabilities of a appropriate action at runtime.
Web form When you create a single event handler to respond
q Creating centralized event-handlers to multiple events that should trigger different
Using Default Events actions, you need to determine which event invoked
Every control exposes an event that is designated as the event handler. To determine which control
the default event. A default event is an event that is caused the event, you need to perform the following
most commonly associated with a control. For steps:
example, the Click event is the default event of a a. Declare a variable in the event handler with a
Button control. Default events are handled by a type that matches the control that raised the
default event handler. event.
b. Assign the sender argument of the event
handler to the variable, casting it to the
appropriate type.
Using Non-Default Events c. Examine the ID property of the variable to
determine which object raised the event. Button1_Command is associated with both the
Consider a Web page containing the following button controls. You need to write the event handler
markup: in such a manner that it will determine which control
<asp:Button ID="Button1" has caused the event. The following code snippet
runat="server" Text="Button1" illustrates how to write such an event handler:
onclick="Button1_Click" /> protected void
<asp:Button ID="Button2" Button1_Command(object
runat="server" Text="Button2" sender, CommandEventArgs e)
onclick="Button1_Click" /> {
In the preceding example, the event handler switch (e.CommandName)
Button1_Click is associated with both the button {
controls. You need to write the event handler in such case "Prev": Response
a manner that it will determine which control has .Write("You clicked the Prev
caused the event. The following code snippet button");
illustrates how to write such an event handler: break;
protected void Button1_Click case "Next": Response
(object sender, EventArgs e) .Write("You clicked the Next
{ button");
Button mybtn = (Button) break;
sender; }
switch (mybtn.ID)
{ }
case "Button1": Respo
nse.write("You have clicked
Button Loading Controls Dynamically
1");
There are situations where you need to add controls
break;
dynamically to a Web page. Consider a situation
case "Button2": Respo where you are designing a registration form for an
nse.write ("You have clicked insurance company. The form has a section where
Button the persons seeking insurance have to enter the
2"); name and age of their family members. The number
break; 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
The preceding code works well to define a situation can be handled by adding the controls at
centralized event handler for the Click event of the run time. Adding controls to a Web page at run time
Button control. However, if you need to create a makes a website flexible, interactive, and user-
centralized event handler for the Command event of friendly.
two button controls, the preceding code will not
When adding a control dynamically to a Web page,
work because the Command event passes a different
you need to place them in a container so as to make
set of arguments to its event handler.
the Web page well-structured. Two controls that act
Consider a Web page containing the following as containers when adding controls dynamically are:
markup:
q PlaceHolder
<asp:Button ID="Button1" q Panel
runat="server" Text="Button1"
CommandName="Prev" PlaceHolder
onCommand="Button1_Command" /> A PlaceHolder control is used as a container that is
<asp:Button ID="Button2" not visible in a Web application. It is added to a Web
runat="server" Text="Button2" page to hold other controls on the page. The
CommandName="Next" PlaceHolder control reserves a place in the structure
onCommand="Button1_Command" /> of the Web page for other controls that are added
In the preceding example, the event handler dynamically. The following markup adds a
PlaceHolder control to a Web page: dynamically at run time for the controls that are
<asp:PlaceHolder created dynamically. For example, to create a Button
id="PlaceHolder1" runat="server"/ control dynamically and associate an event handler
> to it at run time, you need to write the following
The following code snippet shows how to add a code in the .cs file of a Web page:
Button control and a literal in a PlaceHolder control: protected void Page_Load(object
void Page_Load(object sender, EventArgs e)
sender, EventArgs e) {
{ Button btn=new Button();
//creates an instance of a button btn.Text = "Click Me";
control. form1.Controls.Add(btn);//
Button Button1 = new Button(); Adding button to the form
Button1.Text = "Button btn.Click += new EventHandler
1"; (btn_Click);
// Adds the button control in }
a PlaceHolder control. protected void btn_Click(object
PlaceHolder1.Controls.Add sender, EventArgs e)
(Button1); {
// creates an instance of Response.Write("Hello");
a literal control. }
Literal Literal1 = new
Literal();
Literal1.Text = "
Dynamically loaded controls";
// Adds the literal control in
a PlaceHolder control. Implementing Generic Handler
PlaceHolder1.Controls.Add The .aspx files are the default HTTP handler for all
(Literal1); ASP.NET pages. However, there may be situations
} wherein you want that instead of .aspx files the
Panel request is handled by generic handlers. For example,
A Panel control is also used as a container for other you have created the ProductDetails page in which
controls. The only difference between a PlaceHolder you are displaying the details of a product. This page
and a Panel control is that a Panel control renders div has a button control, clicking on which a page having
tag around all the child controls in the panel where the image of the product is displayed. Instead of
as a PlaceHolder will only render its child controls. using a Web page to display an image, you can use a
This makes panels useful when you want to apply a generic handler.
css class to a container. The following code snippet A generic handler can be used when you want to
shows how to add a Label control to a Panel control: display the output of a text file, XML file, or display
//Creating an instance of a Label an image. This is because a generic handler uses
control fewer resources as compared to Web pages.
Label TestLabel = new Label(); Therefore, it enhances the performance of your Web
TestLabel.Text = "testlabel"; application.
//Adding the Label control to The generic handler provides a class that implements
a Panel control the IHttpHandler interface. The class provides the
Panel1.Controls.Add(TestLabel); ProcessRequest method and the IsReusable
property. The ProcessRequest method is
responsible for processing individual HTTP requests.
Adding Event Handlers This method is used to write the code that produces
the output for the handler. The IsReusable
Dynamically property specifies whether the
An event handler for a control is usually created at IHttpHandlerFactory object can put the handler
design time. However, it can also be created in a pool and reuse it to increase performance. The
IHttpHandlerFactory object is the object that Response.Write
calls the appropriate handler. (“MyHandler.ashx”);
Consider the following example:
<%@ WebHandler Language="C#"
Class="SimpleHandler" %>
Creating Custom Controls
using System; Developers use various Web server controls to
using System.Web; enable users to interact with the Web pages. There
might be a situation where you need some
public class functionality that is not provided by the in-built Web
SimpleHandler : IHttpHandler server controls or you might want to reuse the same
{ set of controls, which you have added to one Web
public void ProcessRequest page, on another Web page. For example, you have
(HttpContext context) created a customized Login page with two labels, two
{ textboxes, and one button to enable the user to log
HttpResponse on to a website. You want to reuse the same Login
r = context.Response; //Create page in all other Web applications. In such a case,
and initialize an you can create a custom control with the required
// customizations and then reuse it in as many Web
HttpResponse object applications as you want.
r.ContentType = "image/ Custom controls are controls that are created by
png"; //Set the Content type combining two or more controls and can be reused
for the in multiple Web applications. You can create the
//HttpResponse object following types of custom controls:
//Write the image q Web User Controls
r.WriteFile(@"~\images q Web Custom Controls
\4.JPG"); q Templated User Controls
} Web User Controls
Web user controls are containers that can be created
public bool IsReusable
by combining one or more Web server controls. After
{
creating a Web user control, you can treat it as a unit
get {return true;}
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
In the preceding example, the generic handler is used
and code.
to display an image.
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:
q The file name extension of a user control
is .ascx.
q A user control contains the @Control
directive instead of the @Page directive.
You can navigate to a generic handler by q User controls cannot run as stand-alone files.
using the Respose.redirect() method. They need to be added to ASP.NET pages to
For example, you want that on clicking the make them work.
Show Picture button on the default.aspx q User controls do not have <html>, <body>,
page, the generic handler MyHandler.ashx or <form> elements in them. These
is displayed in the browser. For this, you elements must be present on the Web page
need to write the following code snippet in that is hosting these controls.
the event handler for the Click event of A Web user control on a Web page must be
the button: registered before it is used. You can register a Web
user control by using the @Register directive as
illustrated in the following markup: of your requirements but lacks some
<%@Register TagPrefix="ABC" features. In such a situation, you can
TagName="Header" customize the existing control by defining a
Src="mycontrol.ascx" %> class that derives from the class
The preceding markup contains the following three corresponding to the existing control. You
attributes: can then add new properties and override
q TagPrefix: Specifies the alias to associate existing methods and events of the base
with the namespace of the user control. class to modify the functionality of the
q TagName: Specifies the alias to associate control.
with the class of the user control. q Controls that are not similar to any
q Src: Specifies the virtual path of the file existing control: This type of control is
containing the user control. created when none of the existing controls
After registering the control, you can include it on meets your requirement. In such a case, you
the page by writing the markup as shown in the can create a custom control by deriving from
following example: the System.Web.UI.Control or
<ABC:Header ID=mycontrol1 System.Web.UI.WebControl class,
runat="Server"/> adding public properties to this class, and
overriding existing methods of the base
class.

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
Templated User Controls
code to create a new control. These controls are A templated user control allows developers to
known as Web custom controls. modify the layout of its user interface by defining
Web custom controls provide an approach to reuse their own templates. Templated user controls allow
logic in an ASP.NET application. Web custom controls the separation of control data from its presentation.
are written as classes. Web custom controls are They do not have a user interface; instead they
written entirely by using managed code and have no simply implement a naming container and include a
markup files. These controls are compiled into an class whose properties and methods are accessible to
assembly before the deployment of the application. the host page. The user interface of the control is
Web custom controls are of the following three defined at the time of designing the Web page on
types: which the templated control is to be used.
q Controls that combine two or more To create a templated user control, you need to
existing controls: This type of control is perform the following steps:
known as a composite control and can be a. Add an ASP.NET PlaceHolder control in
created by defining a class that derives from the .ascx file of the user control to specify
the System.Web.UI.Control or the place where you want the template to
System.Web.UI.WebControl class and appear.
overrides the CreateChildControls b. Implement a property of type ITemplate in
method of the base class. In addition, the the code of the user control.
class can expose public properties that will c. Define a server control class that implements
be accessible to the pages that use this the INamingContainer interface as a
control. container in which an instance of the
q Controls that extend the functionality of template can be created. This class is called
an existing control: This type of control is the template’s naming container.
created when an existing control meets most d. Apply the TemplateContainer attribute
to the property that implements ITemplate d. Loading the postback data
and pass the type of the template’s naming e. PreRendering
container as the argument to the attribute’s f. Saving
constructor. g. Rendering
e. For each data item, write code in the h. Disposing
Page_Init event handler of the user i. Unloading
control to: q The various types of server controls provided
a. Create an instance of the naming container by ASP.NET can be classified into the
class. following categories:
b. Create an instance of the template in the HTML server Controls
naming container. Web server Controls
c. Add the naming container instance to the Validation Controls
Controls property of the PlaceHolder server User Controls
control. q 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.
q The two arguments passed by all events in
Repeater, DataList, and GridView Web ASP.NET are:
server controls are the examples of built-in Sender Object
Templated controls. These controls will be Event Object
discussed in detail later in the course. q The two types of events in ASP.NET server
control event model are:
Postback events
Nonpostback events
q The two controls that act as container when
adding controls dynamically are:
Summary PlaceHolder
Panel
In this chapter, you learned that: q The two types of custom controls are:
q Server controls are the fundamental building Web User Controls
blocks that are specifically designed to work Web Custom Controls
with Web forms in an ASP.NET application. Template User Controls
q Server controls provide:
Automatic state maintenance.
Browser independent rendering. Reference Reading
Easily programmable model.
q The sequence in which a server control is Using ASP.NET Web Server Controls
processed when the page is requested for
the first time is:
a. Initializing Chris Hart, John http://
b. Loading Kauffman, Beginning msdn2.microsoft.com/en-
c. PreRendering ASP.NET.3.5 us/library/zsyt68f1.aspx
d. Saving
e. Rendering http://
f. Disposing msdn2.microsoft.com/en-
g. Unloading us/library/k26w4zzx.aspx
q The sequence in which a server control is
processed when the Web page is posted
back to the Web browser is:
Creating Custom Controls
a. Initializing
b. Loading view state
c. Loading control instance Professional Web Parts http://
and Custom Controls with www.codersource.net/
ASP.NET 3.5 by Peter published/view/290/
Vogel Developing .NET creating_custom_controls_i
Custom Controls and n_asp_net.aspx
Designers Using C# by
James Henry http://
msdn.microsoft.com/en-
us/library/ms837926.aspx
Using Inline Styles
Chapter 3 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
Introducing Styles, Themes, and to be implemented. Inline styles are used when you
Master Pages want to apply one-time formatting to an HTML
element.
You can create a website by creating several Web To use inline styles in a Web page, you need to use
pages connected to each other. However, a the style attribute in the relevant HTML tag. For
professional website requires much more than example, if you want to display the text of a
creating individual Web pages and connecting them. paragraph in italicized Arial font, you have to define
The look and feel of the text on a professional the style for the tag as shown in the following
website should be consistent across all the Web markup:
pages. All the information and controls should <p style="font-family:arial;font-
appear in a standard consistent format across all the style:italic">
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. </p>
This chapter discusses how to work with styles, and In the preceding markup, the style applied to the
themes. In addition, it discusses how to define a <p> tag will be applied to all text written within the
standard layout for all the Web pages on a website <p> </p> tag in the preceding example only.
by using master pages.

Objectives Using an Embedded Style Sheet


In this chapter, you will learn to: An embedded style sheet is a group of styles that are
Work with styles defined by using the <style> tag. This tag needs to
Work with themes be placed within the <head> </head> tag on your
Work with master pages Web page. The embedded style sheet is used when
you want to apply a unique style to the various
elements on a Web page.
Working with Styles The embedded style sheet enables you to define all
the styles for a Web page at one place. This reduces
The look and feel of a Web page depends upon the the time required to design a Web page because you
appearance and arrangement of the HTML elements need not define the properties for the tags
contained in it. Therefore, you need to format the individually. You can define the properties for the
HTML elements contained in your Web page to make desired elements once in the embedded style sheet
it look attractive. Formatting each HTML element and the properties will be implemented to all the
individually will be a tedious and complex task. In elements throughout your Web page.
addition, it does not bring about consistency in the For example, consider the following markup:
appearance of all the Web pages on the website. <html> <head>
Styles provide a solution to this problem by enabling <title>
a programmer to apply consistent formatting across An Embedded Style
the entire website. </title>
Styles are used to define a set of formatting options, <style type="text/css">
which can be reused to format different HTML h1 { font-
elements on a single or multiple Web pages. You can style:italic;background:yellow;co
define styles in any of the following ways: lor:red }
q Using Inline Styles p { font-style:bold;color:blue}
q Using an Embedded Style Sheet </style>
q Using an External (Linked) Style Sheet </head>
<body> implemented. This can be done by using the <link>
<h1> An Embedded Style </h1> tag. The link> tag should be defined within the
<p> Embedded style sheet is <head> element of the HTML document. The
a part of HTML document. following markup shows how to link an external style
</p> sheet to an HTML document by using the <link>
</body> tag:
</html> <head>
In the preceding markup, the <style> tag is used to <link rel=stylesheet
define an embedded style sheet. The <style> tag href="style.css" type="text/css">
defines the properties for the <h1> and tag. All the </head>
<h1> and tags defined within the Web page will In the preceding markup,
inherit the style defined in the <style> tag. 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
Using an External (Linked) Style the style definition, and type="text/css" signifies
Sheet that it refers to a .css file for picking up the style
definitions.
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 To apply generic styles created in an
for individual elements or generic styles that can be external style sheet to an element, you
applied to any element. For example, you can create need to include the class=<name of
a stylesheet by the name style.css containing the the style>" or cssClass="<name of
style definitions for the <h1> tag, as shown in the the style>" attribute in the element.
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> Working with Themes
tags. You can also create generic styles, as shown in The style sheet rules are limited to a fixed set of style
the following code snippet: attributes, such as fonts, borders, and foreground
.heading and background colors. These rules cannot control
{ other aspects of ASP.NET controls, such as organizing
font-weight: bold; items into rows and columns in the CheckBoxList
font-size: large; control, specifying graphics for a TreeView control,
color: green; and specifying the template layout of a GridView
font- control. This gap can be filled by using the ASP.NET
family: Verdana, Arial, Sans- themes.
Serif; ASP.NET themes are a collection of properties that
} enable you to define the appearance of Web pages
The preceding style can be applied to any element and controls on your website. A theme can include
on the Web page. skin files, cascading style sheet files (.css files), and
After the .css file is created, it has to be linked with graphics. By applying a theme, you can give Web
HTML documents on which the styles are to be pages a consistent appearance across your website.
theme settings are applied to all the Web pages on
the website.
Creating a Theme Applying a Theme to a Web Page
You can use a theme in Web applications by creating To apply a theme to a particular Web page, you need
a skin file and attaching it to the Web pages on to bind the theme at the page level. If you bind the
which you want to apply the theme. Skin files are theme at the page level, the styles and skins are only
used to define the property settings for ASP.NET applied to that Web page and its controls. To bind a
Web server controls. Generally, skin files are created theme at the page level, you need to set the Theme
and stored in a theme folder. This theme folder is attribute of the @Page directive. For example, the
placed inside the folder named App_Themes. All the following @Page directive specifies that the theme,
themes in a Web application are placed inside the MyTheme, is applied to the Web page:
App_Themes folder. This folder is placed inside the <%@Page Language="C#"
top-level directory of your Web application. AutoEventWireup="true" CodeFile=
For example, you can create a folder named "Default.aspx.cs"
Mytheme for your Web application named MyApp. Inherits="_Default"
This theme folder will be placed inside the MyApp Theme="MyTheme" %>
\App_Themes folder and contains the skin file(s) for If you have defined settings for the control locally as
the theme. well as in the theme, the settings defined in the
You can define multiple themes for your Web theme override the local control settings. This
application. Each theme in a Web application can be strategy enables the theme to create a consistent
defined in a separate folder inside the App_Themes look across all the Web pages, even if you have set
folder. However, you can apply only one theme on a the control properties locally.
given page at a time. However, if you have used a stylesheet theme, the
Consider a scenario wherein you want to create a local page settings override the settings defined in
skin file for providing consistent appearance to all the stylesheet theme. You can use stylesheet theme if
the button controls in your Web page. For this, you you want the theme to be applied only to those
want to specify the ForeColor and BackColor controls whose settings have not explicitly been
properties of the button controls. To set the defined at the page level.
ForeColor and BackColor properties of the button To apply a stylesheet theme to a Web page, you
controls, you need to type the following markup in need to set the StyleSheetTheme attribute of the
the skin file: @Page directive as shown in the following directive:
<asp:Button runat="server" <%@Page Language="C#"
ForeColor="White" AutoEventWireup="true"
BackColor="Orange"/> CodeFile="Default.aspx.cs"
The runat="server" attribute is mandatory. Inherits="_Default"
However, other attributes are optional and are used StyleSheetTheme="MyTheme" %>
according to the requirement. If you do not want the theme property to be applied
You can create multiple skin files in a theme directory to a particular control, you can set the
or place all the control tags in a single skin file. EnableTheming property of that control on the
ASP.NET treats all the skin files in a theme directory Web page to false, as shown in the following
as part of the same theme definition. markup:
<asp:Button ID="Button1"
runat="server" ... EnableTheming=
"false" />
In the preceding markup, no theme will be applied to
Applying a Theme the button control, Button1. However, the settings
defined in the theme will still be applied to other
You can apply a theme either to a particular Web button controls, whose EnableTheming property is
page or to all the Web pages on a website. If a theme not set to false.
is applied to a particular Web page, the theme
settings are applied only to that Web page. However,
Applying Themes Dynamically
In addition to applying a theme at the design time,
if you apply the theme to the entire website, the
you can apply a theme dynamically. To apply a
theme dynamically, you need to set the be avoided by using a named skin. A named skin can
Page.Theme or Page.StyleSheetTheme property be created by supplying the SkinID attribute. The
in your code. These properties must be set in the following markup is used to create multiple skins for
Page_PreInit event. For example, you have a button control:
created a skin file, SkinFile.skin, in the MyTheme <asp:Button runat="server"
folder. To set this theme dynamically, you need to ForeColor="White"
write the following code snippet: BackColor="Orange"/>
protected void Page_PreInit <asp:Button runat="server"
(object sender, EventArgs e) ForeColor="White"
{ BackColor="Green"
Page.Theme = "MyTheme"; / SkinID="AlternateSkin"/>
/name of the folder in which you In the preceding markup, the first is the default skin
//have whereas the second with the SkinID attribute is
stored the skin file. known as the named skin. Default skins are applied
} automatically whereas named skins can be applied to
Similarly, you can set the SkinID property of a a control by setting the SkinID attribute of the
control dynamically to attach it to a different named control, as shown in the following code-snippet:
skin. <asp:Button ID="Button1"
Applying a Theme to a Website runat="server"
To apply the theme to all the Web pages on a SkinID="AlternateSkin" />
website, you need to bind the theme at the website In the preceding example, the named skin,
level. If you bind the theme at the website level, the AlternateSkin, is applied to the button control.
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 Working with Master Pages
file, as shown in the following markup:
<configuration> A website contains multiple Web pages connected to
<system.web> each other. There are certain components that need
<pages theme="MyTheme"> to be present across all the Web pages on the
... website. For example, there could be a company logo
</pages> and a navigation bar that need to appear on each
</system.web> page of the website. The placement and appearance
</configuration> 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
Creating Multiple Skins individually. You also need to make sure that the
logo and the navigation bar are placed at the same
Skin files standardize the look and feel of controls position on all the pages to maintain a consistent
across all the Web pages on a website. However, look and feel. Moreover, any changes in the logo or
there may be situations where you want multiple navigation bar at a later stage will require you to
occurrences of a control to appear differently on the make changes on each page of the website. This is a
same Web page. For example, you can have many complex and time-consuming process of creating
labels on your Web page. Each label can look Web pages. This process can be simplified and made
different depending on whether they are being used quicker by using master pages.
for headings or body text. ASP.NET allows you to
ASP.NET provides you with the master pages feature.
create multiple settings for the same control by using
This feature enables you to create a page layout that
multiple skins.
you can use with selected or all Web pages on your
When you create more than one theme for the same website. Master pages are used to create a consistent
control, ASP.NET generates an error stating that a look and feel for your website.
control can have a single default skin. This error can
Master pages are similar to ordinary ASP.NET pages
and can contain static text, HTML elements, and Master1.master page. The path for the master
server controls. The file extension of master pages page starts with ~/. It specifies the root website
is .master. You cannot view master pages directly on folder. If you directly specify the master page
a browser. In order to view master pages on a filename without using ~/, ASP.NET checks a
browser, they must be used by other Web pages, predetermined subfolder named MasterPages for the
known as content pages. Master pages define the master page. If you have not created the folder or
structure and common ingredients of the content the master page is not found in that folder, ASP.NET
pages. searches the root website folder for the master page.
In addition to the MasterPageFile attribute, the
@Page directive of the content page contains
Creating a Master Page another attribute, Title. The master page file
contains the <Title> tag within the <Head> tag. If
The ordinary .aspx page in ASP.NET contains the
a title is specified in the master page, it will also be
@Page directive. However, the master page in
displayed in the content page because the content
ASP.NET replaces the @Page directive with a special
page cannot modify the contents of the master page.
@Master directive, as shown in the following
However, the title specified in the master page can
markup:
be overridden in the content page by the using the
<%@Master Language="C#"
Title attribute.
CodeFile="MyMaster.master.cs"
The source code of the content page is different from
Inherits="MasterPage" %>
that of a normal page. This is due to the fact that the
In addition to the @Master directive, the master
content page cannot define anything that is already
page contains the following elements:
defined in the master page such as the <head>
q HTML or ASP.NET Elements: You can use
section, the root <html> element, and the <body>
any HTML or ASP.NET element in your
element. It can only supply a Content tag that
master page. For example, you can use an
corresponds to the ContentPlaceHolder in the
HTML table to define the layout, static text to
master page. The Content tag is the place where
display the copyright information, an
you can insert the content for the content page.
element to display the company logo, and
The following figure shows how the place holder
ASP.NET server controls to create navigation
content for the master page is supplied by the
for your website on the master page.
content page.
q 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 Content Page Supplying the Placeholder Content
of the content page. This attribute points to the to the Master Page
master page to be used with the content page, as In the preceding figure, the content page is
shown in the following markup: supplying the content for the content placeholders in
<%@Page Language="C#" the master file. The content placeholders in the
MasterPageFile="~/Master1.master" content page must have the same ID as that of the
Title="Content Page"%> content placeholders in the master page.
In the preceding markup, the MasterPageFile
attribute binds the content page to the
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.
You can also connect a content page to a One way to implement this is by adding a public
master page at run time. For this, you need property to the master page class. This property,
to write the following code within the when set to false, automatically hides the navigation
Page_PreInitevent handler: controls. Such a property can be added to the master
page class by writing the following code snippet:
Page.MasterPageFile = "~/ public partial class
MasterPage.Master"; MyMasterPage : System.Web.UI.Mast
erPage
{
public bool ShowNavigation
Creating Nested Master Pages {
get
Master pages are used to standardize the look and {
feel of all the Web pages on a website. However, return
sometimes it is required that some of the Web pages TreeView1.Visible;
on a website should follow certain standard features }
in addition to the features provided by the master set
pages. In such situations, you can implement the {
nested master pages. TreeView1.Visible = v
Consider an example wherein a website is using a alue;
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 The scope of the preceding property is declared as
header and the TreeView control provided by the public so that it can be accessed by other classes.
master page. This can be implemented by using a This property cannot be directly accessed by the
nested master page. content pages. To access this property, the content
Similar to master pages, the extension of the nested pages have to use the built-in Page.Master
master page file is .master. Like any content page, a property. However, you cannot access the
nested master page contains the <Content> ShowNavigation property directly by using the
controls that are mapped to the Page.Master.ShowNavigation statement. This is
<ContentPlaceHolder> controls on a master because the Page.Master property does not have
page. In addition, a nested master page contains any information about the custom properties that
content placeholders of its own to display the have been added in derived master page class. To
content supplied by its own content pages. 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
Interacting with a Master Page snippet:
Programmatically protected void btnHide_Click
(object sender, EventArgs e)
There are situations wherein you may want to change {
the layout of the master page through a particular MyMasterPage
content page. One such situation is when you want master = (MyMasterPage)
to hide the navigation controls, which are this.Master;
implemented in the master page to have more space master.ShowNavigation = false;
to see the page content in a particular content page. }
You cannot implement this functionality in the protected void btnShow_Click
master page because then the navigation controls (object sender, EventArgs e)
will not be visible in any of the content pages.
{ elements:
MyMasterPage HTML or ASP.NET Elements
master = (MyMasterPage) ContentPlaceHolder Controls
this.Master; q To bind a master page with the content
master.ShowNavigation = true; page, you need to include the
} MasterPageFile attribute in the @Page
In the preceding code snippet, MyMasterPage is the directive of the content page.
name of the master page class and q Content pages can interact with the master
ShowNavigation is the public property of the pages programmatically.
MyMasterPage class.

Reference Reading
Working with Styles
Summary
In this chapter, you learned that: Beginning ASP.NET 3.5 http://www.west-
q Styles are used to define a set of formatting with C# by Chris Hart, wind.com/WebLog/
options that can be reused on a single or John Kauffman, David posts/158367.aspx
multiple Web pages. Sussman, Chris Ullman
q Styles can be defined in any of the following http://
ways: www.15seconds.com/
Using Inline Styles issue/040105.htm
Using an Embedded Style Sheet
Using an External (Linked) Style Sheet Working with Themes
q Inline styles are style definitions that are
applied to the style property of a particular
HTML element. Essential ASP.Net 3.5 by http://
q An embedded style sheet is a group of styles Fritz Onion, Keith Brown www.15seconds.com/
that are defined by using the <style> tag. issue/040105.htm
q The style definitions in an external style sheet
are stored in a separate file having the .css
extension.
Working with Master Pages
q ASP.NET themes are a collection of
properties that enable you to define the
appearance of Web pages and controls on Chris Hart, John http://quickstarts.asp.net/
your website. Kauffman, Beginning QuickStartv20/aspnet/
q You can apply a theme either to a particular ASP.NET.3.5 doc/masterpages/
Web page or to all the Web pages on a default.aspx
website.
q To bind a theme at the page level, you need http://quickstarts.asp.net/
to set the Theme attribute of the @Page QuickStartv20/aspnet/
directive. doc/masterpages/
q To apply a theme to the entire website, you default.aspx
need to configure the <pages> element in
the web.config file. http://
q You can create more than one theme for the www.beansoftware.com/
same control. ASP.NET-Tutorials/
q Master pages enable you to create a page Master-Pages.aspx
layout that you can use with selected or all
Web pages on your website.
q A master page contains the following
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
Chapter 4 map containing the links to all the Web pages can be
rendered in lists or navigation menus on each page
Navigating Websites by including specific Web server controls such as a
TreeView, a SiteMapPath, or a Menu.
A website is a collection of interconnected Web
pages. Users need to navigate between these Web
pages to get the required information. Navigation Defining a Site Map
between Web pages can be made easier by
implementing a proper navigation system. Such a To provide a consistent way to navigate a website,
system can be implemented by using site maps and you need to define the hierarchical structure of the
navigation controls provided by ASP.NET. website by using a site map. A site map is an XML file
This chapter provides an overview of site maps. In that describes the hierarchical and logical structure of
addition, it discusses how to implement navigation the website. It stores links to all the Web pages on a
on a website by using the navigation controls website. These links can be rendered through
provided by ASP.NET. navigation controls.
To create a site map, you need to create an XML file
Objectives with the .sitemap extension. This file must be located
in the application root directory. Every .sitemap file
In this chapter, you will learn to: contains the <siteMap> element. All the
Work with site maps information regarding the site map is written within
Work with navigation controls the opening and closing tags of the <siteMap>
element, as shown in the following example:
<siteMap xmlns="http://
Working with Site Maps schemas.microsoft.com/AspNet/
SiteMap-File-1.0">
A website is a collection of Web pages. The ...
information that needs to be shared by the website is </siteMap>
contained in these Web pages. Therefore, these Web In the preceding example, the xmlns attribute of the
pages should be linked in such a manner that a user siteMap element tells ASP.NET that the XML file uses
can easily move to the desired page. Moving the ASP.NET site map standard.
between the Web pages on a website is known as
A site map defines the hierarchical structure of the
navigation. To provide a smooth navigation on a
Web pages on a website. To create the hierarchical
website, you need to provide a path that can direct a
structure, you need to use the <siteMapNode>
user to any part or Web page on the website. This
element within the opening and closing tags of the
path is known as the navigation path.
<siteMap> element. Each page in the hierarchical
A navigation path describes the structure of a structure is represented by a <siteMapNode>
website and acts as a roadmap for a user. A properly element. The <siteMapNode> element contains
structured navigation path enables a user to easily various attributes, as shown in the following example:
navigate to any part or section of a website and adds
<siteMapNode title="Home"
to the popularity of the website. However, in most of
description="Home" url="~/
the traditional websites a proper navigation path was
default.aspx" />
not provided and the users could move between
In the preceding example, the title attribute specifies
Web pages either by clicking a button or by clicking
the text that is usually used as link text. The
a hyperlink placed on the Web pages. For this, the
description attribute specifies the text that acts as a
developers had to write the same code on every Web
tool tip. The url attribute specifies the linked page.
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 SiteMapPath control is one of the
navigation controls that display the A Hierarchical Group of Links
navigation structure of a website. It is
discussed in detail in the next section.

Creating Hierarchical Group of Links


A site map must always have a single root
in Site Maps node. All the other nodes must be
There are situations when you want the Web pages contained inside this root-level node.
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
Two site map nodes in a .sitemap file
another. For this, you need to split the
<siteMapNode> element into a start and an end cannot have the same URLs. This is because
tag, as shown in the following example: the site map information is stored as a
<siteMapNode title="Home" collection where each item is indexed by its
description="Home" url="~/ unique URL.
default.aspx">
...
</siteMapNode>
You can add more <siteMapNode> elements within Binding a Page to a Site Map
the root <siteMapNode> element and create a Once the navigation structure of a website is defined
group, as shown in the following example: in the site map file, it needs to be bound to a Web
<siteMapNode title="Home" page. To bind the site map file to a Web page, you
description="Home" url="~/ need to add the SiteMapDataSource control to the
default.aspx"> Web page. You can add the SiteMapDataSource
<siteMapNode title="Software" control to the Web page by using the following code:
description="Software choices" <asp:SiteMapDataSource
url="~/software.aspx" /> ID="SiteMapDataSource1"
<siteMapNode title="Hardware" runat="server" />
description="Hardware choices" After adding the SiteMapDataSource control, you
url="~/hardware.aspx" /> need to add navigation controls to the Web page.
</siteMapNode> The navigation controls are linked to the
The preceding example creates a hierarchical group SiteMapDataSource control and are capable of
of links. In this example, the Home group contains displaying the navigation structure contained in the
two more pages, software and hardware. This site map file. To use a navigation control, such as a
hierarchical group of links is represented as shown in TreeView control, you need to use the following
the following figure. 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 site-map provider or the </providers>
XMLSiteMapProvider class to read site-map </siteMap>
information from the Web.sitemap file. However, </system.web>
there are situations wherein instead of using the </configuration>
default site-map provider you may want to In the preceding example, a custom site-map
implement your own site-map provider. Some of the provider is created that is using a text file to store the
situations are: navigation structure. The defaultProvider
q When you want to store the site-map attribute of the siteMap element specifies the name
information in a data source that is not of the custom site-map provider class. You need to
supported by the default site-map provider. specify the complete path of the text file in the
q When you want to use a data source other siteMapFile attribute.
than the Web.sitemap file. If you want to have the same functionalities as
You can create a custom site-map provider by provided by the default site-map provider but want
creating a class that inherits the SiteMapProvider to use a data store other than the Web.sitemap file,
abstract class from the System.Web namespace then you need to configure the web.config file as
and implementing the abstract members that are shown in the following example:
exposed by the SiteMapProvider class. The <siteMap>
following table lists the methods that need to be <providers>
implemented in the custom site-map provider. <add name="MusicManiaSiteMap"
type="System.Web.XMLSiteMapProvid
er"
FindSiteMapNode Gets an instance of the siteMapFile="MusicMania.sitemap"/
SiteMapNode class that >
represents a page. </providers>
GetChildNodes Gets the child nodes of a </siteMap>
specific instance of the
SiteMapNode class.
GetParentNode Gets the parent node of a
specific instance of the
SiteMapNode class. If you are using a custom site-map
GetRootNodeCore Gets the root node of all provider, you need to explicitly set the
the nodes that are SiteMapProvider property of the
managed by the current SiteMapDataSource control.
provider.

The Methods that need to be Implemented in the


Custom Site-Map Provider
Implementing Navigation by
After creating the custom class and implementing Using Navigation Controls
the preceding methods, you need to configure the
The process of implementing navigation on websites
custom provider as the default provider in the
includes creating a navigation structure and
web.config file. This can be done by using the
associating it with navigational controls. This can be
markup as shown in the following example:
done by defining a structure of the site in a site map
<configuration> file and binding it with the page by using the
<system.web> SiteMapDataSource control. After this, you need to
<siteMap associate the SiteMapDataSource control with any of
defaultProvider="CustomProvider"> the following three navigational controls:
<providers>
q The SiteMapPath Control
<add
q The TreeView Control
name="MyProvider"
q The Menu Control
type="<type name>"
siteMapFile = "<path>/
siteMap.txt"/>
direction of the path of
The SiteMapPath Control navigation. If you specify
the property
The SiteMapPath control is one of the navigation
toRootToCurrent, the
controls that display the navigation structure of a
path will be from the root
website. The navigation structure or the navigation
page to the current page.
path of the website displayed in the SiteMapPath
If you specify the property
control is known as breadcrumb. A breadcrumb
toCurrentToRoot, the
shows the user’s current page location and displays a
path will be in reverse
link as a hierarchical path back to the home page.
order.
This allows the user to navigate up the hierarchy by
using these links.
PathSeparator Indicates the characters
that will be placed
Consider a scenario where a user visits the Home
between each level in the
page of a website. From within the Home page, the
path. The default is the
user navigates to the Products page. Further, the user
greater-than symbol (>).
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 Properties of the SiteMapPath Control
following figure.
The TreeView Control
A TreeView control is used to display hierarchical
Path Displayed by the SiteMapPath Control data. Therefore, it can be used to display the
navigational structure of a website. Using a TreeView
The preceding path indicates that the user is
control, you can show a portion of the site map or
currently on the Sports page. The user can navigate
the entire site map. The hierarchy of the Web pages
either to the Home page or to the Products page by
in the site map is shown in the form of nodes and
clicking the corresponding link displayed as a
subnodes. All the nodes or subnodes are represented
breadcrumb in the SiteMapPath control.
as links. These links enable you to navigate to a new
The SiteMapPath control obtains navigation data
page.
from the site map. This data includes information
about the pages on your website, such as the URL, To use the TreeView control on a Web page, you
title, description, and location in the navigation need to add a SiteMapDataSource control to the
hierarchy. Web page. Next, you need to set the
DataSourceID property of the TreeView control to
Properties of the SiteMapPath the ID of the existing SiteMapDataSource control.
Control To use a TreeView control effectively, you must
You can use various properties of a SiteMapPath understand the properties of the TreeView control.
control to customize its appearance. The following Properties of the TreeView Control
table lists some properties of the SiteMapPath The properties of a TreeView control allow you to
control. change the appearance of the control. The following
table lists some properties of the TreeView control.

ShowToolTips Shows the description text


when a user hovers the NodeIndent Sets the number of pixels
mouse pointer over the between each level of
site map path. node in the TreeView
ParentLevelsDisplay Sets the maximum control.
ed number of levels above ImageSet Allows you to use a
the page that is currently predefined collection of
displayed on the user’s node images for collapsed,
Web browser. expanded, and
PathDirection Allows you to set the nonexpendable nodes.
ShowLines Adds lines that connect
every node.
ExpandDepth Specifies how many levels
of nodes will be visible at
first.
Summary
Properties of the TreeView Control In this chapter, you learned that:
q A navigation path describes the structure of
a website and acts as a roadmap for a user.
The Menu Control q A site map is an XML file that describes the
hierarchical and logical structure of the
The Menu control is another control that supports
website.
hierarchical data. Therefore, it can also be used to
q A site map stores links to all the Web pages
display the navigational structure of a website. The
on a website.
Menu control displays hierarchical data in the form of
q After creating the site map file, you need to
a main menu and submenus. It only displays the
bind it to a Web page.
main menu on a Web page. When a user hovers over
q The site map can be bound to a Web page
an option in the main menu, a drop-down menu is
by using the SiteMapDataSource control.
displayed containing links to other Web pages in the
q After adding the SiteMapDataSource control,
hierarchy. This avoids congestion on a Web page
you need to add a navigational control to
when many links are to be displayed.
the Web page.
To use the Menu control on a Web page, you need q The three navigational controls provided by
to add a SiteMapDataSource control to the Web ASP.NET are:
page. Next, you need to set the DataSourceID The SiteMapPath Control
property of the Menu control to the ID of the existing The TreeView Control
SiteMapDataSource control. The Menu 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 Reference Reading
between these two controls.
The following table lists the differences between Working with Site Maps
Menu and TreeView controls.

Beginning ASP.NET 3.5 in http://


Can display a single Can expand arbitrary VB 2005: From Novice to msdn.microsoft.com/en-
submenu at a time. number of node branches Professional by Matthew us/library/aa479320.aspx
at a time. MacDonald
Displays only root level Displays all the levels of http://
node on a Web page. All nodes on the Web page. msdn.microsoft.com/en-
other node items appear us/library/yy2ykkab.aspx
as pop-up when a user
hovers over a node with http://
the mouse pointer. blogs.techrepublic.com.co
Supports templates. Does not support m/programming-and-
templates. development/?p=456
Does not support check Supports check boxes for
boxes for any node. nodes. Implementing Navigation by Using
Supports horizontal and Supports only vertical Navigation Controls
vertical layouts. layout.

Differences between the Menu and the TreeView Beginning ASP.NET 3.5 in http://
Control
VB 2005: From Novice to support.microsoft.com/
Professional by Matthew kb/913721
MacDonald
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
Chapter 5 entered on the Web page will be lost. This problem
can be solved by using client-side state
Managing State in Web management.
Client-side state management allows you to store
Applications information either on a Web page or on a client
Web pages and ASP.NET Framework use HTTP computer. Such state management improves the
protocol to communicate between a Web browser performance of a Web application because it reduces
and a Web server. HTTP is a stateless protocol and the load on the server. The various options available
cannot automatically indicate whether the sequential to implement client-side state management are:
requests are coming from the same or different q Hidden Fields
clients. Therefore, when a Web page is posted to the q View State
server, a new instance of the Web page class is q Control State
created. This results in the loss of all the information q Cookies
associated with the page and the controls placed on q Query Strings
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. You can store only a limited amount of
This chapter discusses the various client-side and information by using client-side state
server-side state management options provided by management.
ASP.NET. In addition, it discusses how to improve the
performance of a Web application by using caching.

Objectives Hidden Fields


In this chapter, you will learn to: A hidden field is a control similar to a TextBox
Implement client-side state management control. However, unlike a TextBox control, it does
not render in a Web browser. As a result, a user
Implement server-side state management
cannot type anything in it.
Manage state by using cross-page posting Hidden fields can be used to store information that
Implement caching 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
Implementing Client-Side State page, the ID of the product can be stored in a hidden
Management field. If the user orders the product, the information
stored in the hidden field will be sent to the server
A new instance of the Web page class is created each and the corresponding product will be added to the
time the page is posted to the server. In traditional shopping cart.
Web programming, this would typically mean that all Hidden fields can also be used to pass session
information associated with the page and the information to and from forms, transparently.
controls on the page would be lost with each round Consider an example. Suppose the home page of
trip. your website asks a user to specify his or her favorite
Consider an example. Suppose a user fills up some color. When the user clicks the submit button to
personal information on a Web form. While filling up move to another page, say Page1.aspx, the
this information, the user selects a country from a information about the favorite color can be passed
drop-down list on the Web page. As soon as the user on to a hidden field on Page1.aspx and the
selects a country, the page needs to be posted back information can be used to change the background
to the server to retrieve a list of state names, which color of the page to the specified color. Similarly,
need to be populated in another drop-down list on when the user moves from Page1.aspx to another
page, say Page2.aspx, the information in the hidden form fields can slow down the processing of
field on Page1.aspx can be passed on to a hidden the page.
field on Page2.aspx. This information, again, can be q If you use hidden fields, you must submit
used to change the background color of Page2.aspx your pages to the server using the HTTP
to the specified color. POST method instead of requesting the page
To pass the information from one page to another, using the page URL. You cannot take
you can invoke the Server.Transfer method on advantage of hidden fields if a page is
the Click event of a Button control, as shown in the processed in response to a link or the HTTP
following example: GET method.
protected void Button1_Click
(object sender, EventArgs e)
{ View State
Server.Transfer Each Web page and controls on the page have a
("Page2.aspx"); property called ViewState. This property is used to
} automatically save the values of the Web page and
The target page can access the passed information each control on the Web page prior to rendering the
by referring to individual controls on the source page. This, in turn, enables you to retain the page
page, as shown in the following example: and control-specific values between round trips to
String name = Request.Form the server.
["TextBox1"]; The view state is implemented with the help of a
String color = Request.Form hidden form field called __ViewState. This hidden
["HiddenField1"]; 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
To ensure that the passed values are formatted into a single encoded string. This encoded
available to the target page, you must string is then assigned to the Value attribute of the
submit the page by using the HTTP Post hidden form field, __ViewState, and is sent to the
method. client as part of the Web page.
During postback of a Web page to itself, one of the
A hidden field acts as a repository for any page- tasks performed by ASP.NET is to restore the values
specific information that you want to store directly in in __ViewState. When the page is initialized during
a page. The advantages of using hidden form fields postback, ASP.NET Framework parses the view state
are: string to restore the information displayed on the
q A hidden field can store page-specific page.
information without accessing any Web The view state of a Web page or a control consists of
server or Web browser resource. the cumulative property values of the page or the
q A hidden field can be easily implemented in control. To preserve these values across stateless
an ASP.NET Web form page. You just need to HTTP requests, Web pages and controls in ASP.NET
add the HiddenField control to a Web page use an instance of the StateBag class.
and use the Value property of the control to The StateBag class is the primary storage
set its value. mechanism for HTML and server controls. This class
Some limitations of using hidden form fields are: works like a dictionary object and allows you to store
q You can view the information stored in the items as a key/value pair in it. It accepts a string as a
hidden field by accessing the source of the key and an object as its value. Items added to this
Web page. Therefore, the values stored in class are automatically added to the hidden
hidden form fields are not very secure. __ViewState form variable.
q A hidden field does not support more than a
single value field to store information.
Storing Information in View State
Information in the form fields on a Web page is
q The hidden fields are stored in a page.
automatically added to the view state. In addition to
Therefore, storing large values in hidden
the information contained in form fields, the view To determine the effect of enabling and disabling the
state can be used to store some additional ViewState property of a control, consider an
information. For example, you can store a key-value example. Add a Label and a Button control to a Web
pair, Counter=1, in the view state by using the page and type the following code in the Page_Load
following code: event handler:
ViewState["Counter"] = 1; if(!IsPostBack)
In the preceding code snippet, a key by the name {
Counter is stored in the view state and the value 1 Label1.Text="Hello World";
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
By default, a Button Web server control
State submits a page back to itself.
A value stored in view state can be retrieved by using
code. For example, you can retrieve the value of the
When this page is loaded for the first time, the
key, Counter, from view state by using the following
message, Hello World, is displayed in the Label
code snippet:
control. When the user clicks the button, the
int counter;
message is still displayed on the Label control. This is
counter = (int) ViewState
because the default value of the EnableViewState
["Counter"];
property of the Label control is True.
In the preceding code snippet, the value stored in the
To see the effect of disabling the ViewState
key, Counter is converted to an integer before
property, set the EnableViewState property of the
storing it into an integer variable.
Label control to False and execute the application.
Enabling and Disabling View State When this page is loaded for the first time, the
By default, the ViewState property of a Web page message, Hello World, is displayed in the Label
and the controls on the Web page is enabled. control. However, when the button is clicked, the
However, you can disable this property for a Web Label control displays the default text, Label. This is
page or any particular control on the Web page. This because the Label control does not maintain its state
is required when you have a large volume of when its EnableViewState property is set to
information to maintain. However, maintaining large False.
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 If the EnableViewStateproperty of a
for users using mobile devices. This is because Web page is set to False, ViewState is not
mobile devices may not have enough storage space maintained for any control on that Web
for storing large volumes of information. page, even if the
You can enable or disable the ViewState property EnableViewStateproperty of a control
of a Web page or an individual control by setting the
on the Web page is set to True.
EnableViewState property of the Web page or
the control to True or False. You can set the
The advantages of using view state are:
EnableViewState property of a Web page by
q The values in view state are stored in a
using the @Page directive, as shown in the following
standard HTML format as part of a Web
example:
page. Therefore, no Web server resource is
<%@ Page Language="C#"
required to maintain it.
AutoEventWireup="true"
q The view state can be easily implemented on
EnableViewState="false"
the ASP.NET Web page. You just need to set
CodeFile="Page1.aspx.cs"
the EnableViewState property of a Web
Inherits="Page1" %>
page and server controls.
q The values in view state are hashed, argument.
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: Cookies
q Storing large values can cause a page to slow
Cookies are used to store small pieces of information
down when users display it or post it
related to a user’s computer, such as its IP address,
because view state is stored in the Web
browser type, operating system, and Web pages last
page.
visited. The purpose of storing this information is to
q View state is stored in a hidden field on a
offer a personalized experience to the user. For
Web page. Although view state stores data
example, if a user has logged on to your website for
in a hashed format, it can be tampered with.
the first time, the name of the user can be stored in a
The information in the hidden field can be
cookie. This information can be retrieved later on
seen if the page output source is viewed
when the same user visits the website again to greet
directly, creating a potential security issue.
the user with his/her name.
Cookies are sent to a client computer along with the
Control State page output. These Cookies are stored on the client’s
computer. When a browser requests the same page
You can use the ViewState property to preserve the next time, it sends the cookie along with the
page and control values between round trips to the request information. The Web server reads the
Web server. If you disable the ViewState property cookie and extracts its value. It then process the Web
of a page, the ViewState of the controls on that page according to the information contained in the
page is not maintained. This can lead to improper cookie and renders it on the Web browser.
functioning of some controls on the page. For
example, the state of the selected node in a TreeView
Types of Cookies
Cookies can either be temporary or persistent.
control needs to be maintained for the control to
Temporary cookies exist in the memory space of a
function properly across postbacks.
browser. When the browser is closed, all temporary
To enable persistence of property information that is
cookies added to the browser are lost. Temporary
specific to a control, ASP.NET allows you to store the
cookies are also known as session cookies.
state of a control by using a client-side state
A temporary cookie is useful for storing information
maintenance mechanism called control state. Unlike
required for only a short time or that should not be
view state, the control state cannot be disabled at the
written to disk on the client computer for security
page level. Therefore, if your Web page contains
reasons. For example, a temporary cookie can be
controls whose state must be maintained, you can
created to store the user name. The user name stored
use the control state mechanism to store their state.
in the cookie can be retrieved and displayed on every
You can implement control state on a custom Web
page of the website.
control by overriding the following methods of the
A persistent cookie is saved as a text file in the file
base class:
system of the client computer. Persistent cookies are
q OnInit: This method should contain the
used when you want to store information for a
following lines of code:
longer period. For example, persistent cookies can be
Page.RegisterRequiresControlState
(this); base.OnInit(e); used to store customized user settings for a website.
q SaveControlState: This method should This helps in customizing the website when the user
return a public property of the control visits the website again.
(whose state needs to be saved) or an object While creating a persistent cookie, you can set the
array containing the values of all the public expiration date of the cookie, which defines the
properties of the control. duration for which the cookie will be stored on the
q LoadControlState: This method should client computer. If you do not set the expiration date
set the value of the public properties to the of a cookie, the cookie is maintained as a temporary
values contained in the object passed to the cookie, as part of the user's session information.
LoadControlState method as an Once the user session is finished, the cookie is
discarded. userName, is checked for null. If the value is not null,
Persistent cookies can be created as shown in the the value is assigned to the Text property of the
following example: Label control.
Response.Cookies Similarly, you can read the values from a cookie that
["userName"].Value = "Peter"; stores multiple values. The following example reads
Response.Cookies values from a cookie that stores multiple values:
["userName"].Expires = DateTime.N if (Request.Cookies["userInfo"] !
ow.AddDays(2); = null)
Response.Cookies {
["lastVisited"].Value = DateTime. Label1.Text = Request.Cookies
Now.ToString(); ["userInfo"]["userName"]);
Response.Cookies Label2.Text = Request.Cookies
["lastVisited"].Expires = DateTim ["userInfo"]["lastVisited"]);
e.Now.AddDays(2); }
In the preceding example, two cookies, username In the preceding example, the value in the cookie,
and lastVisited, are created. The user name Peter is userInfo, is checked for null. If the value is not null,
stored in the first cookie and the date and time when the value of the subkeys, userName and
the user, Peter, last visited the site is stored in the lastVisited, is assigned to the Text properties of
second cookie. The expiry period for both the the Label controls.
cookies is set as 2 days. If you do not set the expiry Advantages and Disadvantages of
period for the cookies, the cookies will be created as
temporary cookies. Cookies
You can also store multiple values in a single cookie. Cookies provide several advantages. Some
For example, instead of creating separate cookies for advantages of using cookies are:
storing the user name and last visited information, q A cookie is stored on the client computer
you can create a single cookie that can hold both the and can be read by the server after a request
values. Such a cookie can be created as shown in the for a page is posted. Therefore, no server
following example: resource is involved in maintaining the
Response.Cookies["userInfo"] cookie.
["userName"] = "Peter"; q A cookie is a text-based data structure that
Response.Cookies["userInfo"] contains key-value pairs. Therefore, it is easy
["lastVisited"] = DateTime.Now.To to create and manipulate cookies.
String(); q A cookie can either expire when the browser
Response.Cookies session ends or exist indefinitely on the client
["userInfo"].Expires = DateTime.N computer, subject to the expiration rules on
ow.AddDays(2); the client.
However, cookies also have the following limitations:
In the preceding example, the cookie, userInfo, with
two subkeys, userName and lastVisited, is created. q Cookies that are stored on the client
computers have a limited size. Most
Reading Cookies browsers allow cookies to be up to 4096
You can access the value of a cookie by using the bytes in size. Therefore, you cannot store a
Request built-in object. However, if you want to large amount of data in a cookie.
modify a cookie, you need to use the Response q Users can disable cookies to prevent them
built-in object of ASP.NET. from being stored on the hard disk of their
The following example reads the value of a cookie computer. If a user denies permission for
that stores a single value: cookies, an ASP.NET Web application cannot
if (Request.Cookies store cookies on the client computer.
["userName"].Value != null) q Users can tamper with cookies because
{ cookies are stored on the client computer.
Label1.Text = Request.Coo
kies["userName"].Value;
} Query String
In the preceding example, the value in the cookie,
Sometimes, it is required to transfer information from BooksInfo.aspx page by using the following
one page to another. For example, on an online book syntax:
shopping website, a Web form displays the list of String cat = Request.QueryString
categories of books. When the user selects a ["Category"];
category, another page with detailed information String pub = Request.QueryString
about the selected category is displayed. This process ["Publisher"];
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 To ensure that the query string values are
information from one page to another. It is the part available during page processing, you must
of a URL that appears after the Question mark (?) submit the page by using the HTTP Get
character. Consider the following URL: method.
http://www.MyBookStore.com/search?
Category=fiction
In the preceding URL, the query string defines a Advantages and Disadvantages of
variable, category, which contains the string, fiction. Query Strings
You can pass data from one page to another page in The advantages of using query strings are:
the form of a query string by using the q A query string is contained in the HTTP
Response.Redirect method, as shown in the request for a specific URL. Therefore, no
following example: server resource is involved in processing a
Response.Redirect query string.
("BooksInfo.aspx? q Many Web browsers support passing values
Category=fiction"); in a query string. Therefore, if you create a
In the preceding example, the string fiction is stored Web application that passes information
in the variable Category and is sent to the from one page to another using a query
BooksInfo.aspx page. The information stored in the string, it will be processed in most of the
variable Category can be retrieved on the browsers.
BooksInfo.aspx page by using the following syntax: Query strings have the following limitations:
String cat = Request.QueryString q They can be used only with the HTTP GET
["Category"]; method.
The preceding example returns the string fiction. q The information in a query string is directly
You can pass multiple values from one page to visible to the users in the browser window.
another by using a query string. For this, the values Therefore, you need to encrypt this
must be separated with the ampersand (&) symbol, information to ensure that any confidential
as shown in the following example: information is not exposed. This causes an
Response.Redirect additional overhead to Web application
("BooksInfo.aspx? development. In addition, query strings are
Category=fiction&Publisher=Sams") not useful for storing sensitive data.
; q 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.

There should be no blank space before and


after the ampersand (&) symbol.
Implementing Server-Side State
Management
In the preceding example, the strings, fiction and
There are situations where you need to store the
Sams, are stored in the variables, Category and
state information at the server-side. One such
Publisher, respectively. The information stored in
situation is when you want to know the number of
these variables can be retrieved on the
users logged on to the Web application. Server-side
state management enables you to manage Application ["MyVariable"] = "Hel
application and session-related information on the lo";
server. This reduces the amount of information to be After the application in which you declared
sent to the client to preserve state. MyVariable is executed, any page in the
ASP.NET provides the following options to manage application can retrieve the value of MyVariable.
state at the server side: To read the value of MyVariable, you can use the
q Application State following code snippet:
q Session State string val = (string) Application
q Profile Properties ["MyVariable"];
You can also add complex objects, such as a
Collection or a Dataset, in the application state. For
Application State example, you can add a dataset to an application
state by using the following code snippet:
ASP.NET provides application state as a means of
DataSet ds = new DataSet();
storing application-specific information such as
Application ["DataSet"] = ds;
objects and variables. The information in the
application state is stored in a key-value pair and is Removing Information from
used to maintain data consistency between server Application State
round trips and between pages. In addition to adding variables and objects to
Application state is created the first time a user application state, you can remove an existing object
accesses any URL resource in an application. After an or variable from application state. For example, you
application state is created, the application-specific can remove the application variable MyVariable
information is stored in it. All the information stored from the application state, by using the following
in the application state is shared among all the pages code snippet:
of the Web application by using the Application.Remove
HttpApplicationState class. The (["MyVariable"]);
HttpApplicationState class is accessed by using You can also remove all the application state
the Application property of the HttpContext variables and objects by using the following code
object. 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
Application state variables are global for an item is explicitly removed from the application state.
ASP.NET application. However, the values
Handling Application Events
stored in the application state variables are Application state has the following events that you
accessible only from the code running can capture to manipulate an ASP.NET Web
within the context of the originating application:
application. Other applications running in q Application.Start: This event is raised
the system cannot access or modify the when the application receives the first
values. request for a Web page. It is also raised on
the next request after the server, Web
Storing Information in Application service, or website has been restarted. The
event handler for this event usually contains
State code for initializing the application variables.
You can add application-specific information to an
q Application.End: This event is raised the
application state by creating variables and objects
server, Web service, or website is stopped or
and adding them to the application state. Variables
restarted. The event handler for this event
and objects added to the application state are global
usually contains code to clean up the
to an ASP.NET application. For example, you can
resources that the application has used.
create a variable called MyVariable with the value
q Application.Error: This event is raised
Hello and store it in the application state by using
when an unhandled error occurs.
the following code snippet:
You can handle the preceding events by adding Application object. Consider the following example:
subroutines in the Global.asax file. The Global.asax Application.Lock();
file contains the event handlers for all the application if (Application
and session events. ["PageCounter"] == null)
Considerations While Using {
Application["PageCounter"]=1;
Application State }
The application state variables are global to an else
application. Therefore, it is important to consider the {
following issues while storing any value in an Application["PageCounter"]=(int)
application state variable: Application["PageCounter"]+1;
q The memory occupied by variables stored in Response.Write(Application
an application state is not released until the ["PageCounter"]);
value is either removed or replaced. }
Therefore, the number of variables and Application.UnLock();
objects in an application state should be
minimum. Otherwise, it will be an overhead In the preceding example, the Lock() method is
on the Web server and the server response called before accessing the value of the
will be slow. PageCounter variable. This ensures that the
q Multiple pages within an application can variable cannot be modified simultaneously by any
simultaneously access the values stored in an other thread. After calling the Lock() method, the
application state. Therefore, explicit value of the PageCounter variable is modified. After
synchronization methods need to be used to the modification is done, the UnLock() method is
avoid deadlocks and access violations. called to release the imposed lock on the
Synchronizing Application State PageCounter application state variable. Then, the
Multiple pages within an ASP.NET Web application variable can be modified by other threads.
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 It is not required to call the Unlock()
requested. If two users access a Web page method explicitly because the .NET
simultaneously, there will be an attempt to update Framework automatically removes the lock
the value of the variable PageCounter by both the when the request completes or times out, or
users which could result in data inconsistency. To when an unhandled error occurs during
avoid such situations, the HttpApplicationState request execution and causes the request to
class provides two methods, Lock() and Unlock().
fail.
These methods allow only one thread at a time to
access application state variables and objects.

The Lock()method locks all the items in


Each browser’s request for a Web page
the application state object. In other words,
initiates a new thread on the Web server.
you cannot selectively lock items in an
application state.
Calling the Lock() method on an Application
object causes ASP.NET to block attempts by the code
The advantages of using the application state are:
running on other worker threads to access anything
in the application state. These threads are unblocked q Application state is easy to use and is
only when the thread that called the Lock() method consistent with other .NET Framework
calls the corresponding Unlock() method on the classes.
q Storing information in application state
involves maintaining only a single copy of Session.Start and Session.End, which
the information. can be handled in the Global.asax file.
Application state has the following limitations: q Automatically release session data if a
q The data stored in an application state is lost browser does not access an application
when the Web server containing the within a specified timeout period.
application state fails due to a server crash, When a user first requests a page from an ASP.NET
upgrade, or shutdown. website, the website automatically adds a session
q Application state requires server memory cookie to the client browser. This cookie is named
and can affect the performance of the server ASP.NET_SessionID cookie. This cookie is used
and the scalability of the Web application, if for the remainder of the user’s visit to the website.
it occupies too much memory space. Identifying a Session
You can implement application state to increase the Each active ASP.NET session is identified and tracked
performance of the Web application. For example, by a unique 120-bit SessionID string containing
storing relatively static dataset in an application state American Standard Code for Information Interchange
can enhance Website performance by reducing the (ASCII) characters. The SessionID strings are
overall number of data requests to a database. communicated across client/server requests either by
However, it is important to remember that means of an HTTP cookie or by using a modified URL
application state variables containing large blocks of with the embedded SessionID string. The
information can reduce Web server performance as SessionStateModule class is responsible for
server load increases. In addition, the memory generating or obtaining SessionID strings.
occupied by a variable stored in an application state Similar to the application state, you can store objects
is not released until the value is either removed or and variables in a session state. By default, a session
replaced. Therefore, it is preferred to use application variable is active for 20 minutes without any user
state variables with small, and less frequently interaction. In an ASP.NET Web application, the
changed datasets. 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
Session State to a page’s view state. The following example adds
the variable, MyVariable, with value HELLO in the
In ASP.NET, session state is used to store session-
session state:
specific information for a Web application. Unlike
Session["MyVariable"]="HELLO";
application state, the scope of session state is limited
You can retrieve the value of the variable,
to the current browser session. If multiple users are
MyVariable, by using the following statement:
accessing a Web application, each will have a
String val = (string) Session
different session state. If a user exits from a Web
["MyVariable"];
application and returns later, the user will have a
The preceding statement returns the value of the
different session state.
variable, MyVariable.
Session state is structured as a key-value pair for
You need to consider the following issues when
storing session-specific information that needs to be
adding variables and objects to a session state:
maintained between server round trips and between
requests for pages. q Any variable or object that you add to a
session state is available only until the user
The session state has a built-in support in ASP.NET.
closes the browser window. The variables
The built-in session state feature automatically
and objects are automatically removed from
performs the following actions:
session state if the user does not request a
q Identify and classify requests coming from a
page for more than 20 minutes because it is
browser into a logical application session on
the default value.
the server.
q Any variable or object added to a session
q Store session-specific data on the server for
state is related to a particular user. For
use across multiple browser requests.
example, you can store different values for
q Raise session lifetime-related events, such as
MyVariable for two different users
accessing the Web page and each user can cookieName="ASP.NET_SessionId"
access only the value that is assigned to him/ timeout="20"
her. mode="InProc" />
q Any object that supports serialization can be </system.web>
added to the session state. The objects </configuration>
stored in session state are stored on the The preceding markup uses the following session
server. Therefore, session objects are not state attributes:
subject to the same size limitations as q cookieless
cookies. q timeout
Session state is global to the entire application for q mode
the current user. Session state is not lost if the user The cookieless attribute
revisits a Web page by using the same browser The cookieless attribute specifies whether a
window. However, session state can be lost in the cookie should be used or not. The following table
following ways: lists the values that the cookieless attribute can
q When the user closes and restarts the have with their description.
browser.
q When the user accesses the same Web page
through a different browser window. UseCookies Specifies that cookies are
q When the session times out because of always used, even if the
inactivity. browser or device does not
q When the Session.Abandon() method is support cookies or cookies
called within the Web page code. are disabled. It is the
Similar to an application state, you can remove an default value. If the device
object or a variable added to the session state by does not support cookies,
using either the Remove() method, or the the session information
RemoveAll() method based on the requirement. will be lost over
Handling Session Events subsequent requests,
Session state has the following events that you can because each request will
capture to manipulate an ASP.NET Web application: get a new ID.
q Session.Start: This event is raised when UseUri Specifies that cookies are
a user requests the first page from a website, never used.
and is useful for initializing session variables. UseDeviceProfile Specifies ASP.NET to
q Session.End: This event is raised when a choose whether to use
user session expires or when the cookies by examining the
Session.Abandon method is called. BrowserCapabilities
You can capture both these events by adding object. It does not take
subroutines in the Global.asax file. The Global.asax into account that the user
file contains the event handlers for all the application may have disabled cookies
and session events. in a browser that supports
Configuring Session State them.
Session state can be configured through the AutoDetect Specifies that cookies
web.config file for the application. The web.config file should be used if the
allows you to set advanced options such as the browser supports them.
timeout and the session state mode. The following ASP.NET determines
markup shows some important options that can be whether the browser
set for the <sessionState> element: supports cookies by
<?xml version="1.0" attempting to set and
encoding="utf-8" ?> retrieve a cookie.
<configuration>
<system.web> Values of the Cookieless Attribute
<sessionState The timeout attribute
cookieless="UseCookies" 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: Mode Attributes in a Web.config File
Session.Timeout = 15; If you want to retrieve objects from session state but
do not want to add objects to it, you can set the
The mode attribute
EnableSessionState attribute to ReadOnly.
The mode attribute specifies where the session state
values are to be stored. The mode attribute can have
the following values:
q Custom: Specifies custom data store to store
session-state information.
q InProc: Specifies that the information is to In ASP.NET, the mode attribute is case-
be stored in the same process as the sensitive.
ASP.NET worker threads. This is the only
mode in which the Session.End event is
raised.
q Off: Specifies that the session state is
disabled.
q SQLServer: Specifies that the session state
is to be stored by using an out-of-process
Profile Properties
SQL Server database to store state Many Web applications provide users with the option
information. to personalize the application. This can be done by
q StateServer: Specifies that the session storing and using information that is unique to a
state is to be stored in an out-of-process user. This information can be used to present the
ASP.NET state service. user with a personalized version of the Web
Disabling the Session State application.
By default, session state is enabled for all the pages Consider an example. Suppose, you have created a
in a Web application. If you need to improve the website for online shopping of books. A user has
performance of the Web application, you can disable used the website to purchase books from the IT
session state for Web pages. This can be done by category. This information can be stored as a profile
using the EnableSessionState attribute in the property for that user. When the same user visits the
page directive, as shown in the following code: website again, you can use the information stored in
<%@ Page the profile properties to display the latest books in
EnableSessionState=”False” %> the IT category to the user.
You can also disable session state for all pages of a ASP.NET provides the profiles feature to implement
Web application by setting the mode attribute to Off personalization in Web applications. Although it is
in the web.config file, as shown in the following possible to store user preferences without using
figure. 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 <add name="UserName" />
membership or profiles features for the first time. <add name="BirthDate"
However, this automatic creation of the type="System.DateTime" />
aspnetdb.mdf file relies on SQL Server 2005 Express. </properties>
If you’re using another version of SQL Server, you </profile>
need to modify the profile configuration and create <system.web>
the database manually. 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
The membership feature will be discussed not defined, it takes the default data type, which is
later in this course. 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
By default, the connection string in the profile only by the logged-on users. Anonymous users
configuration is named as LocalSqlServer. You can cannot set these properties.
modify this connection string in the machine.config You can also create profile properties that can be set
file. The machine.config settings apply to all the by all users including anonymous users. To configure
ASP.NET applications. Therefore, if you have to such profile properties, you need to use the markup
modify the connection string for a single application, as shown in the following example:
it is advisable to use the web.config file. <system.web>
To modify the connection string by using the <anonymousIdentification
web.config file, you need to use the markup as enabled="true"/>
shown in the following example: <profile>
<configuration> <properties>
<connectionStrings> <add name="UserName"
<clear /> type ="System.String"
<add name="LocalSqlServer" allowAnonymous=
providerName="System.Data.SqlClie "true"/>
nt" <add name="BirthDate"
connectionString="Data type="System.DateTime"
Source=localhost;Integrated allowAnonymous=
Security=SSPI; "true"/>
Initial Catalog=aspnetdb" /> </properties>
</connectionStrings> </profile>
... <system.web>
</configuration> Getting and Setting Profile Properties
The <clear/> element clears all the existing After configuring the profile properties in the
connection strings. After clearing the existing web.config file, you can access them by using the
connection strings, you can specify the new Profile object. The value of the Profile property
connection string. can be set, as shown in the following code snippet:
Configuring Profile Properties Profile.UserName = TextBox1.Text;
The properties that need to be stored in each user
profile for an application can be configured in the In the preceding code snippet, the UserName profile
web.config file. You can configure the profile property is set to the Text property of the
properties by using the markup shown in the TextBox1 control. Similarly, the value of the profile
following example: property can be retrieved, as shown in the following
<system.web> code snippet:
<profile> String uname = Profile.UserName;
<properties> The preceding code snippet returns the value of the
Username profile property. t = (TextBox) PreviousPage.FindCo
ntrol
("TextBox1");
if (t != null)
{
When you store profile properties, ASP.NET Response.Write(t.Text);
identifies the user who has set the property. }
}
In the preceding example, the value of the
TextBox1 control, which is on the source page, is
Managing State by Using Cross- accessed in the target page.
Page Posting
By default, a Button control on a Web page submits Checking for Postbacks in the
the page back to itself. However, sometimes, you Target Page
may want to post one page to another. In such a
case, you can set the PostBackUrl property of the In some cases, you need to execute some code on a
Button control to the URL of the target page. This page only if the page is running as a result of a
posting of information from one page to another postback or a cross-page postback. Similarly, you
page is called cross-page posting. may need to execute some code only if the page is
When the source page is posted to the target page, not running as a result of a postback or a cross-page
the target page must be able to access the postback. You can check whether a page is running
information stored in the controls on the source as a result of a postback by using the IsPostBack
page. In addition, the target page must be able to property of the Page class. Similarly, you can check
identify whether the page was loaded as a result of a whether a page is running as a result of a cross-page
cross-page postback. postback by using the IsCrossPagePostBack
property of the Page class.

To make a control submit the page back to


itself, you can set the AutoPostBack Implementing Caching
property of the control to true.
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
Accessing Information Stored in a common problem that arises. The problem of slow
access can be solved by using a technique called
Controls on the Source Page caching.
The Page class exposes a public property named This technique improves the performance of any
PreviousPage. If the source and target pages are Web application by temporarily storing frequently
in the same application, the PreviousPage used Web objects, such as HTML pages, on local hard
property contains a reference to the source page. disks for later retrieval. As a result, the Web server,
However, if the pages are in different applications, or on which the application resides, processes the
if the page is not the target of a cross-page posting, requests for the website only one time and caches
the PreviousPage property is not initialized. the requests for future. Any subsequent request is
You can access the values in the controls on the processed from the cache instead of the Web server.
source page by using the FindControl method, as This leads to a considerable reduction in the load on
shown in the following example: the server and a quicker response time. Caching
if (PreviousPage != null) enables you to improve the performance of Web
{ applications.
TextBox Caching is a very important and extensively used
concept to enhance application performance. The @ OutputCache directive at the top of your .aspx
major benefits of using caching are: file, just below the @ Page directive, as shown in the
q Reduced access time: When most of the following example:
requests are processed by the cache itself <%@ Page Language="C#"
and not required to go to the Web server, AutoEventWireup="true"
the access time is reduced significantly. CodeFile="Default.aspx.cs"
q Less bandwidth required: Cache location Inherits="_Default" %>
can be configured on the client computer. As <%@ OutputCache Duration="20"
a result, most of the requests and responses VaryByParam="None" %>
do not require traveling the network In the preceding example, the @ OutputCache
between the client and server, and this directive contains the two attributes, Duration and
significantly reduces the bandwidth VaryByParam. The Duration attribute instructs
requirement. ASP.NET to cache the page for the specified number
q Less load on server: Caching avoids of seconds. The VaryByParam attribute specifies
executing the same ASP.NET code how many copies of the page need to be saved. In
repetitively to create the same result. This this example, the value of the
reduces the CPU usage at the server, and in VaryByParam attribute is set to None, which
the process, lowers the load on the server. indicates that only one copy of the page is to be
ASP.NET supports three types of caching: cached.
q Output Caching However, there are situations when you want to save
q Fragment Caching more than one cached copy of the page. One such
q Data Caching 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
Output Caching want to use more than one copy of the page. For
this, you need to use the @ OutputCache directive
Output caching improves the performance of an
as shown in the following example:
ASP.NET application by caching the rendered markup
of an ASP.NET Web page. When the user requests <%@ OutputCache Duration="20"
the same page within a specified period of time, VaryByParam="*" %>
instead of re-rendering the page, ASP.NET serves the In the preceding example, the value * of the
cached page to the user. Output caching is useful VaryByParam attribute instructs ASP.NET to cache
when the content of the Web page changes rarely. separate copies of the page for different query string
arguments.
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
Fragment Caching
connection is made to the database, the table is ASP.NET provides one more type of caching in which
queried, and the results are returned to the the data from some specific sections of the page can
requesting client. It takes a substantial amount of be cached. This is called fragment caching.
time affecting the performance. Moreover, it is not Sometimes it is also referred to as partial page
required to fetch the product details from the caching. Fragment caching is used in situations
database table for every request because the product where you want to cache only a portion of the Web
details rarely change. page because it does not change frequently. The
With output caching, when the products page is first remaining content of the page is loaded dynamically.
visited, the rendered HTML of the page is cached for To implement fragment caching, the portion of the
a specified duration. During the specified time page that is to be cached is encapsulated in a user
period, if a user requests this page, the cached control, and then the @ OutputCache directive is
markup is returned, thereby saving the database added to the control, as shown in the following
access and page rendering time. example:
Implementing Output Caching <%@ Control Language="C#"%>
To implement output caching, you need to insert the <%@ OutputCache Duration="120"
VaryByParam="None" %>
Query Strings
q A hidden field is a control similar to a
Data Caching TextBox control but it does not render in a
Web browser.
Data caching is used to store frequently used data in
q Information in the form fields on a Web page
the built-in collection object called Cache. It is a
is automatically added to the view state. It
property of the Page class, and it returns an instance
can also be used to store some additional
of the System.Web.Caching.Cache class. The
information.
Cache object works like the Application object.
q Control state is used to store information
The Cache object is globally available to all requests
that is specific to a control.
from all clients in the application.
q Cookies are used to store small pieces of
The Cache object differs from the Application
information related to a user’s computer,
object in the following ways:
such as its IP address, browser type, and
q The Cache object does not need to be operating system.
explicitly locked or unlocked. q Cookies can either be temporary or
q Items in the Cache object are removed persistent.
automatically. q A query string provides a simple way to pass
q Items in the Cache object can be linked to a information from one page to another.
file, a database table, or another type of q ASP.NET provides the following options to
resource. If this resource changes, the manage state at the server side:
cached object automatically becomes Application State
invalid and is released. Session State
Implementing Data Caching Profile Properties
Data caching can be implemented programmatically. q Application state is used to store the
The Cache class encapsulates data caching and an application-specific information.
object of the Cache class is created for q The information stored in the application
implementing data caching. It stores each item as a state is shared among all the pages of the
key-value pair. Web application.
For example, you can store a variable by the name, q Session state is used to store session-specific
uname, in the Cache object, and assign it a value, as information for a Web application.
shown in the following code snippet: q The scope of session state is limited to the
Cache ["uname"] = "Robert"; current browser session.
You can retrieve the value from the Cache object, as q The profiles feature is used to implement
shown in the following code snippet: personalization in Web applications.
TextBox1.Text = Cache["uname"]; q Caching improves the performance of a Web
The lifetime of the Cache object associated with an application by temporarily storing frequently
application is the same as the lifetime of the used Web objects on local hard disks for
application. Therefore, when an application stops, the later retrieval.
information in the Cache object is lost. q ASP.NET supports three types of caching:
Output Caching
Fragment Caching
Summary Data Caching

In this chapter, you learned that:


q Client-side state management allows you to Reference Reading
store information either on a Web page or
on a client computer. Implementing Client-Side State
q The various options available to implement Management
client-side state management are:
Hidden Fields
View State
Microsoft ASP.NET: Fast & http://dotnet.dzone.com/
Control State
Easy Web Development by news/aspnet-client-side-
Cookies
Nitin Pandey state-manag-1

http://www.exforsys.com/
tutorials/asp.net-2.0/
state-management-in-
asp.net-2.0.html

Implementing Server-Side State


Management

Pro ASP. Net 3. 5 Server http://


Controls and AJAX articles.techrepublic.com.c
Components by Rob om/5100-10878_11-5030
Cameron, Dale Michalk 436.html

http://
www.dotnetspider.com/
resources/1472-STATE-
MANAGEMENT.aspx

Managing State by Using Cross-Page


Posting

Pro ASP.NET 3.5 in C#: http://


Create Next-generation www.hotscripts.com/
Web Applications by Detailed/74287.html
Matthew MacDonald,
Mario Szpuszta

Implementing Caching

Beginning ASP.NET 3.5 in http://www.asp.net/learn/


VB 2005: From Novice to withpss/module7.aspx
Professional by Matthew
MacDonald
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 The Basic N-tier Model
data from a database by using the presentation layer.
The preceding figure shows three layers, which can
In addition, it discusses how to implement DAL to
further be divided into separate layers.
access data from a database.

Objectives Presentation Layer


In this chapter, you will learn to:
In a Web application, the presentation layer is the
Identify basics of data access in Web interface that appears when a user opens a Web
applications page in the browser. If you see the source code of
Access data by using the presentation layer the page, you would only see the code such as
Access data by using DAL 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.
Identifying the Basics of Data This is due to the fact that the presentation layer
does not contain any data access code or program
Access in Web Applications logic. However, in case of small Web applications,
Most Web applications are designed by using the you may find the database access layer merged with
multiple tier model known as the N-tier model. the presentation layer.
Designing an application by using the N-tier model Consider a situation where a developer has
provides increased performance and scalability. This implemented the data source controls to access data
is because the functioning of each layer is completely from the data source. In such a situation, the
hidden from other layers, and this makes it possible database access is merged with the presentation
to change or update one layer without recompiling layer. This approach tightly couples the data access
or modifying the other layers. The following figure logic with the presentation layer. Therefore, this
shows a basic N-tier model. 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 Data controls are the controls that are
a specific code because the code is not cluttered with designed exclusively for use with data
HTML or Javascript. The business rules layer does not sources. Some of the data controls are
contain HTML or JavaScript code. GridView, DataList, ListView, and FormView
controls. Data-aware controls are standard
Data Access Layer controls that can be used with databases,
but are not exclusively for that purpose.
You can implement the data access logic in the These controls can also be used without
presentation layer. However, this is not connecting them to a data source.
recommended because it clutters the data access Examples of such controls include
code with the HTML and Javascript code. In addition, DropDownList and ListBox controls.
it tightly couples the data access logic with the
presentation layer. This prevents the data access Data source controls perform the following tasks:
logic to be reused in other Web applications.
q Retrieve data from a data source and supply
All these limitations can be overcome by separating it to the data controls or data aware controls.
the data access logic from the presentation layer. It q Update the data source when edits take
can be done by creating a new layer and place.
implementing the data access logic in it. This
separate layer is referred to as the Data Access Layer Data Source Controls in ASP.NET
(DAL). DAL is typically implemented as a separate ASP.NET provides various data source controls to
class library. access different types of data sources. These controls
are:
q SqlDataSource
Accessing Data by Using the q AccessDataSource
q ObjectDataSource
Presentation Layer q XmlDataSource
Most of the modern day Web applications need to q SiteMapDataSource
manipulate data in databases. This can be done by SqlDataSource Control
implementing data access logic in applications. If the The SqlDataSource control is generally used to
data access logic is not to be reused in any other access data from an SQL relational database.
application, it can be implemented in the However, it can be used to access any database
presentation layer (ASP.NET pages). This can be done product for which there is a managed ADO.NET
by using: provider.
q Data source Controls
q ADO.NET

Data Source Controls A Provider is a class that communicates


Data source controls allow you to work with different with a specific type of database or data
types of data sources such as a database, an XML file, store.
or a middle-tier business object. Data source controls
act as a bridge between the application and the data The SqlDataSource control is used in conjunction
sources. They can connect to the data sources and with data controls to retrieve data from a relational
retrieve data without requiring you to write any code. database and to display or modify the data on a Web
However, they do not provide the interface to display page with minimal coding. The following table lists
data. To display the retrieved data, it is made some properties of the SqlDataSource control.
available to the data controls or data-aware controls.

ProviderName Gets or sets the name of


the ADO.NET provider
that is used to connect to The AccessDataSource control works with Microsoft
an underlying data source. Access databases. Like the SqlDataSource control, the
ConnectionString Gets or sets the connection AccessDataSource control uses SQL queries to
string that is used to retrieve data. However, unlike the SqlDataSource
connect to an underlying control, you do not set the ConnectionString
data source. property in the AccessDataSource control. Instead of
SelectCommand Gets or sets the SQL string the ConnectionString property, you need to set
that is used to retrieve the location of the Access (.mdb) file in the
data from the underlying DataFile property.
data source. The Access database to be accessed should be
DeleteCommand Gets or sets the SQL string placed in the App_Data directory of the website and
that is used to delete data needs to be referenced by a relative path. Using
from the underlying data relative path for referencing the database provides
source. security for data files because these files will not be
InsertCommand Gets or sets the SQL string served if requested directly by the client Web
that is used to insert data browser.
in the underlying data You cannot access Access databases that are
source. protected by a user name or password by using the
AccessDataSource control. This is because you
UpdateCommand Gets or sets the SQL string
cannot set the ConnectionString property in the
that is used to update
AccessDataSource control. If you need to access an
data in the underlying
Access database that is protected by a user name or
data source.
password, you need to use the SqlDataSource control
because it allows you to specify a complete
Properties of the SqlDataSource Control connection string.
You can retrieve data from a data source by using the
SqlDataSource control, as shown in the following
example:
<asp:SqlDataSource
ID="SqlDataSource1" You cannot set the ConnectionString
runat="server"
property for the AccessDataSource control
ConnectionString="<%
because it is a read only property.
$ ConnectionStrings:MusicConnecti
onString%>"
You can bind data-bound controls to an
SelectCommand="SELECT [album_name
AccessDataSource by using the DataSourceID
] FROM [albums]"></
property of the data-bound control. The following
asp:SqlDataSource>
table lists some properties of the AccessDataSource
In the preceding example, the ConnectionString
control.
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. ProviderName Gets the name of the
ADO.NET provider that is
used to connect to
Microsoft Access.
DataFile Gets or sets the location of
You can bind data controls to the the Microsoft Access file.
SQLDataSource control by using the SelectCommand Gets or sets the SQL string
DataSourceIDproperty of the data that is used to retrieve
controls. data from the underlying
data source.
DeleteCommand Gets or sets the SQL string
AccessDataSource Control that is used to delete data
from the underlying data function that is invoked to
source. retrieve data.
InsertCommand Gets or sets the SQL string SelectParameters Gets the parameters
that is used to insert data collection that contains
in the underlying data the parameters used by
source. the SelectMethod
UpdateCommand Gets or sets the SQL string property.
that is used to update InsertMethod Gets or sets the method or
data in the underlying function that is invoked to
data source. insert data.
InsertParameters Gets the parameters
Properties of the AccessDataSource Control collection that contains
You can retrieve data from an Access database by the parameters used by
using the AccessDataSource control, as shown in the the InsertMethod
following example: property.
<asp:AccessDataSource UpdateMethod Gets or sets the method or
id="AccessDataSource1" function that is invoked to
DataFile="~/App_Data/ update data.
Northwind.mdb" runat="server" UpdateParameters Gets the parameters
SelectCommand="SELECT collection that contains
LastName, FirstName FROM the parameters used by
Employees"> the UpdateMethod
</asp:AccessDataSource> property.
In the preceding example, the DataFile attribute is DeleteMethod Gets or sets the method or
used to specify the Access database file. The function that is invoked to
SelectCommand attribute is used to specify the delete data.
query that retrieves the LastName and FirstName DeleteParameters Gets the parameters
field values from the Employees table. collection that contains
ObjectDataSource Control the parameters used by
The ObjectDataSource control represents a middle- the DeleteMethod
tier object with data retrieval and update capabilities. property.
The ObjectDataSource control is used in conjunction
with a data-bound control to display or modify data Properties of the ObjectDataSource Control
on a Web page with minimal coding. You can retrieve data from business objects by using
Most of the complex Web applications follow the the ObjectDataSource control, as shown in the
three-tier architecture. In this architecture, the following example:
presentation layer is separated from business logic, <asp:objectdatasource
which is encapsulated in business objects. These id="ObjectDataSource1"
business objects form a distinct layer between the runat="server"
presentation layer and the data layer. The selectmethod="GetEmployee"
ObjectDataSource control enables developers to typename="EmployeeLogic" >
access data from business objects. <selectparameters>
The following table lists some properties of the <asp:querystringparamet
ObjectDataSource control. er name="EmployeeID"
querystringfield="empid
"/>
TypeName Identifies the name of the </selectparameters>
class that the </asp:objectdatasource>
ObjectDataSource works In the preceding example, the SelectMethod
with. attribute sets the method, GetEmployee, which is
SelectMethod Gets or sets the method or invoked to retrieve data. The TypeName attribute
defines the name of the class that the
ObjectDataSource is working with. The data. These controls can be used to display a site
<SelectParameters> element passes the map to navigate a site. The SiteMapDataSource
employee ID as parameter because it is required by control can be bound to the navigational controls by
the GetEmployee method. using the DataSourceID property of the
XmlDataSource navigational controls. The following table lists some
The XmlDataSource control presents XML data to properties of the SiteMapDataSource control.
data-bound controls. The XmlDataSource control can
be used by data-bound controls to display
hierarchical as well as tabular data. The SiteMapProvider Gets or sets the name of
XmlDataSource control loads data from an XML file the site map provider.
that is specified by the DataFile property. The StartingUrlNode Sets the URL in the
XmlDataSource control can also load XML data in sitemap that will be
string form by using the Data property. You can bind considered as the root
data-bound controls to an XmlDataSource control by node.
using the DataSourceID property of the data- ShowStartingNode Indicates whether to show
bound control. starting node or not. It can
The following table lists some properties of the only be set to True or
XmlDataSource control. False.

Properties of the SiteMapDataSource Control


DataFile Specifies the filename of You can retrieve data from a sitemap file by using the
the XML file that is to be SiteMapDataSource control, as shown in the
bound with the following example:
XmlDataSource control. <asp:SiteMapDataSource
Data Gets or sets the block of ID="SiteMapDataSource1"
xml data that is to be runat="server" />
bound with the In the preceding example, the SiteMapProvider
XmlDataSource control in attribute is not defined. Therefore, the default
string form. provider, XMLSiteMapProvider, will be used.
When you use the default provider, the
Properties of the XmlDataSource Control SiteMapDataSource control will always look for the
You can retrieve data from an XML file by using the Web.sitemap file in the root folder of the application.
XmlDataSource control, as shown in the following However, if your application has a sitemap file with a
example: name other than the default name, Web.sitemap, you
<asp:xmldatasource need to use a custom provider for the
id="XmlDataSource1" SiteMapDataSource control. You can use the custom
runat="server" provider by adding it in the web.config file, as shown
datafile="books.xml" /> in the following example:
In the preceding example, the datafile attribute <siteMap>
specifies the filename of the XML file that is to be <providers>
bound with the XmlDataSource control. <add
SiteMapDataSource Control name="MusicManiaSiteMap"
The SiteMapDataSource control provides navigation type="System.Web.XMLSite
data to the navigational controls. It obtains MapProvider"
navigation data from a site map. The navigation data siteMapFile="MyWeb.sitem
includes information about the pages on your ap"/>
website, such as the URL, title, description, and </providers>
location in the navigation hierarchy. The </siteMap>
SiteMapDataSource enables Web server controls that In addition to modifying the web.config file, you
are not specifically site navigation controls, such as need to set the SiteMapProvider property of the
the TreeView and Menu controls, to bind to site map SiteMapDataSource control to the custom provider,
as shown in the following example:
<asp:SiteMapDataSource
ID="SiteMapDataSource1" DataSource Gets or sets the object
runat="server" from which the control
SiteMapProvider="MusicManiaSiteMa retrieves the items.
p " /> DataSourceID Gets or sets the ID of the
control from which the
GridView control retrieves
the data items.
AllowPaging Gets or sets the value
In addition to the preceding data source indicating whether paging
controls, ASP.NET provides the is enabled.
LinqDataSource control that allows you to AllowSorting Gets or sets the value
access data from wide variety of data indicating whether sorting
sources such as a database, data-source is enabled.
classes, and in-memory collections. AlternatingRowStyle Gets the reference of the
object that enables you to
Displaying Data in Data-Bound Web set the appearance of the
Server Controls alternate rows.
Data-bound Web server controls are the controls SelectedIndex Gets or sets the index of
that can be bound to a data source control to display the selected row.
and modify data in a Web application. Data-bound SelectedRow Gets the reference of the
Web server controls are composite controls that object that represents the
combine other Web controls, such as Label and selected row.
TextBox controls, into a single unit. In addition to SelectedValue Gets the data key value of
displaying and modifying data, data-bound controls the selected row.
enable you to customize the layout of the control
using templates. ASP.NET provides various data- Properties of the LinqDataSource Control
bound Web server controls. Some of them are:
q GridView Control
q DetailsView Control
q FormView Control DetailsView Control
q ListView Control The DetailsView control allows you to display, edit,
q DataList Control insert, or delete a single record at a time. By default,
q Repeater Control the DetailsView control displays each field of a record
q DataPager Control in a new line. It can display only one record at a time.
q DataGrid Control It is generally used in a master/detail scenario. In
such a scenario, the DetailsView control is used to
GridView Control
update or delete records that are selected in the
When working with data in an application, it is
master control. The DetailsView control can also be
required to display the data in tabular form. To
used to add a new record.
display data in a tabular form, ASP.NET provides a
The following table lists some properties of the
number of controls, one of which is the GridView
DetailsView control.
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 DataSource Gets or sets the object
change the layout of the GridView control. from which the control
The GridView control provides various properties that retrieves the items.
can be set to display data in the desired format. The DataSourceID Gets or sets the ID of the
following table lists some properties of the GridView control from which the
control. DetailsView control
retrieves the data items.
AllowPaging Gets or sets the value indicating whether paging
indicating whether paging is enabled.
is enabled. SelectedValue Gets the data key value of
AlternatingRowStyle Gets the reference of the the current record.
object that enables you to
set the appearance of the Properties of the FormView Control
alternate rows. DataList Control
SelectedValue Gets the data key value of The DataList control allows you to display rows of
the current record. database information in a customizable format. You
can create the format for displaying data by defining
Properties of the DetailsView Control templates. You can create templates for items,
FormView Control alternating items, selected items, and edit items.
Similar to the DetailsView control, the FormView The following table lists some properties of the
control allows you to work with a single record at a DataList control.
time. However, there is a difference between the
FormView and the DetailsView control. The
DetailsView control displays the record in a tabular DataSource Gets or sets the source
format with each field of the record in a new row that contains the list of
whereas the FormView control provides you with the values to be used to
flexibility to modify the layout for displaying the populate the items within
record. You can modify the layout by creating a new the control.
template or by modifying the existing template. The DataSourceID Gets or sets the ID of the
template can contain formatting, controls, and control from which the list
binding expressions. The FormView control is also of values is to be retrieved.
used in master/detail scenarios. SelectedValue Gets or sets the value of
the key field for the
selected item.
SelectedIndex Gets and sets the index of
the selected item.
The FormView control provides various SelectedItem Gets the selected item.
built-in templates such as ItemTemplate,
InsertItemTemplate, and EditItemTemplate
Properties of the DataList Control
that allow you to provide a different
interface for performing different Repeater Control
A Repeater control displays data from different data
operations such as view, insert, and edit.
sources by using customized layouts. A Repeater
Similarly, the EmptyDataTemplate enables
control does not have a default layout. You need to
you to specify a template to display when create templates to provide a layout to the Repeater
the data source returns no data. control. You can create tables, grids, comma
separated lists, and bulleted or numbered lists to
The following table lists some properties of the display data in a Repeater control. After adding the
FormView control. 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
DataSource Gets or sets the object ItemTemplate template is mandatory as it provides a
from which the control basic layout to the Repeater control. Other templates
retrieves the items. can also be created to enhance the layout. The
DataSourceID Gets or sets the ID of the Repeater control does not provide certain features
control from which the such as editing, updating, and paging.
FormView control retrieves The following table lists some properties of the
the data items. Repeater control.
AllowPaging Gets or sets the value
DataPager Control
DataSource Gets or sets the source The DataPager control is used to enable users to
that provides data for page through data in either a ListView control or a
populating the list. control that implements the
DataSourceID Gets or sets the ID of the IPageableItemContainer interface. The
control from which the list DataPager control can be inserted inside the
of values is to be retrieved. LayoutTemplate template or on the page outside the
DataMember Gets or sets the table with ListView control. It the DataPager control is inside the
which the control is to be LayoutTemplate template, the DataPager is a direct
bound. 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
Properties of the Repeater Control
ListView control.
ListView Control The following table lists some properties of the
The ListView control is similar to the GridView and DataPager control.
Repeater controls. The GridView and Repeater
controls have some limitations. The GridView control
does not allow a user to change the layout of the
PagedControlID Gets or sets the ID of the
data display. Similarly, the Repeater control does not
control that contains data
provide features such as editing, updating, and
to be paged.
paging. Both these limitations are overcome in the
ListView control.
PageSize Gets or sets the number of
records that are to be
The ListView control enables you to display data in a
displayed for each page.
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. 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
The ListView control provides various displaying the data in editable controls at run-time.
layouts, templates, and styles that you can The DataGrid control supports paging.
choose according to your requirements. To display data from a data source, you need to bind
the DataGrid control to a data source control by
The following table lists some properties of the using its DataSourceID property. You can also bind
ListView control. 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
DataSource Gets or sets the object
such as the DataSet and data readers by using its
from which the control
DataSource property, the DataGrid control
retrieves the items.
generates a bound column for each field in the data
DataSourceID Gets or sets the ID of the
source. However, you can select which fields in the
control from which the
data source generate columns in the grid. When
ListView control retrieves
using the DataSource property, you need to call
the data items.
the control's DataBind method to load data in the
SelectedValue Gets the data key value of control, as shown in the following code snippet:
the selected item. DataGrid1.DataSource = ds;
SelectedIndex Gets and sets the index of DataGrid1.DataBind();
the selected item. In the preceding example, ds is the object of type
DataSet. The DataBind method is used to load data
Properties of the ListView Control in the DataGrid control. The DataBind method is also
called to refresh the data in the control, in case the q Single-Value Data Binding
data is modified in the data source. q Repeated-Value Data Binding
The following table lists some properties of the Single-Value Data Binding
DataGrid control. 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.
DataSource Gets or sets the source For example, if you have to register five friends of
containing the values to yours on a website by writing their names in a
be displayed in the TextBox and clicking the Submit button, you have to
control. write the name and click the button five times. This is
DataSourceID Gets or sets the ID of the because in controls such as a TextBox you can write
control from which the only one value at a time. Such controls are known as
ListView control retrieves single-value controls. These controls can be bound to
the data items. a data value by using single-value data binding.
AllowCustomPaging Gets or sets a value Single-value data binding involves binding the
indicating whether custom controls that can display one data value at a time to
paging is enabled. a data source. Single-value controls do not support
AllowPaging Gets or sets a value any data binding properties, such as the
indicating whether paging DataSource property or the DataMember property.
is enabled. Therefore, you need to bind a single-value control by
AllowSorting Gets or sets a value providing data as the value of its Text property. For
indicating whether sorting example, you can set the Text property of a TextBox
is enabled. control to display a data source value. This data
source value can be a property, a return value of a
SelectedIndex Gets or sets the index of
method, an expression, or a value from a database.
the selected item in the
You can bind single-value controls to properties,
control.
such as page properties, public variables, and the
properties of other controls. Consider a case where
Properties of the DataGrid Control 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.Pa
The DataGrid control is not a standard ge
control. Therefore, it is not present in the {
Toolbox. It needs to be added to the public string
Toolbox by right-clicking the Toolbox and dt = DateTime.Now.ToString();
selecting . You can find this protected void Page_Load
control in the (object sender, EventArgs e)
tab. {
this.DataBind();//binds
the data source to the invoked
Binding Controls to Data by Using server
Data Binding Syntax //control
Data binding is a technique of linking data and user and all its child controls
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 You can now use the variable dt to display date in a
objects can be updated to the data source. new Label control, as shown in the following markup:
On the basis of the number of bound values that can <asp:Label ID="Label1"
be displayed through a user interface object, binding runat="server"> <%# dt %></
can be classified into: asp:Label>
Repeated-Value Data Binding modifications without being connected to
There are situations when you need to display a list the network all the time.
of values from a data source on to a Web page. One
such situation is when you want to display a list of Accessing Data from a Database by
products on a Web page. This can be done by using
server controls, such as a ListBox, that can display Using ADO.NET
multiple data values at a time. Such controls are You can access data from various data sources such
known as repeated-value server controls. These as MS Access, SQL Server, and Oracle by using
controls can be bound to a data source by using ADO.NET. To access data from a database by using
repeated-value data binding. ADO.NET, you need to use certain objects. Some of
Repeated-value data binding involves binding server the basic objects are:
controls to structures, such as ArrayList and q Connection Objects
DataView objects, which implement the q Command Objects
IEnumerable interface. The DataGrid, DropDownList, q Data Reader Objects
and ListBox controls are some of the repeated-value q Dataset Objects
server controls that can display multiple data values. Connection Objects
The following example shows how you can bind an Before accessing data from a data source, you need
ArrayList to a ListBox control: to make a connection to the data source. For this,
protected void Page_Load(object you need to use the connection object. When
sender, EventArgs e) creating a connection object, you need to set the
{ ConnectionString property. The
ArrayList Month = new ConnectionString property defines all the
ArrayList(); information required to find the data source, log on,
Month.Add("Jan"); and choose an initial database. Consider the
Month.Add("Feb"); following code snippet:
Month.Add("Mar"); SqlConnection myConnection = new
Month.Add("Apr"); SqlConnection();
ListBox1.DataSource = Mon myConnection.ConnectionString = "
th; Data Source=172.23.3.59;Initial
ListBox1.DataBind(); Catalog=Music;Integrated
} Security=SSPI; Persist Security
Info=False";
myConnection.Open();
Using ADO.NET In the preceding example, a connection object
myConnection is created. After creating the
Data source controls enable you to access data from
connection object, the ConnectionString
a database without writing any data access code.
property of the myConnection object is set. The
However, Data source controls do not provide the
connection string is a series of distinct pieces of
flexibility that can be achieved by using ADO.NET. In
information known as connection string properties.
addition, data source controls enable you to access
When writing the code, the connection string
data only by using the connected environment.
properties are separated by semicolons. The
However, ADO.NET provides both the connected and
connection string can have various connection string
disconnected environments to access data.
properties. Some of the important connection string
properties are:
q Data Source: Indicates the name or the IP
address of the server where the data source
is located.
A connected environment requires a q Initial Catalog: Indicates the name of
constant connection to transfer data the database that this connection will be
between the client application and the data accessing.
source. However, a disconnected q Integrated Security: Indicates that you
environment retrieves data and performs want to connect to SQL Server using the
Windows user account. The value specified <add name="myMusic"
for this attribute is SSPI, which indicates connectionString=
ASP.NET to use the credentials under which "Data Source=172.23.3.59;Initial
the Web application is executing to Catalog=Music;Integrated
authenticate with SQL Server. Security=SSPI; Persist Security
q Persist Security Info: Indicates Info=True"
whether the information such as the user Id provideName="System.Data.SqlClien
and password is discarded after it is used to t"/>
open the connection. This information is </connectionStrings>
discarded when the value of the Persist ...
Security Info is set to false. However, </configuration>
if the value of this attribute is set to true, In the <ConnectionStrings> element the <add>
the security-sensitive information, including sub tag is used to add a connection string. The
the user ID and password, can be obtained <add> sub tag contains the following attributes:
from the connection after the connection has q name: It is a required attribute that is used to
been opened. retrieve the connection string.
q connectionString: It is a required
attribute that is used to define the
connection string value.
q provideName: It is an optional attribute
In addition to windows authentication, you that specifies a class that communicates with
can use SQL server authentication. For SQL a specific type of database.
server authentication, instead of the To access the connection string that is defined in the
Integrated Security and Persist Security Info web.config file, you need to use the
attribute, you need to use the User ID and ConnectionStrings property of
Password properties, as shown in the the ConfigurationManager class from any Web
following example: page within the website. After accessing the
connection string, you can use it in the Connection
object by writing code shown in the following
myConnection.ConnectionString = "Data
example:
Source=172.23.3.59;Initial Catalog=Music;
string
User ID=sa;Password=password@123";
connString = ConfigurationM
anager.ConnectionStrings
After specifying the connection string, you need to ["myMusic"].ConnectionString;
open the connection. Then, the connection object is
ready to be used to access the data source. SqlConnection myConnection = new
You need to create the connection objects for all the SqlConnection();
Web pages in which you want to access data from a myConnection.ConnectionString = c
data source. Generally, all the database code in an onnString;
application uses the same connection string. myConnection.Open();
Therefore, it is not advisable to create separate
connection objects for all the Web pages because it Command Objects
makes an application slow. Moreover, you need to After a connection has been established with the
write the same code again. These problems can be data source, you can execute commands and return
solved by storing the connection string in the results from the data source by using a command
web.config file. If the connection string is stored in object.
the web.config file, it can be accessed from any Web To execute SQL statements, you need to create an
page within the application. You can store the instance of the SqlCommand class present in the
connection string in the <connectionStrings> System.Data.SqlClient namespace. The
section of the web.config file, as shown in the command object specifies the SQL statement that
following example: needs to be executed and the connection that needs
<configuration> to be used to execute the statement. You can
<connectionStrings> execute SQL statements or stored procedures
through command objects. r();
The following code snippet demonstrates how to The preceding code snippet defines a variable
create a command object: myReader and then stores data in it by executing the
// Create an object of the command. Once you have retrieved the data in the
SqlConnection class DataReader object, you can view a single row at a
SqlConnection connection = new time by using the Read() method, as shown in the
SqlConnection(); following code snippet:
// Create a connection string to myReader.Read(); // The first row
the HR database in the result set is now
connection.ConnectionString = "Da available.
ta Source=172.23.3.59;
Initial Catalog=HR; User
ID=sa; Password=niit#1234";
connection.Open(); //opening the
connection The Command object can also execute a
// Create an object of the DML statement against a connection object
SqlCommand class and returns the number of rows affected by
SqlCommand cmd = new SqlCommand using the ExecuteNonQuery method.
("select * from
monthlysalary",connection);
Dataset Objects
In the preceding code snippet, the SqlCommand
A dataset is a memory-based relational
object cmd is initialized to the SQL statement that
representation of data. A dataset is a disconnected,
needs to be executed.
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
The SqlCommand object can also be used connection to be opened all the time. Instead, they
to specify insert, update, and delete queries. cache data from the database and after that the
connection can be closed. This improves the
DataReader Objects application performance because once cached the
After defining the command object, you need to data is retrieved from the dataset instead of the Web
execute it to get the data from the data source. The server. It also optimizes the use of server resources
data returned by executing the command object because the connection is not used for a long time.
needs to be stored in another object. The The dataset object requires the data adapter to
DataReader object can be used to store the data retrieve data from the data source. You can retrieve
returned by executing the command object. The data from data source by using dataset by using the
DataReader object supports forward-only read- following code:
only access to the results returned by executing the SqlConnection myConn = new
command object. Therefore, it can be used when you SqlConnection("Data
need to retrieve information from a data source. The Source=SQLSERVER;Initial
DataReader object works in a connected Catalog=Music;User=sa; password=p
environment. It requires an open connection for its assword@123");
working. DataSet ds = new DataSet();
To create a DataReader object, you use the myConn.Open();
ExecuteReader() method of the command object, SqlDataAdapter da = new
as shown in the following code snippet: SqlDataAdapter("Select * from
//You don't need the new albums", myConn);
keyword, as the Command will da.Fill(ds, "albums");
create the //DataReader. GridView1.DataSource = ds;
SqlDataReader myReader; GridView1.DataBind();
myReader = myCommand.ExecuteReade 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 Sqlcon = new SqlConnection
displayed by using the GridView control. (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
Accessing Data by Using DAL DAL, the CreateConnection function creates the
DAL is a layer of code that provides simplified access connection depending on the connection string that
to the data stored in persistent storage such as a is passed as a parameter by the user. This provides
database. This layer is used by other program flexibility to the DAL and it can be reused in any
modules to access and manipulate data within the application that requires data access code.
data source without dealing with the complexities Consider another example that demonstrates a
involved in accessing the data. When using DAL, an function to retrieve data from a database table:
application calls the methods provided by DAL to public class Class1
access data instead of writing complex queries. {
DAL separates the data access code such as creating SqlConnection
a connection to the database, issuing SELECT, Sqlcon=null;
INSERT, UPDATE, and DELETE commands from the public void
application logic. Separating the data access code CreateConnection(String
from the application logic makes it easy to debug. It ConnString)
also makes the code reusable. Other applications can {
also use the code because it is not application Sqlcon = new
specific. SqlConnection(ConnString);
}

Advantages of Using DAL public DataSet


ExecuteQuery(String query)
DAL separates the data access code from the rest of {
the code. This provides the following advantages: SqlDataAdapter
q It minimizes the impact of a change in the Sqlda = null;
database provider. DataSet dset = null;
q It also minimizes the impact of a change in try
data representation such as a change in {
database schema. Sqlcon.Open();
q It simplifies testing and maintenance. Sqlda = new
q It increases code reusability because the data SqlDataAdapter(query, Sqlcon);
access code can be generalized to work dset = new
across applications. DataSet();
Sqlda.Fill(dset);
return dset;
Creating a DAL }
You can create a DAL by creating a class library and catch (Exception ex)
writing all the data access functions in that library. All {
the data access functions written in the class library throw ex;
should be generic. This is because a DAL is created to }
separate the data access logic from the application finally
layer. In addition, the functions written in a DAL {
should be reusable. Consider the following example: if (Sqlcon.State
public void CreateConnection == ConnectionState.Open)
(String ConnString) {
Sqlcon.Close
(); Doug Lowe & Joel Murach, http://www.asp.net/learn/
Sqlcon = null murach's ASP.NET 3.5 withpss/module5.aspx
; upgrader's Guide
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:
q The basic N-tier model consists of the
following layers:
Presentation Layer
Business Rules Layer
Database Access Layer
q You can implement data access logic in the
presentation layer (ASP.NET pages) by using:
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.
q The basic objects used to access data from a
database by using ADO.NET are:
Connection Objects
Command Objects
Data Reader Objects
q 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
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). Model of .NET LINQ
This chapter provides an overview of LINQ. In The .NET Language-Integrated Query model consists
addition, it discusses how to access data from of all the languages in which you can create your
disparate data sources. Web application. It includes the components such as
LINQ to ADO.NET, LINQ to XML, and LINQ to objects,
Objectives using which you can access the data from data
In this chapter, you will learn to: sources such as database, an arraylist, and an XML.
To retrieve data from data sources, you need to write
Identify the basics of LINQ
a LINQ query. Therefore, you need to know the
Access data from disparate data sources by different components of a LINQ query.
using LINQ

Identifying the Basics of LINQ Understanding the LINQ Query


A LINQ query is an expression that retrieves data
When creating a dynamic Web application, you need
from a data source. It enables you to write a standard
to retrieve data from various data sources, such as a
query expression to retrieve data form disparate data
flat file, an XML file, or a database. To access data
sources. It also allows you to filter, sort, group, and
from these disparate data sources, you need to learn
join the results of the query by using additional
and implement different techniques. For example, to
clauses in the query.
access data from files, you need to implement input/
output streams and to access data from a database, Accessing Data by Using a Simple
you need to implement SQL. This complicates your LINQ Query
task as a programmer. This task can be simplified by To access data by using LINQ, you need to perform
using LINQ. the following steps:
LINQ provides a standard way to access data from 1. Specify the data source.
disparate data sources. Using LINQ, you can access 2. Create the query.
data from disparate data sources by writing a 3. Execute the query.
standard query, LINQ query. This eases your task Specifying the Data Source
because you need not learn different technologies to In a LINQ query operation, the first step is to specify
access data. In addition, LINQ provides various the data source. The data source in a LINQ query can
facilities such as stronger typing, compile-time be an XML file, an array, a collection, or a database. If
checking, and improved debugger support. the data source that you want to use is an array, you
The following figure shows a model of .NET LINQ. can specify the data source by using the following
statement:
string[] customers = new string
[2] {John, Mary}; cannot be used when declaring the
In the preceding statement, the array, customers, is member variables of a class. Consider the
the data source. following examples:
Similarly, if the data source that you want to use is an
XML file, you can specify the data source by using var one = 1; //infers an int
the following statement:
XElement var two = "2"; // infers
customers = XElement.Load(@"c: a string
\myCustomerList.xml");
In the preceding statement, the XElement object, var five = null; // This
customers, is the data source. results in a compilation error
After specifying the data source, you need to create a because //the data type is not
query expression to retrieve or manipulate data from specified in the Right hand
the specified data source. side.
Creating the Query
A query describes what information is to be retrieved Executing the Query
from the specified data source. It must include the In LINQ, the query variable only stores the query. The
from and select clauses to retrieve data. The actual execution of the query is deferred until the
from clause specifies the data source from where query variable is iterated by using the foreach loop.
the data is to be retrieved and the select clause The foreach loop is the place where the query
specifies the type of the returned elements. Consider results are retrieved. Consider the following code
the following query: snippet:
var query = from <type of the //Query execution
value returned> cus in customers foreach (var cus in query)
select cus; {
The preceding query contains the from and select Response.Write(cus);
clauses. The from clause specifies the range variable }
cus and the data source Customers, and the In the preceding code snippet, the iteration variable
select clause specifies the type of the values that cus holds each value, one at a time, in the same
will be returned by the query. The query is stored in a sequence as returned by the query.
query variable, query. It is initialized with a query The query variable only stores the query that is to be
expression. 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
The range variable acts as an iteration updated data.
variable in a foreachloop. When the The execution of all the queries is not deferred till
query is executed, the range variable is query variable is iterated by using the foreach loop.
served as a reference of each item stored in The queries that perform aggregate functions such as
the data source, such as a database. 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
The varkeyword is a new keyword that can numbers
infer its data type from the resulting set. A where (num % 2) == 0
vartype variable needs to be initialized at select num;
the time of declaration. The varkeyword 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 In the preceding example, a class customer with
query is used to retrieve data from an ArrayList two properties, Name and City, is created. After
object: creating the class, an object of the ArrayList class
public partial class is created and three objects of the type customer are
Default : System.Web.UI.Page added to the ArrayList object. The ArrayList
{ object is the data source from which the data is
public class customer retrieved by using the LINQ query. The LINQ query
{ retrieves all the data from the data source.
public string Using LINQ Queries to Filter, Sort,
Name { get; set; }
public string
Group, and Join Data
In addition to selecting data, a query can perform the
City { get; set; }
following operations on data:
}
protected void Page_Load(object q Filtering
sender, EventArgs e) q Ordering
{ q Grouping
ArrayList arrList = new q Joining
ArrayList(); Filtering
arrList.Add( To retrieve data depending on certain criteria or
new customer condition, you need to filter the data. Filtering causes
{ the query to return only the data that matches with
Name the specified condition. The condition to retrieve
= "Svetlana", City = "London" 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:
arrList.Add( var query = from <type of the
new customer value returned> cus in customers
{ where
Name cus.City == "London"
= "Claire", City="Paris" select cus;
} You can also use the logical operators in the where
); clause to apply two or more conditions. For example,
arrList.Add( the following code snippet returns the data of the
new customer customers who live in London and have last name as
{ Darcy:
Name var query = from <type of the
= "Cesar", City="New York" value returned> cus in customers
} where
); cus.City == "London" &&
var query = from cust.Name == "Svetlana"
customer cus in arrList select cus;
select cus; Ordering
foreach (var cus in LINQ queries can also be used to retrieve data and
query) display it in a sorted manner. This can be done by
{ using the orderby clause. The orderby clause
Response.Write (c enables a user to sort the retrieved data in ascending
us.Name + " lives in " or descending order. For example, the following code
+ cus.City snippet returns the data for the customers who live in
+ "<br>"); London. The data is sorted by customer names in
} alphabetical order:
var query = you need to join the data from both the tables/
from <type of the value objects. This can be done by using the join clause,
returned> cus in customers as shown in the following code snippet:
where cus.City == "London" var query = from <type of the
orderby cus.Name descending value returned> cus in customers
select cus; join
<type of the value
returned> ord in Order on
cus.order_id
equals ord.order_id
The default value for the orderby clause Select
is ascending. new {CustomerName=cus.Name,
OrderAmount=Order.Amo
Grouping unt};
You can also retrieve data and group it by using the In the preceding code snippet, two ArrayList
group clause. For example, the following code objects customers and Order are the data sources.
snippet returns the data for all the customers, These ArrayList objects contain information about
grouped on the basis of the cities they live in: the cutomers and the orders placed by them. Both
var query = from <type of the the objects have a common field order_id, which is
value returned> cus in customers required to join data from these objects. The data
group cus by cus.City; from the preceding query can be retrieved by using
the following foreach loop:
When you end a query with a group clause, the
results take the form of a list of lists. Each element in foreach (var cus in query)
the list is an object that has a Key member and a list {
of elements that are grouped under that key. When Response.Write
you iterate over a query that produces a sequence of (cus.CustomerName + " has the
groups, you must use a nested foreach loop. The order amount " +
outer loop iterates over each group, and the inner cus.OrderAmount + "<br>");
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:
Accessing Data from Disparate
foreach (var cus in query) Data Sources
{
In Web applications, the data that is to be displayed
foreach (var i in cus)
on the Web pages may exist in disparate data
{
sources. These data sources can be objects,
Response.Write
databases, or XML files. You can access data from
(i.Name + " lives in "
these data sources either by using the LINQ queries
+ i.City +
or by using the LINQ data source control.
"<br>");
}
} Accessing Data by Using the
Joining
It is possible that the data you need to retrieve exists LINQ Queries
in more than one table/object. For example, you LINQ provides a standard query for retrieving data
need to retrieve information regarding the orders from disparate data sources. These queries can be
placed by a customer. The information regarding the used to access data from:
customers is stored in the customers table/object q Objects
and the information regarding the orders is stored in q Databases
the orders table/object. Both the tables/objects must q XML files
have a common field, which is required to join the
tables/objects. To retrieve the required information, Accessing Data from Objects
Data from objects can be accessed by using LINQ to protected void Page_Load(object
Objects. LINQ to Objects provides an easy way to sender, EventArgs e)
create a query for accessing data from an object {
collection such as an ArrayList by writing foreach SqlConnection
loops. MyConn = new SqlConnection();
To use LINQ to query an object collection, you need MyConn.ConnectionString =
to declare a range variable. The type of the range "Data
variable should match the type of the objects in the Source=172.23.3.59;Initial
collection. For example, if you create an ArrayList that Catalog=Music;User
stores objects of type customers, the range variable Id=sa; Password=password@123";
should also be of the customers type, as shown in DataSet ds = new DataSet
the following code snippet: ();
var query = from customers cust SqlDataAdapter da = new
in arrList SqlDataAdapter("Select * from
select cust; albums",MyConn);
In the preceding code snippet, a range variable cust MyConn.Open();
is of the type customers. By declaring a range da.Fill(ds);
variable, each item in the ArrayList is typecasted to a DataTable
customers object. album= ds.Tables[0];
The following example describes how to access data var q = from d in
from a string array that contains the names of album.AsEnumerable()
students in a class: select d;
string[] arr = new string foreach (var i in q)
[] { "Peter", "Sam" , "Philip"}; {
var query = from string person in Response.Write
arr (i.Field<string>
select person; ("Album_Name") + "<br>");
foreach (var p in query) }
{ }
Response.Write(p + "<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()
Accessing Data from Databases method. It changes the compile time type of a query
A Web application accesses most of the data from
to IEnumerable<T>. This means that the type can
databases. To access data from a database, you can
be used in a foreach loop.
use LINQ to ADO.NET. LINQ to ADO.NET includes the
following technologies to access data: LINQ to SQL
q LINQ to dataset LINQ to SQL provides a run-time infrastructure for
q LINQ to SQL managing relational data as objects. In LINQ to SQL,
the data model of a relational database is mapped to
LINQ to Dataset an object model created by the developer. While
A Dataset is a collection of cached data presented in querying data by using LINQ to SQL, it translates the
a tabular form. The data from a Dataset can be language-integrated queries in the object model
retrieved by using LINQ. LINQ to Dataset is basically defined by the developer and sends the data to the
used in situations where you have used ADO.NET for database for execution. The database returns the
accessing data from a database. Now, you want to result, and LINQ to SQL translates the result back into
implement LINQ queries in the application to get the the form of objects that can be used in a
benefits such as compile time checking of the query programming language to query data. This helps in
syntax and better performance. However, you want integrating the object-oriented features such as
minimal changes in the coding. In such a situation, classes and methods with SQL. The methods written
you can use LINQ to ADO.NET because by using to query data can be reused in any application
LINQ to ADO.NET, you just need to change the data because these methods are generic.
retrieval code that was used to access data from the
In addition, IDE such as Microsoft Visual Studio
Dataset. The rest of the code will remain the same.
provides the Object Relational Designer (O/R CustomerID>
designer), which provides a visual designer surface <Name>Cesar</Name>
for creating LINQ to SQL entity classes and <City>New York</City>
relationships that are based on objects in a database. </Customer>
</CustomersDetails>
To access the data from the
CustomersDetails.Xml by using LINQ, you need
LINQ to SQL entity classes are also used by the to write the following code snippet:
ASP.NET Dynamic Data to determine the user XDocument xmlDoc = XDocument.Load
interface that is based on the LINQ to SQL data ("D:\\Website7\\XMLFile2.xml");
model. ASP.NET Dynamic Data is a framework that var q = from c in
enables a user to create data-driven ASP.NET Web xmlDoc.Descendants("Customer")
applications with minimal or no coding. ASP.NET select (string)c.Element
Dynamic Data does this by automatically discovering ("CustomerID") + "-" + (string)
data-model metadata at run time and rendering the c.Element("Name")+"-" + (string)
user interface according to it. The data-driven c.Element("City")+"<br>";
ASP.NET Web applications created by using ASP.NET foreach (string name in q)
Dynamic Data provides: {
q Data access operations such as create, Response.Write(name);
update, remove, and display, relational }
operations, and data validation.
q Built-in support for foreign-key relationships.
q The ability to customize the user interface Accessing Data by Using the
rendered to display and edit specific data
fields.
LINQ Data Source Control
q The ability to customize data field validation. 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
Accessing Data from XML Files connected to any kind of data collection that is
XML is widely used to exchange data between stored in a public field or property. The declarative
various applications. LINQ to XML is a programming markup and code to perform data operations in a
interface that enables you to access data stored in LinqDataSource control are the same for all data
XML files. The following example shows the code in sources. You can bind data-bound controls to a
an XML file, CustomersDetails.Xml: LinqDataSource control by using the DataSourceID
CustomersDetails.Xml: property of the data-bound control.
<?xml version="1.0" The following table lists some properties of the
encoding="utf-8" ?> LinqDataSource control.
<CustomersDetails>
<Customer>
<CustomerID>C001</ ContextTypeName Gets or sets the name of
CustomerID>
the type that contains the
<Name>Svetlana</Name>
property whose value has
<City>London</City>
the data that is to be
</Customer>
retrieved.
<Customer>
TableName Gets or sets the name of
<CustomerID>C002</
the property or field in the
CustomerID>
data context object that
<Name>Claire</Name>
represents a data
<City >Paris</City>
collection.
</Customer>
<Customer> DeleteParameters Gets the collection of
<CustomerID>C003</ parameters that are used
during the delete q LINQ provides a standard query for
operation. retrieving data from disparate data sources.
Delete Performs the delete q LINQ queries can be used to access data
operation. from:
InsertParameters Gets the collection of Objects
parameters that are used Databases
during the insert XML files
operation. q You can also use the LINQ data source
Insert Performs the insert control to access data from disparate data
operation. sources.
SelectParameters Gets the collection of
parameters that are used
during the data retrieval
Reference Reading
operation. Identifying the Basics of LINQ
Select Gets or sets the properties
and the calculated values
included in the retrieved
Pro ASP.NET 3.5 in C# http://www.develop.com/
data.
2008 by Matthew course/new-net3-net35-
UpdateParameters Gets the collection of MacDonald, Mario linq
parameters that are used Szpuszta
during the update
operation.
Update Performs the insert Accessing Data from Disparate Data
operation. Sources

Properties of the LinqDataSource Control


You can retrieve data by using the LinqDataSource Professional ASP.NET 3.5: http://www.develop.com/
control, as shown in the following example: In C# and VB by Bill Evjen, course/new-net3-net35-
<asp:LinqDataSource Scott Hanselman, Devin linq
ID="LinqDataSource1" Rader
runat="server"
ContextTypeName="MyMusicDataConte
xt"
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:
q LINQ provides a standard way to access data
from disparate data sources.
q When accessing data by using LINQ, you
need to perform the following steps:
Specify the data source
Create the query
Execute the query
debugging because the users can see the event log
to know about the errors that occurred previously in
the application.
Chapter 8
Implementing Error Handling and Handling Errors
Debugging ASP.NET allows you to handle errors at the following
levels:
While developing a Web application, you may come q Page Level
across several errors. These errors can occur because q Application Level
of invalid data, unexpected circumstances, or even
hardware failure. Whenever an error occurs, the Page-Level Error Handling
application ends abruptly. Being a professional Web Page-level error handling is used to handle errors
developer, you need to ensure that your application that occur on ASP.NET pages. For example, when you
is able to handle errors. For this, you need to try to write to a non existing file, an error occurs on
consider all the possible cases of errors that can ASP.NET pages and can be handled by using Page-
occur in an application. level error handling. You can implement page-level
ASP.NET provides several error-handling and error handling either by using the try-catch block or
debugging techniques that you can use to secure by using the Page_Error subroutine.
your ASP.NET applications against common errors. Using the Try-Catch Block
This chapter discusses how to implement error- You can place the statements susceptible to errors in
handling techniques to capture errors in a Web a try-catch block. It is an error handling feature
application. It also discusses how to add error provided by most of the languages. It enables you to
messages to the event log. In addition, it discusses programmatically handle the errors that occur at
how to debug Web applications. runtime. The try block contains the code that may
cause an exception. It is followed by one or more
Objectives catch blocks, which specify the code for handling
the exception. To handle errors properly, you need to
In this chapter, you will learn to: retrieve information about the type and cause of the
Handle and log errors error and then handle the error. You can retrieve
Debug Web applications 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
Handling and Logging Errors inherited from the Exception class. The properties
included in the Exception class help you handle
A Web application may contain various types of
errors easily and efficiently. You can use the following
errors or bugs. Errors such as typing errors and
properties of the Exception class to handle errors:
syntax errors are detected at compile time. However,
q Message: Returns a string that represents
run-time errors such as division by zero and type
the error message.
mismatch cannot be detected at compile time. Such
q Source: Returns a string that represents the
errors can be dealt with by implementing effective
object or application that caused the error.
error-handling and debugging techniques.
q StackTrace: Returns a string that
For implementing effective error-handling
represents the methods called immediately
techniques, you should be able to classify errors and
before the error occurred.
identify situations where errors can occur in your
q TargetSite: Returns a MethodBase
Web applications. This is possible only for the errors
object, which represents the method that
that can be anticipated, such as division by zero.
caused the error.
However, there are errors such as logical errors that
Consider the following example. It uses the
cannot be anticipated. To secure your application
preceding properties to handle an error that can
against such types of errors, you need to implement
occur while opening a database connection:
debugging techniques to identify and solve the error.
<%@ Page Language="C#" %>
When an error occurs, details about the error can be
<%@ Import
added to an event log. This logging of errors helps in
Namespace="System.Data.SqlClient" <asp:DataGrid
%>
<script language="C#"
runat=server> ID="dgrdProducts"
void Page_Load(Object Runat="Server" />
sender , EventArgs e) </body>
{ </html>
SqlConnection mycon; In the preceding example, if an error occurs within
SqlCommand mycommand; the try block, statements in the catch block are
mycon = new SqlConnection( executed and detailed information about the error is
@"Server=localhost;Database displayed. The Exception object used in the catch
=SimpleCon;Connection block represents a generic exception. The catch
Timeout=15" ); block can also be used to capture particular
mycommand = new SqlCommand exceptions such as InvalidArgumentException
( "select * from or IndexOutOfRangeException. This is required
Products", mycon ); if specific information on the cause of error is
try { needed.
mycon.Open(); You can include the finally block in a try-catch
dgrdProducts.DataSource = block for cleaning up the resources. The finally
mycommand.ExecuteReader(); block always executes, irrespective of whether or not
dgrdProducts.DataBind(); an exception has occurred. For example, you can use
mycon.Close(); the finally block to close a database connection,
} as shown in the following code snippet:
catch (Exception try
objException) {
{ DgrdProducts.DataSource=mycommand
//Exception objException; .ExecuteReader();
Response.Write("Sorry we DgrdProducts.DataBind();
are experiencing technical }
problems..."); catch(Exception objException)
Response.Write("<hr>"); {
Response.Write Response.Write("Could Not Execute
("<li> Message: " Statement");
+ objException.Message); }
Response.Write finally
("<li> Source: " {
+ objException.Source); // closing the connection to the
Response.Write database
("<li> Stack Trace: " + mycon.Close();
objException.StackTra }
ce ); In the preceding code snippet, the finally block
Response.Write closes the database connection even if no exception
("<li> Target Site: " + is caught.
objException.TargetSi Using the Page_Error Subroutine
te.Name); 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
</script> running in a real-world environment. To handle such
<html> errors, you should include the Page_Error
<head><title>CatchException.aspx< subroutine in the .cs file for the page. This subroutine
/title></head> executes in case an unhandled exception occurs on a
<body> page. For example, you can use the Page_Error
subroutine to display an error message, as shown in
the following code snippet: The <customErrors>element will work
void Page_Error (Object when you start the application without
sender , EventArgs e) { debugging support.
Response.Write( "Sorry, an
error was encountered:" ); Consider the following example in the web.config
Response.Write( "<p>" ); file:
Response.Write <configuration>
( Server.GetLastError().Message); <system.web>
Server.ClearError(); <customErrors mode="On"
} defaultRedirect="Error.aspx">
In the preceding code snippet, the GetLastError </customErrors>
() method of the Server object returns the </system.web>
previous exception that had occurred in the page. </configuration>
The ClearError() method is used to clear the In the preceding example, the following two
error message. Clearing an error means that it has attributes of the <customErrors> element have
been handled. Once you have cleared the error, it is been set:
not passed to any higher level error handler such as
q mode: Specifies the mode for handling
the Application_Error event.
custom errors. The mode attribute can be set
Application-Level Error Handling to any of the following values:
Application-level error handling enables you to Off: Disables the display of custom
handle errors on ASP.NET pages, irrespective of error messages. The default error
where the errors occur in the application. If an error message is displayed for both local and
is not handled at the page level, it is passed to the remote users in case of an error.
application-level error handler. On: Enables the display of custom error
Some errors, such as leaving a required field blank, messages. The user-defined custom
are common on Web pages. Instead of writing error error messages are displayed instead of
handler code for the common errors on every Web the default error message for both local
page, you can use the application-level error and remote users.
handling code to handle these errors. RemoteOnly: Enables the display of
You can implement application-level error handling custom error messages for remote
either by using the <customErrors> element in the users only. The local users are shown
web.config file or by using the the default error message only.
Application_Error subroutine in the global.asax RemoteOnly is the default value of the
file. mode attribute.
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 Local users are the developers who
default error message to the user. You can use the are working on the same computer
<customErrors> element of the web.config file to on which the Web application is
control the details of the error information made deployed. Remote users are those
available to the users of ASP.NET applications. users who are accessing the Web
By using the <customErrors> element, you can application from a computer other
either completely hide the error information from the than the one on which the website
users or display customized error messages. You can is deployed.
also redirect users to an appropriate error page in
case an unhandled error occurs. q 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, occurs anywhere in the Web application.
Error.aspx, specifying that in the case of
an unhandled run-time error, the browser
should be redirected to the Web form, Logging Errors
Error.aspx.
It is possible that certain unexpected errors occur in a
The preceding example displays a single error page
Web application while it is running in a real-world
for all types of errors. However, it is possible to
environment. It would be easy to resolve such errors
display different error pages for different types of
if a log of these errors is maintained. ASP.NET
errors by including <error> elements within the
enables you to log unhandled errors in an event log,
customErrors section. Consider the following
database, or some other file. These event logs,
example:
databases, or files can be used by the administrator
<configuration>
to learn about the errors that are occurring in a Web
<system.web>
application. You can log information about all the
<customErrors mode="On"
errors whether they occur at the page-level or at the
defaultRedirect="Error.aspx">
application-level.
<error statusCode="404"
To log errors occurring in an application, you need to
redirect="PageNotFound.aspx" />
create a log for the application in the event log.
<error statusCode="408"
Whenever an unhandled error occurs in a Web
redirect="SessionTimeedOut.aspx"
application, the Application_Error event
/>
handler, written in the Global.asax file, is executed.
</customErrors>
Therefore, the event logging code can be written in
</system.web>
the Application_Error event handler.
</configuration>
A log can be created by using the EventLog class of
In the preceding example, if an error with the status
the .NET Framework. For using this class, you need to
code 404 occurs, the user will be redirected to the
import the System.Diagnostics namespace.
error page, PageNotFound.aspx. If an error with
the status code 408 occurs, the user will be The following table describes the various properties
redirected to the error page, of the EventLog class.
SessionTimedOut.aspx. However, if an error with
any other status code occurs, the user will be
redirected to the default error page, Error.aspx. Entries Retrieves the contents
from an event log.
Using the Application_Error Subroutine
Application-level errors can also be handled in the Log Specifies the name of the
event handler for the Application.Error event log from where the log
that occurs whenever an unhandled error occurs in information is to be read
an application. The event handler for this event is or written.
written in the Global.asax file. You can use this event Source Specifies the name by
handler to capture the errors for logging or which the application
notification. needs to be registered in
This event handler is similar to the Page_Error the event log. The name
event handler. The only difference is that it operates specified as the Source
at the application level. property should be unique
Consider the following code snippet: in an event log. A single
protected void Application_Error event log can contain
(Object sender, EventArgs e) content from multiple
{ sources.
Response.Redirect
("ErrorPage.aspx"); Properties of the EventLog Class
} The following table describes the various methods of
In the preceding code snippet, the the EventLog class.
Application_Error event handler redirects the
user to the ErrorPage.aspx page in case an error
Exists Determines whether the To enable debugging in an ASP.NET Web application,
log to which the you must configure the application to compile into a
information is to be debug build. A debug build includes the information
written or read exists on that the debugger needs to debug the code. You can
the specified computer. If configure a Web application to compile into a debug
the computer is not build by setting the debug attribute in the
specified, the existence of <compilation> element of the web.config file to
the log is checked on the true, as shown in the following markup:
local computer. <configuration>
SourceExists Determines whether a <system.web>
particular source name <compilation debug="true" />
already exists on the </system.web>
specified computer. If the </configuration>
computer is not specified, However, if you want to debug only a single page in
the existence of the event your Web application, you can add the debug
source is checked on the attribute and set its value to true in the @ Page
local computer. directive of the page that you wish to debug, as
CreateEventSource Establishes an application shown in the following markup:
as a valid event source for <%@ Page debug="true" %>
adding information to a Application execution becomes slow when
log. debugging is turned on. For this reason, debugging
WriteEntry Writes information to an has to be turned off before the deployment of the
event log. 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
Methods of the EventLog Class
following markup:
<compilation defaultLanguage="C#"
debug="false" />

Debugging Web Applications Features of Debugging


Debugging is the process of finding and fixing errors Debugging allows you to run your code line by line
in an application. An application may contain syntax to monitor the program execution. You can check the
errors, logical errors, and run-time errors. The syntax state of the application objects such as variables and
errors are resolved during the compilation of the database table values to ensure that the application
Web application. However, logical errors and run- is running properly. A debugger includes the
time errors cannot be identified during compilation. following features that help you debug Web
Such errors require you to debug the code while it is applications:
running. q Breakpoints: Breakpoints are places in the
There are various tools available that help you debug code where the debugger stops the
your Web application. One such tool is Visual execution of the Web application. This allows
Debugger. It is available in Visual Studio IDE. These you to view the current state of data in your
tools enable you to step line-by-line through the Web application. You can step through each
statements in an application to ensure that the line of code when executing the Web
execution path and the data are correct. Before using application.
these tools, you need to configure your Web q Stepping: Once the execution of the Web
application for debugging. application has been stopped at a
breakpoint, you can execute the code line by
line, which is known as stepping through the
Configuring Web Applications for code.
q Data Viewing: This feature allows you to
Debugging 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 Reference Reading
can then continue to run the application with
the modified data. Handling and Logging Errors
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 Beginning ASP.NET 3.5 in http://wiki.asp.net/
does by using the debugger. VB 9.0: From Novice to page.aspx/383/custom-
Professional by Matthew error-logging/
MacDonald

Debugging Web Applications

Summary Beginning ASP.NET 3.5 in http://www.informit.com/


VB 9.0: From Novice to articles/article.aspx?
In this chapter, you learned that: Professional by Matthew p=29419
q The errors can be handled at the following MacDonald
two levels:
Page Level
Application Level
q The page-level error can be handled either
by using the try-catch block or by using the
Page_Error subroutine.
q Application-level error handling enables you
to handle errors on ASP.NET pages,
irrespective of where they occur in the
application.
q 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.
q ASP.NET enables you to log unhandled
errors in an event log, database, or some
other file.
q An event log can be created by using the
EventLog class of the .NET Framework.
q Debugging is the process of finding and
fixing errors in an application.
q There are various tools available that help
you debug your Web application. One such
tool is Visual Debugger, available in Visual
Studio IDE.
q The features of a debugger that help you
debug Web applications are:
Breakpoints
Stepping
Data Viewing
q The aspnet_wp.exe process is attached to the
debugger to debug a running page.
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
Chapter 9 information. A Web part enables a user to create a
personalized user interface and enables you to
Enhancing Web Applications by present information in a better way. It also enables
you make your websites interactive.
Using Web Parts
Being a Web developer, you need to develop
websites that appeal users. Users today want to do Advantages of Using Web Parts
much more than just viewing the content on the Web parts allow the information displayed on a
website. They want to personalize Web pages website to be broken down into manageable parts.
according to their interest and preferences. You can Users can rearrange, move, or close the Web parts to
implement personalization on your websites by suit their preferences. Users can also save their
implementing Web parts. Users can use these Web preferences for future browser sessions.
parts to personalize Web pages. The advantages of using Web parts on a website are:
In addition to using Web parts, you can enhance a q Web parts enable users to personalize the
Web application by including commonly-used content of a Web page. Users can move or
features such as information about astrology, latest hide Web parts to customize the Web page.
news updates, cricket scores, temperature of the day, They can even add new Web parts to change
or weather forecast. These features are common and the layout of the page.
are provided on the Internet through Web services. q Web parts can be assigned role-based
You can easily include these features on your website access, thereby, determining which Web part
by consuming existing Web services. can be shared by all users or which should
This chapter discusses Web parts and their be hidden for certain roles. This helps in
implementation. In addition, it discusses how to providing customized content based on
consume Web services for providing various features security.
in a Web application. q Web parts can be connected to each other.
One of the connected Web parts is defined
Objectives as a provider and the other as a consumer.
In this chapter, you will learn to: Consider the example of a Web parts page
that contains two Web parts, one displays a
Implement Web parts in a Web application
chart and another displays the stock market
Consume Web services in a Web application 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
Implementing Web Parts in a the other Web part. In this example, the Web
Web Application part providing the stock market data is the
provider and the Web part displaying the
Today, a website may contain a wide variety of chart is the consumer.
information regarding various domains, such as
entertainment, astrology, business, sports, and
technology. However, users may be interested in Web Part Modes
viewing only the information of their interest.
Therefore, websites such as MSN.com organize their Personalization is one of the main advantages of
data into discrete units. Each unit represents a using Web parts. You can implement personalization
standalone part of the website and contains by allowing a user to view a Web page in several
information about a specific domain. These units display modes.
support a degree of personalization. Users can Display modes allow users to modify or personalize
rearrange or hide these units to suit their individual the Web page. Users can edit the Web part controls,
working styles. These units can be developed by change the layout of the Web page, and add new
using ASP.NET and are known as Web parts. Web part controls by using different types of display
modes. The different types of display modes
available are: WebPartManager Manages all the Web part
q Browse: This is the default mode. This mode controls on a page. Each
allows users to view Web parts on the Web Web parts page contains
page. It also allows users to minimize or exactly one
close the Web part. If you close a Web part, WebPartManager control.
it cannot be restored from the Browse mode. CatalogZone Contains CatalogPart
However, you can restore it in another mode controls and is used to
called the Catalog mode. The following create a catalog of Web
figure shows a Web part in the Browse part controls from which a
mode. user can select a Web part
control to add to a page.
EditorZone Contains EditorPart
controls and is used to
A Web Part in the Browse Mode enable a user to edit and
q Edit: This mode allows users to edit Web personalize Web part
parts on the Web page at runtime. Users can controls on a page.
set the title, color, or custom properties of WebPartZone Contains the overall
the Web parts. layout for the Web Part
q Design: This mode allows users to rearrange controls that compose the
the order of Web parts on the Web page by main user interface of a
dragging and dropping them. page.
q Catalog: This mode allows users to add new ConnectionsZone Contains Connection
Web parts on the Web page. It also allows controls.
users to rearrange or delete the existing Web CatalogPart Contains a list of available
parts from the Web page. Web part controls that a
q Connect: This mode allows users to connect user can add to a page.
two Web part controls on a Web page. Connection Creates a connection
between two Web part
controls on a page.
EditorPart Serves as the base class for
specialized controls that
A Web page can be displayed in only one provide the functionality
display mode at a time. to edit Web parts.

Some of the Web Part Controls Available in


ASP.NET
Web Parts Control Set To implement Web parts on your website, you first
ASP.NET provides you with the Web parts control set need to add a WebPartManager control and one or
that are designed to implement Web parts on your more WebPartZone controls to the Web page. The
websites. A Web parts control set consists of a group WebPartManager control is used to manage all the
of Web parts that work together to enable users to Web part controls on the Web page. The
create Web parts pages. A Web page that is WebPartZone control serves as a container for the
composed of Web parts is known as a Web parts Web part controls. After adding these controls, you
page. A Web parts page is divided into zones that need to add the controls on your Web pages. These
provide the structure for placing Web parts. You can controls can be the existing Web server controls or
place Web parts in any of these zones according to Web user controls.
your requirements. Once you have created a Web parts page, you can
The following table describes some of the Web part allow users to change the appearance of the user
controls available in ASP.NET. interface elements on the Web page. This can be
done by changing the display mode of the Web parts
page. consumer control can use once the connection is
To enable a user to switch between the various established.
modes, you can include a drop-down list on the Web To participate in a connection, a Web part needs to
page that allows a user to select the desired mode. define a connection point. A connection point
After including the drop-down list on the Web page, contains the details necessary for a server control to
you can type the following code snippet in the connect to another control. These details include
SelectedIndexChanged event of the information such as the type of the control itself, the
DropDownList control: type of data the control recognizes, an ID for the
WebPartManager wpm = connection point object, and whether the control can
WebPartManager.GetCurrentWebPartM form multiple connections. Connection points are of
anager(Page); two types, provider connection points and consumer
string connection points.
selectedMode = DropDownList1.Sele To create connected Web parts, you need to perform
ctedValue; the following tasks:
WebPartDisplayMode mode = 1. Create the provider Web part as a custom
wpm.SupportedDisplayModes control that derives from the WebPart class
[selectedMode]; and implements an interface that defines the
if (mode != null) communication contract. The provider Web
{ part defines a connection point in the form
wpm.DisplayMode = mode; of a method to which the
} ConnectionProvider attribute has been
The preceding code snippet, enables a user to applied.
change the mode of the Web parts present on the 2. Create the consumer Web part as a custom
Web page by selecting the edit mode from the control that derives from the WebPart class
DropDownList control. 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
Connecting Web Parts to a Web parts page and assign an ID and
There are situations where you need to connect sets title to each of the two controls.
of data from different data sources. For example, a 5. Add the connection information to the
Web parts page contains two Web parts, one that WebPartManager control by opening the
contains details of senior managers of a department Web parts page in the Source view and
and the other that displays their photographs, one at adding a <staticConnections> element
a time. You can connect these Web parts in such a inside the <asp:WebPartManager>
way that when you select the name of a manager in element, as shown in the following example:
the first Web part, the other Web part displays the <StaticConnections>
photograph of the selected manager. <asp:WebPartConnection
In the preceding example, the Web part containing
ID="wpCon"
the details of senior managers is the provider and the
ProviderID="Provider1"
Web part that displays the photograph of the
ProviderConnectionPoint
selected senior manager is the consumer.
ID="Color"
ConsumerID="Consumer1"
Web part connections are based on a pull model,
ConsumerConnectionPoint
where the consumer pulls data from the provider. To
ID="Color" />
create a connection, the provider control defines a
</StaticConnections>
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
a standard protocol called SOAP. SOAP defines a
Consuming Web Services in a standard way of passing the XML-encoded data.
Web Application Developing ASP.NET Web services starts by creating
an .asmx file and hosting it on a Web server, such as
There are certain things that most websites require. IIS. Once hosted or published on the server, a Web
For example, almost all websites provide the service can be consumed by any client. The client can
searching functionality on their home pages. One be a Web application, desktop application, console
way to provide this functionality on your website is to application, or another Web service based on .NET or
write your own code. The other way is to use an other platforms such as Java.
existing code, and this can be done by using Web The client, who has to consume a Web service,
services. locates the service by adding a Web reference. This
Web services are the application components that adds a proxy class on the client side, which exposes
can be used by other Web applications. You can the methods, parameters, and return types of the
create a Web service and publish it on a Web server, methods contained in the Web service. After adding
thereby, making it available for other Web the proxy class, the client application creates an
applications to use. 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
Invoking Web Services class. It transforms the method calls of the client into
A Web service is a self-describing Web component the SOAP message format, which can be transmitted
that exposes its functionality to the consumers over HTTP to the server. After processing the request,
through open standards such as XML and Simple the response is also sent as a SOAP message to the
Object Access Protocol (SOAP). It is a widely used proxy. The proxy then converts this SOAP message
method for implementing Service-Oriented into method return value, which is returned to the
Architecture (SOA). client.

SOA is software architecture, which is Invoking WCF Services


essentially a collection of services
communicating with each other. It was In distributed computing, Web services along with
developed for enabling the development of various other technologies, such as COM+, .NET
loosely-coupled distributed applications. 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.
Coupling refers to the interrelatedness and
If a developer decides to use more than one
interdependency between two or more
technology, a lot of code needs to be written and
components of a Web application. In
unification becomes tedious. In addition, developers
loosely-coupled distributed applications, it need to learn different technologies to cater to the
is possible to change one component different needs of distributed application
without affecting other components. development. For example, to provide security to the
Web services, WSE support needs to be separately
Web services allow integration of applications added with the Web service. Similarly, if there is a
developed in different languages and running on requirement to host a Web service on TCP and HTTP,
different platforms. This integration and separate coding needs to be defined for both.
interoperability in Web services is made possible with To overcome the complexity in the integration of
the use of XML. Web services communicate by using 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. A WCF Service is a program that exposes a
WCF aims at providing encoding, hosting, messaging collection of Endpoints. An Endpoint is used
patterns, networking, security, and interoperability in for communicating with other services and
a single infrastructure. This helps in simplifying the applications. An Endpoint has an Address, a
development of distributed applications. Binding, and a Contract. An Endpoint
The following figure shows the WCF architecture. 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
The WCF Architecture <system.serviceModel> element.
The following set of APIs is unified in the WCF
architecture: The design goals for building WCF services are:
q ASP.NET Web Services (ASMX): It provides q Unification: WCF increases productivity by
support and interoperability with Web bringing together various technologies such
services running on non-Windows platforms. as COM+ and .NET Enterprise services,
q WSE: It provides end-to-end standards- Message Queues, .NET Remoting, ASP.NET
based security for Web services. Web Services, and WSE for building
q System.Messaging: It is a namespace in distributed applications by using a unified
the .NET Framework that provides managed programming model.
APIs to Microsoft Message Queues (MSMQ), q Interoperability: WCF increases the
enabling developers to build asynchronous interoperability options with .NET-to-.NET
reliable distributed applications. applications by providing built-in support
q Enterprise Services: It provides managed of .NET Remoting. It allows basic
APIs to COM+. COM+ provides component- communication with other applications
based programming for functionality such as running on other platforms.
transactions. q Service orientation: WCF provides a highly
q Remoting: It exposes the Common productive programming model for building
Language Runtime (CLR) type system distributed systems that involve developing
remotely and provides location transparency loosely-coupled services. These services can
for objects. Remoting is designed for tightly be independently managed, updated, and
coupled .NET-to-.NET application deployed.
communication. It provides seamless and
simple development experience for
applications on the local network and the
Internet.

Summary
In this chapter, you learned that:
q A Web part is a modular unit that can
In tightly coupled applications, the
contain any type of Web-based information.
components are interconnected with each
q The advantages of using Web parts on a
other such that any change in one website are:
component will lead to changes in other Web parts enable users to personalize
components as well. the content of a Web page.
Web parts can be assigned role-based
access, thereby determining which Web Beginning ASP.NET 3.5: In http://
parts can be shared by all users or C# and VB by Imar encosia.com/2008/03/27/
which should be hidden for certain Spaanjaars using-jquery-to-consume-
roles. aspnet-json-web-services/
Web parts can be connected to each
other. http://
q The different types of display modes of a www.codedigest.com/
Web part are: Articles/
Browse mode ASPNET/52_ASPNET_35_A
Edit mode JAX_and_WebServices__.as
Design mode px
Catalog mode
Connect mode
q A Web page that is composed of Web parts
is known as a Web parts page.
q A Web parts page is divided into zones that
provide the structure for placing Web parts.
q 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).
q 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

Pro ASP.NET 3.5 in C# http://


2008 by Matthew www.hotscripts.com/
MacDonald, Mario Detailed/79303.html
Szpuszta
http://books.google.co.in/
books?q=Implementing
+Web+Parts+in+a+Web
+Applications+in
+ASP.NET
+3.5&source=in&sa=X&o
i=book_group&resnum=1
1&ct=title&cad=bottom-3
results

Consuming Web Services in a Web


Application
q The full page is rendered and transferred to
the client after each postback, which is time
consuming and traffic intensive.
Chapter 10 To overcome these drawbacks, a technology called
AJAX is implemented in Web applications. By
Creating Rich Internet implementing AJAX in Web applications, the
interaction between the client and the server
Applications Using AJAX becomes asynchronous. This allows users to interact
In a traditional Web application, when a user submits with the Web application while waiting for a
any data, it is transferred synchronously to the Web response from the server. In addition to this, AJAX
server. This means that the user cannot interact with implementation enables partial updates in Web
the application till the data transfer activity is applications. This means that instead of sending the
completed. Moreover, these applications always entire page, only the portion that needs to be
reload the complete Web page even when a single updated is sent to the server.
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 Understanding AJAX
Asynchronous JavaScript and XML (AJAX). AJAX is a Web development technique that is used to
This chapter provides an overview of AJAX. It further create dynamically interactive applications. It enables
discusses the various AJAX server controls provided Web applications to retrieve data from the server,
by ASP.NET. In addition, it discusses the client life- asynchronously in the background, without
cycle events and explains how to consume Web interfering with the display and behavior of the
services in AJAX-enabled applications. existing page. To understand the concept of AJAX,
you need to understand the relevance of the
Objectives following terms:
In this chapter, you will learn to: q Asynchronous communication:
Asynchronous communication is the ability
Explain the AJAX framework
of an application to send multiple requests
Identify the ASP.NET AJAX server controls and receive responses from the server
Identify the ASP.NET AJAX client life-cycle events simultaneously. This enables the users to
Consume Web services in AJAX-enabled work continuously on the application without
applications being affected by the responses received
from the server.
q JavaScript: JavaScript is the scripting
Explaining the AJAX Framework language that is used to generate client-side
scripts. JavaScript forms an integral part of
In traditional Web applications, the client and the
the AJAX-enabled Web applications because
server interact synchronously. This means that the
these applications process most of the
processing of a Web application happens
requests on the client side, unless there is a
sequentially, one after the other. When the client
need to connect to the Web server. The
requests a page for the first time, the server sends
client-side processing of data is handled by
the full page containing HTML and Cascading Style
using JavaScript object support in AJAX.
Sheet (CSS) code at once. The client enters or
The XMLHttpRequest object is one of the
updates the information on the page and submits it
primary objects used by JavaScript because it
to the server. The server then processes the
enables asynchronous communication
information, rebuilds the page with the updated
between the client and the server.
information, and sends the full page back to the
q XML: XML is the standard used for
client. This leads to the following drawbacks:
transferring data between applications. XML
q The user interaction with the application is forms the base for manipulating the data
interrupted every time a postback is made by received from the server and presenting of
the server. the data in the Web application.
q The user has to wait during each postback. 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:
q Quick response to a user’s 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.
q 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.
q Auto-generated proxy classes that are used
to call Web service methods from client
script such as JavaScript.
q 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:
q Browser Integration: The AJAX-enabled
Web application does not register the
dynamically-created Web page in the Web
browser’s 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 The ASP.NET AJAX Architecture
to bookmark a particular state of the Web The preceding figure shows that the ASP.NET AJAX
application. architecture consists of the following components:
q Dependency on JavaScript: The AJAX- q Client-based Microsoft AJAX library
enabled Web applications are based on q Server-based AJAX features for ASP.NET
JavaScript. JavaScript may be interpreted
differently by different Web browsers or Client-Based Microsoft AJAX Library
versions of a particular Web browser. The ASP.NET AJAX client architecture provides
You can create AJAX-enabled Web applications by features that enable you to create rich, intuitive,
using the .NET Framework. The .NET Framework responsive, and interactive Web applications. This
enables you to create rich and intuitive websites by architecture includes the ASP.NET AJAX library. This
providing support for AJAX features. It provides a set library includes:
of extensions to ASP.NET for implementing AJAX q Components
functionality. This set of extensions is known as q Browser compatibility
ASP.NET AJAX. To create AJAX-enabled Web q Networking
applications by using the .NET Framework, you need q Core services
to understand the ASP.NET AJAX architecture. Components
The client components enable a Web application to
render dynamic behavior to the Web browser
Architecture of ASP.NET AJAX without requiring a postback to the Web server.
There are various client components such as non-
The ASP.NET AJAX Web applications consist of client-
visual objects and controls. Non-visual objects, such
side and server-side scripts. Therefore, these
as a timer object, encapsulate the code that needs to
applications use both, the client-side and the server-
be repeated after a fixed interval.
side functionality. The client-side and the server-side
functionality are provided by the two components of Browser Compatibility
the ASP.NET AJAX architecture, client-script libraries The browser compatibility feature provides
and server components. These components together compatibility for client scripts with major Web
provide a strong development framework for browsers, such as Microsoft Internet Explorer, Mozilla
developing AJAX-enabled applications. Firefox, and Apple Safari. This feature makes your
The following figure displays the ASP.NET AJAX Web application browser-independent.
architecture. 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 Web browser when the application is requested for
to the methods or services at the remote locations. the first time. These client scripts provide the
The networking layer automatically handles partial- following features:
page updates for the UpdatePanel control in your q Partial-page rendering: Enables you to
Web application. It also allows Web applications to update portions of the page by using an
access the server-based forms authentication, role asynchronous postback.
information, and profile information in a client script. q The Microsoft AJAX library: Provides a set
The Web applications that are not created by using of JavaScript extensions that provide
ASP.NET can also use the networking layer if they namespaces, inheritance, interfaces,
have access to the Microsoft AJAX library. enumerations, and reflection.
Core Services You can also create your own custom client scripts
The ASP.NET AJAX client architecture provides for the AJAX-enabled Web applications. The custom
various core services, such as JavaScript base class client scripts can be saved as static files or can be
extensions, support for JavaScript libraries, embedded in an assembly with .js extension.
debugging, error handling, and globalization. The Web Services
JavaScript libraries are either embedded in the An AJAX-enabled Web application can call ASP.NET
assemblies or provided as standalone JavaScript files Web services (.asmx) and WCF services (.svc) by using
with the .js extension. client scripts. An AJAX-enabled Web application can
The core services also include the Sys.Debug class call the Web services without a postback. When a
to handle debugging in your Web application. In user requests for a Web page for the first time, the
addition to the Sys.Debug class, the core services proxy class is automatically generated by the server
also include the Error object for handling errors in and downloaded to the browser at the page-load
your Web application. The Error object provides time. This proxy class can be used to call the
support for the release mode and the debug mode corresponding Web service methods.
of the Web application. 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
In the debug mode, the debug information performed to verify credentials, such as login id and
is generated, which is used for rectifying the password, of the users. The ASP.NET roles are used to
errors in the code. It is used at the time of group multiple users under one role, such as
development of an application. In the grouping all the heads of each department in an
release mode, the debug information is not administrator role. The profile of a user consists of
generated. It is used at the time of the information such as background and foreground
deployment of an application because it is colors of the application that is set when the user
much faster than the debug mode. logs on to the application.
The application services can be called by various
clients, such as a client script in an AJAX-enabled
Server-Based AJAX Features for Web page, a WCF-compatible client, or a Windows
ASP.NET application.
The ASP.NET AJAX server architecture provides the Server Controls
functionality for the following server-based AJAX The ASP.NET AJAX server controls consist of server-
features: side script as well as client-side script. This allows a
q Script support Web application to provide rich client behavior. A
q Web services Web page that consists of AJAX server controls sends
q Application services supporting client script to a Web browser while it is
q Server controls rendered to a user to provide AJAX functionality on
Script Support the Web page. The AJAX functionality include partial-
AJAX features in an ASP.NET application can be refreshing of the Web page, asynchronous
implemented with the support of client scripts. These communication between the Web browser and the
client scripts are sent from the Web server to the Web server, and faster response to the user.
EnablePageMethods Gets or sets a value that
indicates whether static
Identifying the ASP.NET AJAX page methods on an
Server Controls ASP.NET page can be
called from a client script.
ASP.NET offers various AJAX server controls that The default value is false.
implement AJAX functionality in a Web application. EnablePartialRender Gets or sets a value that
Some of the controls offered by ASP.NET are: ing enables partial rendering
q ScriptManager control of a page, which in turn,
q ScriptManagerProxy control enables you to update
q UpdatePanel control regions of the page
q UpdateProgress control individually by using the
q Timer control UpdatePanel server
controls.

The ScriptManager Control Properties of the ScriptManager Control


The ScriptManager control can be used to manage
the client script for AJAX-enabled Web applications.
The ScriptManager control provides: The ScriptManagerProxy Control
q The custom scripts that you need to send to The ScriptManager control is used to manage the
the Web browser to enable asynchronous client script for AJAX-enabled Web applications. The
communication with the Web service and ScriptManager control provides features such as
partial-page refreshes. partial page updates. However, there is a limitation in
q The JavaScript classes that are used to using the ScriptManager control. You can add only
access the ASP.NET application services for one instance of the ScriptManager control to a Web
forms authentication, roles, and user profiles. page. A Web page can include the control either
q The JavaScript proxy classes that are used directly or indirectly inside a nested component such
to call Web service methods from the client as a user control or a content page for a master
script. page. This means that if a master page has a
The ScriptManager control can be added to a Web ScriptManager control, you cannot add a
page by using the following markup: ScriptManager control to the content page, which is
<asp:ScriptManager using the master page.
ID="ScriptManager1" This limitation can be overcome by using the
runat="server"> </ ScriptManagerProxy Control. This means that if a
asp:ScriptManager> page that already contains a ScriptManager control
The preceding markup adds a ScriptManager server needs another ScriptManager control for a nested or
control with a unique ID ScriptManager1 to the parent component, the component can include a
Web page. ScriptManagerProxy control. The ScriptManagerProxy
The following table describes some properties of the control enables you to add scripts and services that
ScriptManager control. are specific to nested components.
The following table describes some properties of the
ScriptManagerProxy control.
AsyncPostBackErrorM Sends error message to
essage the client when an
unhandled server Scripts Gets a
exception occurs during an ScriptReferenceColl
asynchronous postback. ection object that
AsyncPostBackTimeou Gets or sets a value that contains a
t indicates the period of ScriptReference
time, in seconds, before object for each script file
asynchronous postbacks that is explicitly registered
are timed out.
with the UpdatePanel control.
ScriptManagerProxy
control.
Services Gets a ChildrenAsTriggers Gets or sets a value that
ScriptReferenceColl indicates whether
ection object that postbacks from immediate
contains a child controls of an
ScriptReference UpdatePanel control
object for each service that update the panel's
is explicitly registered with content. The default value
the ScriptManagerProxy is false.
control. Triggers Gets a collection of all the
triggers that are applied
Properties of the ScriptManagerProxy Control on the UpdatePanel
control such as
AsyncPostBackTrigger and
The UpdatePanel Control PostBackTrigger
objects.
The UpdatePanel server control is a container control
that helps you create highly interactive and UpdateMode Gets or sets a value that
responsive Web applications. The UpdatePanel indicates when an
control is used with the ScriptManager control to UpdatePanel control's
enable partial-page rendering. content is updated.
You can add more than one UpdatePanel controls to RenderMode Gets or sets a value that
a Web page. The UpdatePanel control can contain indicates whether an
other Web server controls such as Label and TextBox UpdatePanel control's
controls. When the Web page with multiple content is enclosed in an
UpdatePanel controls is rendered for the first time, HTML <div> or <span>
the content for the controls present in the element.
UpdatePanel controls is sent to the Web browser. For
subsequent page postbacks, the controls present in Properties of the UpdatePanel Control
the UpdatePanel controls update independently.
For example, in your AJAX-enabled Web application,
you have used three UpdatePanel controls. In each The UpdateProgress Control
UpdatePanel control, you have placed one GridView The UpdateProgress control is used to provide
control. When the Web page is loaded for the first information on the status of the partial-page updates
time, the data for all the GridView controls is in the UpdatePanel controls. If the partial-page
rendered by the Web server. On subsequent partial- update is slow, you can use the UpdateProgress
page refreshes, the data in the GridView controls is control to provide a message about the status of the
updated independently when the user interacts with update. For example, you can use the
them. UpdateProgress control in situations where the client
You can use the UpdatePanel control on Master application has requested for voluminous data that
pages, content pages, and in the GridView or will take a substantial amount of time to load, such
Repeater controls. as retrieving more than 500 records in a single
You can add an UpdatePanel controls to a Web page request or request for a heavy video file from the
by using the following markup: server.
<asp:UpdatePanel The UpdateProgress control can be customized. You
ID="UpdatePanel1" runat="server"> can modify the default content and the layout of the
</asp:UpdatePanel> UpdateProgress control.
The preceding markup adds an UpdatePanel server The UpdateProgress control can be added to a Web
control with a unique ID UpdatePanel1 to the Web page by using the following markup:
page. <asp:UpdateProgress
The following table describes some properties of the
ID="UpdateProgress1" page to the Web server at predefined time
runat="server"> </ intervals.
asp:UpdateProgress> The Timer control embeds a JavaScript component
The preceding markup adds an UpdateProgress into the Web page. The JavaScript component
server control with a unique ID initiates the postback from the Web browser to the
UpdateProgress1 to the Web page. Web server, every time the predefined time interval
The following table describes some properties of the has lapsed. When the postback is initiated, the Timer
UpdateProgress control. 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
AssociatedUpdatePan Gets or sets the ID of the the event.
elID UpdatePanel control for You can place multiple Timer controls on a Web
which the UpdateProgress page. You can associate each Timer control with a
control displays the status different UpdatePanel control. However, you can also
of update. place one Timer control on the Web page and
DisplayAfter Gets or sets the value (in associate it with all the UpdatePanel controls.
milliseconds) before the You can add a Timer control to a Web page by using
UpdateProgress control is the following markup:
displayed. The default <asp:Timer ID="Timer1"
value is 500 milliseconds. runat="server"> </asp:Timer>
DynamicLayout Gets or sets a value that The preceding code adds a Timer server control with
determines whether the a unique ID Timer1 to the Web page.
progress template is The following table describes some properties of the
rendered dynamically. Timer control.

Properties of the UpdateProgress Control


Enabled Gets or sets a value that
indicates whether the
The Timer Control Timer control initiates a
postback to the server
The Timer control is used with the UpdatePanel after the number of
control to perform partial-page updates at a milliseconds specified in
predefined time interval. The Timer control can also the Interval property has
be used to post the entire Web page at a predefined elapsed.
time interval. Interval Gets or sets the number of
You can use the Timer control in your Web milliseconds to wait before
application to perform the following tasks: initiating a postback to
q Periodical updates of one or more the server. The default
UpdatePanel controls without refreshing the value is 60,000
entire Web page. milliseconds.
q Execution of the code at the server each time
the Timer control causes a postback. When Properties of the Timer Control
the tick event of the Timer control is raised, it
AJAX server controls raise some events when a client
causes a postback and the code written
interacts with them. These events describe how an
under the tick event handler is executed. For
AJAX-enabled Web application is loaded when
example, a part of a website that displays the
requested for the first time or how it behaves when a
score of a cricket match is updated after
user sends a request to the Web server. To
every one minute. The code for updating the
understand the events raised by an AJAX-enabled
score can be written under the tick event
Web application, you need to understand the client
handler of a timer control so that it executes
life-cycle events of ASP.NET AJAX.
after the set time interval.
q Synchronous postback of the entire Web
custom component to the
Web page. This event is
raised only when the page
is rendered for the first
time.
Identifying the ASP.NET AJAX Sys.Application.loa Is raised after all scripts
Client Life-Cycle Events d have been loaded on the
Web browser and all the
AJAX-enabled Web applications mainly consist of a objects in the application
client-side script that is processed by the Web are initialized. This event
browser. When a user interacts with an ASP.NET is raised for all postbacks
AJAX-enabled application, it raises some client to the server, including the
events. These events are handled at the client side asynchronous postbacks.
and are called client life-cycle events. Sys.Application.unl Is raised before all objects
The client events enable you to customize both oad are disposed and before
synchronous and asynchronous (partial-page the window.unload
updates) postbacks. These events also help you event of the Web browser
manage custom script components during the window occurs.
lifetime of the Web page on the browser. Sys.Component. Is raised when a property
Client events are raised by the classes present in the propertyChanged of a component changes.
Microsoft AJAX Library. The two main Microsoft AJAX To raise this event, you
Library classes that raise events are Application need to call the
and PageRequestManager. These classes are Sys.Component.raise
automatically instantiated when an event is raised on PropertyChange
a Web page that contains AJAX server controls. method in a set accessor.
These classes provide APIs that enable you to bind Sys.Component.dispo Is raised when the
the events to the controls and provide handlers for sing Application instance is
those events. For example, when an UpdatePanel disposed.
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
Client Events of the Application Class
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
PageRequestManager Class
Client Events of the Application To enable a Web page to perform partial-page
update, you need to add a ScriptManager control
Class and an UpdatePanel control. When such a page is
displayed on the Web browser, an instance of the
The Application class of Microsoft AJAX Library is
PageRequestManager class is automatically
instantiated when a Web page displayed on the Web
instantiated on the browser. This class raises client
browser contains a ScriptManger control. It inherits
events that are specific to asynchronous postbacks
the Sys.Component class.
(partial-page update).
The following table lists the client events of the
The following table lists the client events of the
Application class that are raised in AJAX-enabled
PageRequestManager class that are raised in the
Web pages.
AJAX-enabled Web pages.

Sys.Application.ini Is raised after all scripts


t Sys.WebForms.PageRe Is raised before an
have been loaded on the
questManagerintiali asynchronous request
Web browser. You can use zeRequest starts. You can use this
this event to add your
event to cancel a
postback. AJAX-Enabled Applications
Sys.WebForms.PageRe Is raised before an
questManagerbeginRe asynchronous postback In AJAX-enabled Web applications, the Web service
quest starts and till the postback is called by using client-side scripts. To enable client
is sent to the server. If a scripts to communicate asynchronously with the
postback is already server, ASP.NET AJAX provides the asynchronous
processing, the other communication layer. This layer enables a client
postback is stopped by application to call Web services by using JavaScript.
using the abortPostBack The asynchronous communication layer acts as an
method. This event can be intermediary layer between the browser and the
used to begin an server. It uses the XMLHTTP object to communicate
animation on the page to asynchronously.
indicate that the request is
in process.
Sys.WebForms.PageRe Is raised after the response The Asynchronous
questManagerpageLoa from the server to an Communication Layer
ding asynchronous postback is
received by the Web The ASP.NET AJAX architecture provides an
browser, but before any asynchronous communication layer that enables a
content on the page is Web browser to call the Web service methods by
updated or displayed. This using JavaScript. JavaScript can use the APIs that are
event can be used to exposed by the asynchronous communication layer.
provide a custom These APIs use the asynchronous behavior provided
transition effect for by the browser’s XMLHTTP object.
updated content. The asynchronous communication layer offers the
Sys.WebForms.PageRe Is raised after all content following features:
questManagerpageLoa on the page is refreshed, q It enables the JavaScript code to perform
ded as a result of either a asynchronous calls to the server.
synchronous or an q It can invoke methods in Web services that
asynchronous postback. are implemented as .asmx or .svc files. It
This event can be used to makes Web service interactions easier by
manage a custom generating JavaScript proxies for Web
transition effect for services that can be accessed from the client
updated content. script.
Sys.WebForms.PageRe Is raised after the response q It can invoke ASP.NET static page methods
questManagerendRequ for an asynchronous like a Web service method.
est postback is processed and q It supports a variety of serialization formats
the page is updated, or such as JavaScript Object Notation (JSON),
during the processing of string data, and XML data for passing data
the response if there is an between the browser and the server.
error. If an error occurs, q It provides extensibility for client executors
the page is not updated. that are used by the proxy objects.
This event is used to
provide customized error
notification to users or to
log errors.
An executor is a component that functions
Client Events of the PageRequestManager Class as an interface between a client Web
request and the network or other media.
You can write your own executor that plugs
Consuming Web Services in into the asynchronous communication
layer.
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile=
JSON Support in Consuming Web "Default.aspx.cs"
Services Inherits="_Default" %>

To call a Web service by using JavaScript, a Web <!DOCTYPE html PUBLIC "-//W3C//
browser interacts with a Web server through DTD XHTML 1.0 Transitional//EN"
asynchronous communication layer. While "http://www.w3.org/TR/xhtml1/DTD/
communicating, the asynchronous communication xhtml1-transitional.dtd">
layer exchanges data between the Web browser and
the Web server. This data is exchanged in a format <script type="text/javascript"
named as JSON. language="JavaScript">
JSON is a standard and default format used for
serialization by the asynchronous communication function HelloWorld()
layer. It makes the interaction between the client and {
the server easy by eliminating the need for the client alert(’Hello World!’);
script to construct request. }
Data that is formatted in the JSON format is </script>
lightweight and easy to be parsed by implementing
JavaScript. JSON is the ideal format for data <html xmlns="http://
exchange for AJAX-enabled Web applications. It can www.w3.org/1999/xhtml">
also be used to exchange or store structured <head runat="server">
information as text. A JSON object provides two <title>Untitled Page</title>
methods, JSON.parse and </head>
JSON.stringify. The JSON.parse method is <body>
used to serialize objects and arrays into JSON text <form id="form1"
format and the JSON.stringify method is used runat="server">
to convert JSON text format to in-memory objects. <div>
<input id="Button1"
type="button" value="Hello"
Creating and Registering Client onclick="HelloWorld()" />
Scripts </div>
</form>
An AJAX-enabled Web application calls a Web </body>
service by using client script. There might be a </html>
possibility that the built-in client scripts in an AJAX- In the preceding code snippet, a script block is
enabled Web application does not provide the defined that consists of a function, HelloWorld.
functionality that you want when calling a Web When a user clicks the Hello button on the Web
service. To implement such functionality, you need to page, the HelloWorld function is called and an
create a custom client scripts and integrate it with an alert box showing the Hello World! Message is
AJAX-enabled ASP.NET application. A custom client displayed.
script can be created and integrated with an AJAX- An inline script is not registered in an AJAX-enabled
enabled ASP.NET application as: ASP.NET application because the script block is
q Inline script defined in a Web page only.
q External java script file External Java Script File
q Script embedded as a resource in an You can also add a reference of an external java
assembly script file in an AJAX-enabled ASP.NET application.
Inline Script To add the reference, you need to add the java script
An inline script can be created as a script block in a file in your Web application. After adding the java
Web page. A script block is defined in a Web page as script file, you need to set the src attribute of the
an HTML markup. The following code snippet shows script element of the Web page to the name of the
how you can define a script block in a Web page: java script file.
The following code snippet is written in a java script script consists of a java script file that is embedded
file, JScript.js: as resources in an assembly. The java script that is
function HelloWorld() embedded in an assembly acts as a Web resource.
{ For example, you are creating a custom control that
alert(’Hello World!’); consists of a java script file. This file can be
} embedded as a Web resource in the assembly of the
In the preceding code snippet, a function custom control.
HelloWorld is created and an alert message, To access such a java script file, an HTTPhandler
Hello World!, is defined. WebResource.axd is used by the ASP.NET application.
The highlighted part of the following code snippet This handler retrieves assembly resources and serves
shows how you can set the src attribute of the script them to a Web browser. To access the assembly
element of the Web page to a java script file: resources using a ScriptManager control, you need to
<%@ Page Language="C#" add the reference of the assembly and the java script
AutoEventWireup="true" CodeFile= file as shown in the following markup:
"Default.aspx.cs" <asp:ScriptManager
Inherits="_Default" %> ID="ScriptManager1"
runat="server" >
<!DOCTYPE html PUBLIC "-//W3C// <scripts>
DTD XHTML 1.0 Transitional//EN" <asp:ScriptReference
"http://www.w3.org/TR/xhtml1/DTD/ Assembly="ClassLibrary"
xhtml1-transitional.dtd"> Name="ClassLibrary.JScrip
t1.js" />
<script type="text/javascript" </scripts>
src="JScript.js" > </asp:ScriptManager>
</script> In the preceding markup, a ScriptManager control is
<html xmlns="http:// defined. A reference of the assembly and the java
www.w3.org/1999/xhtml"> script file is added in the scripts tag of the
<head runat="server"> ScriptManager control.
<title>Untitled Page</title> Most client-side code is added at design time.
</head> However, it can also be generated and added in the
<body> Web page at run time by using the
<form id="form1" System.Web.UI.ClientScriptManager class.
runat="server"> Consider the following code snippet:
<div> protected void Page_Load(object
<input id="Button1" sender, EventArgs e)
type="button" value="Hello" {
onclick="HelloWorld()" /> string str="return confirm
</div> (’Do you want to submit the
</form> page?’)";
</body> ClientScript.RegisterOnSubmit
</html> Statement(this.GetType(),"ABC",
In the preceding markup, a java script file, str);
JScript.js is specified in the src attribute of the }
script element of the Web page. When a user clicks To manage, register, and add a script to a Web page,
the Hello button, the function HelloWorld you need an object of the ClientScriptManager
defined in the java script file is called and an alert class. In the preceding code snippet, the
message box showing the message, Hello World!, ClientScript property of the Page object has
is displayed. been used to obtain a ClientScriptManager
Script Embedded as a Resource in an object. The RegisterOnSubmitStatement
method registers an OnSubmit statement with the
Assembly Page object.
You can also add a custom client script in a web page In RegisterOnSubmitStatement (Type type,
by using the ScriptManager control. Such a client
String key, String script) method: as JavaScript.
q The type parameter defines the type of the They provide support for the widely
control that is registering the OnSubmit used Web browsers such as Microsoft
statement. Internet Explorer, Mozilla Firefox, and
q The key parameter defines a key that Apple.
uniquely identifies the script statement. q The limitations of AJAX-enabled Web
q The script parameter defines the script literal applications are:
for the OnSubmit statement. Browser Integration
Dependency on JavaScript
q The ASP.NET AJAX architecture consists of
the following components:
Client-based Microsoft AJAX library
A custom client script can also be used to Server-based AJAX features for
add AJAX functionality into a server ASP.NET
control. To provide AJAX functionality in a q Some of the AJAX server controls offered by
server control, you need to embed the ASP.NET are:
JavaScript file as a resource in the assembly ScriptManager control
ScriptManagerProxy control
that is created when the server control is
UpdatePanel control
precompiled.
UpdateProgress control
Timer control
q Client events are raised when a user interacts
with an ASP.NET AJAX-enabled application.
q Client events are raised by the classes
present in the Microsoft AJAX Library.
q The two main Microsoft AJAX Library classes
that raise events are:
Application
Summary PageRequestManager
In this chapter, you learned that: q The ASP.NET AJAX architecture provides an
asynchronous communication layer that
q AJAX is a Web development technique that
enables a Web browser to call the Web
is used to create dynamically interactive
service methods by using JavaScript.
applications.
q JSON is a standard and default format used
q AJAX enables Web applications to retrieve
for serialization by the asynchronous
data from the server, asynchronously in the
communication layer.
background, without interfering with the
q A custom client script can be created and
display and behavior of the existing page.
integrated with an AJAX-enabled ASP.NET
q AJAX includes the following terms:
application as:
Asynchronous communication
Inline script
JavaScript
External java script file
XML
Script embedded as a resource in an
q The advantages offered by AJAX-enabled
assembly
Web applications are:
They provide quick response to a user’s
request. Reference Reading
They allow users to interact with the
rest of the Web page while the Explaining the AJAX Frameworkn
application is processing the changed
or updated parts of the Web page.
They provide auto-generated proxy
ASP.NET AJAX http://blogs.sun.com/
classes that are used to call Web
Programmer’s Reference: enterprisetechtips/entry/
service methods from client script such
With ASP.NET 2.0 Or building_an_ajax_enabled_
ASP.NET 3.5 by Shahram web
Khosravi

Identifying the ASP.NET AJAX Server


Controls

Pro ASP. Net 3. 5 Server http://www.asp.net/AJAX/


Controls and AJAX Documentation/Live/
Components by Rob overview/
Cameron, Dale Michalk PartialPageRenderingOver
view.aspx

Identifying the ASP.NET AJAX Client


Life-Cycle Events

Pro ASP.NET 3.5 in C# http://www.asp.net/AJAX/


2008 by Matthew Documentation/Live/
MacDonald overview/
PartialPageRenderingOver
view.aspx

http://www.dcs-
media.com/desdev/
dotNet/aspnet-ajax-client-
life-cycle-events.aspx
Consider the scenario of an organization that has a
chain of hotels in various countries. The organization
is maintaining the information about the hotels
Chapter 11 through a website. This website is accessed by
people from various countries.
Implementing The website has a limitation. The information
provided by the website is in English and the
Internationalization and currency is set to United States Dollar (USD). This
Accessibility poses problems for the non-English speaking people
because they are unable to understand the
An organization that does business in the global information given on the website. As a result, people
marketplace must design applications to from the countries where the currency is other than
accommodate users from a wide variety of cultures. USD have to calculate the fares according to their
Users in different parts of the world use different currency. These problems are affecting the popularity
languages and different formatting standards for of the website.
numbers, currency, and dates. Therefore, you need to To accommodate users from different countries and
enable your Web applications to represent enable them to use the website efficiently, the
information in the users’ native language and organization decides to implement
formats. This functionality can be provided by internationalization in the application. Implementing
implementing internationalization. internationalization on the website would enable
Web applications may also be accessed by users with people from various countries to have the
disabilities. These users may not be able to interact information on the website in their native language
with the user interface properly because of their and formats. This would help users to easily
disabilities. A Web application should be designed in understand the information given on the website.
such a way that it is easily accessible to such users. To target the wide range of audience and to enable
This can be achieved by implementing accessibility them to browse through your website, your Web
features. application must be designed to accommodate users
This chapter discusses how to implement from various countries and cultures. This can be done
internationalization and accessibility features in a by implementing internationalization in the
Web application to make the application accessible application.
to everyone. International applications should be customizable
according to the preferences of users belonging to
Objectives different nations, cultures, or regions. User
In this chapter, you will learn to: preferences refer to the language, currency, and
formats. To make an international application
Implement internationalization
customizable, you need to understand the following
Implement accessibility phases that are involved in developing an
internationalized application:
q Globalization: Globalization is the process of
Implementing designing and developing a Web application
Internationalization in such a way that it is culture-neutral and
language-neutral. In this phase, the
Web applications are accessed by people from
executable code is separated from the data
different countries, cultures, and regions. These
specific to a locale.
people may want the information on the websites to
q Localizability: Localizability is an
be in their native language and formats. This would
intermediate process that ensures that a
make it easy for them to understand the content
globalized Web application is ready for
given on the site. To enable the people from different
implementing localization. The purpose of
countries, cultures, and regions to access your Web
this step is to test whether the application's
application, you need to implement
executable code is independent of the
internationalization in the application. The process of
culture and language-specific data. This
making an application ready for international users is
means that the culture and language-specific
called internationalization.
details should not be hard-coded into the applications designed for multiple languages or
application code. cultures. Formatting differences may arise in the
q Localization: Localization is the process of addresses, currency, dates, numerals, telephone
customizing the globalized Web application numbers, time, and units of measure of various
to a specific locale and culture. In this phase, languages.
various resources, such as images and text, String-Related Issues
for the designated locale are created. For When developing international applications,
example, to localize an application for French programmers must consider issues related to strings.
users, all text messages should be translated When strings are translated from one language to
to French. 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
Locale is a combination of a language and these strings may convey different meanings in
a country. It includes information about the different languages.
formats used for representing time and
date, symbols, and conventions used for
User-Interface Issues
Various user interfaces are associated with the design
representing currency, and the character
of an international application. The size of user
encoding scheme being used.
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
Factors Related to Creating grow in size as a result of translation to another
International Applications language, they should be allowed to wrap to
subsequent lines. You should also ensure that all the
Application developers need to attend to locale access-key and shortcut-key combinations are
considerations when they develop international available on international keyboards. This is because
applications because negligence of these every language has a different keyboard layout, and
considerations can lead to issues. The factors that some characters do not exist on all keyboards.
need to be considered while designing an
internationalized application are:
q Language issues Creating International
q Formatting issues
q String-related issues Applications
q User-interface issues The structure of an application that is created with
Language Issues internationalization in mind is divided into the
Languages around the world differ in display, following two blocks:
alphabets, grammar, and syntactical rules. For q Data block: Contains user-interface
example, some languages such as Arabic are written resources, such as the text on Label controls
from right-to-left, whereas other languages are that are to be translated into various
written from left-to-right. Some languages include languages. This block is locale-specific, and
uppercase and lowercase characters, whereas others each locale will have one data block.
do not even have the concept of uppercase and q Code block: Contains the application code
lowercase. Languages differ in the number of or the executable part of an application that
characters, storage requirements, keyboard layouts, is applicable to all cultures/locales. This block
and code representations. This diversity makes it will remain same for all locales.
difficult to share data between cultures. It is even The separation of culture/locale specific and culture/
more difficult to create a multilingual user interface. locale independent parts allows a user to dynamically
Formatting Issues switch the user interface to a localized version.
Formatting is the main source of differences in 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 a specific culture. The information includes details
default language/culture. For each additional such as the name of the culture, the formatting styles
language/culture that your website needs to support, used, and the calendar used.
you need to create a separate resource file, called a The following table lists some of the commonly used
localized resource file. properties of the CultureInfo class.
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 CurrentCulture Returns an instance of the
key named WelcomeText. The resource files for each CultureInfo class that
language/culture can then specify a different value to represents the culture for
the key depending on the language/culture. the current thread.
The .NET Framework represents different cultures CurrentUICulture Returns an instance of the
across the world by using a culture code. A culture CultureInfo class that
code consists of two parts, a two-letter language represents the current
code and an optional two-letter country/region code. culture used by the
The general format of the culture code is: Resource Manager to look
<Language code>-<Country/Region for culture-specific
code> resources at run time.
The following table lists some culture codes and their Name Returns the name of the
descriptions. culture in the <Language
code>-<Country/
Region code> format.
En Specifies English language, IsNeutralCulture Returns a Boolean value
no region indicating whether the
en-CA Specifies English language, culture represented by the
Canada CultureInfo object is a
fr-FR Specifies French language, neutral culture.
France NumberFormat Gets or sets a
De Specifies German NumberFormatInfo
language, no region object that defines the
Zh-CN Specifies Chinese appropriate format of
language, China region displaying numbers,
de-DE Specifies German currency, and percentage.
language, Germany region
Properties of the CultureInfo Class
Culture code snippets that only specify a language The following table lists some of the commonly used
are called neutral cultures, whereas culture code methods of the CultureInfo class.
snippets that specify a language as well as a region
are called specific cultures.
To implement globalization in an application, you CreateSpecificCultu Creates a CultureInfo
need to include the System.Gloablization re object that represents the
namespace in your application. The specific culture that is
System.Gloablization namespace provides associated with the
classes that define culture-related information, such specified name.
as the language, country, calendars, and formats. GetCultureInfo Returns a read-only
Two important classes included in the instance of a culture.
System.Gloablization namespace are: GetCultures Gets a list of supported
q CultureInfo cultures filtered by the
q RegionInfo specified type.
The CultureInfo Class GetFormat Returns an object that
The CultureInfo class provides information about represents the format of a
specified type. For protected override void
example, this method will InitializeCulture()
return an object {
representing the format of if (Request.Form
the date when the ["ListBox1"] != null)
specified type is date/time. {
String
Methods of the CultureInfo Class language = Request.Form
You can set two culture values for an ASP.NET ["ListBox1"];
application, the Culture and UICulture UICulture = language;
properties. These values determine the types of Culture = language;
resources loaded for an application and the Thread.CurrentThread.Curr
formatting options for various fields like currency, entCulture =
numbers, and dates. The resources loaded are CultureInfo.CreateSpecifi
determined by the UICulture property and the cCulture(language);
formatting options are determined by the Culture Thread.CurrentThread.Curr
property. entUICulture = new
You can set the Culture and UICulture CultureInfo(language);
properties for all pages on a website by using the }
globalization section of the web.config file, as shown base.InitializeCulture();
in the following example: }
<globalization The code given in the preceding example allows
UICulture=”fr” culture=”fr-FR”> users to select their preferred language from a drop-
You can set the Culture and UICulture down list and sets the UICulture and
properties for individual pages by using the @Page Culture properties accordingly.
directive of the page, as shown in the following The RegionInfo Class
example: The RegionInfo class contains information about a
<%@ Page country/region. The following table lists some
UICulture=”fr” Culture=”fr-FR”> properties of the RegionInfo class.
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 CurrencySymbol Gets the currency symbol
and Culture values to auto. for the country/region.
However, you should not rely exclusively on the CurrentRegion Gets a RegionInfo
browser settings to determine the UI culture for a object that represent the
page because users frequently use browsers that are county/region used by the
not set to their preferences. Therefore, you must current thread.
provide users a method to explicitly select a IsMetric Gets a value that indicates
language/culture for their page.
whether the country/
You can set the UICulture and Culture values for region uses the metric
a page programmatically by overriding the system for measurement.
InitializeCulture method and using any of the
following methods in the overridden method:
The following table lists some methods of the
q Set the UICulture and
RegionInfo class.
Culture properties of the page to the
desired values.
q Set the CurrentUICulture and
CurrentCulture properties of the current Equals Determines whether the
thread to the desired UI culture and culture, specified object is the
respectively. same instance as the
Consider the following example that demonstrates current RegionInfo
how to use both the methods: object.
GetType Gets the type of the ("d", FrenchCulture);
current instance. 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
Implementing Culture-Specific first parameter of the ToString() method. The
Formatting second parameter specifies the culture to be used for
the short date format.
The resource files allow you to specify the text At run time, if the user’s browser settings specify
appearing on a website in different languages. French (France) as the preferred language, the date
However, if you want to change the format of date, will be displayed in the format, dd/MM/yyyy.
time, or currency values depending on the current However, if the preferred language is set to any other
culture, you need to specifically write code for value, the date will be displayed in the US format,
implementing the same. MM/dd/yyyy.
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 Implementing Accessibility
formats. Each format has a format character
When you develop a Web application, you want the
associated with it.
application to be used by as many users as possible.
The following table lists some date formats, and their
Your Web application may be used by users with
corresponding format characters.
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
Date Formats people having disabilities as well as enables other
The preceding table specifies the pattern of date/ users to interact with the application more efficiently.
time in the en-US culture. Other cultures may have ASP.NET provides some guidelines that you should
slightly different patterns for each date format. consider while designing your Web application to
The following code snippet demonstrates how to use achieve high accessibility.
a different format for displaying a date depending on
the current culture:
protected void Page_Load(object Fundamentals of Designing an
sender, EventArgs e) Accessible Application
{
DateTime dt = DateTime.Now; Creating an application that complies with all
CultureInfo USCulture = new accessibility guidelines is not feasible because it
CultureInfo("en-US"); requires a substantial amount of time and money.
CultureInfo Therefore, you need to select the suitable
FrenchCulture = new CultureInfo accessibility features that would be implemented in
("fr-FR"); an application. The selection of features should
if (CultureInfo.CurrentCultur depend upon the profile of the users accessing the
e.Equals (FrenchCulture)) application. For example, if you are creating an
Label2.Text = dt.ToString application for retired people, most of the users will
be over 60 years of age. These users may be suffering are instances when people are not able to access
from old age ailments such as diminished vision. information just because of bad accessibility design,
Therefore, your application should have accessibility such as small font size of the text given in an
features such as appropriate font size and application or improper navigational structure. Some
background color to enable the users to easily guidelines for implementing accessibility in an
interact with the application. application are:
The features of a Web application that are used q Standardize font styles: While deciding the
frequently should have a high degree of accessibility. font style, you should keep in mind that
For example, on an online shopping site, shopping users having diminished eyesight may also
cart feature is a frequently-used feature. Therefore, a access your website. Therefore, you need to
developer should strictly follow the accessibility select the font style and the color for the
guidelines while designing this feature. The principles background and foreground such that the
that should be followed while implementing text is easily readable. Some of the important
accessibility support in an application are: guidelines for designing a website that can
q Flexible user interface: Flexibility of a user be used by the users having diminished
interface refers to its capability to change its eyesight are:
presentation to adapt to changing user Font size should be greater than 12
preferences. points. However, the font size may
q Flexible input and output features: Flexible differ depending upon the font style.
input features refer to numerous ways in Text should not be italicized.
which a user can interact with an application. Important points should be in bold.
All features should be accessible through Decorative fonts should be avoided.
keyboard with the same degree of ease as Text color and background color
while using mouse. Three-click rule should should be selected in such a way that
always be followed, which states that all the text can be easily read.
functionality should be accessible in a q Support keyboard navigation: Keyboard
maximum of three clicks. Flexible output navigation in an application can be provided
features refer to the numerous ways in which by using the TAB key. The TAB key
a user can retrieve information from an navigation direction should be from top to
application. It is a good accessibility practice bottom and left to right. The navigation
to keep a wide range of output options such order while using the TAB key should be
as text, images, sound, and graphics. correct. All navigation links should have tool
q Simple and Intuitive: The user interface tip that explains the use of the link. All
should be simple and easy to understand, controls should be assigned keyboard
regardless of a user's experience, knowledge, shortcuts. ASP.NET provides the following
language skills, or current concentration properties that are set for the controls used
level. Any unnecessary complexity should be in a Web page so as to enable a user to
eliminated. Each object on the screen should navigate properly by using the Tab key:
be assigned a unique and descriptive label to TabIndex: You can specify the
assist users who cannot see its context on TabIndex property of a control to set
the screen. tab order for proper navigation.
The application should interact with other DefaultButton: You can specify default
applications in a standard manner. For example, the button for a form or a panel by setting
application should provide a standard mechanism for its DefaultButton property. The
importing data from and exporting data to other DefaultButton property specifies
applications. that a user can cause a postback by
pressing the ENTER button in an input
control in the form such as a text box.
Accessibility Design Guidelines AccessKey: Keyboard shortcuts can be
assigned to each control by using the
for the Web AccessKey property of the control.
Accessibility makes an application user friendly. There ToolTip: Tool tips can be displayed for
each control by using the ToolTip
property of the control. caption to help assistive technologies such
AssociatedControlID: You can as screen readers to identify the purpose of
associate a Label control to another the table by setting its caption property.
control by setting the q Minimize the use of style sheets: The
AssociatedControlID property of the layout of a form should not be affected when
Label control to the ID of the relevant it is displayed in a browser that does not
control. You can then use the support style sheets. For this, you need to
properties of the Label control to set provide an alternate page that does not
some properties of the associated make use of style sheets for every page that
control. For example, you can use the uses a style sheet.
Text and AccessKey properties of the q Use controls properly: While using controls
Label control to provide the caption at the time of designing an application, you
and short-cut key for the associated should consider the following points:
control. Do not use ActiveX controls as some
q Standardize the use of images: When you browsers may not support them. If you
use images in the form of buttons, links, or are using an ActiveX control on a Web
image maps in your application, you should page, it should have an alternate page
provide a meaningful text for the images to that does not contain the ActiveX
enable user to understand its functionality. control.
ASP.NET allows you to do this by setting the Use either LABEL or TITLE tags to
following properties of controls: specify the name of each control.
AlternateText property: You can
specify the AlternateText property
of the image to provide a meaningful
text to the image.
GenerateEmptyAlternateText: You An ActiveX control can be automatically
can specify the downloaded and executed by a Web
GenerateEmptyAlternateText browser. ActiveX is a set of rules for how
property to true if the image does not applications should share information.
provide any functionality or does not Programmers can develop ActiveX controls
convey information relevant to the
in a variety of languages, including C, C++,
context of the Web page and is used
Visual Basic, and Java.
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 Assistive Technologies Used for
images for the expand and the collapse
button for each node in the TreeView Accessibility of the Web
control. The TreeView control generates
People with disabilities use various assistive
alternate text for these images based on the
technologies for accessing a Web application. These
text of the node. By default, the alternate
assistive technologies are the products used by them
text for the image of the expand button that
to access a Web application in an easy way. You
has the text as Start is rendered as Expand
should develop a Web application that should
Start on a Web page. You can also specify
support these technologies so as to enable the
your own alternate text by setting the
maximum number of users to access your Web
ExpandImageToolTip and
application. Some assistive technologies used by
CollapseImageToolTip properties for the
people with disabilities are:
TreeView control.
q Braille and Refreshable Braille: Braille is a
q Standardize the use of tables on a Web
system using six to eight raised dots in
page: You use tables in your Web
various patterns to represent letters and
application to place each control in a well-
numbers that can be read by the fingertips.
organized and structured manner. While
Braille system is used by blind people. Braille
creating a table, you should specify the
consists of an 8-dot version that has been recognition.
developed to allow all ASCII characters to be q Visual Notifier: Visual notifier is an
represented on a Web browser. Refreshable alternative feature of some operating
Braille offers mechanical display where the systems that allows hearing impaired users
dots are raised and lowered dynamically that to receive a visual alert of a warning or error
allows a Braille character to be displayed on message that might otherwise be issued by
a Web browser. Refreshable Braille displays sound.
can be incorporated into portable Braille
devices with the capabilities of small
computers, which can also be used as Summary
interfaces to devices, such as information
In this chapter, you learned that:
kiosks.
q The process of making an application ready
q Scanning Software: Scanning software is
for international users is called
adaptive software used by individuals with
internationalization.
some physical or cognitive disabilities that
q The phases that are involved in developing
highlights or announces selection choices
an internationalized application are:
such as menu items, links, or phrases one at
Globalization
a time. A user selects a desired item by
Localizability
hitting a switch when the desired item is
Localization
highlighted or announced.
q The factors that need to be considered while
q Screen Magnifiers: Screen magnifier is
designing an internationalized application
software used primarily by individuals with
are:
low vision that magnifies a portion of the
Language issues
screen that allows them to easily view a Web
Formatting issues
application on a Web browser. Screen
String-related issues
magnifiers make presentations larger, and
User-interface issues
reduce the area of the document that can be
q The two blocks that make a structure of an
viewed by removing surrounding context.
internationalized application are:
Some screen magnifiers offer two views of
Data block
the screen, one magnified and one default
Code block
size for navigation.
q The System.Gloablization namespace
q Screen Readers: Screen reader is software
provides classes that define culture-related
that is used by individuals who are blind or
information, such as the language, country,
who have dyslexia. It interprets what is
calendars, and formats.
displayed on a screen and directs it either to
q The two important classes included in the
speech synthesis for audio output or to
System.Gloablization namespace are:
refreshable Braille for tactile output. Some
CultureInfo
screen readers use the document tree such RegionInfo
as the parsed document code as their input. q The principles that should be followed while
In addition, the screen readers use implementing accessibility support in an
linearization process for interpreting the text application are:
in each column of each row of a table on Flexible user interface
your Web page. It reads all the text in the Flexible input and output features
first cell of row one, the second cell, the Simple and Intuitive
third, and so on until it runs out of cells. It q The guidelines to implement accessibility in
then moves on to the second row. an application are:
q Speech Recognition: Speech recognition is Standardize font styles
used by people with physical disabilities or Support keyboard navigation
temporary injuries to hands and forearms. It Standardize the use of images
is used by them as an input method in a Standardize the use of tables
voice browser that allows voice-driven Minimize the use of style sheets
navigation. Applications that have full Use controls properly
keyboard support can be used with speech
Reference Reading
Implementing Internationalization

Ethical and Social Issues in http://wiki.asp.net/


Professional Education by page.aspx/55/
Celeste M. Brody, James internationalization/
Wallace

Managing Across Cultures


by Susan C. Schneider,
Jean-Louis Barsoux

Implementing Accessibility

Pro ASP.NET 3.5 in C# http://


2008 by Matthew www.globalknowledge.co
MacDonald, Mario m/training/course.asp?
Szpuszta pageid=9&courseid=1134
5&catid=184&country=U
nited+States
information from unauthorized access. It also helps in
maintaining data integrity and confidentiality. The
following figure displays the architecture of the
Chapter 12 ASP.NET security model.

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:
IIS and ASP.NET Interaction
Identify the ASP.NET security process
The preceding figure indicates that ASP.NET security
Configure an ASP.NET Web application for works in conjunction with Internet Information
security Services (IIS) to implement security in a Web
application. The following steps describe the working
of the ASP.NET security model:
Identifying the ASP.NET Security 1. IIS receives a request from a Web client.
Process 2. It attempts to authenticate the user. If the
user is authenticated, the request is checked.
Most of the websites restrict access to some of its If the request is for a non ASP.NET Web
content. This is necessary to provide different levels page, the request is directly passed to the
of access to different types of users. For example, on operating system. The operating system
an online shopping website, the product catalog is performs its own security checks to verify
accessible to all the users accessing the website. that the authenticated user is allowed to
However, certain portions of the website such as access the specified file and directory.
status of customer's order or customer's payment However, if the request is for an ASP.NET
details should only be accessible to users with certain Web page, it is passed to ASP.NET with
credentials, such as employees. additional information about the
Controlling access to the content in a Web authenticated user. ASP.NET uses its own
application helps you protect your application from security services, depending on the settings
various security threats, such as tampering with data in the web.config file and the page that was
files and stealing passwords. The ASP.NET security requested.
model allows you to deal with these security threats 3. If ASP.NET authenticates the user, it allows
to help secure your Web applications. requests to the specified Web page. Your
code can perform additional security checks
such as manually asking for another
Introducing the ASP.NET Security password by using the .NET Framework.
Model 4. When the ASP.NET code requests resources,
the operating system performs its own
The ASP.NET security model allows you to implement security checks to verify that the
security in your Web applications. It provides authenticated user is allowed access to the
restricted levels of access to secure website
specified file and directory. q Integrated Windows: In this type, IIS does
5. If access is granted, the requested resource is not prompt the user to pass credentials.
returned through IIS. Instead, it extracts the user credentials from
All Web users communicate with ASP.NET the operating system by retrieving the
applications through IIS. Therefore, to implement account information used by the user to log
security in your Web applications, you need to first on to the machine. The user is granted
configure IIS. access only if the current account under
which the user has logged on is a valid
account on the server.
Configuring IIS for Implementing
Security
Whenever a user requests for a Web application, the
request is received by IIS. After receiving the request, A sniffing attack is a security threat in
IIS tries to authenticate the user who has requested which an attacker gains access to the
for the application by using a specific type of network communication. The attacker can
authentication. The type of authentication depends extract the message transmitted over a
on how the security for Web applications is network. This increases the risk of private
configured on IIS. Therefore, you first need to information being misused.
configure security on IIS to authenticate users before
they are permitted access to a Web application. You can configure the preceding authentication
IIS provides the following different types of types in IIS for a Web application by using the
authentications to control access to your Web Internet Services Manager.
application:
q Anonymous: In anonymous authentication,
IIS uses a default logon name and password Configuring an ASP.NET
to request for resources from a Web
application. Therefore, this type of Application for Security
authentication mechanism does not require The initial check for user authentication is done by
the user to provide a user ID or password to IIS. After the user is authenticated, IIS sends the Web
browse through a Web application. request to ASP.NET to perform a second level
q Basic: In basic authentication, users access checking. ASP.NET uses its own security mechanism
resources only after specifying a valid user ID to authenticate the user.
and password. However, in this type, the ASP.NET first authenticates the user by using the
user’s password is transmitted over the authentication settings defined in the web.config file
Internet in the form of plain text. It makes of the application. If the user is authenticated, it
the method vulnerable to a sniffing attack. checks whether the user has the right to access the
This method should be used in conjunction requested resource of the Web application. All this
with Secure Socket Layer/Transport Layer requires you to configure the security settings in the
Security (SSL/TLS). If a website is configured web.config file of the Web application. These security
to use SSL/TLS and basic authentication, all settings include configuring authentication,
data including username and password are authorization, and impersonation for accessing
encrypted before they are transmitted. resources in your application.
q Digest: In digest authentication, the user
password is transmitted as a hash value
rather than as plain text. This authentication Configuring Authentication
is similar to the basic authentication
mechanism, but it is more secure. The major Authentication is the process of validating the
drawback of this method is that it is identity of a user before granting access to a
supported by very few browsers and Web restricted resource. When ASP.NET receives a Web
servers. For example, digest authentication is request from IIS, it tries to authenticate the user. This
only supported by IIS 5.0 and later versions. 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 Implementing Forms Authentication
authenticated to access the Web application. When you implement Forms authentication to a Web
Authentication in a Web application can be page, you have to create an HTML-based Web page
configured by using the <authentication> for collecting user’s credentials and then authenticate
element in the web.config file. The the user. When a user enters his or her credentials
<authentication> element specifies the and gets authenticated to view a Web page, ASP.NET
authentication type that is used by an application to generates a cookie that is served as an authentication
authenticate the user. The authentication type can be token to the user. The browser uses this cookie for
specified by using the mode attribute of the the future requests made by the user, allowing the
<authentication> element. The mode attribute application to validate the requests. This cookie can
can have the following values: be encrypted by a private key located on the Web
q Windows: This mode specifies that the server to identify that the request is sent by the same
authentication is performed by IIS by using user.
Basic, Digest, or Integrated Windows To authenticate users by using Forms authentication,
authentication. you need to create and store the user credentials in a
q Forms: This mode specifies that the user will data source. You can create and manage users in
be authenticated by using form-based ASP.NET by using the membership management
authentication method. This method displays service. The membership management service is
a logon form to verify the user’s credentials. used to authenticate the users who require access to
q Passport: This mode specifies that the user Web pages. This service provides an API suite and
will be authenticated by using Microsoft some server controls such as CreateUserWizard to
Passport authentication method. Passport manage users in an ASP.NET Web application.
authentication relies on cookie-based To configure an ASP.NET Web application for forms
authentication and single signing authentication, you first need to change the mode
authentication service provided by Microsoft. attribute of the <authentication> element to
q None: This mode specifies that no Forms, as shown in the following markup:
authentication mechanism is set and that any <authentication mode="Forms" />
anonymous user can access the Web If a user tries to access a restricted page without first
application. logging on, the user should be redirected to the
Implementing Windows logon page. You are required to specify the settings
Authentication to redirect anonymous users to the logon page.
If you choose windows as the authentication mode These settings are specified by using the <forms>
for your Web application, IIS takes care of the element in the web.config file. The <forms> element
authentication process. In this mode, ASP.NET uses has the following four attributes:
the user credentials authenticated by IIS for security q name: It specifies the HTTP cookie that will
checks. be used for authentication. .ASPXAUTH is
To configure an ASP.NET Web application for the default value of this attribute.
Windows authentication, you need to change the q loginUrl: It specifies the URL to which the
mode attribute of the <authentication> element user requests are redirected for logon when
to Windows, as shown in the following markup: no valid authentication cookie is found. The
<authentication mode="Windows" /> default value is default.aspx.
This type of authentication is best suited to an q protection: It specifies the type of
intranet environment where a set of known users are protection that a Web application uses to
already logged on to a network. For example, if you protect the HTTP cookie. The valid values of
are creating a Web application that is to be used this attribute are All, None, Encryption,
within an organization, you can use the Windows and Validation. The default value of this
authentication mode to authenticate the users. This is attribute is All.
because the existing users already have their q timeout: It specifies the life span of the
accounts in the database of the Web server. A Web cookie that is used for authentication. After
application that implements Windows authentication the time specified in the timeout attribute,
rejects a user’s request that is not an authenticated the cookie expires. The value of the
user or has an invalid user name or password. timeout attribute is specified in minutes.
q path: It specifies the path of the cookie. Visual Studio provides the following
methods to add users to the ASP.NET
membership management service:

q Using the CreateUserWizard Server Control


When a user visits your website without provided by ASP.NET
logging in or providing his/her credentials, q Using the ASP.NET Website Administration
the user is called anonymous user. Tool (WAT)
Adding Users by Using the
The following markup shows a web.config file that is <credentials> Element
configured for forms authentication:
The <credentials> element is defined within the
<configuration> <forms> tag in the web.config file. It contains the
<system.web> <user> tag to specify the user credentials, as shown
<authentication mode="Forms"> in the following markup:
<forms <configuration>
name=".AuthenticationCook <system.web>
ie" <authentication mode="Forms">
loginUrl="~/mylogin.aspx" <forms
timeout="5"/> name=".AuthenticationCook
</authentication> ie"
</system.web> loginUrl="/login.aspx"
</configuration> protection="All"
In the preceding markup, the name of the HTTP timeout="60"
cookie is AuthenticationCookie and URL to path="/">
which the user will be directed for logon is <credentials
mylogin.aspx. The life span of the cookie is 5 passwordFormat="Clear">
minutes. <user
After configuring the Web application for forms name="John" password="P@ssw0rd"/
authentication, you are required to add users to the >
ASP.NET membership management service. You can <user
add users by using the following methods: name="Tom" password="123_P@ss"/>
q Using the <credentials> element in the </credentials>
web.config file </forms>
q Using the Membership API </authentication>
When you add users to the membership </system.web>
management service by using either of the preceding </configuration>
methods, the user information is stored in the In the preceding markup, two username/password
ASPNETDB.MDF file. The user information stored in pairs John/P@ssw0rd and Tom/123_P@ss are
the ASPNETDB.MDF file is made available to the stored in the web.config file. The passwordFormat
membership management service by the attribute of the <credentials> tag is used to
membership provider. specify the format in which the password is stored in
The membership provider specifies the type of the web.config file. The passwordFormat attribute
database that will be used to store the membership is set to Clear which means the password is stored
information. The default provider uses a Microsoft as plain text. Other options available with
SQL Server database, ASPNETDB. You can also passwordFormat attribute are MD5 and SHA both
choose to use Active Directory or specify a custom of which are encryption algorithms.
provider to store membership information. 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
In addition to the preceding methods, validate users, the users are validated automatically
by using the credentials stored in the membership FormsAuthentication class. If the user is
management service. However, if you create the authenticated, the message Welcome <username>
login form manually, you are required to perform the is displayed on the Web form. However, if the user is
validation programmatically. ASP.NET provides you not authenticated, the message Sorry! Login
with the FormsAuthentication class that helps failed is displayed on the Web form.
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 Adding Users by Using the Membership
methods of the FormsAuthentication class. API
When adding users by using the <credentials>
element in the web.config file, you need to add all
Authenticate Validates the user the users at design time. In addition, if you want to
credentials passed to it modify or delete a user, you need to manually
and returns a boolean remove or modify the users in the web.config file.
value indicating whether However, if you want to add, modify, or delete users
the authentication process at run time, you need to use the Membership class.
was successful or not. To implement the Membership class, you need to
RedirectFromLoginPa Redirects an authenticated use the System.Web.Security namespace. The
ge user back to the specified Membership class has various static methods that
URL. allow you to manage users at run time. The following
SignOut Removes the table lists some useful static methods.
authentication cookies
created on the computer
of an authenticated user. CreateUser Adds a new user to the
database.
Methods of the FormsAuthentication Class DeleteUser Deletes an existing user
Consider a scenario wherein you have created a login from the database. To
form manually. To validate the user credentials, you delete a user, you need to
need to write code as shown in the following specify the user name.
example: GetUser Gets information from the
protected void Button1_Click data source for the
(object sender, EventArgs e) membership users
{ associated with the unique
if (FormsAuthentication.Authent identifier .
icate GetAllUsers Gets a collection that
(UserName.Text, Password.Text)) represents all the users in
{ the database.
Response.Write("Welcome " UpdateUser Updates information for a
+ UserName.Text); specific user.
} ValidateUser Validates the supplied user
else name and password.
{
Response.Write
Static Methods of the Membership Class
("Sorry! Login failed");
} Consider the following example:
} protected void AddUser_Click
In the preceding example, the user name and the (object sender, EventArgs e)
password are authenticated by using the {
Authenticate function of the MembershipCreateStatus
result; currentUser = Membership.GetUser
try ("user1");
{ if (currentUser.ChangePassword
MembershipUser newUser = ("OldPassword", "NewPassword"))
Membership.CreateUser {
(UserName.Text, Label1.Text = "Your password
Password.Text, Email.Text is successfully changed";
, passwordQuestion.Text, }
passwordAnswer.Text, true else
, out result); {
if (result==MembershipCre Label1.Text = "Your password
ateStatus.Success) could not be changed";
{ }
Response.Write("User
Successfully Created");
ShowAllUsers();
}
else When you modify user details such as the
{ e-mail address, you need to use the
Response.Write("Sorry UpdateUser method of the Membership
cannot create the user"); class after modifying the details. The
} UpdateUser method takes the
} MembershipUser class object as an
argument.
catch (Exception err)
{
You can customize the membership settings, if
Response.Write
required, by configuring the membership provider.
(err.Message);
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
public void ShowAllUsers()
change the default password policy. To configure the
{
membership provider, you need to add the
GridView1.DataSource = Member
<membership> element to the web.config file. All
ship.GetAllUsers();
the custom settings are defined inside the
GridView1.DataBind();
<membership> element as shown in the following
}
example:
In the preceding example, the code within the
AddUser_Click event handler is written to create a <membership
user. If the user gets created successfully, the method defaultProvider="CustomMembership
ShowAllUsers is invoked. This method is used to Provider">
retrieve all the users and display them in the <providers>
GridView control. However, if any exception is thrown <clear/>
by the code, the error message is displayed on the <add
Web form. name="CustomMembershipP
rovider"
Once created, you can change the user details by
type="System.Web.Securi
using the methods of the Membership class. For
ty.SqlMembershipProvider"
example, you have created a user with the name
connectionStringName="M
user1. Now, you want to change the password for
ySqlServer"
the user. For this, you need to write the following
enablePasswordRetrieval
code snippet:
="true"
MembershipUser
enablePasswordReset="tr
ue" specify authorization rules for the users.
requiresQuestionAndAnsw You need to grant different permissions to different
er="true" users to provide accessibility to the Web pages on
minRequiredPasswordLeng your website. For example, on an online shopping
th="5" website, the users are able to view the product
minRequiredNonalphanume catalog. They cannot make changes to the products
ricCharacters="0" being displayed on the website. However, the
passwordFormat="Hashed" administrator of the website can add or remove any
/> product from the website. This requires providing
</providers> different levels of permission to different users of the
</membership> website.
In the preceding example, the membership provider Maintaining a different set of settings for each user is
is configured. The <add> element in the preceding a complex task. Therefore, the users are assembled
example contains the following attributes: into groups called roles and the permissions are
q Name: Specifies a name for the membership defined on these roles. In ASP.Net, you can provide
provider. It is mandatory. authorization by using the role management service.
q type: Specifies the type of membership The role management service enables you to create
provider. It is mandatory. roles, assign users to each role, and then restrict user
q connectionStringName: Specifies the access based on these roles.
name of the connection string setting. The To use role-based authorization in your Web
name must correspond to the connection application, you need to enable it by using the
string defined in the <roleManager> element in the web.config file, as
<connectionStrings> section. It is shown in the following markup:
mandatory. <configuration>
q enablePasswordRetrieval: Determines <system.web>
whether a password can be retrieved in case <roleManager enabled="true" />
the user forgets it. ...
q enablePasswordReset: Determines </system.web>
whether a password can be reset. ...
q requiresQuestionAndAnswer: </configuration>
Determines whether the membership In the preceding markup, setting the value of the
security answer will be required when enabled attribute to true will enable role-based
requesting or resetting the password. It is authorization for the Web application.
optional.
q minRequiredPasswordLength: Specifies
Creating and Assigning Roles
After you have enabled the role management service,
the minimum length of a password.
q minRequiredNonalphanumericCharact you need to create roles, such as Users,
ers: Specifies minimum number of Administrator, and Guest. You can then assign users
nonalphanumeric characters that the to one or more roles.
password should contain. It is optional. ASP.NET provides you with the Roles class to help
q passwordFormat: Specifies the way you create roles. The Roles class contains a number
passwords are stored in the database. The of methods that help you modify role information.
values that this attribute can hold are Clear, The following table lists the various methods of the
Encypted, and Hashed. Roles class and their description.

Configuring Authorization CreateRole Adds a new role to the


data source.
Authorization is the process of verifying whether an
DeleteCookie Deletes the cookie where
authenticated user has the privilege to access a
role names are cached.
requested resource. After creating users that can
access your Web application by using the
DeleteRole Removes a role from the
membership management service, you need to data source.
FindUsersInRole Gets a list of users in a <authorization> element is specified in the
specified role where the web.config file. The <authorization> element
user name contains the includes two child elements, <allow> and <deny>.
specified user name to You can specify the list of users who are allowed to
match. access the website in the <allow> element and the
GetRolesForUser Gets a list of the roles that list of users who should not be allowed to access the
has been assigned to a website in the <deny> element.
user. Some attributes of the <allow> and <deny>
elements are:
Methods of the Role Class q users: It enables you to assign a list of users
You can create roles by using the to be granted or denied access. The symbol ?
CreateRole method as shown in the following is used to denote anonymous users and the
code snippet: symbol * is used to denote all users.
Roles.CreateRole(“Admin”); q roles: It enables you to assign a list of roles
In the preceding code snippet, the role Admin is to be granted or denied access.
created. A Web application contains certain Web pages that
can be accessed only by specific users. For example,
You can add a user to a role by using the
there are certain Web pages that should be accessed
AddUserToRole method as shown in the following
only by the administrator. For restricting access to
code snippet:
such Web pages, these Web pages need to be stored
Roles.AddUserToRole
in a separate subdirectory. After storing the Web
(“Peter”, “Admin”);
pages in the subdirectory, you need to add a
In the preceding code snippet, the user Peter is
Web.config file to that subdirectory. Then, you need
added to the Admin role. You can get a list of all the
to use the following markup in the web.config file to
users in a particular role. For this you need to write
restrict users having roles other than Admin to access
the code as shown in the following example:
the Web pages:
protected void Button1_Click
<authorization>
(object sender, EventArgs e)
<allow roles="Admin"/>
{
<deny users="*"/>
MembershipUserCollection
</authorization>
users = Membership.GetAllUsers();
The preceding markup specifies that the users who
foreach (MembershipUser
have been assigned to the Admin role are allowed to
MyUser in users)
access the Web pages stored in the subdirectory. All
{
users having roles other than the Admin role are
if (Roles.IsUserInRole
denied access on these Web pages.
(MyUser.UserName, "Manager"))
{
Label1.Text += MyUser Configuring Impersonation
.UserName + "<br>";
} 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
In the preceding example, all the users are retrieved impersonation is disabled, irrespective of the user
and the names of those users who have assigned the who has logged on, the ASP.NET application will be
Manager role are displayed on the label control. 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
Restricting User Access compilation and viewing information in any database
Once you have created and assigned users to roles, or files in your application that you would not want
you can restrict the access of users. You can specify to grant to a user. For example, if a user visits the
the list of users who are allowed to access a website current account page, you need to make sure that
in the <authorization> element. The the user is able to view the information only for his
\her account. To allow users to access the ASP.NET q The ASP.NET security model provides
application according to the permissions granted to restricted levels of access to secure website
them, you need to use impersonation. information from unauthorized access.
Impersonation is the process of executing code q IIS provides the following different types of
under the authenticated user identity and not under authentication to control access to your Web
the ASPNET account. When a user tries to access a application:
Web application, the first step is to check whether Anonymous
impersonation is enabled for the application. Basic
Impersonation involves the following steps: Digest
1. When a request from a remote client is Integrated Windows
received, IIS carries out authentication. If the q Authentication is the process of validating
client is authenticated, it passes the request the identity of a user before granting access
to the ASP.NET application. to a restricted resource.
2. The application impersonates the client and q Authentication in a Web application can be
uses the authentication given by IIS to access configured by using the
the restricted resources. <authentication> element in the
3. If authorized to access resources, the web.config file.
ASP.NET application returns the requested q Authorization is the process of verifying
resources to the client through IIS. whether an authenticated user has the
By default, impersonation is disabled in ASP.NET and privilege to access a requested resource.
unless overridden, all applications inherit this setting. q Impersonation is the process of executing
When impersonation is disabled, the account used code under the authenticated user identity
for executing ASP.NET resources is controlled by the and not under the ASPNET account.
<processModel> element in the machine.config
file. However, you can enable impersonation in an
ASP.NET application by adding the following markup Reference Reading
in the <system.web> section of the web.config file:
<identity impersonate="true" /> Identifying the ASP.NET Security
In the preceding markup, impersonation is enabled Process
for the Web application. Therefore, the application
uses the user credentials authenticated by IIS to
provide access to the requested resources. Pro ASP.NET 3.5 in C# http://
You can also enable your Web application to run 2008 by Matthew msdn.microsoft.com/en-
under a specific user’s identity. For this, you need to MacDonald, Mario us/magazine/
specify the user credentials for that specific user in Szpuszta cc301387.aspx http://
the web.config file, as shown in the following www.springerlink.com/
markup: content/
<identity impersonate="true" q6w220jt19065733/
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 host computer because a remote user or a client
cannot manipulate any data.
A virtual directory exposes the components of a Web
Chapter 13 application to the remote clients and allows them to
access your Web application through Web browsers.
Deploying an ASP.NET When a client requests a Web page in a virtual
directory, the Web server searches the page in the
Application corresponding physical directory that exists on the
After creating a Web application, you need to make it host computer. After locating the page, the server
available to the users to enable them to access the sends it back to the client.
application through the Internet. To make a Web For example, your Web application exists in a
application available to the users, you need to deploy directory named D:\MusicMania on the host
it on a Web server. computer. To allow remote users to access the
This chapter explains how to configure a Web server application through their browsers, you need to
for deploying a Web application. In addition, it deploy it on a Web server as a virtual directory. The
discusses about how to deploy a Web application. virtual directory can either have the same name as
the name of the Web application or a different name.
Objectives When the user requests a page in a virtual directory,
for example, http://172.23.3.203/MusicMania/
In this chapter, you will learn to: AboutUs.aspx, the Web server searches for the file in
Configure a Web server for deployment the corresponding physical directory, D:\MusicMania\
Deploy a Web application AboutUs.aspx and renders it to the user.

Configuring a Web Server for Configuring Application Pools


Deployment After creating the virtual directory, you can configure
the application pool for your application. An
Web servers accept requests from Web browsers and Application pool can contain one or more
respond accordingly. To enable a Web server to applications and allows you to configure the level of
respond to a browser, you need to configure it. The isolation between different Web applications. For
configuration of a Web server involves performing example, if you want to isolate your Web applications
the following tasks: running on the same computer, you need to create a
1. Creating a virtual directory separate application pool for every Web application
2. Defining Web application URLs and place the applications in the corresponding
3. Registering ASP.NET file mappings application pool. When the applications are placed in
separate application pools, errors in one application
pool will not affect the applications running in other
The Virtual Directory application pools.
During the development phase, a Web application is You can configure application pools for your Web
saved in a folder on the computer on which it is applications by using the IIS manager. For this, you
developed. However, once the application is need to right-click the virtual directory that is created
developed, it needs to be deployed on a Web server. for the Web application and select the Properties
When you deploy the application on a Web server option. You can set the isolation for your application
such as IIS, you need to create a directory on the by selecting the appropriate option from the
Web server that contains all the components such as Application Protection drop-down list, as shown in
the Web pages, images, user controls, and data the following figure.
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
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
The Virtual Directory Properties Dialog Box using a unique name known as the domain name.
For example, the airlines’ Web application can be
The Properties dialog box provides the following
accessed by using the domain name, as specified in
application protection options:
the following URL:
q Low (IIS Process): The applications that are
http://www.MyFlight.com/MyWebApp/default.aspx
configured to run under this application
protection run in Inetinfo.exe. The In the preceding statement, www.MyFlight.com is the
Inetinfo.exe hosts IIS core processes. domain name for the airline website.
Therefore, if the application fails, it might
stop the functioning of the Web server.
q Medium (Pooled): The applications that are
configured to run under this application
protection share an instance of dllhost.exe IP address is a unique 32-bit number and is
and do not run in Inetinfo.exe. If the typically written as four numbers in the
applications fail, the Web server does not get range of 0 to 255 separated by periods (as
affected. However, other application running in 172.23.3.203).
under this application protection share may
get affected. It is the default option.
q 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 A domain name is the address that is used
application fails, it will not affect any other by users to access a Web application. A
application or the Web server. domain name is registered by companies
so that it can be used by its users to access
the company’s website.
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 Registering ASP.NET File
the Uniform Resource Locator (URL). Mappings
A URL is the location of a file on the Web. It is unique
for every application. To access a Web application, When multiple versions of .NET Framework are
installed on the same computer, each version installs
an ASP.NET Internet Server Application Programming components are deployed to the Web server in their
Interface (ISAPI) extension version associated with it. un-compiled form. This type of deployment has the
This extension version determines which version of following issues:
the Common Language Runtime (CLR) will be used q The application is deployed even if it
by a particular Web application. contains compilation errors.
A Web application can be configured to use any q The source code of the application is
version of the .NET Framework that is installed on the exposed.
computer. To configure a Web application to use a q The application loads slowly initially because
particular version, you need to register a script map it is compiled when it is accessed for the first
in the Internet Information Services (IIS). A script map time.
is a path to the ASP.NET ISAPI version used by the These problems can be resolved by precompiling an
application. It associates a file extension and HTTP application before deploying it to a Web server.
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 Precompiling a Web Application
the requested file to the ASP.NET ISAPI for
Precompiling a Web application involves compilation
processing. Therefore, when you need to use a
of the source code into DLL assemblies before
particular version of the .NET Framework, you need
deployment. Precompiling a Web application
to update the script maps so that they direct the
provides the following advantages:
request for a Web page to the appropriate version of
q It provides faster response time because the
the ASP.NET ISAPI.
Web application does not need to be
To update the script map, you need to use the
compiled the first time it is accessed.
ASP.NET registration tool called aspnet_regiis.exe, as
q It helps in identifying the bugs that can occur
shown in the following figure.
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.
q 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
The aspnet_regiis command can be used compiles source files such as Web pages, user
with several options. You can check all the controls, resources, and utility classes into assemblies
available options by typing aspnet_regiis/? and creates output in the form of an executable
at the command prompt. 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
Deploying a Web Application contain pointers to the appropriate assembly for that
In today’s scenario, the Internet is the best and the page. Assemblies are the .dll files that contain the
most used medium for getting information on any compiled version of .aspx.cs file.
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 All source code on an ASP.NET Web form is
application on a Web server is known as deployment. dynamically compiled into intermediate
The most basic technique for deployment is to copy language. When the intermediate language
the application components to the hard drive of the code is executed on a machine it gets
Web server. In this technique, the various application compiled just-in-time (JIT) into native
machine code and then executes. source markup files and
recompiling.
To compile a website, you need to execute the -c Specifies that the
aspnet_complier command, as shown in the application to be compiled
following figure. 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
Using the aspnet_compiler Tool the application that have
In the preceding example, the path, E:\MyWebSite been modified since
specifies the physical directory containing the source compilation was last
code, and the path, E:\TargetSite specifies the performed.
location where the compiled project needs to be
saved. Options Used with aspnet_compiler.exe
The following table lists some options that can be
used with aspnet_compiler.exe tool.
Managing ASP.NET Precompiled
Output for Deployment
-v Specifies the virtual path
of the application to be The compilation tool of ASP.NET,
compiled. For example, if aspnet_compiler.exe, compiles the source files and
the application is hosted creates separate assemblies for each source file.
in the virtual directory, These assemblies are then combined and managed
MyWebApp, the virtual by using the ASP.NET merge tool, aspnet_merge.exe.
path can be specified as / The ASP.NET merge tool merges all the assemblies
MyWebApp. If the produced by the compilation tool to create a single
application to be compiled assembly for the entire application. The merged
is not stored in a virtual assembly helps in making the deployment process
path, the -v parameter fairly simple.
can specify / as the virtual The ASP.NET merge tool can be used to combine:
directory. q All assemblies on a precompiled website into
-p Specifies the physical path a single assembly.
of the application to be q All Web user interface content assemblies
compiled. into a single assembly.
-u Specifies that q All Web user interface content assemblies
aspnet_compiler.exe into an assembly for each folder on the
should create a website.
precompiled application When you use the aspnet_merge tool, without any
that allows subsequent options, and only specify the target folder name, as
updates of contents such shown in the following figure, output assemblies are
as .aspx pages. created for each Web user interface content folder.

If this option is omitted,


the resulting application
contains only compiled
files and cannot be Using the aspnet_merge Tool Without Specifying
updated on the any Option
deployment server. You To create a single assembly that combines all Web
can update the application user interface content assemblies, you need to use
only by changing the the -w switch with the aspnet_merge tool and specify
a name for the merged assembly, as shown in the assemblies before deployment. Precompiling
following figure. 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.
Using the aspnet_merge Tool with the -w Switch
It helps in identifying the bugs that can
To create a single assembly that combines all
occur when a Web page is requested.
assemblies on a precompiled website, you need to
These bugs are rectified at the time of
use the -o switch with the aspnet_merge tool and
compiling the Web application. Then,
specify a name for the merged assembly, as shown in
the compiled and error-free Web
the following figure.
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.
Using the aspnet_merge Tool with the -o Switch q 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

Summary
Beginning ASP.NET 3.5: In http://
In this chapter, you learned that: C# and VB by Imar msdn.microsoft.com/en-
q The configuration of a Web server involves Spaanjaars us/library/aa244279
performing the following tasks: (VS.60).aspx
Creating a virtual directory
Defining Web application URLs
Registering ASP.NET file mappings
Deploying a Web Application
q A virtual directory is created so that the user
does not get direct access to the Web
application folder residing on the host ASP.NET 3.5 For Dummies http://e-docs.bea.com/wls/
computer. by Ken Cox docs81/webapp/
q A virtual directory exposes the components deployment.html
of a Web application to the remote clients http://
and allows them to access your Web www.beansoftware.com/
application through Web browsers. ASP.NET-Tutorials/
q An Application pool can contain one or more Deploy-ASP.NET.aspx
applications and allows you to configure the
level of isolation between different Web
applications.
q A URL is the location of a file on the Web. It
is unique for every application.
q Precompilation involves compilation of the
source code of the Web application into DLL
In addition to the standard diagnostic information,
tracing can also be used to display custom tracing
information about the execution of an application.
Chapter 14 Tracing information can also be written to an event
log or a text file by using trace listeners.
Tracing and Monitoring Web
Applications Implementing Tracing
After you have deployed a Web application, you Tracing can be implemented at any of the following
need to make sure that it is running properly. The levels:
errors occurring while the application is running need q Page Level
to be diagnosed and fixed. You also need to ensure q Application Level
that there are not any performance related issues
with your Web application. Page-Level Tracing
ASP.NET provides you with the tracing and health Page-level tracing is used to generate diagnostic
monitoring features that can be used to troubleshoot information at the end of page rendering. This
and diagnose problems with your Web application. diagnostic information includes all the information
By using these features, you can constantly monitor about the requests made to the page and their
the application while it is running for any issues that responses. This information is used to diagnose
could affect its performance. problems on the page. For example, suppose the
processing of your Web page is taking too long. You
This chapter discusses how to implement tracing in
can use the trace information to check which of the
Web applications. In addition, it discusses how to
Web page methods or events are taking too long to
monitor the health and performance of Web
execute. Once you are able to determine the reason
applications.
for delayed processing of your Web page, you can
Objectives easily resolve the problem.
To enable page-level tracing, you need to perform
In this chapter, you will learn to: the following steps:
Implement tracing in Web applications 1. Include the following directive at the top of
Monitor Web applications the page:
<%@ Page Trace="True" %>
2. Include the TraceMode attribute in the
Implementing Tracing in Web @ Page directive to specify the sort order for
your trace messages. You can sort the trace
Applications messages either by time or category. For
As a developer, you are focused on creating a Web example, you can sort the trace messages on
application that runs smoothly after its deployment. the basis of category, as shown in the
Once an application is deployed, you need to ensure following code snippet:
that the application is working properly and is not <%@ Page Language="C#"
giving unexpected results. For this, you need to keep Trace="True"
TraceMode="SortByCategory" %>
track of the execution of your Web application. This
If you enable tracing on a Web page of your Web
will enable you to track any errors or performance-
application, the tracing information is displayed at
related issues in your application.
the end of the Web page, as shown in the following
ASP.NET provides you with the tracing feature that
figure.
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.
this Web page.
q Response Cookies Collection: It displays
information about all the cookies that were
returned by the Web server with the
response.
q 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.
q 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
The Tracing Information of a Web Page
pages).
The following information is displayed when page- q Form Collection: It displays the list of values
level tracing is enabled: that are posted back to the Web server. It
q Request Details: It displays some basic includes all the values that are submitted by
information, such as current session ID, the Web controls, such as hidden field values,
time when the request for the Web page was the text in a textbox, and the current
made, the request and response encodings, selection in a list box.
the request type, and the return status code. q Querystring Collection: It displays the list of
q Trace Information: It displays performance- values included in the query string. You can
related information about the Web page life- also view this information in the Web page
cycle events. The events are displayed under URL. However, if the query string contains a
the Message column. The Category column lot of information, it is easier to review the
displays the category of the message. The individual items in the trace display.
From First(s) column displays the running q Server Variables: It displays all the server
time from the instant when the page request variables and their values at the time of Web
started. The From Last(s) column shows the page request.
elapsed time since the previous event. You
can use this information to determine which Application-Level Tracing
of the Web page events are taking too long When you enable tracing at the page-level, the
to execute. tracing information is displayed at the end of the
q Control Tree: It displays information about Web page. As a result, every visitor to the website
each control on the Web page, such as the will see the tracing output at the bottom of the Web
size of the rendered controls. You can use page. This is not a good approach to display Web
this information to be aware of the number pages on a website. To view the tracing output for all
of bytes that each control on the Web page the Web pages on the website, you need to enable
uses. This will help you keep a check on the tracing for every Web page if you are using page-
overall weight of the Web page. level tracing. These limitations can be overcome by
q Session State: It displays information about enabling tracing for the entire Web application.
all the session variables, their types, and Application-level tracing is used to trace information
values. for every Web page in a Web application. A special
q Application State: It displays information page named trace.axd is used to view this trace
about all the application variables, their information. This page should ideally be accessible to
types, and values. the website administrator only. To use the trace.axd
q Request Cookies Collection: It displays page, you have to first enable application-level
information about all the cookies that were tracing within the Web.config file for your
sent by the Web browser with the request for application. You can use the following attributes of
the <trace> element to change the tracing settings attributes. The trace information will be sorted by
of your website: time as specified by the traceMode attribute. It is
q enabled: Indicates whether tracing is only available to the local clients as specified by the
enabled for the application. The default value localOnly attribute.
is false. You can open the trace.axd page in the Web browser
q requestLimit: Stores tracing information just by replacing the page name in the URL with
for a maximum number of HTTP requests. trace.axd, as shown in the following figure.
The default value is 10.
q pageOutput: Indicates whether trace
information is displayed at the bottom of
every page in the application. The default
value is false.
q traceMode: Indicates the order in which
trace messages are displayed. The possible
values are SortByTime and
SortByCategory. The default value is
SortByTime.
q 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
The Trace.axd Page
computers. The default value is true, which
The preceding figure shows that three requests have
means that remote clients cannot see the
been made to this application and the right side of
tracing information.
the header indicates "Remaining: 97". The page
q mostRecent: Stores only the most recent
displays tracing information for only three requests.
trace messages if set to true. When the
Therefore, there are 97 more requests remaining
maximum limit specified by the
before tracing stops for this application. After all the
requestLimit attribute is reached, the
100 requests have been made to the application,
information for the oldest request is
tracing data is not displayed for further requests. You
discarded every time a new request is
need to click the "clear current trace" hyperlink on
received. If the mostRecent attribute is set
the trace.axd page to start displaying tracing data for
to false, which is the default value,
further requests. You can click the View Details link to
ASP.NET stops collecting new trace
see the detailed information for any request. This
messages when the maximum number of
detailed information is similar to the information that
requests has been received.
you see for a Web page when you implement page-
For example, you can make the necessary settings to
level tracing.
enable application-level tracing in the web.config file,
Application-level tracing gathers and processes the
as shown in the following code snippet:
trace information for each page in the application. If
<configuration>
you need to disable tracing for a particular page, you
<system.web>
have to set the Trace attribute of the @Page
<trace
directive to false. The trace settings made at the
enabled="true"
application-level are overridden by the page-level
requestLimit="100"
settings.
pageOutput="false"
traceMode="SortByTime"
localOnly="true" Writing Trace Information
mostRecent="false" />
</system.web> When a Web application is in the development stage,
</configuration> you often use several Response.Write statements
In the preceding code snippet, the trace information in the program code to display debugging
will be displayed for the first 100 Web requests as information. This information is used to troubleshoot
specified by the requestLimit and mostRecent the application. However, these statements need to
be removed once your application is ready for section.
deployment because the messages displayed using q category: This argument refers to an
Response.Write statements are required for arbitrary string that is basically used to group
debugging and should not be displayed to an end similar kinds of messages. It helps sort and
user. display the messages category-wise in the
Tracing resolves this problem by allowing you to Trace Information section.
insert debugging code within an application such q errorInfo: This argument refers to an
that the debugging code does not need to be object of the Exception class that contains
removed at the time of deployment. This is because the exception details associated with the
you can disable tracing to prevent the debug request.
information from being displayed as trace For example, you can write the following code in the
information. Page_Load event of your Web page:
The Trace property of the Page class returns a int i = 30;
Trace object, which can be used to write custom int j = 0;
trace statements. The Trace object is an instance of try
the TraceContext class. The Trace object {
provides a set of methods and properties that help int z = i / j;
you trace the execution of your application. Response.Write(z);
The properties of the Trace object are: }
q IsEnabled: Denotes whether tracing is catch(DivideByZeroException exp)
enabled for the current request {
q TraceMode: Sets the trace modes such as Trace.Write("Errors","Testing
sortByCategory or sortByTime the limits of infinity?",exp);
Some of the methods of the Trace object are: Response.Write("A numeric
q Warn: Displays the trace information in red value divided by zero gives
color result as
q Write: Displays the trace information in infinity.");
black color }
You can use the Trace object to write custom trace In the preceding code snippet, an exception is raised
statements when tracing is enabled for a page or an in the try block. This exception is caught in the catch
application. You can use the Write and Warn block. Then, a message, A numeric value divided by
methods of the TraceContext class to write trace zero gives result as infinity, is displayed to a user. The
statements to the trace log. The only difference information of the execption caught in the catch
between these two methods is that the Warn method block is displayed in the Trace.axd file in the browser,
displays the statements in red while the Write as shown in the following figure.
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:
q message: This argument refers to the
message displayed in the Trace Information Displaying Custom Trace Information
In the preceding figure, the trace messages are
sorted and displayed as per the execution time. <system.diagnostics>
Therefore, the trace messages are being displayed <trace autoflush="true">
between the Begin Load and End Load events. <listeners>
However, if you sort the trace messages as per the <add name="MyListener"
category, the tracing information is displayed in the type="System.Diagnostic
browser, as shown in the following figure. s.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:
Sorting of Trace Information Category-Wise <system.web>
<trace
writeToDiagnosticsTrace = "true"
Using Trace Listeners />
Trace listeners are used to collect, store, and route <customErrors mode="off" />
tracing messages. You can also use trace listeners to </system.web>
redirect the tracing information to logs, windows, or Removing a Trace Listener
text files. To remove a trace listener from the Listeners
ASP.NET provides the following three types of collection, you need to include the following code
predefined trace listeners: snippet in the web.config file:
q TextWriterTraceListener: Used to redirect <configuration>
the trace output to a file or console. <system.diagnostics>
q EventLogTraceListener: Used to redirect the <trace>
trace output to an event log. <listeners>
q DefaultTraceListener: Used to redirect the <remove
trace output to OutputDebugString API name="MyListener"/>
function and the Debugger.Log method. </listeners>
To enable a trace listener, you need to add it to the </trace>
Listeners collection. All the three types of trace </system.diagnostics>
listeners receive the same trace output when </configuration>
included in the Listeners collection but each of In the preceding code snippet, the trace listener,
them then redirects this output to a different target. MyListener is removed by using the <remove>
Adding a Trace Listener element within the <listeners> element.
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
Trace Switches
listeners. To add a trace listener in the web.config file, Trace switches allow you to enable, disable, and filter
you need to include the following code snippet in the tracing output even after the application has been
web.config file: deployed on the server. This can be done by
<configuration>
configuring the trace switches through the
web.config file. The .NET Framework provides the
following types of switches:
q 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. The Levels of the TraceLevel Enumeration and
q TraceSwitch: It allows you to set the level Their Integer Values
from which you want to receive trace You can configure a trace switch by setting it to any
statements. By configuring TraceSwitch to of the values in the TraceLevel enumeration. The
the appropriate level, you can control the following code snippet shows how you can configure
type of tracing output you want to receive. a trace switch:
To use trace switches to filter the tracing <system.diagnostics>
output, you need to initialize and configure <switches>
the trace switches. <add name="MySwitch"
q SourceSwitch: It provides multilevel switch value="2" />
to control tracing and debug output without </switches>
recompiling the code. It provides a Level </system.diagnostics>
property to test the event level of the switch. In the preceding code snippet, the value attribute of
The Level property gets or sets the switch's the switch MySwitch is set to 2 to display the
TraceLevel value. warning and error messages.
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 Monitoring Web Applications
MyTraceSwitch =
new After deploying a Web application, you, as a system
System.Diagnostics.TraceSwitch administrator, need to constantly monitor it for its
("MySwitch", "Entire proper functioning. Many unexpected problems, such
application"); as website experiencing heavy load, may occur while
In the preceding code snippet, an object of the application is running in the real-world
TraceSwitch class is created and initialized. The environment. By monitoring a Web application, you
System.Diagnostics.TraceSwitch class takes can detect the problems occurring in the application
two parameters, name and description of trace and troubleshoot them.
switch. Monitoring and troubleshooting is required to
improve the performance of a Web application. To
Configuring Trace Switches help you track and monitor a Web application,
You can configure a trace switch to trace a Web
ASP.NET provides you with the following two
application at different levels. These levels enable
features:
you to trace various types of messages such as error
q Health Monitoring
messages, warning messages, informational
q Performance Monitoring
messages, and detailed messages.
The following table lists the levels of the
TraceLevel enumeration and their integer values. 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 enabled Specifies whether health
scenarios where you want to monitor an application monitoring is enabled.
and be notified when a critical error occurs. For heartbeatInterval Specifies the interval, in
example, you can use health monitoring system to seconds, that indicates
monitor events such as start and end of an how often the
application, successful and failed logons, and WebHeartbeatEvent
unhandled exceptions. If you detect any unhandled event is raised.
exception in your Web application, you can make
appropriate changes so that it does not occur again.
The Attributes of the <healthMonitoring>
The ASP.NET health monitoring system is
Element
implemented by using the
The following table lists the child elements of the
System.Web.Management namespace. This
<healthMonitoring> element.
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 bufferModes Specifies the buffering
Web application. You can capture Web events by capabilities for a provider.
using built-in event providers. For example, there is a eventMappings Maps friendly event names
provider to capture events and send e-mail to the related event types.
notifications, a provider to log events to SQL Server, profiles Defines a collection of
and a provider to drop events into an event log. parameter sets to use
Configuring Health Monitoring when configuring events.
You can configure applications to use built-in or providers Defines the health
customized monitoring providers. These providers monitoring providers that
process the health-monitoring information and process events.
report on the health status and the performance rules Maps events to providers.
characteristics of a Web application. To use the
health monitoring system, you need to perform the The Child Elements of the
following configuration jobs: <healthMonitoring> Element
q Configure and enable Web events to be Web Events
monitored.
Web events contain information about the health of
q Configure and enable event providers that
a Web application. These events need to be trapped
listen for and process various Web events.
to report the status of the application’s health. Each
The following code snippet shows how you can
Web event is defined by a class. When a Web event is
configure health monitoring by using the
raised, an instance of the associated event class is
<healthMonitoring> element in the web.config
created. This instance stores the event data, which is
file:
processed by the event providers.
<healthMonitoring
There are several events that you can trap to monitor
enabled="true|false"
the health of a Web application. Some of the
heartbeatInterval="time
important events are:
interval">
q WebBaseEvent: It acts as a base class for all
<bufferModes>...</bufferModes>
the other Web events.
<providers>...</providers>
q WebBaseErrorEvent: It acts as a base class
<eventMappings>...</
for all Web events related to errors in the
eventMappings>
system.
<profiles>...</profiles>
q WebHeartbeatEvent: It records Web
<rules>...</rules>
events after a predefined interval of time.
</healthMonitoring>
q WebRequestEvent: It occurs when a user
The following table lists the attributes of the
sends a request to a Web server.
<healthMonitoring> element.
q WebErrorEvent: It represents the errors
that occurred at the configuration or
compilation time. </rules>
q WebApplicationLifetimeEvent: It is </healthMonitoring>
raised when an application starts or stops. In the preceding example, a <rule> child element is
q WebRequestErrorEvent: It is raised when created under the <healthmonitoring> element
any unhandled exception occurs or an error of the web.config file. Then, a rule, Default
related to a user’s request is generated. Success Audits, is created to handle success
q WebAuditEvent: It represents a base class audit events.
for Web events that are raised when a user
attempts to log on.
q WebSuccessAuditEvent: It is raised when Performance Monitoring
a logon attempt by a user is successful.
Performance is an important factor in making a Web
q WebFailureAuditEvent: It is raised when
application or project successful. You need to
a logon attempt by a user fails.
monitor a Web application to troubleshoot any
You need to enable the Web events by connecting
performance-related issues. For example, a user
them to the event providers.
request may not be processed because of insufficient
Event Providers server resources. You need to keep track of such
The event providers are used to listen for Web events errors to improve the performance of your Web
that are raised by a Web application. These providers application.
process the event information either by logging the ASP.NET provides you with several performance
information or by notifying the system administrator. counters, such as Application Restarts, Requests
ASP.NET provides you with several built-in event Queued, and Errors Total to help you keep track of
providers that you can use to capture Web events the execution of your Web application. These
raised by the Web application. Some of the built-in performance counters are valuable in determining
providers are: the performance-related problems in Web
q EventLogWebEventProvider: It logs Web applications.
events in the Windows event log. For example, you can determine the number of
q SqlWebEventProvider: It is a Web event requests that are in queue for your Web application.
provider for SQL Server databases. It logs A large number of Web requests in the queue may
Web events in the SQL Server and the SQL indicate that the application is not efficient enough
Server Express databases. and needs to be tuned. By monitoring the Requests
q SimpleMailWebEventProvider and Queued performance counter, you can track the
TemplatedMailWebEventProvider: These number of requests waiting for service in the queue.
providers respond to Web events by sending If it is affecting the performance of the application,
an e-mail message. you can make the necessary changes in the
q TraceWebEventProvider: It sends Web configuration file of the application to improve its
events to the diagnostics trace. performance. You can use the System Monitor
q WmiWebEventProvider: It sends Web (PerfMon) with ASP.NET applications to track the
events to the Microsoft Windows performance counters affecting the performance of
Management Instrumentation (WMI) applications.
subsystem.
The following example shows how to use the
Performance Counters for ASP.NET
EventLogWebEventProvider in the web.config ASP.NET supports the following groups of
file to log Web events in the Windows event log: performance counters:
<healthMonitoring enabled="true" q System performance counters
heartbeatInterval="0"> q Application performance counters
<rules> System Performance Counters
<add name="Default System performance counters are displayed in the
Success Audits" Windows Performance monitor in the form of the
eventName="Success Audits" ASP.NET performance counter object.
provider="EventLogProvide The following table lists some of the system
r" profile="Default" performance counters.
minInterval="00:02:00"/>
number of entries in the
cache.
Application Running Represents the number of Cache Total Hits Represents the total
applications running number of hits from the
simultaneously on a Web cache.
server. Debugging Requests Represents the number of
Requests Disconnected Represents the number of requests that occur while
requests that have been debugging is enabled.
disconnected due to
communication failure. The Application Performance Counters
Request Wait Time Represents the number of
milliseconds that the most
recent request waited in
the queue for being
processed by the server. Summary
State Server Sessions Represents the number of
Active user sessions that have In this chapter, you learned that:
become inactive because q Tracing can be implemented at any of the
of some user action. This following levels:
counter is available only Page Level
on the computer where Application Level
the state server service, q The properties of the Trace object are:
aspnet_state is running. IsEnabled
Worker Process Running Represents the number of TraceMode
worker processes running q Some of the methods of the Trace object are:
on a Web server. Warn
Write
The System Performance Counters q ASP.NET provides three types of predefined
trace listeners:
Application Performance Counters TextWriterTraceListener
Application performance counters are displayed as EventLogTraceListener
the ASP.NET application performance object. These DefaultTraceListener
counters enable you to monitor the performance of a q ASP.NET provides you with the following
single instance of an ASP.NET Web application. features for monitoring a Web application:
A unique instance of each ASP.NET application Health Monitoring
collects all the counters of each application. These Performance Monitoring
counters will display a value of zero when no q ASP.NET supports the following groups of
application is running on a Web server. performance counters:
The following table lists some of the application System performance counters
performance counters. Application performance counters

Reference Reading
Anonymous Requests Represents the number of
requests that are using Monitoring Web Applications
anonymous
authentication.
Anonymous Requests/Sec Represents the number of Pro ASP.NET 3.5 in C# http://www.mail-
requests per second that 2008 by Matthew archive.com/
are using anonymous MacDonald, Mario mumbaiusergroup@group
authentication. Szpuszta s.msn.com/
Cache Total Entries Represents the total msg15921.html
http://www.ajaxline.com/
health-monitoring-in-asp-
net-3-5
Working with Mobile Web
Chapter 15 Controls
ASP.NET provides you with mobile Web controls that
Creating Web Applications for can be used to create a mobile Web page. Some of
these controls are similar to the controls used for
Mobile Devices creating Web pages for desktop browsers. The
Web applications enable users to access information ASP.NET mobile Web controls are contained in the
on a 24x7 basis. Users may need to access Web System.Web.UI.MobileControls namespace
applications even while they are on the move. This is that provides the user interface elements for
possible by using mobile devices such as PDAs and rendering mobile Web applications. Most of the
cellular phones. However, accessing information by mobile Web controls are similar to the normal Web
using such devices requires you to make the Web server controls. However, there are some specific
pages available in a format that can be viewed on controls that are specific to the mobile Web pages.
mobile devices. ASP.NET allows you to create Web These controls are:
applications having Web pages that can run on a q Form
variety of mobile devices. q Command
This chapter discusses about how to create mobile q PhoneCall
Web pages. In addition, it discusses about rendering q List and ObjectList
content on mobile Web pages. q DeviceSpecific
q SelectionList
Objectives q StyleSheet
q TextView
In this chapter, you will learn to:
Form Control
Create mobile Web pages Mobile devices have small display areas. Therefore, it
Render content on mobile Web pages 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
Creating Mobile Web Pages break these pages into a collection of forms by using
Mobile devices have many limitations such as small the Form control. A Form control is a container
display area and low bandwidth. Due to these control that provides the capability to group controls
limitations, a Web page created for desktop browsers together. Each Form control can hold a group of
cannot be properly displayed on mobile devices. For logically related controls. These Form controls can be
example, you can create a Web page that contains a displayed by setting the ActiveForm property of
header, a navigation bar at the left side of the page, the Web page, as shown in the following example:
and content in the rest of the page. This Web page <html xmlns="http://
can be rendered on desktop browsers. However, this www.w3.org/1999/xhtml" >
layout of the Web page may not be suitable for <body>
mobile device browsers because mobile devices have <mobile:Form id="Form1"
a smaller display area than desktop monitors. runat="server">
Therefore, you need to create specifically designed <mobile:Label text="Welcome
Web pages for mobile devices. the mobile application"
ASP.NET provides you with the ID="Label1"
System.Web.Mobile namespace that is used runat="server" />
specifically for mobile Web development. The <mobile:Command ID="Button1"
System.Web.Mobile namespace contains the core text="Click Me" runat="server"
capabilities such as authentication and error OnClick="Button1_Click" />
handling, required for building ASP.NET mobile Web </mobile:Form>
applications.
<mobile:Form id="Form2"
runat="server">
<mobile:Label text="Welcome PhoneNumber property of the PhoneCall Control is
the second page" ID="Label2" displayed as hyperlink, selecting which a user can
runat="server" /> initiate a telephone call.
</mobile:Form> However, if the mobile device does not support the
</body> capability of placing phone calls, the PhoneCall
</html> control displays the phone number as text. The
protected void Button1_Click PhoneCall control can be added to a mobile page by
(object sender, EventArgs e) using the <PhoneCall> element, as shown in the
{ following example:
this.ActiveForm=Form2; // <mobile:PhoneCall ID="Phone1"
Form2 is the name of the Form PhoneNumber="9999037202"
control runat="server"/>
} In the preceding example, a PhoneCall control with
In the preceding example, when the application the PhoneNumber property set to 9999037202 is
starts, the default form control Form1 is displayed. added to a Form control.
When the user clicks the Button1 button control in To use a PhoneCall control, you need to add the
the Form1 control, the Form2 Form control is control onto a Form or Panel control or inside a
displayed. control's template on an ASP.NET mobile Web page.
ASP.NET Web pages can contain more than one After adding the control, you need to specify the Text
Form controls. However, a mobile Web application and the PhoneNumber properties. You can optionally
can display only one Form control at a time. When a use the AlternateUrl property, which is set to the
user browses a mobile Web page, by default, the first URL of the page that the application will navigate to
form appears on the page. when running on devices that cannot initiate phone
calls.

A mobile Web page must contain at least


one Form control. Form controls cannot be The PhoneNumber property must be set,
nested. to use the PhoneCall control. If the
PhoneNumber property is not set, the
Command Control application will throw an error.
The Command control is similar to the Button Web
server control. It combines the functionality of the List and ObjectList Controls
normal Button, ImageButton, and LinkButton Mobile Web controls do not include the DataList and
controls. The Command control can be added to a Repeater controls. Instead of these controls, the
mobile page by using the <Command> element, as mobile Web controls include the List control. The List
shown in the following example: control includes the functionality that is provided by
<mobile:Command ID="Button1" the DataList and Repeater controls. The List control
text="Click Me" runat="server" can be added to a mobile page by using the
OnClick="Button1_Click" /> <List>> element, as shown in the following
In the preceding example, a Command control, example:
Button1, is added to a Form control. The Text <mobile:List ID="List1"
property of the Command control is set to Click Me Runat="server">
and the event handler Button1_Click is attached <Item Text="Sam" />
with the Click event of the Command button. <Item Text="Peter" />
PhoneCall Control <Item Text="Jack" />
A PhoneCall control is used to enable applications to </mobile:List>
initiate telephone calls if the user's mobile device In the preceding example, a List control, List1, is
supports that capability. If the mobile supports the added to a form control. The list control has three
capability, the phone number specified by using items.
Similarly, in place of the DataGrid control, the mobile
Web controls include the ObjectList control. The property are displayed as check boxes. You can set
ObjectList control includes the functionality that is the SelectType property of the SelectionList
provided by the DataGrid control. The ObjectList control as shown in the following code snippet:
control can be added to a mobile page by using the SelectionList sl = new
<ObjectList>> element, as shown in the following SelectionList();
example: sl.SelectType = ListSelectType.Dr
<mobile:ObjectList opDown;
ID="ObjectList1" Runat="server"/> StyleSheet Control
The following code nippet binds the ObjectList The StyleSheet control enables you to use styles in
control with a dataset: the ASP.NET mobile Web Forms. It has no visual
ObjectList1.DataSource = ds; representation. The StyleSheet control can only be
ObjectList1.DataBind(); attached to ASP.NET mobile Web forms or to mobile
DeviceSpecific Control user controls. There can be only one style sheet for a
The DeviceSpecific control is used to specify a choice page or a control.
among multiple content alternatives. The Each style sheet can contain one or more styles. A
DeviceSpecific control allows you to specify one or control can use the styles defined in the StyleSheet
more choices, each containing attributes that specify control by using the StyleReference property.
how to evaluate the choice against target device The following example shows how to define styles by
capabilities. During run time, each choice specified in using the StyleSheet control:
the DeviceSpecific control is evaluated in order, and <mobile:StyleSheet ID="MyStyle"
the first choice that is successfully evaluated is used. Runat="server">
The DeviceSpecific control is used to specify template <mobile:Style Name="Style1"
sets and override properties. For example, you can ForeColor="#ff0066"
use the DeviceSpecific control to specify device- Font-Size="Large"/>
specific images for the Image control, as shown in <mobile:Style Name="Style2"
the following example: ForeColor="#009900"
<mobile:Image runat=server> Font-Size="Normal"/>
<DeviceSpecific> </mobile:StyleSheet>
<Choice Filter="isColor" The preceding example defines two styles, Style1 and
ImageURL="colorImg.gif" /> Style2. To use these styles for a control, you need to
<Choice Filter="isWML11" set the StyleReference property of the control as
ImageURL="myImage.wbmp" /> shown in the following example:
</DeviceSpecific> Label1.StyleReference = "Style1";
</mobile:Image> TextView Control
In the preceding example, if the device is colored as
The TextView control is used to display large
specified by the isColor value of the Filter
quantities of text. The TextView control supports
attribute, the colorImg.gif image will be
device filters for overriding property values. This
displayed. For WML device, myImage.wbmp image
enables the TextView control to customize its
will be displayed.
appearance according to the capabilities of the
SelectionList Control device on which it is rendered. The TextView control
The SelectionList control provides different visual can be added to a mobile page by using the
representations for a list of selectable items. It <TextView> element, as shown in the following
combines the functionality of the CheckBox, example:
CheckBoxList, DropDownList, ListBox, RadioButton, <mobile:TextView ID="TextView1"
and the RadioButton Web server controls. You can Wrapping="Wrap"/>
use the SelectType property of the SelectionList
control to define the type of selection list button to
render. Working with Device Emulators
For example, if you set the SelectType property of
After developing a mobile Web application, you need
the SelectionList control to CheckBox, the item
to test it on a mobile device. Although, you can test
passed to the control as the value of its DataSource
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 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
Rendering Content on Mobile comes from Internet Explorer, the Calendar control is
rendered as shown in the following figure.
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 Rendering of a Calendar Control on Internet
tedious and complex task. This task can be simplified Explorer
by using control adapters and device filters provided This type of browser-based rendering of controls is
by ASP.NET. known as adaptive rendering and can be
implemented by using control adapters.
A control adapter is used for device-specific
Implementing Control Adapters rendering of mobile Web controls instead of using
the control's default rendering logic. To customize
Mobile devices have different screen sizes and the behavior of Web controls, you need to specify an
capabilities. When a mobile device requests a Web object of the ControlAdapter class. The
page, the server first checks the capabilities of the ControlAdapter class is an abstract class that
browser that has made the request. Based on the defines the basic functionality for all adapters. It
browser capabilities, the controls are rendered on the overrides certain methods and events of the
Web page. For example, consider that a mobile Control class to allow browser or markup-specific
device requests for a Web page that displays a handling.
calendar control. Since a mobile device does not
When a control is rendered on a Web page, the
have enough space on the screen, the calendar
Control base class first checks whether a control
control is rendered as a hyperlink, as shown in the
adapter is currently associated with the control. If an
following figure.
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 if (Request.Browser.IsMobileD
contains information about the browser capabilities. evice)
ASP.NET uses the .browser files to determine the {
capabilities of the browser, and to decide how to Response.Redirect
render markup to that browser. ("Mobile/Home.aspx");
The browser definition file, in addition to the }
mapping control adapters, is used to populate the }
HttpBrowserCapabilities class. This class The preceding code is written within the Page_Load
contains information about the capabilities of the event handler of the home page that is created for
browser, such as name, type, and version of the the desktop computers. It is the default startup page
browser. You can determine the capabilities of the for the application. When the page is requested by
browser by accessing the any computer, the type of the device is checked. If
HttpBrowserCapabilities class through the the request is from a desktop computer, the default
Request.Browser property. home page is returned. However, if the request
The following table lists some commonly used comes from a mobile device, the Mobile/Home.aspx
Request.Browser properties with their page is returned.
description.

Request.Browser.Bro Gets the name of the


wser browser You can check the browser capabilities by
Request.Browser.Ver Gets the full version declaring a
sion number of the browser as HttpBrowserCapabilitiestype
string variable as shown in the following code
Request.Browser.Typ Gets the name and major snippet:
e version number of the
browser HttpBrowserCapabilities browser
Request.Browser.IsC Gets a boolean value that = Request.Browser;
olor indicates whether the
browser has a color Response.Write
display (browser.ActiveXControls);
Request.Browser.IsM Gets a boolean value that
obileDevice indicates whether the
browser is a mobile device
Request.Browser.Can Gets a boolean value that
InitiateVoiceCall indicates whether the
browser is capable of Some mobile controls require you to use
initiating a voice call fully qualified redirects. For converting
relative paths into fully qualified paths, you
Some Commonly Used Request.Browser need to use the <httpRuntime>element
Properties as shown in the following example:
Consider an example wherein you have created
separate home pages for desktop computers and <system.web>
mobile computers. You want to render the home
pages depending upon the type of the computer <httpRuntime
that has requested the page. For this, you need to useFullyQualifiedRedirectUrl="t
check the browser capabilities. This can be done by rue" />
using the following code:
protected void Page_Load(object </system.web>
sender, EventArgs e)
<DeviceSpecific><Choice> tags. For this, you
Implementing Device-Specific need to use the
Rendering <DeviceSpecific><Choice> tags as shown in
the following example:
Different mobile devices have different capabilities. <mobile:Image runat=server>
Some devices can access the Internet and send e- <DeviceSpecific>
mail messages while others cannot. Similarly, some <Choice Filter="isColor"
devices have color screens, whereas others have ImageURL="colorImg.gif" />
gray-scale screens. When you design a Web page for <Choice Filter="isWML11"
mobile devices, you do not know which device will be ImageURL="myImage.wbmp" />
used by the user to access that page. Therefore, you <Choice
should design a Web page that caters to all the ImageURL="monoImage.gif" />
possible types of mobile devices. </DeviceSpecific>
For example, you may want to display a colored </mobile:Image>
image on your mobile Web page. However, there are In the preceding example, if the device is colored as
mobile devices that do not support colored images. specified by the isColor value of the Filter
Therefore, you need to design your Web page in attribute, the colorImg.gif image will be
such a way that it can be used by both types of displayed. For WML device, myImage.wbmp image
mobile devices. For this, you need to design the Web will be displayed. The third <Choice> tag does not
page in such a way that it displays a gray image on have any Filter attribute. Therefore, it is the
devices that do not support colored images and a default choice and will be evaluated if the preceding
colored image on the rest of the devices. two choices are not matched.
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 WML devices are those devices that support
page for specific types of devices by defining a set of Wireless Markup Language (WML) intended
device filters for the page. for displaying Web pages on mobile
ASP.NET allows you to specify device filters for each devices. Currently, in place of WML,
type of device by using the Extensible HyperText Markup Language
<DeviceSpecific><Choice> tags. You can insert (XHTML) is used in mobile devices.
the <DeviceSpecific> tag as a child element of
any mobile control on the Web page. This tag acts as The Filter attribute in each <Choice> tag either
an outer container for holding a number of choices specifies the name of a method on the mobile form
defined by the <Choice> tag. or associated .ascx file, or the name of a device filter
The <Choice> tag represents device characteristic/ defined in the <deviceFilters> element of the
value pairs, where the device characteristic is drawn web.config file.
from a number of sources. A control can contain only
one <DeviceSpecific> tag. However, it can Using the Name of a Method as
contain many <Choice> tags. Choices are evaluated Filters
in the order in which they appear in the When the name of a method is used as a filter, the
DeviceSpecific/Choice construct. Each <Choice> tag choice is applied on the basis of the Boolean value
contains: returned by the method.
q A Filter attribute that specifies the devices The filter method must conform to the following
that this choice applies to. signature:
q Additional property values that override the public bool methodName(
properties of the original control when the System.Web.Mobile.MobileCapabilit
device specified by the Filter attribute is ies capabilities,
used. string optionalArgument);
Consider a scenario wherein you need to control the
display of an image by using the
Using Device Filters in the
Web.config File
The Filter attribute can also specify the name of a you can use the XhtmlTextWriterand
filter defined in the web.config file. These filters can ChtmlTextWriterclasses to provide
be of two types: additional adaptive rendering capabilities
q Comparison filter: Comparison filters make to the controls.
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> Summary
<deviceFilters>
In this chapter, you learned that:
<filter name="TestIsColor"
compare="IsColor" q A Web page created for desktop browsers
argument="true" /> cannot be properly displayed on mobile
</deviceFilters> devices because mobile devices have small
</system.web> display area and low bandwidth.
In the preceding markup, q ASP.NET provides you with the
TestIsColor is the name of System.Web.Mobile namespace that is
the filter and IsColor is used specifically for mobile Web
the capability that is to development.
be compared against the q Mobile Web pages have some specific
value, true. controls. These are:
Form
q Evaluator-delegate filter: The evaluator-
Command
delegate filter is used for more complex
PhoneCall
evaluation. In evaluator-delegate filter, you
List and ObjectList
need to specify an evaluator-delegate filter
DeviceSpecific
by providing the class and the name of a
SelectionList
method. The following markup shows a
StyleSheet
evaluator-delegate filter:
<system.web> TextView
q Device emulators are software programs that
<deviceFilters>
simulate the environment of a cell phone or
<filter
PDA on the desktop of your PC.
name="TestIsColor"
type="CustomFilter" q A control adapter is used for device-specific
rendering of mobile Web controls instead of
method="checkColor" /
using the control's default rendering logic.
>
q To customize the behavior of Web controls,
</deviceFilters>
you need to specify an object of the
</system.web>
ControlAdapter class.
In the preceding markup, TestIsColor is
q The ControlAdapter class is an abstract
the name of the filter, CustomFilter is the
class that defines the basic functionality for
name of the class, and checkColor is the
all adapters.
method that is called at run time to test the
q The ability to render a control based on the
evaluator. You need to write and compile the
type of the device is known as device-
class containing the method that is used to
specific rendering.
test the evaluator.

Reference Reading
Creating Mobile Web Pages
In addition to device-specific rendering by
using the <DeviceSpecific>element,
Pro ASP.NET 3.5 in C# http://
2008 by Matthew msdn.microsoft.com/en-
MacDonald, Mario us/library/8htez1ds.aspx
Szpuszta

Rendering Content on Mobile Web


Pages

Pro ASP. Net 3. 5 Server http://en.wikipedia.org/


Controls and AJAX wiki/Mobile_browser
Components by Rob http://
Cameron, Dale Michalk msdn.microsoft.com/en-
us/library/7s9fybz5.aspx
execution of the Web application.
C
Client-side Scripting
Refers to the class of computer programs on the
Web that are executed client-side, by the user's Web
Glossary browser.
A CLR
Accessibility A core component of Microsoft's .NET initiative that
The degree of ease with which an application can be runs a form of bytecode called the Common
used by a variety of people. Intermediate Language (CIL).
Active Server Pages (ASP) COM+
Microsoft's first server-side script engine for A component that is a combination of Component
dynamically-generated Web pages. Object Model (COM) and Microsoft Transaction
AJAX Service.
A Web development technique that is used to create Cross-Page Posting
dynamically interactive applications. The process of configuring controls to post
AJAX Engine information to a different page rather than back to
itself.
Serves as a mediator that sends only small page bits
that are to be updated to the server as XML and Connection String
subsequently processes server response to update A string that provides necessary information, such as
the relevant page elements without reloading the the server location, the database to use, and the
entire page. authentication information, so that the underlying
Application-level Error Handling provider can communicate and connect to the
required database.
Enables you to handle errors on ASP.NET pages,
irrespective of where the errors occur in the Content Page
application. A Web page that references a master page.
ASCII ContentPlaceHolder
A character-encoding scheme based on the English A control in the master file that defines the location
alphabet. ASCII codes represent text in computers, where the content from a referencing Web page is
communications equipment, and other devices that merged at run time.
work with text. CSS
ASP.NET(Active Server Pages for .Net) A stylesheet language that is used to describe the
A component of the Microsoft .NET Framework that presentation of a document written in a markup
is used for building, deploying, and running Web language.
applications and distributed applications. Custom Web Server Control
Attribute A user-defined control that provides an approach to
A declarative tag that is used to convey information reusing logic in an ASP.NET application. A Custom
to runtime about the behavior of programmatic Web Server Control is compiled into an assembly
elements. before the application is run.
Authentication D
A process of validating the identity of a user before Data Access Layer
granting access to a restricted resource. A layer of a computer program which provides
Authorization simplified access to data stored in persistent storage
A process of verifying whether an authenticated user of some kind, such as an entity-relational database.
has the privilege to access a requested resource. Data-bound Web Server Controls
B The controls that can be bound to a data source
Breadcrumb control to display and modify data in a Web
application.
The navigation structure or the navigation path of
the website displayed in the SiteMapPath control. Data Source Control
Breakpoints A control that pulls together everything required to
connect to a database. This is done to retrieve or
Places in the code where the debugger stops the
manipulate data. HTML Control
Debugging A control that is a representation of the HTML
The process to locate and fix errors in a computer markup that is rendered by Web browsers.
program. I
Deployment Identifier (ID)
A process of installing a Web application on a Web An attribute that establishes the identity of a control.
server. Impersonation
Device Emulators A process of executing code under the authenticated
Software programs that simulate the environment of user identity and not under the ASPNET account.
a cell phone or PDA on the desktop of your PC. Internet Information Services (IIS)
DLL The standard Web server available in Windows.
Is Microsoft's implementation of the shared library ISAPI
concept in the Microsoft Windows and OS/2 An extension version that determines which version
operating systems. of the CLR will be used by a particular Web
E application.
Event J
An action or occurrence, such as a click, a key press, a JavaScript
mouse movement, or a system-generated A scripting language that is used to generate client-
notification. side scripts.
Event Wire-Up JSON
The mechanism that ASP.NET uses to determine A lightweight computer data interchange format. It is
which procedures to call when objects raise events. a text-based, human-readable format for
Exception representing simple data structures and associative
An abnormal condition encountered by an arrays called objects.
application during execution. JSP
EnableViewState A Java technology that allows software developers to
A property of a Web Server control that determines dynamically generate HTML, XML or other types of
whether the control should retain its state for the documents in response to a Web client request.
duration of the postback. L
G Localizability
Garbage Collection An intermediate process that ensures that a
A process that automatically frees the memory of globalized Web application is ready for
objects that are no more in use. implementing localization.
Global.asax File Localization
An optional file that contains code for responding to The process of customizing the globalized Web
application-level events raised by ASP.NET or by application to a specific locale and culture.
HttpModules. M
Globalization Master Page
The process of designing and developing a Web An ASP.NET file with the extension .master with a
application in such a way that it is culture-neutral and predefined layout that can include static text, HTML
language-neutral. elements, and server controls.
H Machine.config
Health Monitoring A file that defines global, default settings for all
A system that enables you to monitor the status of applications on a server.
the deployed Web applications. Master Page
HTML A file that contains common content and
A predominant markup language for Web pages that functionality that is merged with other Web pages at
provides a way to describe the structure of text- run time.
based information in a document and to supplement Membership
that text with interactive forms, embedded images, A class that provides methods for managing user
and other objects. accounts, authorizing users, and managing
passwords. pages in the application but scoped to only the
Message Queues current browser session.
Software-engineering component used for Site Map
interprocess communication or inter-thread An XML file that describes the hierarchical and logical
communication within the same process. structure of the website.
N SOA
Namespace Software architecture, which is essentially a collection
A collection of classes. of services communicating with each other.
.NET Remoting SOAP
A Microsoft Application Programming Interface (API) A protocol specification for exchanging structured
for interprocess communication released in 2002 information in the implementation of Web services in
with the 1.0 version of .NET Framework. computer networks.
Nonpostback Event SqlDataSource
An event which is raised when a Web page does not A control that allows you to retrieve and update data
immediately cause a postback. from different databases by using SQL commands.
N-tier Model SSL
A client-server architecture in which, the A protocol developed by Netscape for transmitting
presentation, the application processing, and the private documents via the Internet.
data management are logically separate processes. Styles
P Define a set of formatting options, which can be
Page-level Error Handling reused to format different HTML elements on a
Used to handle errors that occur on ASP.NET pages. single or multiple Web pages.
Performance Monitoring T
A system that helps you track the execution of your TCP
Web application. One of the core protocols of the Internet Protocol
Precompilation Suite that provides reliable, ordered delivery of a
The process of compiling a site and creating output stream of bytes from one program on one computer
to a specified folder that can be deployed to a to another program on another computer.
production server. Templated Control
Provider A type of composite control that provides more
A class that communicates with a specific type of power while presenting data by using user-defined
database. templates.
Postback Event Templated User Control
An event which is raised when a Web page is sent Controls that allow developers to modify the layout
back to the server for processing. of its user interface by defining their own templates.
Q Themes
Query String The collection of properties that enable you to define
The information appended to the URL of the target the appearance of Web pages and controls on your
page. It contains information shared by the source website.
page. TLS
R A protocol that allows applications to communicate
Role across a network in a way designed to prevent
A name assigned to a group of users. Any permission eavesdropping, tampering, and message forgery.
assigned to the role automatically applies to all the Tracing
members of that role. The process of retrieving crucial information related
S to the execution of an application. Tracing is used for
Server.Transfer debugging and optimization purposes.
A method to transfer execution from the source to U
the target page on the server. Uniform Resource Locator
Session State The global address of documents and other
A global storage mechanism, accessible from all the resources on the World Wide Web (www).
User Control
A control that provides an approach to encapsulate
the reusable logic for Web pages. User controls
consist of a number of Web server controls and
HTML controls.
V
ViewState
The default method used by Web pages to preserve
the page- and control-property values between
roundtrips to the server.
Virtual Directory
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.
W
WCF
A programming framework used to build
applications that inter-communicate.
Web.config
A file that defines the configuration settings for Web
applications.
Web Custom Controls
Controls that provide an approach to reuse logic in
an ASP.NET application.
Web Form
A .NET Framework object that allows development of
Web-based applications and websites.
Web Parts
A modular unit that can contain any type of Web-
based information.
WebPartManager
An invisible control that performs a number of
essential tasks such as keeping a track of the Web
parts in a page, the zones that contain them, and the
order of the Web parts in the zone.
Web Parts Control Set
Consists of a group of Web parts that work together
to enable users to create Web part pages.
WSE
An add-on to the Microsoft .NET Framework which
includes a set of classes that implement additional
WS-* Web service specifications chiefly in areas such
as security, reliable messaging, and sending
attachments.
Web Service
A software system designed to support interoperable
machine-to-machine interaction over a network.
Web User Controls
Containers that can be created by combining one or
more Web server controls.
Certification Mapping
This course along with the Developing Database
Applications Using ADO.NET and XML course
includes the necessary information to help you clear
the 70-562 exam. However, you need to supplement
the course with additional work.
The course consists of the following books:
q Book 1: Developing Web Applications Using
ASP.NET - Student Guide
q Book 2: Developing Web Applications Using
ASP.NET - Activity Book
The following table lists the exam objectives covered
in this course and the corresponding chapter and
section names.

The preceding table lists the chapters and


sections of Book 1 that need to be referred
for each objective of the certification.
However, in addition to Book 1, you also
need to refer to the corresponding chapters
of Book 2 for information on the practical
applicability of the concepts included in
Book 1.

You might also like