Professional Documents
Culture Documents
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.
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
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.
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.
http://www.exforsys.com/
tutorials/asp.net-2.0/
state-management-in-
asp.net-2.0.html
http://
www.dotnetspider.com/
resources/1472-STATE-
MANAGEMENT.aspx
Implementing Caching
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
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" />
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
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.
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
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
Implementing Accessibility
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:
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.
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.
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