Professional Documents
Culture Documents
Introducing ASP.NET
Web applications have revolutionized the way business is conducted. These applications
enable organizations to share and access information from anywhere and at anytime. This has
majorly moved the focus of application development from desktop applications to Web
applications. One of the most popular server-side technologies used today for developing
Web applications is ASP.NET.
This chapter introduces the basics of Web development. It also discusses the architecture,
functioning, and features of ASP.NET. In addition, it explains how to develop ASP.NET
applications.
Objectives
In this chapter, you will learn to:
Identify the basics of Web development
Explore ASP.NET
Develop ASP.NET applications
Static Web Page: A Web page that consists of only Hyper Text Markup Language
(HTML) is a static Web page. A static Web page does not respond dynamically to the
actions performed by a user.
Dynamic Web Page: A Web page that responds dynamically to the actions
performed by a user is a dynamic Web page and an application that consists of
dynamic Web pages is a dynamic Web application. Such an application can be created
by using server-side scripts, client-side scripts, or both in addition to HTML pages.
Server-Side Scripting
With the increase in the usage of the Internet as the information medium, organizations are
creating dynamic Web applications. Dynamic Web applications enable a user to:
Retrieve data from a database that may not reside on the computer where the Web
server is located.
Submit data from HTML forms.
Get information based on the input.
Client-Side Scripting
Client-side scripting enables you to develop Web pages that can dynamically respond to user
input without having to interact with a Web server. Suppose, you have a Web application that
requires users to enter the user name and password before displaying the home page. You
need to ensure that a user does not leave the user name and password fields blank. To check
whether a user has left the user name and password fields blank, you can write client-side
scripts.
In addition to providing dynamic content, a client-side script helps reduce network traffic
because it does not need to interact with a Web server to provide dynamic response to the
user input. Client-side scripting also speeds up the response time of a Web application. This
happens because a Web server is not overloaded with the job of processing the client-side
script for every client. Scripting languages, such as VBScript and JavaScript, are used to
write client-side scripts.
The following figure shows the working of client-side scripts.
Browser support: Client-side scripting is not supported equally by all browsers and
operating systems.
Isolation: Client-side scripts cannot access server-side resources. It is difficult and
requires a lot of coding to access a file or interact with a database on the server by
using client-side scripts.
Security: Client-side scripts are visible to the end users. Therefore, they can be
tampered by malicious users.
Thin clients: Web-enabled devices such as mobile phones, palmtop computers, and
Personal Digital Assistants (PDAs) can communicate with Web servers. These
devices act as thin clients that can use Web applications containing server-side
scripting. However, these devices do not support client-side scripting such as
JavaScript or VBScript.
Note
In spite of all the limitations, client-side scripting is still in use. ASP.NET allows you to use
client-side scripting in addition to the server-side scripting to create rich and responsive Web
applications.
Exploring ASP.NET
ASP.NET is a server-side technology that enables programmers to create dynamic Web
applications. It has a number of advanced features such as simplicity, security, and scalability
that help you develop robust Web applications. These advanced features of ASP.NET are
based on the .NET Framework.
Web Form Pages: Enable you to include user interfaces, such as Text box control,
List box control, and the application logic of Web applications.
Configuration Files: Enable you to store the configuration settings of an ASP.NET
application.
XML Web Service Files: Define a Web service that can be called by an ASPX file
over the Internet or from a local network.
Web forms and the state management feature of ASP.NET constitute the ASP.NET Page
Framework. There are also a number of runtime services available in ASP.NET. The
ASP.NET runtime services include view state, session state, and application state
management, Web security, and the caching mechanism of ASP.NET applications. The
runtime services of ASP.NET interact with .NET Framework base classes, which in turn,
interact with the Common Language Runtime (CLR) to provide a robust Web-based
development environment.
platform. The Web server processes the ASP.NET files and then executes the scripts. Finally,
the results are sent to the Web browser that requested the ASP.NET file.
The following figure depicts how a Web server processes a request for an ASP.NET file.
Note
ASP.NET script engine is the engine that processes the server-side scripts contained in an
ASP.NET application. After processing the scripts, the engine renders the result as an HTML
document and sends it back to the browser.
Features of ASP.NET
In addition to hiding the code of the ASP.NET file from the users, ASP.NET has the
following advanced features that help develop robust Web applications:
Compiled code: The code written in ASP.NET is compiled and not interpreted. This
makes ASP.NET applications faster to execute than other server-side scripts, such as
the scripts written in a previous version of ASP that are interpreted.
Power and flexibility: ASP.NET applications are based on CLR. As a result, the
power and flexibility of the .NET platform is available to ASP.NET applications.
ASP.NET applications enable you to ensure that the .NET Framework class library,
messaging, and data access solutions are seamlessly accessible on the Web. ASP.NET
is also language-independent. As a result, you can choose any .NET language to
develop your application.
Simplicity: ASP.NET enables you to build user interfaces that separate application
logic from the presentation content. In addition, CLR simplifies application
development by using managed code services, such as automatic reference counting
and garbage collection. Therefore, ASP.NET makes it easy to perform common tasks
ranging from form submission and client authentication to website configuration and
deployment.
Manageability: ASP.NET enables you to manage Web applications by storing the
configuration information in an Extensible Markup Language (XML) file. You can
open the XML file and modify it.
Scalability: ASP.NET has been designed with scalability in mind. It has features that
help improve performance in a multiprocessor environment.
Security: ASP.NET provides a number of options for implementing security and
restricting user access to a Web application. All these options are configured within
the configuration file.
Extensibility: ASP.NET provides a number of options to create an extensible Web
application. For example, you can create custom controls and extend the default
Hypertext Transfer Protocol (HTTP) pipeline. The path through which the data flows
from the client to the server is called the HTTP pipeline. It is a technique in which
multiple HTTP requests are written out to a single socket without waiting for the
corresponding responses. It improves the page loading time.
Integrated error checking: Visual Studio can detect various problems such as data
type conversion errors, missing namespaces or classes, and undefined variables.
When you type code, Visual Studio detects and underlines these problems.
The Web form designer: Visual Studio provides the Web form designer that enables
you to create a Web page by simply dragging the ASP.NET controls to the
appropriate location and configuring their properties. The actual Web page markup is
created automatically.
An integrated Web server: Web applications need to be hosted on a Web server
such as IIS to be accessible for the users. Therefore, you need to install IIS on the
development computer to test the applications. However, if you are creating a Web
application by using Visual Studio, you need not install IIS on the computer. This is
because Visual Studio has an integrated development Web server that enables you to
run a Web application directly from the design environment.
Developer productivity enhancements: Visual Studio provides features such as
automatic statement completion and color-coded syntax that makes coding quick and
efficient. In addition, Visual Studio has an integrated debugger that allows you to
watch code execution, pause your program at any point, and inspect the contents of
any variable. This helps in debugging the code quickly and efficiently.
Complete extensibility: Visual Studio allows you to use macros, change project
templates, and even add your own custom add-ins. This provides you to extend the
existing functionality of the existing environment.
domains also restrict a Web page in one application from accessing the in-memory
information of another application. Each Web application is a separate entity that has its own
set of data. It can be described as a combination of files, pages, handlers, modules, and
executable code that can be invoked from a virtual directory on a Web server.
The following figure shows a Web server that is hosting four Web applications.
Note
A virtual directory is a directory that is exposed to the public on a Web server.
Description
Bin
App_Code
App_Browsers
App_GlobalResources
App_LocalResources
App_WebReferences
App_Data
App_Themes
Some of the subdirectories given in the preceding table are created in specific applications.
For example, the App_Themes directory is created when you use themes in your application.
Files Used in ASP.NET Web Applications
The ASP.NET Web applications can include different types of files. The following table lists
some of the important file types with their descriptions.
File Name
Description
web.config
Global.asax
Provides control and flexibility over the way you run applications.
Eliminates the need to recompile the application every time a setting changes.
Controls access to protected resources, and the location of remote applications and
objects by defining configuration settings.
To understand the benefits of configuration files, consider an example. Suppose, your Web
application includes a number of forms that are required to connect to an SQL Server
database. You have written the code to create the connection on each of these forms.
However, if the location of the database is modified, you will have to update the code for
connecting to the database in each form. A better option is to store the details of the
connection string in a configuration file for the Web application and refer to the connection
string from within the code. As a result of this, even if the database location is changed, only
the connection string in the configuration file needs to be updated.
ASP.NET allows you to easily edit the configuration data before, or after an application is
deployed on the server. The files in the configuration hierarchy allow you to make
configuration settings at different levels.
The following table lists the levels, the corresponding configuration files, and their
description.
The visual portion: Refers to the static HTML and ASP.NET server controls that
define the layout of a Web page.
The programming logic: Refers to the code that is required to interact with the Web
page.
ASP.NET provides two models for managing the visual elements and code:
At run time, the compiler converts a single-file page into a class that derives from the
System.Web.UI.Page class.
The single-file page model provides the following advantages:
In pages with less code, keeping the programming code and the HTML markup in a
single file proves to be very convenient while studying the file.
Pages written by using the single-file model are slightly easier to deploy or to send to
another programmer because there is only one file.
A single-file page is easier to rename because there is no dependency between files.
Managing files in a source code control system is slightly easier because the page is
self-contained in a single file.
file with
which the page is associated, and the Inherits attribute specifies a code-behind class
for the page to inherit. This class can be any class that is derived from the Page class.
This attribute is used with the CodeFile attribute, which contains the path to the
source file for the code-behind class.
When the page is compiled, ASP.NET creates a new partial class for the .aspx file. This class
is a peer of the code-behind partial class file and contains the declarations for the controls of
the page. Finally, ASP.NET generates a class that inherits from the partial class created from
the .aspx file and the code-behind partial class. The generated class is compiled into an
assembly that runs in order to render output to the browser.
The code-behind model provides the following advantages:
Description
Init
Load
Unload
Application
Request
Response
Server
Session
HttpContext
Application
The Application object provides a reference to an object of the HttpApplicationState
class. The Application object is used to store information that is defined for the entire Web
application. For example, the connection string, which is used to connect to the database
server, is defined for the entire Web application. Therefore, the connection string can be
stored in the Application object. The following table describes some of the properties of the
Application object.
Property
Description
Count
Item
Description
Description
ApplicationPath
Url
UserHostAddress
UserLanguage
Browser
Cookies
QueryString
Method
byte[] BinaryRead(int)
stores it in an array.
Request Objects Method with Description
Response
The Response object provides a reference to an object of the HttpResponse class. The object
enables ASP.NET applications to send information to the client. The following table
describes some of the properties of the Response object.
Property
Description
Buffer
Cache
ContentType
Cookies
IsClientConnected
Description
Server
The Server object provides a reference to an object of the HttpServerUtility class. The
Server object provides methods that can be used to access the methods and properties of the
Web server. The following table describes some of the properties of the Server object.
Property
Description
MachineName
ScriptTimeout
Description
Description
Count
SessionID
Timeout
Description
Property
Description
AllErrors
ApplicationInstance
Timestamp
Users
Description
Summary
In this chapter, you learned that:
ASP.NET has the following advanced features that help develop robust Web
applications:
o Compiled code
o Enriched tool support
o Power and flexibility
o Simplicity
o Manageability
o Scalability
o Security
o Extensibility
A Web form is made up of the following two components:
o The visual portion
o The programming logic
ASP.NET provides two models for managing the visual elements and code:
o Single-file page model
o Code-behind page model
ASP.NET provides the following built-in objects:
o
o
o
o
o
o
Application
Request
Response
Server
Session
HttpContext
Reference Reading
Introducing Web Development
Reference Reading:
Books
Mastering Web
Development with
Microsoft Visual Studio
2005 by John Paul
Mueller Beginning
ASP.NET 3.5 in VB: by
Matthew MacDonald
http://en.wikipedia.org/wiki/Server-side_scripting
http://www.eggheadcafe.com/articles/20041016.asp
Exploring ASP.NET
Reference Reading:
Books
Programming ASP.NET:
Building Web
Applications and Services
http://en.wikipedia.org/wiki/.NET_Framework
http://en.wikipedia.org/wiki/ASP.NET
http://articles.techrepublic.com.com/5100-10878_115771721.html
ASP.NET in a Nutshell:
by G. Andrew Duthie,
Matthew MacDonald
Developing Web
Applications with Visual
Basic.NET and ASP.NET
by John Alexander, Billy
Hollis
http://www.asp.net/
http://www.microsoft.com/learning/en/us/syllabi/2310Bfinal.mspx
Chapter 2
Objectives
In this chapter, you will learn to:
Use ASP.NET Web Server controls
Create custom controls
Note
Postback is the process by which a browser posts information back to itself. It can
also be defined as the process by which a browser posts information back to the
server by requesting the same page.
Note
In addition to the server controls, ASP.NET provides HTML controls. Most HTML controls
are similar to server controls. However, there is a major difference. Unlike server controls,
HTML controls are processed by the Web browser.
To understand the processing of the server controls in a Web page, you need to understand
the sequence of their processing and how they are rendered on a Web page.
3. PreRendering: The control is updated with the changes made to it by the user. This
phase prepares the control for rendering.
4. Saving: The state information of the control is saved. For example, if a value is set for
the control during the Load event, it is embedded in the HTML tag that will be
returned to the browser.
5. Rendering: The server creates the corresponding HTML tag for the control.
6. Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed.
7. Unloading: All cleanup tasks, such as destroying the instances of server controls are
performed. This is the final event in the life cycle of a server control.
When the Web page is posted back to the Web server, the server controls are processed in the
following sequence:
1. Initializing: The server creates an instance of the server control.
2. Loading view state: The view state of the control, posted by the client, is reloaded
into the new instance of the control.
3. Loading control instance: The instance of the control is loaded onto the page object
in which it is defined.
4. Loading the postback data: The server searches any data corresponding to the
control that is loaded in the data posted by the client.
5. PreRendering: The control is updated with the changes made in it by the user. This is
done in preparation for rendering.
6. Saving: The change in the state of the controls between the current request and the
previous request of the page is saved. For each change, the corresponding event is
raised. For example, if the text of a textbox is changed, the new text is saved and a
TextChanged event is raised.
7. Rendering: The server creates the corresponding HTML tag for the control.
8. Disposing: All cleanup tasks, such as closing files and database connections opened
by the control are performed.
9. Unloading: All cleanup tasks like destroying the instances of server control are
performed. This is the final event in the life cycle of a server control.
The following figure illustrates the processing of a server control.
Note
In ASP.NET, Web page refers to an instance of thePage class and a Web form refers to the
Web page and all the controls on it.
In traditional websites, HTML controls were used to enable users to interact with the website.
Developers had to write the methods and events for these controls manually to provide
functionality to them. This was a very tedious task. In addition, these controls were processed
by the Web browser that is on the client-side, which does not provide the functionality for
validating the user input or managing the state.
To overcome these limitations, ASP.NET provides the HTML server controls, which are
processed by the Web server and make full use of the .NET Framework utilities such as
validation. Some of the common HTML server controls are:
HtmlAnchor Control
HtmlInputText Control
HtmlInputCheckBox Control
HtmlInputRadioButton Control
HtmlSelect Control
HtmlAnchor Control
The HtmlAnchor control works like the HTML <a> tag but runs on the server. It is used to
direct the user from one page to another. The following table lists some properties of the
HtmlAnchor control.
Property
Description
ID
Href
Name
Target
Title
When you click the HtmlAnchor control, the ServerClick event is raised. Consider the
following markup:
<a id="myAnchor1" href="URLLocation" runat="server">Click here</a>
<a id="myAnchor2" OnServerClick="myFunction" runat="server">Click here</a>
The preceding markup illustrates the HTML code of two HtmlAnchor server controls with
the name myAnchor1 and myAnchor2, as specified by the id attribute. When myAnchor1 is
clicked, the browser navigates to the new location, URLLocation, as specified in the href
attribute. When myAnchor2 is clicked, the function, myFunction, attached to the
ServerClick event is invoked. The OnServerClick attribute is used to attach an event
handler to the ServerClick event.
HtmlInputText Control
The HtmlInputText control works like the HTML <input type="text"> tag but runs on the
server. The HtmlInputText server control is used to gather information from the user. The
following table lists some properties of the HtmlInputText control.
Property
Description
ID
Type
Name
Size
MaxLength
Value
ServerChange
The preceding markup illustrates the HTML code of two HtmlInputText server controls with
the names txtName1 and txtName2, as specified by the id attributes. The txtName1 can
accommodate a maximum of 12 characters whereas txtName2 can accommodate a maximum
of 15 characters, as specified by the maxlength attribute.
HtmlInputCheckBox Control
The HtmlInputCheckBox control works as the HTML <input type="checkbox"> tag but
runs on the server. The HtmlInputCheckBox control is useful to implement questions that can
have only two answers, such as yes/no or true/false. For example, do you like Coffee? The
answer is either yes or no.
The following table lists some properties of the HtmlInputCheckBox control.
Property
Description
ID
Name
Checked
Value
The HtmlInputRadioButton control works as the HTML <input type="radio"> tag but
runs on the server. You can use the HtmlInputRadioButton control to implement multiplechoice questions, where a user can select only one option.
The following table lists some properties of the HtmlInputRadioButton control.
Property
Description
ID
Checked
Name
Value
HtmlSelect Control
The HtmlSelect control is same as the HTML <select> element but it runs on the server.
This control is used to create a list box. The HtmlSelect control is used when a user has to
select an option from a list of options. The following table lists some properties of the
HtmlSelect control.
Property
Description
ID
Name
Items
Multiple
SelectedIndex
Size
Value
The preceding markup creates a list box containing four movie names as list items. Out of
these movie names only one can be selected at a time.
TextBox Control
Label Control
ListBox Control
CheckBox and CheckBoxList Control
RadioButton and RadioButtonList Control
AdRotator Control
Calendar Control
DropDownList Control
ImageButton Control
Button Control
Wizard Control
MultiView Control
HyperLink Control
FileUpload Control
XML Control
Substitution Control
TextBox Control
The TextBox control is used to obtain information, such as text, numbers, and dates from
users in a Web form. You can set a TextBox control as single-line, password, or multi-line
TextBox control. By default, a TextBox control is single-line that allows users to type
characters in a single line only. A password TextBox control is similar to the single-line
TextBox control, but masks the characters typed by users and displays them as asterisks (*).
A multi-line TextBox displays multiple lines and allows text wrapping.
The properties of a TextBox control determine the appearance of the TextBox control. The
following table lists some properties of the TextBox control.
Property
Description
Text
Height
Rows
The Label control is used to display static text in a Web form that cannot be edited by the
user. The Text property of the Label control can be set to modify the controls caption. The
following table lists some properties of the Label control.
Property
Description
Text
Visible
The ListBox control is a collection of list items. It allows users to select one or more items
from the list. The following table lists some properties of the ListBox control.
Property
Description
Items
Rows
SelectionMode
Static item addition method: In this method, the items are added during the design
phase.
Dynamic item addition method: In this method, the items are added during run time.
A check box provides you with independent choices or options that you can select. You can
add check boxes to a Web form by using either the CheckBox control or the CheckBoxList
control. The CheckBox control provides you with a single check box whereas the
CheckBoxList control is a collection of several check boxes. The choice between using the
CheckBox control and using the CheckBoxList control depends on the requirement. The
CheckBox control provides more control over the layout of the check boxes on a page. For
instance, you can set the font and color of check boxes individually or include text between
different check boxes. The CheckBoxList control is a better choice if you need to add a series
of check boxes.
The following table lists some properties of the CheckBox and CheckBoxList controls.
Note
Methods for adding items to a CheckBoxList control are similar to the methods used to add
items to the ListBox control.
RadioButton and RadioButtonList Controls
Radio buttons provide a set of choices or options that you can select. You can add radio
buttons to a Web form by using either the RadioButton control or the RadioButtonList
control. The RadioButton control is a single radio button that you can work with whereas the
RadioButtonList control is a collection of radio buttons. Usually, you use radio buttons in a
group. A group of radio buttons provides a set of mutually exclusive options. You can select
only one radio button in a group.
You can group a set of radio buttons in the following ways:
Place a set of RadioButton controls in a page and assign them manually to a group by
using the GroupName property.
Place a RadioButtonList control in a page. The radio buttons in this control are
grouped by default.
After you add a RadioButtonList control, you need to add individual radio buttons. You can
do so by using the Items property in the same way as you do for the CheckBoxList control.
Similar to the CheckBox and CheckBoxList controls, the RadioButton control offers more
control over the layout of the radio buttons on the page.
The following table lists some properties of the RadioButton and RadioButtonList controls.
Note
The methods for adding items to a RadioButtonList control are similar to the methods for
adding items to the ListBox control.
AdRotator Control
The AdRotator control is used to display flashing banner advertisements on Web pages. This
control is capable of displaying advertisements randomly. AdRotator is one of the rich Web
controls available in ASP.NET. The following table lists some properties of the AdRotator
control.
Property
Description
AdvertisementFile
KeywordFilter
Target
window
_blank: Loads the linked page into a new
browser window
_self: Loads the linked page in the same
window
_parent: Loads the linked page in the parent
The Calendar control is used to display a one-month calendar. Users can use this control to
view dates or select a specific day, week, or month. Calendar is one of the rich web controls
available in ASP.NET. The following table lists some properties of the Calendar control.
Property
Description
DayNameFormat
VisibleDate
FirstDayOfWeek
SelectedDate
SelectionMode
The DropDownList control allows users to select an item from a set of predefined items,
where each item is a separate object with its own properties, such as Text, Value, and
Selected. You can add items to a DropDownList control by using the Items property. Unlike
the ListBox control, you can select only one item at a time and the list of items remains
hidden until the user clicks the drop-down button. The following table lists some properties
of the DropDownList control.
Property
Description
Items
Width
Height
The ImageButton control is similar to a button control but unlike the button control, it can
also display an image. The ImageButton control has a few properties that are identical to the
Image control. It inherits these properties from the Image control. It also has a few properties
that are identical to the Button control. The following table lists some properties of the
ImageButton control.
Property
Description
AlternativeText
CausesValidation
CommandArgument
ImageAlign
ImageURL
CommandName
The Button control is generally used to submit the data that is entered by a user as an input in
a Web application. When the user clicks a button control on a Web page, the page is posted
back to the Web server, and the click event is triggered. ASP.NET provides three types of
button controls; Button, LinkButton, and ImageButton.
The following table describes how these buttons appear on a Web page.
Control
Description
Button
LinkButton
ImageButton
Description
ID
Text
PostBackURL
Enabled
ToolTip
Description
ID
WizardSteps
EnableViewState
Enabled
ToolTip
A Multiview control is a set of View controls. These View controls, in turn, contain child
controls such as buttons and textboxes. A Web application dynamically displays a View
control to a user based on certain criteria such as user identity, preferences, or information
passed in a query string parameter. It is used to present alternate views of information.
The following table lists some properties of the MultiView control.
Property
Description
ID
Views
Visible
A HyperLink control is used to link all the Web pages in a Web application. By using a
HyperLink control, a user can easily move between the Web pages. It is rendered as a
clickable text or an image on a Web page. A HyperLink control does not raise an event in the
server code when a user clicks it. Instead, it simply performs navigation. In other words, it
directs the user to another Web page. The following table lists some properties of the
HyperLink control.
Property
Description
Text
ImageUrl
Target
The FileUpload control enables users to send a file from their computer to the server. It is
useful for allowing users to upload various types of files such as pictures, text files, or other
files. The files that are to be uploaded are submitted to the server as part of the browser
request during postback.
The FileUpload control displays a textbox to type the name of the file that is to be uploaded
on the server. It also displays a Browse button that that can be used to browse for the file. The
following table lists some properties of the FileUpload control.
Property
Description
Filename
HasFile
The XML control is used to write the output of an XML document on a Web page. The XML
output appears at the location of the control on the Web page. The following table lists some
properties of the XML control.
Property
Description
Document
DocumentContent
DocumentSource
The Substitution control is used on the Web pages that are configured to be cached. It allows
you to create areas on the page that can be updated dynamically and integrated into the
cached page.
When a page is cached, the entire output of the page is cached. However, there may be
situations wherein you need to cache a page but want to update the selected portions of the
page on each request. For updating the selected portions in a cached page, you can place the
Substitution control in the cached page and insert dynamic content into the Substitution
control. The following table lists some properties of the Substitution control.
Property
Description
MethodName
Site
RequiredFieldValidator Control
RegularExpressionValidator Control
CompareValidator Control
RangeValidator Control
ValidationSummary Control
CustomValidator Control
RequiredFieldValidator Control
Description
ControlToValidate
ErrorMessage
Text
The RegularExpressionValidator control is used to check whether the server control added to
a Web form matches with a specific regular expression or not. The regular expression can be
the format of a telephone number or an e-mail address.
The following table lists some properties of the RegularExpressionValidator control.
Property
Description
ControlToValidate
ErrorMessage
ValidationExpression
The CompareValidator control is used to compare the entered value with another value. The
other value can be a number or a value entered into another control. The following table lists
some properties of the CompareValidator control.
Property
Description
ControlToCompare
ControlToValidate
ErrorMessage
ValueToCompare
The RangeValidator control is used to check whether the value of a particular Web form field
is within the range specified by the RangeValidator controls MinimumValue and the
MaximumValue properties. The MinimumValue and MaximumValue properties can contain
dates, numbers, currency amounts, or strings.
The following table lists some properties of the RangeValidator control.
Property
Description
ControlToValidate
ErrorMessage
MaximumValue
MinimumValue
The ValidationSummary control is used to summarize all errors and display the error list at a
location specified by the user on the Web page. The following table lists some properties of
the ValidationSummary control.
Property
Description
HeadText
ShowMessageBox
ShowSummary
Description
ControlToValidate
ErrorMessage
When a user interacts with a server control, its corresponding event is invoked and the code
written on the event is executed. For example, when a user clicks a button, the Click event of
the button control is invoked and the code written on the event is executed.
Most of the ASP.NET events pass the following two arguments:
Sender Object: This is the first argument and is an instance of System.Object class.
This represents the control that raised the event.
Event Object: This is an instance of System.EventArgs class. This contains
information about the event that is generated.
Postback events: In postback events, a Web page is sent back to the server for
processing. When a user clicks a button, the click event of the button causes a Web
page to be posted back to the server. When a Web page is posted back to the server,
the server processes the page and sends it back to the user.
Nonpostback events: In nonpostback events, a Web page does not immediately cause
a postback. For example, change events in HTML server controls and Web server
controls, such as the TextBox control, are captured but do not immediately cause a
post. These events are cached by the control until the next time a post occurs. When a
post occurs, the page is processed on the server and all the pending events are raised
and processed.
Event Handlers
When an event is raised, the corresponding event handler is searched and the code written in
the event handler is executed. If you want your application to perform some action when an
event is raised, you need to add an event handler for that event.
The various approaches that can be used to work with event handlers include:
Every control exposes an event that is designated as the default event. A default event is an
event that is most commonly associated with a control. For example, the Click event is the
default event of a Button control. Default events are handled by a default event handler.
In addition to the default event, each control exposes other events, called non-default events.
For example, the Command event is a non-default event of a Button control. Non-default
events are handled by non-default event handlers.
ASP.NET provides the event wire-up capability to a Web form using which events can be
automatically associated with event-handling procedures having well-defined names and
signatures. Event wire-ups determine the procedures that need to be called when objects raise
events. To enable the event wire-up capability of a Web form, you need to set the
AutoEventWireUp attribute of the .aspx page to true. By default, the AutoEventWireUp
attribute of the .aspx pages is set to true, as shown in the following markup:
<%@ Page Language="C#" AutoEventWireup="true"%>
The AutoEventWireup attribute can have two values, true or false. When the value is set to
true, the ASP.NET runtime does not require events to specify event handlers, such as
Page_Load and Page_Init. This means that in Visual C#, you do not have to initialize and
create the delegate structures. However, when the value is set to false, the events need to
specify event handlers explicitly.
Creating Centralized Event-Handlers
There are situations when you want to associate the same event handler with different
controls. Such situations can be handled by using a centralized event handler. A centralized
event handler eliminates the need for declaring separate event handlers for different
ASP.NET objects. You can create one centralized event handler that can perform appropriate
action at runtime.
When you create a single event handler to respond to multiple events that should trigger
different actions, you need to determine which event invoked the event handler. To determine
which control caused the event, you need to perform the following steps:
1. Declare a variable in the event handler with a type that matches the control that raised
the event.
2. Assign the sender argument of the event handler to the variable, casting it to the
appropriate type.
3. Examine the ID property of the variable to determine which object raised the event.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1"
onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button2"
onclick="Button1_Click" />
In the preceding example, the event handler Button1_Click is associated with both the
button controls. You need to write the event handler in such a manner that it will determine
which control has caused the event. The following code snippet illustrates how to write such
an event handler:
protected void Button1_Click(object sender, EventArgs e)
{
Button mybtn = (Button)sender;
switch (mybtn.ID)
{
case "Button1": Response.write("You have clicked Button
1");
break;
case "Button2": Response.write ("You have clicked Button
2");
break;
}
}
The preceding code works well to define a centralized event handler for the Click event of
the Button control. However, if you need to create a centralized event handler for the
Command event of two button controls, the preceding code will not work because the
Command event passes a different set of arguments to its event handler.
Consider a Web page containing the following markup:
<asp:Button ID="Button1" runat="server" Text="Button1" CommandName="Prev"
onCommand="Button1_Command" />
<asp:Button ID="Button2" runat="server" Text="Button2" CommandName="Next"
onCommand="Button1_Command" />
In the preceding example, the event handler Button1_Command is associated with both the
button controls. You need to write the event handler in such a manner that it will determine
which control has caused the event. The following code snippet illustrates how to write such
an event handler:
protected void Button1_Command(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Prev": Response.Write("You clicked the Prev
button");
break;
case "Next": Response.Write("You clicked the Next
button");
break;
}
PlaceHolder
Panel
PlaceHolder
A PlaceHolder control is used as a container that is not visible in a Web application. It is
added to a Web page to hold other controls on the page. The PlaceHolder control reserves a
place in the structure of the Web page for other controls that are added dynamically. The
following markup adds a PlaceHolder control to a Web page:
<asp:PlaceHolder id="PlaceHolder1" runat="server"/>
The following code snippet shows how to add a Button control and a literal in a PlaceHolder
control:
void Page_Load(object sender, EventArgs e)
{
//creates an instance of a button control.
Button Button1 = new Button();
Button1.Text = "Button 1";
// Adds the button control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Button1);
// creates an instance of a literal control.
Literal Literal1 = new Literal();
Literal1.Text = " Dynamically loaded controls";
// Adds the literal control in a PlaceHolder control.
PlaceHolder1.Controls.Add(Literal1);
}
Panel
A Panel control is also used as a container for other controls. The only difference between a
PlaceHolder and a Panel control is that a Panel control renders div tag around all the child
controls in the panel where as a PlaceHolder will only render its child controls. This makes
panels useful when you want to apply a css class to a container. The following code snippet
shows how to add a Label control to a Panel control:
//Creating an instance of a Label control
Label TestLabel = new Label();
TestLabel.Text = "testlabel";
//Adding the Label control to a Panel control
Panel1.Controls.Add(TestLabel);
An event handler for a control is usually created at design time. However, it can also be
created dynamically at run time for the controls that are created dynamically. For example, to
create a Button control dynamically and associate an event handler to it at run time, you need
to write the following code in the .cs file of a Web page:
protected void Page_Load(object sender, EventArgs e)
{
Button btn=new Button();
btn.Text = "Click Me";
form1.Controls.Add(btn);//Adding button to the form
btn.Click += new EventHandler(btn_Click);
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Hello");
}
the IHttpHandlerFactory object can put the handler in a pool and reuse it to increase
performance. The IHttpHandlerFactory object is the object that calls the appropriate
handler.
Consider the following example:
<%@ WebHandler Language="C#" Class="SimpleHandler" %>
using System;
using System.Web;
//HttpResponse object
//Write the image
r.WriteFile(@"~\images\4.JPG");
}
Note
You can navigate to a generic handler by using the Respose.redirect() method. For
example, you want that on clicking the Show Picture button on the default.aspx page, the
generic handler MyHandler.ashx is displayed in the browser. For this, you need to write the
following code snippet in the event handler for the Click event of the button:
Response.Write(MyHandler.ashx);
User controls cannot run as stand-alone files. They need to be added to ASP.NET
pages to make them work.
User controls do not have <html>, <body>, or <form> elements in them. These
elements must be present on the Web page that is hosting these controls.
A Web user control on a Web page must be registered before it is used. You can register a
Web user control by using the @Register directive as illustrated in the following markup:
<%@Register TagPrefix="ABC" TagName="Header" Src="mycontrol.ascx" %>
TagPrefix: Specifies the alias to associate with the namespace of the user control.
TagName: Specifies the alias to associate with the class of the user control.
Src: Specifies the virtual path of the file containing the user control.
After registering the control, you can include it on the page by writing the markup as shown
in the following example:
<ABC:Header ID=mycontrol1 runat="Server"/>
Controls that combine two or more existing controls: This type of control is known
as a composite control and can be created by defining a class that derives from the
System.Web.UI.Control or System.Web.UI.WebControl class and overrides the
CreateChildControls method of the base class. In addition, the class can expose
public properties that will be accessible to the pages that use this control.
Controls that extend the functionality of an existing control: This type of control
is created when an existing control meets most of your requirements but lacks some
features. In such a situation, you can customize the existing control by defining a class
that derives from the class corresponding to the existing control. You can then add
new properties and override existing methods and events of the base class to modify
the functionality of the control.
Controls that are not similar to any existing control: This type of control is created
when none of the existing controls meets your requirement. In such a case, you can
create a custom control by deriving from the System.Web.UI.Control or
System.Web.UI.WebControl class, adding public properties to this class, and
overriding existing methods of the base class.
Note
Repeater, DataList, and GridView Web server controls are the examples of built-in
Templated controls. These controls will be discussed in detail later in the course.
Summary
In this chapter, you learned that:
Server controls are the fundamental building blocks that are specifically designed to
work with Web forms in an ASP.NET application.
Server controls provide:
o
o
o
1.
The sequence in which a server control is processed when the page is requested for
the first time is:
Initializing
2. Loading
3. PreRendering
4. Saving
5. Rendering
6. Disposing
7. Unloading
The sequence in which a server control is processed when the Web page is posted
back to the Web browser is:
0.
Initializing
1. Loading view state
2. Loading control instance
3. Loading the postback data
4. PreRendering
5. Saving
6. Rendering
7. Disposing
8. Unloading
The various types of server controls provided by ASP.NET can be classified into the
following categories:
o
o
o
o
An event is a message that contains details about the user action, such as the cause of
the event and the control on which the event occurred.
The two arguments passed by all events in ASP.NET are:
o
o
Sender Object
Event Object
The two types of events in ASP.NET server control event model are:
o
o
Postback events
Nonpostback events
The two controls that act as container when adding controls dynamically are:
o
o
PlaceHolder
Panel
Reference Reading
Using ASP.NET Web Server Controls
Reference Reading: Books
http://msdn2.microsoft.com/en-us/library/zsyt68f1.aspx
http://msdn2.microsoft.com/en-us/library/k26w4zzx.aspx
Profession
al Web
Parts and
Custom
Controls
with
http://www.codersource.net/published/view/290/creating_custom_controls_in_a
sp_net.aspx
http://msdn.microsoft.com/en-us/library/ms837926.aspx
ASP.NET
3.5 by
Peter
Vogel
Developin
g .NET
Custom
Controls
and
Designers
Using C#
by James
Henry
Chapter 3
Objectives
In this chapter, you will learn to:
Work with styles
Work with themes
Work with master pages
Inline styles are style definitions that are applied to the style property of a particular HTML
element, and are placed directly inside the element on which it has to be implemented. Inline
styles are used when you want to apply one-time formatting to an HTML element.
To use inline styles in a Web page, you need to use the style attribute in the relevant HTML
tag. For example, if you want to display the text of a paragraph in italicized Arial font, you
have to define the style for the tag as shown in the following markup:
<p style="font-family:arial;font-style:italic">
...
...
</p>
In the preceding markup, the style applied to the <p> tag will be applied to all text written
within the <p> </p> tag in the preceding example only.
<body>
<h1> An Embedded Style </h1>
<p> Embedded style sheet is a part of HTML document.
</p>
</body>
</html>
In the preceding markup, the <style> tag is used to define an embedded style sheet. The
<style> tag defines the properties for the <h1> and tag. All the <h1> and tags defined
within the Web page will inherit the style defined in the <style> tag.
The preceding style can only be applied to the <h1> tags. You can also create generic styles,
as shown in the following code snippet:
.heading
{
font-weight: bold;
font-size: large;
color: green;
font-family: Verdana, Arial, Sans-Serif;
The preceding style can be applied to any element on the Web page.
After the .css file is created, it has to be linked with HTML documents on which the styles
are to be implemented. This can be done by using the <link> tag. The link> tag should be
defined within the <head> element of the HTML document. The following markup shows
how to link an external style sheet to an HTML document by using the <link> tag:
<head>
<link rel=stylesheet href="style.css" type="text/css">
</head>
In the preceding markup, rel=stylesheet specifies that the document will use a style sheet,
href="style.css" specifies that the document will refer to the file, style.css, for the style
definition, and type="text/css" signifies that it refers to a .css file for picking up the style
definitions.
Note
To apply generic styles created in an external style sheet to an element, you need to include
the class=<name of the style>" or cssClass="<name of the style>" attribute in the
element.
The style sheet rules are limited to a fixed set of style attributes, such as fonts, borders, and
foreground and background colors. These rules cannot control other aspects of ASP.NET
controls, such as organizing items into rows and columns in the CheckBoxList control,
specifying graphics for a TreeView control, and specifying the template layout of a GridView
control. This gap can be filled by using the ASP.NET themes.
ASP.NET themes are a collection of properties that enable you to define the appearance of
Web pages and controls on your website. A theme can include skin files, cascading style
sheet files (.css files), and graphics. By applying a theme, you can give Web pages a
consistent appearance across your website.
Creating a Theme
You can use a theme in Web applications by creating a skin file and attaching it to the Web
pages on which you want to apply the theme. Skin files are used to define the property
settings for ASP.NET Web server controls. Generally, skin files are created and stored in a
theme folder. This theme folder is placed inside the folder named App_Themes. All the
themes in a Web application are placed inside the App_Themes folder. This folder is placed
inside the top-level directory of your Web application.
For example, you can create a folder named Mytheme for your Web application named
MyApp. This theme folder will be placed inside the MyApp\App_Themes folder and
contains the skin file(s) for the theme.
You can define multiple themes for your Web application. Each theme in a Web application
can be defined in a separate folder inside the App_Themes folder. However, you can apply
only one theme on a given page at a time.
Consider a scenario wherein you want to create a skin file for providing consistent
appearance to all the button controls in your Web page. For this, you want to specify the
ForeColor and BackColor properties of the button controls. To set the ForeColor and
BackColor properties of the button controls, you need to type the following markup in the
skin file:
<asp:Button runat="server" ForeColor="White" BackColor="Orange"/>
The runat="server" attribute is mandatory. However, other attributes are optional and are
used according to the requirement.
You can create multiple skin files in a theme directory or place all the control tags in a single
skin file. ASP.NET treats all the skin files in a theme directory as part of the same theme
definition.
Applying a Theme
You can apply a theme either to a particular Web page or to all the Web pages on a website.
If a theme is applied to a particular Web page, the theme settings are applied only to that Web
page. However, if you apply the theme to the entire website, the theme settings are applied to
all the Web pages on the website.
Applying a Theme to a Web Page
To apply a theme to a particular Web page, you need to bind the theme at the page level. If
you bind the theme at the page level, the styles and skins are only applied to that Web page
and its controls. To bind a theme at the page level, you need to set the Theme attribute of the
@Page directive. For example, the following @Page directive specifies that the theme,
MyTheme, is applied to the Web page:
<%@Page Language="C#" AutoEventWireup="true"
Inherits="_Default" Theme="MyTheme" %>
CodeFile="Default.aspx.cs"
If you have defined settings for the control locally as well as in the theme, the settings
defined in the theme override the local control settings. This strategy enables the theme to
create a consistent look across all the Web pages, even if you have set the control properties
locally.
However, if you have used a stylesheet theme, the local page settings override the settings
defined in the stylesheet theme. You can use stylesheet theme if you want the theme to be
applied only to those controls whose settings have not explicitly been defined at the page
level.
To apply a stylesheet theme to a Web page, you need to set the StyleSheetTheme attribute of
the @Page directive as shown in the following directive:
<%@Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" StyleSheetTheme="MyTheme" %>
If you do not want the theme property to be applied to a particular control, you can set the
EnableTheming property of that control on the Web page to false, as shown in the
following markup:
<asp:Button ID="Button1" runat="server" ... EnableTheming="false" />
In the preceding markup, no theme will be applied to the button control, Button1. However,
the settings defined in the theme will still be applied to other button controls, whose
EnableTheming property is not set to false.
Applying Themes Dynamically
In addition to applying a theme at the design time, you can apply a theme dynamically. To
apply a theme dynamically, you need to set the Page.Theme or Page.StyleSheetTheme
property in your code. These properties must be set in the Page_PreInit event. For example,
you have created a skin file, SkinFile.skin, in the MyTheme folder. To set this theme
dynamically, you need to write the following code snippet:
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "MyTheme"; //name of the folder in which you
//have stored the skin file.
}
Similarly, you can set the SkinID property of a control dynamically to attach it to a different
named skin.
Applying a Theme to a Website
To apply the theme to all the Web pages on a website, you need to bind the theme at the
website level. If you bind the theme at the website level, the styles and skins are applied to all
the Web pages and controls on the website unless you override a theme for an individual Web
page.
To apply a theme to the entire website, you need to configure the <pages> element in the
web.config file, as shown in the following markup:
<configuration>
<system.web>
<pages theme="MyTheme">
...
</pages>
</system.web>
</configuration>
In the preceding markup, the first is the default skin whereas the second with the SkinID
attribute is known as the named skin. Default skins are applied automatically whereas named
skins can be applied to a control by setting the SkinID attribute of the control, as shown in
the following code-snippet:
<asp:Button ID="Button1" runat="server" SkinID="AlternateSkin" />
In the preceding example, the named skin, AlternateSkin, is applied to the button control.
In addition to the @Master directive, the master page contains the following elements:
HTML or ASP.NET Elements: You can use any HTML or ASP.NET element in
your master page. For example, you can use an HTML table to define the layout,
static text to display the copyright information, an element to display the company
logo, and ASP.NET server controls to create navigation for your website on the
master page.
ContentPlaceHolder Controls: ContentPlaceHolder controls are that portion of the
master page that a content page can change. A master page should contain at least one
ContentPlaceHolder control.
In the preceding markup, the MasterPageFile attribute binds the content page to the
Master1.master page. The path for the master page starts with ~/. It specifies the root
website folder. If you directly specify the master page filename without using ~/, ASP.NET
checks a predetermined subfolder named MasterPages for the master page. If you have not
created the folder or the master page is not found in that folder, ASP.NET searches the root
website folder for the master page.
In addition to the MasterPageFile attribute, the @Page directive of the content page contains
another attribute, Title. The master page file contains the <Title> tag within the <Head>
tag. If a title is specified in the master page, it will also be displayed in the content page
because the content page cannot modify the contents of the master page. However, the title
specified in the master page can be overridden in the content page by the using the Title
attribute.
The source code of the content page is different from that of a normal page. This is due to the
fact that the content page cannot define anything that is already defined in the master page
such as the <head> section, the root <html> element, and the <body> element. It can only
supply a Content tag that corresponds to the ContentPlaceHolder in the master page. The
Content tag is the place where you can insert the content for the content page.
The following figure shows how the place holder content for the master page is supplied by
the content page.
Note
You can also connect a content page to a master page at run time. For this, you need to write
the following code within the Page_PreInit event handler:
Page.MasterPageFile = "~/MasterPage.Master";
Consider an example wherein a website is using a master page for displaying the company
logo in the header and a TreeView control on the left side for navigation. Some of the Web
pages on the website require a footer to be displayed in addition to the header and the
TreeView control provided by the master page. This can be implemented by using a nested
master page.
Similar to master pages, the extension of the nested master page file is .master. Like any
content page, a nested master page contains the <Content> controls that are mapped to the
<ContentPlaceHolder> controls on a master page. In addition, a nested master page
contains content placeholders of its own to display the content supplied by its own content
pages.
}
}
The scope of the preceding property is declared as public so that it can be accessed by other
classes. This property cannot be directly accessed by the content pages. To access this
property, the content pages have to use the built-in Page.Master property. However, you
cannot access the ShowNavigation property directly by using the
Page.Master.ShowNavigation statement. This is because the Page.Master property does
not have any information about the custom properties that have been added in derived master
page class. To access such custom properties from the content page, you need to cast the
Page.Master object to the appropriate type, as shown in the following code snippet:
protected void btnHide_Click(object sender, EventArgs e)
{
MyMasterPage master = (MyMasterPage)this.Master;
master.ShowNavigation = false;
}
protected void btnShow_Click(object sender, EventArgs e)
{
MyMasterPage master = (MyMasterPage)this.Master;
master.ShowNavigation = true;
}
In the preceding code snippet, MyMasterPage is the name of the master page class and
ShowNavigation is the public property of the MyMasterPage class.
Summary
In this chapter, you learned that:
Styles are used to define a set of formatting options that can be reused on a single or
multiple Web pages.
Styles can be defined in any of the following ways:
o
o
o
Inline styles are style definitions that are applied to the style property of a particular
HTML element.
An embedded style sheet is a group of styles that are defined by using the <style>
tag.
The style definitions in an external style sheet are stored in a separate file having the
.css extension.
ASP.NET themes are a collection of properties that enable you to define the
appearance of Web pages and controls on your website.
You can apply a theme either to a particular Web page or to all the Web pages on a
website.
To bind a theme at the page level, you need to set the Theme attribute of the @Page
directive.
To apply a theme to the entire website, you need to configure the <pages> element in
the web.config file.
You can create more than one theme for the same control.
Master pages enable you to create a page layout that you can use with selected or all
Web pages on your website.
A master page contains the following elements:
o
o
To bind a master page with the content page, you need to include the
MasterPageFile attribute in the @Page directive of the content page.
Content pages can interact with the master pages programmatically.
Reference Reading
Working with Styles
Reference Reading: Books
http://www.west-wind.com/WebLog/posts/158367.aspx
http://www.15seconds.com/issue/040105.htm
http://www.15seconds.com/issue/040105.htm
Chris Hart,
John
Kauffman,
Beginning
ASP.NET.3.5
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/masterpages/default.aspx
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/masterpages/default.aspx
http://www.beansoftware.com/ASP.NET-Tutorials/Master-Pages.aspx
Chapter 4
Navigating Websites
A website is a collection of interconnected Web pages. Users need to navigate between these
Web pages to get the required information. Navigation between Web pages can be made
easier by implementing a proper navigation system. Such a system can be implemented by
using site maps and navigation controls provided by ASP.NET.
This chapter provides an overview of site maps. In addition, it discusses how to implement
navigation on a website by using the navigation controls provided by ASP.NET.
Objectives
In this chapter, you will learn to:
Work with site maps
Work with navigation controls
To provide a consistent way to navigate a website, you need to define the hierarchical
structure of the website by using a site map. A site map is an XML file that describes the
hierarchical and logical structure of the website. It stores links to all the Web pages on a
website. These links can be rendered through navigation controls.
To create a site map, you need to create an XML file with the .sitemap extension. This file
must be located in the application root directory. Every .sitemap file contains the <siteMap>
element. All the information regarding the site map is written within the opening and closing
tags of the <siteMap> element, as shown in the following example:
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
...
</siteMap>
In the preceding example, the xmlns attribute of the siteMap element tells ASP.NET that the
XML file uses the ASP.NET site map standard.
A site map defines the hierarchical structure of the Web pages on a website. To create the
hierarchical structure, you need to use the <siteMapNode> element within the opening and
closing tags of the <siteMap> element. Each page in the hierarchical structure is represented
by a <siteMapNode> element. The <siteMapNode> element contains various attributes, as
shown in the following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx" />
In the preceding example, the title attribute specifies the text that is usually used as link text.
The description attribute specifies the text that acts as a tool tip. The url attribute specifies
the linked page.
Note
The SiteMapPath control is one of the navigation controls that display the navigation
structure of a website. It is discussed in detail in the next section.
Creating Hierarchical Group of Links in Site Maps
There are situations when you want the Web pages in a site map to be divided into groups.
One such situation is when you want to display the Home page as the root node and all other
Web pages such as the products page within the root node (Home page). To represent such a
group in the site map file, you need to place one <siteMapNode> element inside another. For
this, you need to split the <siteMapNode> element into a start and an end tag, as shown in the
following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx">
...
</siteMapNode>
You can add more <siteMapNode> elements within the root <siteMapNode> element and
create a group, as shown in the following example:
<siteMapNode title="Home" description="Home" url="~/default.aspx">
<siteMapNode title="Software" description="Software choices"
url="~/software.aspx" />
<siteMapNode title="Hardware" description="Hardware choices"
url="~/hardware.aspx" />
</siteMapNode>
The preceding example creates a hierarchical group of links. In this example, the Home group
contains two more pages, software and hardware. This hierarchical group of links is
represented as shown in the following figure.
Note
A site map must always have a single root node. All the other nodes must be contained inside
this root-level node.
Note
Two site map nodes in a .sitemap file cannot have the same URLs. This is because the site
map information is stored as a collection where each item is indexed by its unique URL.
After adding the SiteMapDataSource control, you need to add navigation controls to the Web
page. The navigation controls are linked to the SiteMapDataSource control and are capable
of displaying the navigation structure contained in the site map file. To use a navigation
control, such as a TreeView control, you need to use the following code:
<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="SiteMapDataSource1"/>
When you want to store the site-map information in a data source that is not supported
by the default site-map provider.
When you want to use a data source other than the Web.sitemap file.
You can create a custom site-map provider by creating a class that inherits the
SiteMapProvider abstract class from the System.Web namespace and implementing the
abstract members that are exposed by the SiteMapProvider class. The following table lists
the methods that need to be implemented in the custom site-map provider.
Method
Description
FindSiteMapNode
GetChildNodes
GetRootNodeCore
In the preceding example, a custom site-map provider is created that is using a text file to
store the navigation structure. The defaultProvider attribute of the siteMap element
specifies the name of the custom site-map provider class. You need to specify the complete
path of the text file in the siteMapFile attribute.
If you want to have the same functionalities as provided by the default site-map provider but
want to use a data store other than the Web.sitemap file, then you need to configure the
web.config file as shown in the following example:
<siteMap>
<providers>
Note
If you are using a custom site-map provider, you need to explicitly set the SiteMapProvider
property of the SiteMapDataSource control.
The preceding path indicates that the user is currently on the Sports page. The user can
navigate either to the Home page or to the Products page by clicking the corresponding link
displayed as a breadcrumb in the SiteMapPath control.
The SiteMapPath control obtains navigation data from the site map. This data includes
information about the pages on your website, such as the URL, title, description, and location
in the navigation hierarchy.
Properties of the SiteMapPath Control
You can use various properties of a SiteMapPath control to customize its appearance. The
following table lists some properties of the SiteMapPath control.
Property
Description
ShowToolTips
ParentLevelsDisplayed
PathDirection
PathSeparator
Description
NodeIndent
ImageSet
ShowLines
ExpandDepth
TreeView Control
Supports templates.
Summary
In this chapter, you learned that:
A navigation path describes the structure of a website and acts as a roadmap for a
user.
A site map is an XML file that describes the hierarchical and logical structure of the
website.
A site map stores links to all the Web pages on a website.
After creating the site map file, you need to bind it to a Web page.
The site map can be bound to a Web page by using the SiteMapDataSource control.
After adding the SiteMapDataSource control, you need to add a navigational control
to the Web page.
The three navigational controls provided by ASP.NET are:
o The SiteMapPath Control
o The TreeView Control
o The Menu Control
Reference Reading
Working with Site Maps
Reference Reading:
Books
http://msdn.microsoft.com/en-us/library/aa479320.aspx
http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx
http://blogs.techrepublic.com.com/programming-and-
development/?p=456
Implementing Navigation by Using Navigation Controls
Reference Reading:
Books
http://support.microsoft.com/kb/913721
Chapter 5
Objectives
In this chapter, you will learn to:
Implement client-side state management
Implement server-side state management
Manage state by using cross-page posting
Implement caching
will be created, and therefore, all information previously entered on the Web page will be
lost. This problem can be solved by using client-side state management.
Client-side state management allows you to store information either on a Web page or on a
client computer. Such state management improves the performance of a Web application
because it reduces the load on the server. The various options available to implement clientside state management are:
Hidden Fields
View State
Control State
Cookies
Query Strings
Note
You can store only a limited amount of information by using client-side state management.
Hidden Fields
A hidden field is a control similar to a TextBox control. However, unlike a TextBox control,
it does not render in a Web browser. As a result, a user cannot type anything in it.
Hidden fields can be used to store information that needs to be submitted along with the Web
page, but should not be displayed on the page. For example, when the details of a product are
displayed on a Web page, the ID of the product can be stored in a hidden field. If the user
orders the product, the information stored in the hidden field will be sent to the server and the
corresponding product will be added to the shopping cart.
Hidden fields can also be used to pass session information to and from forms, transparently.
Consider an example. Suppose the home page of your website asks a user to specify his or
her favorite color. When the user clicks the submit button to move to another page, say
Page1.aspx, the information about the favorite color can be passed on to a hidden field on
Page1.aspx and the information can be used to change the background color of the page to
the specified color. Similarly, when the user moves from Page1.aspx to another page, say
Page2.aspx, the information in the hidden field on Page1.aspx can be passed on to a hidden
field on Page2.aspx. This information, again, can be used to change the background color of
Page2.aspx to the specified color.
To pass the information from one page to another, you can invoke the Server.Transfer
method on the Click event of a Button control, as shown in the following example:
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("Page2.aspx");
}
The target page can access the passed information by referring to individual controls on the
source page, as shown in the following example:
String name = Request.Form["TextBox1"];
String color = Request.Form["HiddenField1"];
Note
To ensure that the passed values are available to the target page, you must submit the page
by using the HTTP Post method.
A hidden field acts as a repository for any page-specific information that you want to store
directly in a page. The advantages of using hidden form fields are:
A hidden field can store page-specific information without accessing any Web server
or Web browser resource.
A hidden field can be easily implemented in an ASP.NET Web form page. You just
need to add the HiddenField control to a Web page and use the Value property of the
control to set its value.
You can view the information stored in the hidden field by accessing the source of the
Web page. Therefore, the values stored in hidden form fields are not very secure.
A hidden field does not support more than a single value field to store information.
The hidden fields are stored in a page. Therefore, storing large values in hidden form
fields can slow down the processing of the page.
If you use hidden fields, you must submit your pages to the server using the HTTP
POST method instead of requesting the page using the page URL. You cannot take
advantage of hidden fields if a page is processed in response to a link or the HTTP
GET method.
View State
Each Web page and controls on the page have a property called ViewState. This property is
used to automatically save the values of the Web page and each control on the Web page
prior to rendering the page. This, in turn, enables you to retain the page and control-specific
values between round trips to the server.
The view state is implemented with the help of a hidden form field called __ViewState. This
hidden form field is automatically created in every Web page.
When ASP.NET executes a Web page on the Web server, the values stored in the ViewState
property of the page and controls on it are collected and formatted into a single encoded
string. This encoded string is then assigned to the Value attribute of the hidden form field,
__ViewState, and is sent to the client as part of the Web page.
During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore
the values in __ViewState. When the page is initialized during postback, ASP.NET
Framework parses the view state string to restore the information displayed on the page.
The view state of a Web page or a control consists of the cumulative property values of the
page or the control. To preserve these values across stateless HTTP requests, Web pages and
controls in ASP.NET use an instance of the StateBag class.
The StateBag class is the primary storage mechanism for HTML and server controls. This
class works like a dictionary object and allows you to store items as a key/value pair in it. It
accepts a string as a key and an object as its value. Items added to this class are automatically
added to the hidden __ViewState form variable.
Storing Information in View State
Information in the form fields on a Web page is automatically added to the view state. In
addition to the information contained in form fields, the view state can be used to store some
additional information. For example, you can store a key-value pair, Counter=1, in the view
state by using the following code:
ViewState["Counter"] = 1;
In the preceding code snippet, a key by the name Counter is stored in the view state and the
value 1 is assigned to the key. If currently no key has the name Counter, a new key will be
added automatically. If a key with the name Counter already exists, it will be replaced.
Retrieving Information from View State
A value stored in view state can be retrieved by using code. For example, you can retrieve the
value of the key, Counter, from view state by using the following code snippet:
int counter;
counter = (int) ViewState["Counter"];
In the preceding code snippet, the value stored in the key, Counter is converted to an integer
before storing it into an integer variable.
Enabling and Disabling View State
By default, the ViewState property of a Web page and the controls on the Web page is
enabled. However, you can disable this property for a Web page or any particular control on
the Web page. This is required when you have a large volume of information to maintain.
However, maintaining large volume of information leads to a significantly slower rendering
of a Web page. Therefore, disabling the ViewState property is important when users are
accessing a Web page with limited bandwidth.
You also need to disable the ViewState property for users using mobile devices. This is
because mobile devices may not have enough storage space for storing large volumes of
information.
You can enable or disable the ViewState property of a Web page or an individual control by
setting the EnableViewState property of the Web page or the control to True or False. You
can set the EnableViewState property of a Web page by using the @Page directive, as shown
in the following example:
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false"
CodeFile="Page1.aspx.cs" Inherits="Page1" %>
To determine the effect of enabling and disabling the ViewState property of a control,
consider an example. Add a Label and a Button control to a Web page and type the following
code in the Page_Load event handler:
if(!IsPostBack)
{
Label1.Text="Hello World";
}
Note
By default, a Button Web server control submits a page back to itself.
When this page is loaded for the first time, the message, Hello World, is displayed in the
Label control. When the user clicks the button, the message is still displayed on the Label
control. This is because the default value of the EnableViewState property of the Label
control is True.
To see the effect of disabling the ViewState property, set the EnableViewState property of
the Label control to False and execute the application. When this page is loaded for the first
time, the message, Hello World, is displayed in the Label control. However, when the button
is clicked, the Label control displays the default text, Label. This is because the Label control
does not maintain its state when its EnableViewState property is set to False.
Note
If the EnableViewState property of a Web page is set to False, ViewState is not maintained
for any control on that Web page, even if the EnableViewState property of a control on the
Web page is set to True.
The advantages of using view state are:
The values in view state are stored in a standard HTML format as part of a Web page.
Therefore, no Web server resource is required to maintain it.
The view state can be easily implemented on the ASP.NET Web page. You just need
to set the EnableViewState property of a Web page and server controls.
The values in view state are hashed, compressed, and encoded for Unicode
implementations. Therefore, values in view state are more secure than the values
stored in hidden fields.
Storing large values can cause a page to slow down when users display it or post it
because view state is stored in the Web page.
View state is stored in a hidden field on a Web page. Although view state stores data
in a hashed format, it can be tampered with. The information in the hidden field can
be seen if the page output source is viewed directly, creating a potential security issue.
Control State
You can use the ViewState property to preserve page and control values between round trips
to the Web server. If you disable the ViewState property of a page, the ViewState of the
controls on that page is not maintained. This can lead to improper functioning of some
controls on the page. For example, the state of the selected node in a TreeView control needs
to be maintained for the control to function properly across postbacks.
To enable persistence of property information that is specific to a control, ASP.NET allows
you to store the state of a control by using a client-side state maintenance mechanism called
control state. Unlike view state, the control state cannot be disabled at the page level.
Therefore, if your Web page contains controls whose state must be maintained, you can use
the control state mechanism to store their state.
You can implement control state on a custom Web control by overriding the following
methods of the base class:
control
(whose state needs to be saved) or an object array containing the values of all the
public properties of the control.
LoadControlState: This method should set the value of the public properties to the
values contained in the object passed to the LoadControlState method as an
argument.
Cookies
Cookies are used to store small pieces of information related to a users computer, such as its
IP address, browser type, operating system, and Web pages last visited. The purpose of
storing this information is to offer a personalized experience to the user. For example, if a
user has logged on to your website for the first time, the name of the user can be stored in a
cookie. This information can be retrieved later on when the same user visits the website again
to greet the user with his/her name.
Cookies are sent to a client computer along with the page output. These Cookies are stored on
the clients computer. When a browser requests the same page the next time, it sends the
cookie along with the request information. The Web server reads the cookie and extracts its
value. It then process the Web page according to the information contained in the cookie and
renders it on the Web browser.
Types of Cookies
Cookies can either be temporary or persistent. Temporary cookies exist in the memory space
of a browser. When the browser is closed, all temporary cookies added to the browser are
lost. Temporary cookies are also known as session cookies.
A temporary cookie is useful for storing information required for only a short time or that
should not be written to disk on the client computer for security reasons. For example, a
temporary cookie can be created to store the user name. The user name stored in the cookie
can be retrieved and displayed on every page of the website.
A persistent cookie is saved as a text file in the file system of the client computer. Persistent
cookies are used when you want to store information for a longer period. For example,
persistent cookies can be used to store customized user settings for a website. This helps in
customizing the website when the user visits the website again.
While creating a persistent cookie, you can set the expiration date of the cookie, which
defines the duration for which the cookie will be stored on the client computer. If you do not
set the expiration date of a cookie, the cookie is maintained as a temporary cookie, as part of
the user's session information. Once the user session is finished, the cookie is discarded.
Persistent cookies can be created as shown in the following example:
Response.Cookies["userName"].Value = "Peter";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2);
Response.Cookies["lastVisited"].Value = DateTime.Now.ToString();
Response.Cookies["lastVisited"].Expires = DateTime.Now.AddDays(2);
In the preceding example, two cookies, username and lastVisited, are created. The user name
Peter is stored in the first cookie and the date and time when the user, Peter, last visited the
site is stored in the second cookie. The expiry period for both the cookies is set as 2 days. If
you do not set the expiry period for the cookies, the cookies will be created as temporary
cookies.
You can also store multiple values in a single cookie. For example, instead of creating
separate cookies for storing the user name and last visited information, you can create a
single cookie that can hold both the values. Such a cookie can be created as shown in the
following example:
Response.Cookies["userInfo"]["userName"] = "Peter";
Response.Cookies["userInfo"]["lastVisited"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(2);
In the preceding example, the cookie, userInfo, with two subkeys, userName and lastVisited,
is created.
Reading Cookies
You can access the value of a cookie by using the Request built-in object. However, if you
want to modify a cookie, you need to use the Response built-in object of ASP.NET.
The following example reads the value of a cookie that stores a single value:
if (Request.Cookies["userName"].Value != null)
{
Label1.Text = Request.Cookies["userName"].Value;
}
In the preceding example, the value in the cookie, userName, is checked for null. If the value
is not null, the value is assigned to the Text property of the Label control.
Similarly, you can read the values from a cookie that stores multiple values. The following
example reads values from a cookie that stores multiple values:
if (Request.Cookies["userInfo"] != null)
{
Label1.Text = Request.Cookies["userInfo"]["userName"]);
Label2.Text = Request.Cookies["userInfo"]["lastVisited"]);
}
In the preceding example, the value in the cookie, userInfo, is checked for null. If the value
is not null, the value of the subkeys, userName and lastVisited, is assigned to the Text
properties of the Label controls.
Advantages and Disadvantages of Cookies
Cookies provide several advantages. Some advantages of using cookies are:
A cookie is stored on the client computer and can be read by the server after a request
for a page is posted. Therefore, no server resource is involved in maintaining the
cookie.
A cookie is a text-based data structure that contains key-value pairs. Therefore, it is
easy to create and manipulate cookies.
A cookie can either expire when the browser session ends or exist indefinitely on the
client computer, subject to the expiration rules on the client.
Cookies that are stored on the client computers have a limited size. Most browsers
allow cookies to be up to 4096 bytes in size. Therefore, you cannot store a large
amount of data in a cookie.
Users can disable cookies to prevent them from being stored on the hard disk of their
computer. If a user denies permission for cookies, an ASP.NET Web application
cannot store cookies on the client computer.
Users can tamper with cookies because cookies are stored on the client computer.
Query String
Sometimes, it is required to transfer information from one page to another. For example, on
an online book shopping website, a Web form displays the list of categories of books. When
the user selects a category, another page with detailed information about the selected category
is displayed. This process requires you to transfer the information about the selected category
to the other page so that the relevant details can be displayed. You can perform this task by
using a query string.
A query string provides a simple way to pass information from one page to another. It is the
part of a URL that appears after the Question mark (?) character. Consider the following
URL:
http://www.MyBookStore.com/search?Category=fiction
In the preceding URL, the query string defines a variable, category, which contains the string,
fiction.
You can pass data from one page to another page in the form of a query string by using the
Response.Redirect method, as shown in the following example:
Response.Redirect("BooksInfo.aspx?Category=fiction");
In the preceding example, the string fiction is stored in the variable Category and is sent to
the BooksInfo.aspx page. The information stored in the variable Category can be retrieved on
the BooksInfo.aspx page by using the following syntax:
String cat = Request.QueryString["Category"];
Note
There should be no blank space before and after the ampersand (&) symbol.
In the preceding example, the strings, fiction and Sams, are stored in the variables,
Category and Publisher, respectively. The information stored in these variables can be
retrieved on the BooksInfo.aspx page by using the following syntax:
String cat = Request.QueryString["Category"];
String pub = Request.QueryString["Publisher"];
Note
To ensure that the query string values are available during page processing, you must submit
the page by using the HTTP Get method.
Advantages and Disadvantages of Query Strings
The advantages of using query strings are:
A query string is contained in the HTTP request for a specific URL. Therefore, no
server resource is involved in processing a query string.
Many Web browsers support passing values in a query string. Therefore, if you create
a Web application that passes information from one page to another using a query
string, it will be processed in most of the browsers.
Application State
Session State
Profile Properties
Application State
ASP.NET provides application state as a means of storing application-specific information
such as objects and variables. The information in the application state is stored in a key-value
pair and is used to maintain data consistency between server round trips and between pages.
Application state is created the first time a user accesses any URL resource in an application.
After an application state is created, the application-specific information is stored in it. All
the information stored in the application state is shared among all the pages of the Web
application by using the HttpApplicationState class. The HttpApplicationState class is
accessed by using the Application property of the HttpContext object.
Note
Application state variables are global for an ASP.NET application. However, the values
stored in the application state variables are accessible only from the code running within the
context of the originating application. Other applications running in the system cannot
access or modify the values.
After the application in which you declared MyVariable is executed, any page in the
application can retrieve the value of MyVariable. To read the value of MyVariable, you can
use the following code snippet:
string val = (string) Application["MyVariable"];
You can also add complex objects, such as a Collection or a Dataset, in the application state.
For example, you can add a dataset to an application state by using the following code
snippet:
DataSet ds = new DataSet();
Application ["DataSet"] = ds;
You can also remove all the application state variables and objects by using the following
code snippet:
Application.RemoveAll();
After an object is added to an application state, it remains in the application state until the
application is shut down, the Global.asax file is modified, or the item is explicitly removed
from the application state.
Handling Application Events
Application state has the following events that you can capture to manipulate an ASP.NET
Web application:
Application.Start:
Application.End:
You can handle the preceding events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Considerations While Using Application State
The application state variables are global to an application. Therefore, it is important to
consider the following issues while storing any value in an application state variable:
The memory occupied by variables stored in an application state is not released until
the value is either removed or replaced. Therefore, the number of variables and
objects in an application state should be minimum. Otherwise, it will be an overhead
on the Web server and the server response will be slow.
Multiple pages within an application can simultaneously access the values stored in an
application state. Therefore, explicit synchronization methods need to be used to
avoid deadlocks and access violations.
Note
Each browsers request for a Web page initiates a new thread on the Web server.
Calling the Lock() method on an Application object causes ASP.NET to block attempts by
the code running on other worker threads to access anything in the application state. These
threads are unblocked only when the thread that called the Lock() method calls the
corresponding Unlock() method on the Application object. Consider the following example:
Application.Lock();
if (Application["PageCounter"] == null)
{
Application["PageCounter"]=1;
}
else
{
Application["PageCounter"]=(int)Application["PageCounter"]+1;
Response.Write(Application["PageCounter"]);
}
Application.UnLock();
In the preceding example, the Lock() method is called before accessing the value of the
PageCounter variable. This ensures that the variable cannot be modified simultaneously by
any other thread. After calling the Lock() method, the value of the PageCounter variable is
modified. After the modification is done, the UnLock() method is called to release the
imposed lock on the PageCounter application state variable. Then, the variable can be
modified by other threads.
Note
It is not required to call the Unlock() method explicitly because the .NET Framework
automatically removes the lock when the request completes or times out, or when an
unhandled error occurs during request execution and causes the request to fail.
Note
The Lock() method locks all the items in the application state object. In other words, you
cannot selectively lock items in an application state.
The advantages of using the application state are:
Application state is easy to use and is consistent with other .NET Framework classes.
Storing information in application state involves maintaining only a single copy of the
information.
The data stored in an application state is lost when the Web server containing the
application state fails due to a server crash, upgrade, or shutdown.
Application state requires server memory and can affect the performance of the server
and the scalability of the Web application, if it occupies too much memory space.
You can implement application state to increase the performance of the Web application. For
example, storing relatively static dataset in an application state can enhance Website
performance by reducing the overall number of data requests to a database. However, it is
important to remember that application state variables containing large blocks of information
can reduce Web server performance as server load increases. In addition, the memory
occupied by a variable stored in an application state is not released until the value is either
removed or replaced. Therefore, it is preferred to use application state variables with small,
and less frequently changed datasets.
Session State
In ASP.NET, session state is used to store session-specific information for a Web application.
Unlike application state, the scope of session state is limited to the current browser session. If
multiple users are accessing a Web application, each will have a different session state. If a
user exits from a Web application and returns later, the user will have a different session
state.
Session state is structured as a key-value pair for storing session-specific information that
needs to be maintained between server round trips and between requests for pages.
The session state has a built-in support in ASP.NET. The built-in session state feature
automatically performs the following actions:
Identify and classify requests coming from a browser into a logical application session
on the server.
Store session-specific data on the server for use across multiple browser requests.
Raise session lifetime-related events, such as Session.Start and Session.End,
which can be handled in the Global.asax file.
Automatically release session data if a browser does not access an application within
a specified timeout period.
When a user first requests a page from an ASP.NET website, the website automatically adds
a session cookie to the client browser. This cookie is named ASP.NET_SessionID cookie.
This cookie is used for the remainder of the users visit to the website.
Identifying a Session
Each active ASP.NET session is identified and tracked by a unique 120-bit SessionID string
containing American Standard Code for Information Interchange (ASCII) characters. The
SessionID strings are communicated across client/server requests either by means of an
HTTP cookie or by using a modified URL with the embedded SessionID string. The
SessionStateModule class is responsible for generating or obtaining SessionID strings.
Similar to the application state, you can store objects and variables in a session state. By
default, a session variable is active for 20 minutes without any user interaction. In an
ASP.NET Web application, the objects stored in the session state are stored on the server.
Using the Session State
The syntax for adding and retrieving items from the session state is basically the same as for
adding items to a pages view state. The following example adds the variable, MyVariable,
with value HELLO in the session state:
Session["MyVariable"]="HELLO";
You can retrieve the value of the variable, MyVariable, by using the following statement:
String val = (string) Session["MyVariable"];
Any variable or object that you add to a session state is available only until the user
closes the browser window. The variables and objects are automatically removed
from session state if the user does not request a page for more than 20 minutes
because it is the default value.
Any variable or object added to a session state is related to a particular user. For
example, you can store different values for MyVariable for two different users
accessing the Web page and each user can access only the value that is assigned to
him/her.
Any object that supports serialization can be added to the session state. The objects
stored in session state are stored on the server. Therefore, session objects are not
subject to the same size limitations as cookies.
Session state is global to the entire application for the current user. Session state is not lost if
the user revisits a Web page by using the same browser window. However, session state can
be lost in the following ways:
Similar to an application state, you can remove an object or a variable added to the session
state by using either the Remove() method, or the RemoveAll() method based on the
requirement.
Handling Session Events
Session state has the following events that you can capture to manipulate an ASP.NET Web
application:
Session.Start:
This event is raised when a user requests the first page from a
website, and is useful for initializing session variables.
Session.End: This event is raised when a user session expires or when the
Session.Abandon method is called.
You can capture both these events by adding subroutines in the Global.asax file. The
Global.asax file contains the event handlers for all the application and session events.
Configuring Session State
Session state can be configured through the web.config file for the application. The
web.config file allows you to set advanced options such as the timeout and the session state
mode. The following markup shows some important options that can be set for the
<sessionState> element:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<sessionState
cookieless="UseCookies" cookieName="ASP.NET_SessionId"
timeout="20"
mode="InProc" />
</system.web>
</configuration>
cookieless
timeout
mode
The cookieless attribute specifies whether a cookie should be used or not. The following
table lists the values that the cookieless attribute can have with their description.
Value
Description
UseCookies
UseUri
UseDeviceProfile
AutoDetect
The mode attribute specifies where the session state values are to be stored. The mode attribute
can have the following values:
Custom:
InProc:
You can also disable session state for all pages of a Web application by setting the mode
attribute to Off in the web.config file, as shown in the following figure.
Note
In ASP.NET, the mode attribute is case-sensitive.
Profile Properties
Many Web applications provide users with the option to personalize the application. This can
be done by storing and using information that is unique to a user. This information can be
used to present the user with a personalized version of the Web application.
Consider an example. Suppose, you have created a website for online shopping of books. A
user has used the website to purchase books from the IT category. This information can be
stored as a profile property for that user. When the same user visits the website again, you
can use the information stored in the profile properties to display the latest books in the IT
category to the user.
ASP.NET provides the profiles feature to implement personalization in Web applications.
Although it is possible to store user preferences without using profiles, using it enables
developers to store preferences without writing much code. These preferences are stored as
named properties in profiles. The preferences can be stored in the form of simple data types,
complex data structures, or .NET Framework classes.
The profile information is stored in the aspnetdb.mdf file. It is created automatically when
you use any membership or profiles features for the first time. However, this automatic
creation of the aspnetdb.mdf file relies on SQL Server 2005 Express. If youre using another
version of SQL Server, you need to modify the profile configuration and create the database
manually.
Note
The membership feature will be discussed later in this course.
The <clear/> element clears all the existing connection strings. After clearing the existing
connection strings, you can specify the new connection string.
Configuring Profile Properties
The properties that need to be stored in each user profile for an application can be configured
in the web.config file. You can configure the profile properties by using the markup shown in
the following example:
<system.web>
<profile>
<properties>
<add name="UserName" />
<add name="BirthDate" type="System.DateTime" />
</properties>
</profile>
<system.web>
In the preceding example, two profile properties, UserName and BirthDate, are defined. The
name attribute is used to define the name of the profile properties and the type attribute is
used to specify the data type. If the data type for a profile property is not defined, it takes the
default data type, which is String. Therefore, the data type of the UserName property is
String. The data type for the BirthDate property is defined as DateTime. The properties
UserName and BirthDate can be set only by the logged-on users. Anonymous users cannot
set these properties.
You can also create profile properties that can be set by all users including anonymous users.
To configure such profile properties, you need to use the markup as shown in the following
example:
<system.web>
<anonymousIdentification enabled="true"/>
<profile>
<properties>
<add name="UserName" type ="System.String" allowAnonymous=
"true"/>
<add name="BirthDate" type="System.DateTime" allowAnonymous=
"true"/>
</properties>
</profile>
<system.web>
In the preceding code snippet, the UserName profile property is set to the Text property of the
TextBox1 control. Similarly, the value of the profile property can be retrieved, as shown in
the following code snippet:
String uname = Profile.UserName;
The preceding code snippet returns the value of the Username profile property.
Note
When you store profile properties, ASP.NET identifies the user who has set the property.
Note
To make a control submit the page back to itself, you can set the AutoPostBack property of
the control to true.
Response.Write(t.Text);
}
}
In the preceding example, the value of the TextBox1 control, which is on the source page, is
accessed in the target page.
Implementing Caching
Speed is a critical factor that judges the success or failure of any website. When multiple
users access a website simultaneously, slow access to Web pages is a common problem that
arises. The problem of slow access can be solved by using a technique called caching.
This technique improves the performance of any Web application by temporarily storing
frequently used Web objects, such as HTML pages, on local hard disks for later retrieval. As
a result, the Web server, on which the application resides, processes the requests for the
website only one time and caches the requests for future. Any subsequent request is
processed from the cache instead of the Web server. This leads to a considerable reduction in
the load on the server and a quicker response time. Caching enables you to improve the
performance of Web applications.
Caching is a very important and extensively used concept to enhance application
performance. The major benefits of using caching are:
Reduced access time: When most of the requests are processed by the cache itself and not
required to go to the Web server, the access time is reduced significantly.
Less bandwidth required: Cache location can be configured on the client computer. As a
result, most of the requests and responses do not require traveling the network between
the client and server, and this significantly reduces the bandwidth requirement.
Less load on server: Caching avoids executing the same ASP.NET code repetitively to create
the same result. This reduces the CPU usage at the server, and in the process, lowers the
load on the server.
Output Caching
Fragment Caching
Data Caching
Output Caching
Output caching improves the performance of an ASP.NET application by caching the
rendered markup of an ASP.NET Web page. When the user requests the same page within a
specified period of time, instead of re-rendering the page, ASP.NET serves the cached page
to the user. Output caching is useful when the content of the Web page changes rarely.
For example, on an online shopping website, the products page gets the details of the
products from a database table. If output caching is not implemented, each time the products
page is accessed, a connection is made to the database, the table is queried, and the results are
returned to the requesting client. It takes a substantial amount of time affecting the
performance. Moreover, it is not required to fetch the product details from the database table
for every request because the product details rarely change.
With output caching, when the products page is first visited, the rendered HTML of the page
is cached for a specified duration. During the specified time period, if a user requests this
page, the cached markup is returned, thereby saving the database access and page rendering
time.
Implementing Output Caching
To implement output caching, you need to insert the @ OutputCache directive at the top of
your .aspx file, just below the @ Page directive, as shown in the following example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="20" VaryByParam="None" %>
In the preceding example, the @ OutputCache directive contains the two attributes,
Duration and VaryByParam. The Duration attribute instructs ASP.NET to cache the page
for the specified number of seconds. The VaryByParam attribute specifies how many copies
of the page need to be saved. In this example, the value of the VaryByParam attribute is set to
None, which indicates that only one copy of the page is to be cached.
However, there are situations when you want to save more than one cached copy of the page.
One such situation is when the page is requested with a query string. In this case the output of
the page differs, depending on the query string. In such a case, you want to use more than one
copy of the page. For this, you need to use the @ OutputCache directive as shown in the
following example:
In the preceding example, the value * of the VaryByParam attribute instructs ASP.NET to
cache separate copies of the page for different query string arguments.
Fragment Caching
ASP.NET provides one more type of caching in which the data from some specific sections
of the page can be cached. This is called fragment caching. Sometimes it is also referred to as
partial page caching. Fragment caching is used in situations where you want to cache only a
portion of the Web page because it does not change frequently. The remaining content of the
page is loaded dynamically.
To implement fragment caching, the portion of the page that is to be cached is encapsulated
in a user control, and then the @ OutputCache directive is added to the control, as shown in
the following example:
<%@ Control Language="C#"%>
<%@ OutputCache Duration="120" VaryByParam="None" %>
Data Caching
Data caching is used to store frequently used data in the built-in collection object called
Cache. It is a property of the Page class, and it returns an instance of the
System.Web.Caching.Cache class. The Cache object works like the Application object.
The Cache object is globally available to all requests from all clients in the application.
The Cache object differs from the Application object in the following ways:
You can retrieve the value from the Cache object, as shown in the following code snippet:
TextBox1.Text = Cache["uname"];
The lifetime of the Cache object associated with an application is the same as the lifetime of
the application. Therefore, when an application stops, the information in the Cache object is
lost.
Summary
In this chapter, you learned that:
Client-side state management allows you to store information either on a Web page or
on a client computer.
The various options available to implement client-side state management are:
o
o
o
o
o
A hidden field is a control similar to a TextBox control but it does not render in a
Web browser.
Information in the form fields on a Web page is automatically added to the view state.
It can also be used to store some additional information.
Control state is used to store information that is specific to a control.
Cookies are used to store small pieces of information related to a users computer,
such as its IP address, browser type, and operating system.
Cookies can either be temporary or persistent.
A query string provides a simple way to pass information from one page to another.
ASP.NET provides the following options to manage state at the server side:
o
o
o
Hidden Fields
View State
Control State
Cookies
Query Strings
Application State
Session State
Profile Properties
Output Caching
Fragment Caching
Data Caching
Reference Reading
http://dotnet.dzone.com/news/aspnet-client-side-state-manag-1
http://www.exforsys.com/tutorials/asp.net-2.0/statemanagement-in-asp.net-2.0.html
http://articles.techrepublic.com.com/5100-10878_115030436.html
http://www.dotnetspider.com/resources/1472-STATEMANAGEMENT.aspx
http://www.hotscripts.com/Detailed/74287.html
Implementing Caching
Reference Reading: Books
http://www.asp.net/learn/withpss/module7.aspx
Chapter 6
Objectives
In this chapter, you will learn to:
Identify basics of data access in Web applications
Access data by using the presentation layer
Access data by using DAL
Presentation Layer
In a Web application, the presentation layer is the interface that appears when a user opens a
Web page in the browser. If you see the source code of the page, you would only see the code
such as HTML, Javascript, and Cascading Style Sheets. You would not be able to see the
database queries, loops, calls to classes, or any behind-the-scenes processing. This is due to
the fact that the presentation layer does not contain any data access code or program logic.
However, in case of small Web applications, you may find the database access layer merged
with the presentation layer.
Consider a situation where a developer has implemented the data source controls to access
data from the data source. In such a situation, the database access is merged with the
presentation layer. This approach tightly couples the data access logic with the presentation
layer. Therefore, this approach is not recommended because the data access logic, being
tightly coupled, cannot be implemented by any other application.
You can implement the data access logic in the presentation layer. However, this is not
recommended because it clutters the data access code with the HTML and Javascript code. In
addition, it tightly couples the data access logic with the presentation layer. This prevents the
data access logic to be reused in other Web applications.
All these limitations can be overcome by separating the data access logic from the
presentation layer. It can be done by creating a new layer and implementing the data access
logic in it. This separate layer is referred to as the Data Access Layer (DAL). DAL is
typically implemented as a separate class library.
Note
Data controls are the controls that are designed exclusively for use with data sources. Some
of the data controls are GridView, DataList, ListView, and FormView controls. Data-aware
controls are standard controls that can be used with databases, but are not exclusively for
that purpose. These controls can also be used without connecting them to a data source.
Examples of such controls include DropDownList and ListBox controls.
Data source controls perform the following tasks:
Retrieve data from a data source and supply it to the data controls or data aware
controls.
Update the data source when edits take place.
SqlDataSource
AccessDataSource
ObjectDataSource
XmlDataSource
SiteMapDataSource
SqlDataSource Control
The SqlDataSource control is generally used to access data from an SQL relational database.
However, it can be used to access any database product for which there is a managed
ADO.NET provider.
Note
A Provider is a class that communicates with a specific type of database or data store.
The SqlDataSource control is used in conjunction with data controls to retrieve data from a
relational database and to display or modify the data on a Web page with minimal coding.
The following table lists some properties of the SqlDataSource control.
Property
Description
ProviderName
ConnectionString
SelectCommand
DeleteCommand
InsertCommand
Note
You can bind data controls to the SQLDataSource control by using the DataSourceID
property of the data controls.
AccessDataSource Control
The AccessDataSource control works with Microsoft Access databases. Like the
SqlDataSource control, the AccessDataSource control uses SQL queries to retrieve data.
However, unlike the SqlDataSource control, you do not set the ConnectionString property
in the AccessDataSource control. Instead of the ConnectionString property, you need to set
the location of the Access (.mdb) file in the DataFile property.
The Access database to be accessed should be placed in the App_Data directory of the
website and needs to be referenced by a relative path. Using relative path for referencing the
database provides security for data files because these files will not be served if requested
directly by the client Web browser.
You cannot access Access databases that are protected by a user name or password by using
the AccessDataSource control. This is because you cannot set the ConnectionString
property in the AccessDataSource control. If you need to access an Access database that is
protected by a user name or password, you need to use the SqlDataSource control because it
allows you to specify a complete connection string.
Note
You cannot set the ConnectionString property for the AccessDataSource control because it
is a read only property.
You can bind data-bound controls to an AccessDataSource by using the DataSourceID
property of the data-bound control. The following table lists some properties of the
AccessDataSource control.
Property
Description
ProviderName
DataFile
SelectCommand
DeleteCommand
InsertCommand
UpdateCommand
In the preceding example, the DataFile attribute is used to specify the Access database file.
The SelectCommand attribute is used to specify the query that retrieves the LastName and
FirstName field values from the Employees table.
ObjectDataSource Control
The ObjectDataSource control represents a middle-tier object with data retrieval and update
capabilities. The ObjectDataSource control is used in conjunction with a data-bound control
to display or modify data on a Web page with minimal coding.
Most of the complex Web applications follow the three-tier architecture. In this architecture,
the presentation layer is separated from business logic, which is encapsulated in business
objects. These business objects form a distinct layer between the presentation layer and the
data layer. The ObjectDataSource control enables developers to access data from business
objects.
The following table lists some properties of the ObjectDataSource control.
Property
Description
TypeName
SelectMethod
SelectParameters
InsertMethod
InsertParameters
UpdateMethod
UpdateParameters
DeleteMethod
DeleteParameters
In the preceding example, the SelectMethod attribute sets the method, GetEmployee, which
is invoked to retrieve data. The TypeName attribute defines the name of the class that the
ObjectDataSource is working with. The <SelectParameters> element passes the employee
ID as parameter because it is required by the GetEmployee method.
XmlDataSource
The XmlDataSource control presents XML data to data-bound controls. The XmlDataSource
control can be used by data-bound controls to display hierarchical as well as tabular data. The
XmlDataSource control loads data from an XML file that is specified by the DataFile
property. The XmlDataSource control can also load XML data in string form by using the
Data property. You can bind data-bound controls to an XmlDataSource control by using the
DataSourceID property of the data-bound control.
The following table lists some properties of the XmlDataSource control.
Property
Description
DataFile
Data
In the preceding example, the datafile attribute specifies the filename of the XML file that is
to be bound with the XmlDataSource control.
SiteMapDataSource Control
Description
SiteMapProvider
StartingUrlNode
ShowStartingNode
You can retrieve data from a sitemap file by using the SiteMapDataSource control, as shown
in the following example:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
In the preceding example, the SiteMapProvider attribute is not defined. Therefore, the
default provider, XMLSiteMapProvider, will be used. When you use the default provider, the
SiteMapDataSource control will always look for the Web.sitemap file in the root folder of the
application. However, if your application has a sitemap file with a name other than the
default name, Web.sitemap, you need to use a custom provider for the SiteMapDataSource
control. You can use the custom provider by adding it in the web.config file, as shown in the
following example:
<siteMap>
<providers>
<add name="MusicManiaSiteMap"
type="System.Web.XMLSiteMapProvider"
siteMapFile="MyWeb.sitemap"/>
</providers>
</siteMap>
In addition to modifying the web.config file, you need to set the SiteMapProvider property
of the SiteMapDataSource control to the custom provider, as shown in the following
example:
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
SiteMapProvider="MusicManiaSiteMap " />
Note
In addition to the preceding data source controls, ASP.NET provides the LinqDataSource
control that allows you to access data from wide variety of data sources such as a database,
data-source classes, and in-memory collections.
Displaying Data in Data-Bound Web Server Controls
Data-bound Web server controls are the controls that can be bound to a data source control to
display and modify data in a Web application. Data-bound Web server controls are composite
controls that combine other Web controls, such as Label and TextBox controls, into a single
unit. In addition to displaying and modifying data, data-bound controls enable you to
customize the layout of the control using templates. ASP.NET provides various data-bound
Web server controls. Some of them are:
GridView Control
DetailsView Control
FormView Control
ListView Control
DataList Control
Repeater Control
DataPager Control
DataGrid Control
GridView Control
When working with data in an application, it is required to display the data in tabular form.
To display data in a tabular form, ASP.NET provides a number of controls, one of which is
the GridView control. The GridView control allows you to display, edit, and delete data from
different kinds of data sources, such as databases, XML files, and business objects that
expose data. However, you cannot change the layout of the GridView control.
The GridView control provides various properties that can be set to display data in the
desired format. The following table lists some properties of the GridView control.
Property
Description
DataSource
DataSourceID
AllowPaging
AllowSorting
AlternatingRowStyle
SelectedIndex
SelectedRow
SelectedValue
DetailsView Control
The DetailsView control allows you to display, edit, insert, or delete a single record at a time.
By default, the DetailsView control displays each field of a record in a new line. It can
display only one record at a time. It is generally used in a master/detail scenario. In such a
scenario, the DetailsView control is used to update or delete records that are selected in the
master control. The DetailsView control can also be used to add a new record.
The following table lists some properties of the DetailsView control.
Property
Description
DataSource
DataSourceID
AllowPaging
AlternatingRowStyle
SelectedValue
Similar to the DetailsView control, the FormView control allows you to work with a single
record at a time. However, there is a difference between the FormView and the DetailsView
control. The DetailsView control displays the record in a tabular format with each field of the
record in a new row whereas the FormView control provides you with the flexibility to
modify the layout for displaying the record. You can modify the layout by creating a new
template or by modifying the existing template. The template can contain formatting,
controls, and binding expressions. The FormView control is also used in master/detail
scenarios.
Note
The FormView control provides various built-in templates such as ItemTemplate,
InsertItemTemplate, and EditItemTemplate that allow you to provide a different interface for
performing different operations such as view, insert, and edit. Similarly, the
EmptyDataTemplate enables you to specify a template to display when the data source
returns no data.
The following table lists some properties of the FormView control.
Property
Description
DataSource
DataSourceID
AllowPaging
SelectedValue
The DataList control allows you to display rows of database information in a customizable
format. You can create the format for displaying data by defining templates. You can create
templates for items, alternating items, selected items, and edit items.
The following table lists some properties of the DataList control.
Property
Description
DataSource
DataSourceID
SelectedValue
SelectedIndex
SelectedItem
A Repeater control displays data from different data sources by using customized layouts. A
Repeater control does not have a default layout. You need to create templates to provide a
layout to the Repeater control. You can create tables, grids, comma separated lists, and
bulleted or numbered lists to display data in a Repeater control. After adding the Repeater
control to a Web form, you can set its properties and then create different templates to
provide the layout to the Repeater control. The ItemTemplate template is mandatory as it
provides a basic layout to the Repeater control. Other templates can also be created to
enhance the layout. The Repeater control does not provide certain features such as editing,
updating, and paging.
The following table lists some properties of the Repeater control.
Property
Description
DataSource
DataSourceID
DataMember
ListView Control
The ListView control is similar to the GridView and Repeater controls. The GridView and
Repeater controls have some limitations. The GridView control does not allow a user to
change the layout of the data display. Similarly, the Repeater control does not provide
features such as editing, updating, and paging. Both these limitations are overcome in the
ListView control.
The ListView control enables you to display data in a format that is defined by using
templates and styles. In addition, it enables you to edit, insert, delete, and sort and page data
without writing code.
Note
The ListView control provides various layouts, templates, and styles that you can choose
according to your requirements.
The following table lists some properties of the ListView control.
Property
Description
DataSource
DataSourceID
SelectedValue
SelectedIndex
The DataPager control is used to enable users to page through data in either a ListView
control or a control that implements the IPageableItemContainer interface. The DataPager
control can be inserted inside the LayoutTemplate template or on the page outside the
ListView control. It the DataPager control is inside the LayoutTemplate template, the
DataPager is a direct part of the generated output. If it is not in the ListView control, you
need to set the PagedControlID property of the DataPager control to the ID of the ListView
control.
Description
PagedControlID
PageSize
The DataGrid control is used to display data in a tabular layout. By default, it displays data in
the read-only mode. However, it is capable of automatically displaying the data in editable
controls at run-time. The DataGrid control supports paging.
To display data from a data source, you need to bind the DataGrid control to a data source
control by using its DataSourceID property. You can also bind the DataGrid control from a
data source such as the DataSet and data readers by using its DataSource property.
When binding a DataGrid control with data source such as the DataSet and data readers by
using its DataSource property, the DataGrid control generates a bound column for each field
in the data source. However, you can select which fields in the data source generate columns
in the grid. When using the DataSource property, you need to call the control's DataBind
method to load data in the control, as shown in the following code snippet:
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
In the preceding example, ds is the object of type DataSet. The DataBind method is used to
load data in the DataGrid control. The DataBind method is also called to refresh the data in
the control, in case the data is modified in the data source.
The following table lists some properties of the DataGrid control.
Property
Description
DataSource
DataSourceID
AllowPaging
AllowSorting
SelectedIndex
Note
The DataGrid control is not a standard control. Therefore, it is not present in the Toolbox. It
needs to be added to the Toolbox by right-clicking the Toolbox and selecting Choose Items.
You can find this control in the .NET Framework Components tab.
Binding Controls to Data by Using Data Binding Syntax
Data binding is a technique of linking data and user interface objects. Using data binding, you
can bind data in a data source to a user interface object. Any modifications to the data in
these user interface objects can be updated to the data source.
On the basis of the number of bound values that can be displayed through a user interface
object, binding can be classified into:
Interactive Web pages are majorly designed by using controls such as TextBox, Label, and
RadioButton. These controls can display one data value at a time. For example, if you have to
register five friends of yours on a website by writing their names in a TextBox and clicking
the Submit button, you have to write the name and click the button five times. This is because
in controls such as a TextBox you can write only one value at a time. Such controls are
known as single-value controls. These controls can be bound to a data value by using singlevalue data binding.
Single-value data binding involves binding the controls that can display one data value at a
time to a data source. Single-value controls do not support any data binding properties, such
as the DataSource property or the DataMember property. Therefore, you need to bind a
single-value control by providing data as the value of its Text property. For example, you can
set the Text property of a TextBox control to display a data source value. This data source
value can be a property, a return value of a method, an expression, or a value from a database.
You can bind single-value controls to properties, such as page properties, public variables,
and the properties of other controls. Consider a case where you need to bind a Label control
to a public variable that displays the current date and time. For this, you can write the
following code in the .aspx.cs file:
public partial class _Default : System.Web.UI.Page
{
public string dt = DateTime.Now.ToString();
protected void Page_Load(object sender, EventArgs e)
{
this.DataBind();//binds the data source to the invoked server
//control and all its child controls
}
}
You can now use the variable dt to display date in a new Label control, as shown in the
following markup:
<asp:Label ID="Label1" runat="server"> <%# dt %></asp:Label>
There are situations when you need to display a list of values from a data source on to a Web
page. One such situation is when you want to display a list of products on a Web page. This
can be done by using server controls, such as a ListBox, that can display multiple data values
at a time. Such controls are known as repeated-value server controls. These controls can be
bound to a data source by using repeated-value data binding.
Repeated-value data binding involves binding server controls to structures, such as ArrayList
and DataView objects, which implement the IEnumerable interface. The DataGrid,
DropDownList, and ListBox controls are some of the repeated-value server controls that can
display multiple data values. The following example shows how you can bind an ArrayList to
a ListBox control:
Using ADO.NET
Data source controls enable you to access data from a database without writing any data
access code. However, Data source controls do not provide the flexibility that can be
achieved by using ADO.NET. In addition, data source controls enable you to access data only
by using the connected environment. However, ADO.NET provides both the connected and
disconnected environments to access data.
Note
A connected environment requires a constant connection to transfer data between the client
application and the data source. However, a disconnected environment retrieves data and
performs modifications without being connected to the network all the time.
Accessing Data from a Database by Using ADO.NET
You can access data from various data sources such as MS Access, SQL Server, and Oracle
by using ADO.NET. To access data from a database by using ADO.NET, you need to use
certain objects. Some of the basic objects are:
Connection Objects
Command Objects
Data Reader Objects
Dataset Objects
Connection Objects
Before accessing data from a data source, you need to make a connection to the data source.
For this, you need to use the connection object. When creating a connection object, you need
to set the ConnectionString property. The ConnectionString property defines all the
information required to find the data source, log on, and choose an initial database. Consider
the following code snippet:
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=172.23.3.59;Initial
Catalog=Music;Integrated Security=SSPI; Persist Security Info=False";
myConnection.Open();
In the preceding example, a connection object myConnection is created. After creating the
connection object, the ConnectionString property of the myConnection object is set. The
connection string is a series of distinct pieces of information known as connection string
properties. When writing the code, the connection string properties are separated by
semicolons. The connection string can have various connection string properties. Some of the
important connection string properties are:
Data Source:
Indicates the name or the IP address of the server where the data
source is located.
Initial Catalog: Indicates the name of the database that this connection will be
accessing.
Integrated Security: Indicates that you want to connect to SQL Server using the
Windows user account. The value specified for this attribute is SSPI, which indicates
ASP.NET to use the credentials under which the Web application is executing to
authenticate with SQL Server.
Persist Security Info: Indicates whether the information such as the user Id and
password is discarded after it is used to open the connection. This information is
discarded when the value of the Persist Security Info is set to false. However,
if the value of this attribute is set to true, the security-sensitive information,
including the user ID and password, can be obtained from the connection after the
connection has been opened.
Note
In addition to windows authentication, you can use SQL server authentication. For SQL
server authentication, instead of the Integrated Security and Persist Security Info attribute,
you need to use the User ID and Password properties, as shown in the following example:
myConnection.ConnectionString = "Data Source=172.23.3.59;Initial Catalog=Music; User
ID=sa;Password=password@123";
After specifying the connection string, you need to open the connection. Then, the connection
object is ready to be used to access the data source.
You need to create the connection objects for all the Web pages in which you want to access
data from a data source. Generally, all the database code in an application uses the same
connection string. Therefore, it is not advisable to create separate connection objects for all
the Web pages because it makes an application slow. Moreover, you need to write the same
code again. These problems can be solved by storing the connection string in the web.config
file. If the connection string is stored in the web.config file, it can be accessed from any Web
page within the application. You can store the connection string in the
<connectionStrings> section of the web.config file, as shown in the following example:
<configuration>
<connectionStrings>
<add name="myMusic" connectionString=
"Data Source=172.23.3.59;Initial Catalog=Music;Integrated
Security=SSPI; Persist Security Info=True"
provideName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>
In the <ConnectionStrings> element the <add> sub tag is used to add a connection string.
The <add> sub tag contains the following attributes:
string value.
provideName:
To access the connection string that is defined in the web.config file, you need to use the
ConnectionStrings property of the ConfigurationManager class from any Web page
within the website. After accessing the connection string, you can use it in the Connection
object by writing code shown in the following example:
string connString =
ConfigurationManager.ConnectionStrings["myMusic"].ConnectionString;
myConnection.Open();
Command Objects
After a connection has been established with the data source, you can execute commands and
return results from the data source by using a command object.
To execute SQL statements, you need to create an instance of the SqlCommand class present
in the System.Data.SqlClient namespace. The command object specifies the SQL
statement that needs to be executed and the connection that needs to be used to execute the
statement. You can execute SQL statements or stored procedures through command objects.
The following code snippet demonstrates how to create a command object:
// Create an object of the SqlConnection class
SqlConnection connection = new SqlConnection();
// Create a connection string to the HR database
connection.ConnectionString = "Data Source=172.23.3.59;
Initial Catalog=HR; User ID=sa; Password=niit#1234";
connection.Open(); //opening the connection
// Create an object of the SqlCommand class
SqlCommand cmd = new SqlCommand("select * from
monthlysalary",connection);
In the preceding code snippet, the SqlCommand object cmd is initialized to the SQL statement
that needs to be executed.
Note
The SqlCommand object can also be used to specify insert, update, and delete queries.
DataReader Objects
After defining the command object, you need to execute it to get the data from the data
source. The data returned by executing the command object needs to be stored in another
object. The DataReader object can be used to store the data returned by executing the
command object. The DataReader object supports forward-only read-only access to the
results returned by executing the command object. Therefore, it can be used when you need
to retrieve information from a data source. The DataReader object works in a connected
environment. It requires an open connection for its working.
To create a DataReader object, you use the ExecuteReader() method of the command
object, as shown in the following code snippet:
//You don't need the new keyword, as the Command will create
the //DataReader.
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
The preceding code snippet defines a variable myReader and then stores data in it by
executing the command. Once you have retrieved the data in the DataReader object, you can
view a single row at a time by using the Read() method, as shown in the following code
snippet:
myReader.Read(); // The first row in the result set is now available.
Note
The Command object can also execute a DML statement against a connection object and
returns the number of rows affected by using the ExecuteNonQuery method.
Dataset Objects
da.Fill(ds, "albums");
GridView1.DataSource = ds;
GridView1.DataBind();
In the preceding example, the data from the data source is retrieved by the data adapter and
filled into the dataset. After that the data in the dataset is displayed by using the GridView
control.
Creating a DAL
You can create a DAL by creating a class library and writing all the data access functions in
that library. All the data access functions written in the class library should be generic. This is
because a DAL is created to separate the data access logic from the application layer. In
addition, the functions written in a DAL should be reusable. Consider the following example:
public void CreateConnection(String ConnString)
{
Sqlcon = new SqlConnection(ConnString);
}
In the preceding example, the function CreateConnection is created to set the connection
string to be used in the application. Instead of hard coding the connection string in the DAL,
the CreateConnection function creates the connection depending on the connection string
that is passed as a parameter by the user. This provides flexibility to the DAL and it can be
reused in any application that requires data access code.
Consider another example that demonstrates a function to retrieve data from a database table:
public class Class1
{
SqlConnection Sqlcon=null;
public void CreateConnection(String ConnString)
{
Sqlcon = new SqlConnection(ConnString);
}
return dset;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (Sqlcon.State == ConnectionState.Open)
{
Sqlcon.Close();
Sqlcon = null;
Sqlda = null;
dset = null;
}
}
}
}
Summary
In this chapter, you learned that:
You can implement data access logic in the presentation layer (ASP.NET pages) by
using:
o
o
Data Source Controls: Allow you to work with different types of data sources by
acting as a bridge between the application and the data sources.
ADO.NET: Allows you to write flexible data access code.
The basic objects used to access data from a database by using ADO.NET are:
o
o
o
Presentation Layer
Business Rules Layer
Database Access Layer
Connection Objects
Command Objects
Data Reader Objects
DAL is a layer of code that provides simplified access to the data stored in persistent
storage such as a database.
Reference Reading
Identifying the Basics of Data Access in Web Applications
Reference Reading: Books
http://www.asp.net/learn/withpss/module5.aspx
Chapter 7
Objectives
In this chapter, you will learn to:
Identify the basics of LINQ
Access data from disparate data sources by using LINQ
In a LINQ query operation, the first step is to specify the data source. The data source in a
LINQ query can be an XML file, an array, a collection, or a database. If the data source that
you want to use is an array, you can specify the data source by using the following statement:
string[] customers = new string[2] {John, Mary};
In the preceding statement, the XElement object, customers, is the data source.
After specifying the data source, you need to create a query expression to retrieve or
manipulate data from the specified data source.
Creating the Query
A query describes what information is to be retrieved from the specified data source. It must
include the from and select clauses to retrieve data. The from clause specifies the data
source from where the data is to be retrieved and the select clause specifies the type of the
returned elements. Consider the following query:
var query = from <type of the value returned> cus in customers
select cus;
The preceding query contains the from and select clauses. The from clause specifies the
range variable cus and the data source Customers, and the select clause specifies the type
of the values that will be returned by the query. The query is stored in a query variable,
query. It is initialized with a query expression.
Note
The range variable acts as an iteration variable in a foreach loop. When the query is
executed, the range variable is served as a reference of each item stored in the data source,
such as a database.
Note
The var keyword is a new keyword that can infer its data type from the resulting set. A var
type variable needs to be initialized at the time of declaration. The var keyword cannot be
used when declaring the member variables of a class. Consider the following examples:
var one = 1; //infers an int
var two = "2"; // infers a string
var five = null; // This results in a compilation error because //the data
type is not specified in the Right hand side.
In LINQ, the query variable only stores the query. The actual execution of the query is
deferred until the query variable is iterated by using the foreach loop. The foreach loop is
the place where the query results are retrieved. Consider the following code snippet:
//Query execution
foreach (var cus in query)
{
Response.Write(cus);
}
In the preceding code snippet, the iteration variable cus holds each value, one at a time, in the
same sequence as returned by the query.
The query variable only stores the query that is to be executed. Therefore, you can execute
the query variable as many times as you want. It is useful in situations where the database is
constantly updated. In such a situation, you can create a query variable and execute it at some
interval to retrieve the updated data.
The execution of all the queries is not deferred till query variable is iterated by using the
foreach loop. The queries that perform aggregate functions such as Max and Count over a
range of source elements must first iterate over those elements. Such queries execute without
explicitly using the foreach loop. This is because such queries itself use the foreach loop in
order to return the result. These queries return a single value. Consider the following
example:
In the preceding example, the foreach loop has not been used to execute the query. It gets
executed automatically when the Count function is used.
Consider the following example in which the LINQ query is used to retrieve data from an
ArrayList object:
public partial class Default : System.Web.UI.Page
{
public class customer
{
public string Name { get; set; }
public string City { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
ArrayList arrList = new ArrayList();
arrList.Add(
new customer
{
Name = "Svetlana", City = "London"
}
);
arrList.Add(
new customer
{
Name = "Claire", City="Paris"
}
);
arrList.Add(
new customer
{
Name = "Cesar",
City="New York"
}
);
var query = from customer cus in arrList
select cus;
foreach (var cus in query)
{
Response.Write (cus.Name + "
lives in
" + cus.City
+ "<br>");
}
}
}
In the preceding example, a class customer with two properties, Name and City, is created.
After creating the class, an object of the ArrayList class is created and three objects of the
type customer are added to the ArrayList object. The ArrayList object is the data source
from which the data is retrieved by using the LINQ query. The LINQ query retrieves all the
data from the data source.
Using LINQ Queries to Filter, Sort, Group, and Join Data
In addition to selecting data, a query can perform the following operations on data:
Filtering
Ordering
Grouping
Joining
Filtering
To retrieve data depending on certain criteria or condition, you need to filter the data.
Filtering causes the query to return only the data that matches with the specified condition.
The condition to retrieve data can be specified by using the where clause. For example, the
following code snippet returns the data of the customers who live in London:
var query = from <type of the value returned> cus in customers
where cus.City == "London"
select cus;
You can also use the logical operators in the where clause to apply two or more conditions.
For example, the following code snippet returns the data of the customers who live in London
and have last name as Darcy:
var query = from <type of the value returned> cus in customers
where cus.City == "London" && cust.Name == "Svetlana"
select cus;
Ordering
LINQ queries can also be used to retrieve data and display it in a sorted manner. This can be
done by using the orderby clause. The orderby clause enables a user to sort the retrieved
data in ascending or descending order. For example, the following code snippet returns the
data for the customers who live in London. The data is sorted by customer names in
alphabetical order:
var query =
from <type of the value returned> cus in customers
where cus.City == "London"
orderby cus.Name descending
select cus;
Note
The default value for the orderby clause is ascending.
Grouping
You can also retrieve data and group it by using the group clause. For example, the following
code snippet returns the data for all the customers, grouped on the basis of the cities they live
in:
var query = from <type of the value returned> cus in customers
When you end a query with a group clause, the results take the form of a list of lists. Each
element in the list is an object that has a Key member and a list of elements that are grouped
under that key. When you iterate over a query that produces a sequence of groups, you must
use a nested foreach loop. The outer loop iterates over each group, and the inner loop iterates
over each member of the group. For example, to execute the preceding query and to display
the results, you need to use nested foreach loops as shown in the following code snippet:
foreach (var cus in query)
{
foreach (var i in cus)
{
Response.Write(i.Name + "
lives in
" + i.City +
"<br>");
}
}
Joining
It is possible that the data you need to retrieve exists in more than one table/object. For
example, you need to retrieve information regarding the orders placed by a customer. The
information regarding the customers is stored in the customers table/object and the
information regarding the orders is stored in the orders table/object. Both the tables/objects
must have a common field, which is required to join the tables/objects. To retrieve the
required information, you need to join the data from both the tables/objects. This can be done
by using the join clause, as shown in the following code snippet:
var query = from <type of the value returned> cus in customers join
<type of the value returned> ord in Order on cus.order_id
equals ord.order_id
Select new {CustomerName=cus.Name,
OrderAmount=Order.Amount};
In the preceding code snippet, two ArrayList objects customers and Order are the data
sources. These ArrayList objects contain information about the cutomers and the orders
placed by them. Both the objects have a common field order_id, which is required to join
data from these objects. The data from the preceding query can be retrieved by using the
following foreach loop:
foreach (var cus in query)
{
Response.Write(cus.CustomerName + " has the order amount " +
cus.OrderAmount + "<br>");
}
Objects
Databases
XML files
In the preceding code snippet, a range variable cust is of the type customers. By declaring a
range variable, each item in the ArrayList is typecasted to a customers object.
The following example describes how to access data from a string array that contains the
names of students in a class:
string[] arr = new string[] { "Peter", "Sam" , "Philip"};
var query = from string person in arr
select person;
foreach (var p in query)
{
Response.Write(p + "<BR>");
}
LINQ to dataset
LINQ to SQL
LINQ to Dataset
A Dataset is a collection of cached data presented in a tabular form. The data from a Dataset
can be retrieved by using LINQ. LINQ to Dataset is basically used in situations where you
have used ADO.NET for accessing data from a database. Now, you want to implement LINQ
queries in the application to get the benefits such as compile time checking of the query
syntax and better performance. However, you want minimal changes in the coding. In such a
situation, you can use LINQ to ADO.NET because by using LINQ to ADO.NET, you just
need to change the data retrieval code that was used to access data from the Dataset. The rest
of the code will remain the same.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection MyConn = new SqlConnection();
MyConn.ConnectionString = "Data Source=172.23.3.59;Initial
Catalog=Music;User Id=sa; Password=password@123";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from
albums",MyConn);
MyConn.Open();
da.Fill(ds);
DataTable album= ds.Tables[0];
var q = from d in album.AsEnumerable()
select d;
foreach (var i in q)
{
Response.Write(i.Field<string>("Album_Name") + "<br>");
}
}
In the preceding example, LINQ to Dataset is used to retrieve data from the Dataset and
display it on the Web page. Notice the use of the AsEnumerable() method. It changes the
compile time type of a query to IEnumerable<T>. This means that the type can be used in a
foreach loop.
LINQ to SQL
LINQ to SQL provides a run-time infrastructure for managing relational data as objects. In
LINQ to SQL, the data model of a relational database is mapped to an object model created
by the developer. While querying data by using LINQ to SQL, it translates the languageintegrated queries in the object model defined by the developer and sends the data to the
database for execution. The database returns the result, and LINQ to SQL translates the result
back into the form of objects that can be used in a programming language to query data. This
helps in integrating the object-oriented features such as classes and methods with SQL. The
methods written to query data can be reused in any application because these methods are
generic.
In addition, IDE such as Microsoft Visual Studio provides the Object Relational Designer
(O/R designer), which provides a visual designer surface for creating LINQ to SQL entity
classes and relationships that are based on objects in a database.
LINQ to SQL entity classes are also used by the ASP.NET Dynamic Data to determine the
user interface that is based on the LINQ to SQL data model. ASP.NET Dynamic Data is a
framework that enables a user to create data-driven ASP.NET Web applications with minimal
or no coding. ASP.NET Dynamic Data does this by automatically discovering data-model
metadata at run time and rendering the user interface according to it. The data-driven
ASP.NET Web applications created by using ASP.NET Dynamic Data provides:
Data access operations such as create, update, remove, and display, relational
operations, and data validation.
Built-in support for foreign-key relationships.
The ability to customize the user interface rendered to display and edit specific data
fields.
The ability to customize data field validation.
To access the data from the CustomersDetails.Xml by using LINQ, you need to write the
following code snippet:
XDocument xmlDoc = XDocument.Load("D:\\Website7\\XMLFile2.xml");
var q = from c in xmlDoc.Descendants("Customer")
select (string)c.Element("CustomerID") + "-" + (string)c.Element("Name")+"" + (string)c.Element("City")+"<br>";
foreach (string name in q)
{
Response.Write(name);
}
Description
ContextTypeName
TableName
DeleteParameters
Delete
InsertParameters
Insert
SelectParameters
Select
UpdateParameters
Update
In the preceding example, the ContextTypeName attribute sets the name of the type that
contains the property that provides the data. The TableName attribute sets the name of the
table in the data context object that represents a data collection.
Summary
In this chapter, you learned that:
LINQ provides a standard way to access data from disparate data sources.
When accessing data by using LINQ, you need to perform the following steps:
o
o
o
LINQ provides a standard query for retrieving data from disparate data sources.
LINQ queries can be used to access data from:
o
o
o
Objects
Databases
XML files
You can also use the LINQ data source control to access data from disparate data
sources.
Reference Reading
Identifying the Basics of LINQ
Reference Reading: Books
http://www.develop.com/course/new-net3-net35-linq
Professional ASP.NET
3.5: In C# and VB by Bill
Evjen, Scott Hanselman,
Devin Rader
http://www.develop.com/course/new-net3-net35-linq
Chapter 8
Objectives
In this chapter, you will learn to:
Handle and log errors
Debug Web applications
Handling Errors
Page Level
Application Level
You can place the statements susceptible to errors in a try-catch block. It is an error handling
feature provided by most of the languages. It enables you to programmatically handle the
errors that occur at runtime. The try block contains the code that may cause an exception. It
is followed by one or more catch blocks, which specify the code for handling the exception.
To handle errors properly, you need to retrieve information about the type and cause of the
error and then handle the error. You can retrieve error information by using a try block and
handle the error by using the catch block.
The exceptions that occur in a Web application are inherited from the Exception class. The
properties included in the Exception class help you handle errors easily and efficiently. You
can use the following properties of the Exception class to handle errors:
Consider the following example. It uses the preceding properties to handle an error that can
occur while opening a database connection:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat=server>
void Page_Load(Object sender , EventArgs e)
{
SqlConnection mycon;
SqlCommand mycommand;
mycon = new SqlConnection(
@"Server=localhost;Database=SimpleCon;Connection Timeout=15" );
mycommand = new SqlCommand( "select * from Products", mycon );
try {
mycon.Open();
dgrdProducts.DataSource = mycommand.ExecuteReader();
dgrdProducts.DataBind();
mycon.Close();
}
catch (Exception objException)
{
//Exception objException;
Response.Write("Sorry we are experiencing technical
problems...");
Response.Write("<hr>");
Response.Write("<li> Message: " + objException.Message);
Response.Write("<li> Source: " + objException.Source);
Response.Write("<li> Stack Trace: " +
objException.StackTrace );
Response.Write("<li> Target Site: " +
objException.TargetSite.Name);
}
}
</script>
<html>
<head><title>CatchException.aspx</title></head>
<body>
<asp:DataGrid
ID="dgrdProducts"
Runat="Server" />
</body>
</html>
In the preceding example, if an error occurs within the try block, statements in the catch
block are executed and detailed information about the error is displayed. The Exception
object used in the catch block represents a generic exception. The catch block can also be
used to capture particular exceptions such as InvalidArgumentException or
IndexOutOfRangeException. This is required if specific information on the cause of error is
needed.
You can include the finally block in a try-catch block for cleaning up the resources. The
finally block always executes, irrespective of whether or not an exception has occurred. For
example, you can use the finally block to close a database connection, as shown in the
following code snippet:
try
{
DgrdProducts.DataSource=mycommand.ExecuteReader();
DgrdProducts.DataBind();
}
catch(Exception objException)
{
Response.Write("Could Not Execute Statement");
}
finally
{
// closing the connection to the database
mycon.Close();
}
In the preceding code snippet, the finally block closes the database connection even if no
exception is caught.
It is not always possible to anticipate and handle all the errors that may occur on a page.
Many unexpected errors can occur while the application is running in a real-world
environment. To handle such errors, you should include the Page_Error subroutine in the .cs
file for the page. This subroutine executes in case an unhandled exception occurs on a page.
For example, you can use the Page_Error subroutine to display an error message, as shown
in the following code snippet:
void Page_Error (Object sender , EventArgs e) {
Response.Write( "Sorry, an error was encountered:" );
Response.Write( "<p>" );
Response.Write( Server.GetLastError().Message);
Server.ClearError();
}
In the preceding code snippet, the GetLastError() method of the Server object returns the
previous exception that had occurred in the page. The ClearError() method is used to clear
the error message. Clearing an error means that it has been handled. Once you have cleared
the error, it is not passed to any higher level error handler such as the Application_Error
event.
Application-Level Error Handling
When a user accesses an ASP.NET Web application from a Web browser and an error
occurs, the default error message is displayed to the user. However, it is not a good
programming practice to display the default error message to the user. You can use the
<customErrors> element of the web.config file to control the details of the error information
made available to the users of ASP.NET applications.
By using the <customErrors> element, you can either completely hide the error information
from the users or display customized error messages. You can also redirect users to an
appropriate error page in case an unhandled error occurs.
Note
The <customErrors> element will work when you start the application without debugging
support.
Consider the following example in the web.config file:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx">
</customErrors>
</system.web>
</configuration>
In the preceding example, the following two attributes of the <customErrors> element have
been set:
mode:
Specifies the mode for handling custom errors. The mode attribute can be set to
any of the following values:
o
o
Off: Disables the display of custom error messages. The default error message is
Note
Local users are the developers who are working on the same computer on which the
Web application is deployed. Remote users are those users who are accessing the
Web application from a computer other than the one on which the website is
deployed.
defaultRedirect:
The preceding example displays a single error page for all types of errors. However, it is
possible to display different error pages for different types of errors by including <error>
elements within the customErrors section. Consider the following example:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="PageNotFound.aspx" />
<error statusCode="408" redirect="SessionTimeedOut.aspx" />
</customErrors>
</system.web>
</configuration>
In the preceding example, if an error with the status code 404 occurs, the user will be
redirected to the error page, PageNotFound.aspx. If an error with the status code 408 occurs,
the user will be redirected to the error page, SessionTimedOut.aspx. However, if an error
with any other status code occurs, the user will be redirected to the default error page,
Error.aspx.
Using the Application_Error Subroutine
Application-level errors can also be handled in the event handler for the Application.Error
event that occurs whenever an unhandled error occurs in an application. The event handler
for this event is written in the Global.asax file. You can use this event handler to capture the
errors for logging or notification.
This event handler is similar to the Page_Error event handler. The only difference is that it
operates at the application level.
Consider the following code snippet:
protected void Application_Error(Object sender, EventArgs e)
{
Response.Redirect("ErrorPage.aspx");
}
In the preceding code snippet, the Application_Error event handler redirects the user to the
ErrorPage.aspx page in case an error occurs anywhere in the Web application.
Logging Errors
It is possible that certain unexpected errors occur in a Web application while it is running in a
real-world environment. It would be easy to resolve such errors if a log of these errors is
maintained. ASP.NET enables you to log unhandled errors in an event log, database, or some
other file. These event logs, databases, or files can be used by the administrator to learn about
the errors that are occurring in a Web application. You can log information about all the
errors whether they occur at the page-level or at the application-level.
To log errors occurring in an application, you need to create a log for the application in the
event log. Whenever an unhandled error occurs in a Web application, the
Application_Error event handler, written in the Global.asax file, is executed. Therefore,
the event logging code can be written in the Application_Error event handler.
A log can be created by using the EventLog class of the .NET Framework. For using this
class, you need to import the System.Diagnostics namespace.
The following table describes the various properties of the EventLog class.
Property
Description
Entries
Log
Source
Description
Exists
CreateEventSource
WriteEntry
<system.web>
<compilation debug="true" />
</system.web>
</configuration>
However, if you want to debug only a single page in your Web application, you can add the
debug attribute and set its value to true in the @ Page directive of the page that you wish to
debug, as shown in the following markup:
<%@ Page debug="true" %>
Application execution becomes slow when debugging is turned on. For this reason,
debugging has to be turned off before the deployment of the Web application. To disable the
debug mode, set the debug attribute to false in the <compilation> element of the
web.config file, as shown in the following markup:
<compilation defaultLanguage="C#" debug="false" />
Features of Debugging
Debugging allows you to run your code line by line to monitor the program execution. You
can check the state of the application objects such as variables and database table values to
ensure that the application is running properly. A debugger includes the following features
that help you debug Web applications:
Breakpoints: Breakpoints are places in the code where the debugger stops the
execution of the Web application. This allows you to view the current state of data in
your Web application. You can step through each line of code when executing the
Web application.
Stepping: Once the execution of the Web application has been stopped at a
breakpoint, you can execute the code line by line, which is known as stepping through
the code.
Data Viewing: This feature allows you to view and track data while the Web
application is running. It also allows you to modify data while the execution of the
Web application is stopped at a breakpoint. You can then continue to run the
application with the modified data.
Debugging enables you to observe and change values of variables and objects in your
application code. You can get a close look at what your code does by using the debugger.
Summary
In this chapter, you learned that:
The page-level error can be handled either by using the try-catch block or by using the
Page_Error subroutine.
Application-level error handling enables you to handle errors on ASP.NET pages,
irrespective of where they occur in the application.
The application-level error can be handled either by using the <customErrors>
element in the web.config file or by using the Application_Error subroutine in the
Global.asax file.
ASP.NET enables you to log unhandled errors in an event log, database, or some
other file.
An event log can be created by using the EventLog class of the .NET Framework.
Debugging is the process of finding and fixing errors in an application.
There are various tools available that help you debug your Web application. One such
tool is Visual Debugger, available in Visual Studio IDE.
The features of a debugger that help you debug Web applications are:
o
o
o
Page Level
Application Level
Breakpoints
Stepping
Data Viewing
Reference Reading
Handling and Logging Errors
Reference Reading: Books
eference
Reading: Books
Beginning
ASP.NET 3.5 in
VB 9.0: From
Novice to
Professional by
Matthew
MacDonald
http://www.informit.com/articles/article.aspx?p=29419
Chapter 9
Objectives
In this chapter, you will learn to:
Implement Web parts in a Web application
Consume Web services in a Web application
Web parts enable users to personalize the content of a Web page. Users can move or
hide Web parts to customize the Web page. They can even add new Web parts to
change the layout of the page.
Web parts can be assigned role-based access, thereby, determining which Web part
can be shared by all users or which should be hidden for certain roles. This helps in
providing customized content based on security.
Web parts can be connected to each other. One of the connected Web parts is defined
as a provider and the other as a consumer. Consider the example of a Web parts page
that contains two Web parts, one displays a chart and another displays the stock
market data. These Web parts can be connected in such a way that the chart Web part
displays the chart for the stock market data present in the other Web part. In this
example, the Web part providing the stock market data is the provider and the Web
part displaying the chart is the consumer.
Browse: This is the default mode. This mode allows users to view Web parts on the
Web page. It also allows users to minimize or close the Web part. If you close a Web
part, it cannot be restored from the Browse mode. However, you can restore it in
another mode called the Catalog mode. The following figure shows a Web part in the
Browse mode.
Edit: This mode allows users to edit Web parts on the Web page at runtime. Users
can set the title, color, or custom properties of the Web parts.
Design: This mode allows users to rearrange the order of Web parts on the Web page
by dragging and dropping them.
Catalog: This mode allows users to add new Web parts on the Web page. It also
allows users to rearrange or delete the existing Web parts from the Web page.
Connect: This mode allows users to connect two Web part controls on a Web page.
Note
A Web page can be displayed in only one display mode at a time.
Description
WebPartManager
CatalogZone
WebPartZone
ConnectionsZone
CatalogPart
Connection
EditorPart
{
wpm.DisplayMode = mode;
}
The preceding code snippet, enables a user to change the mode of the Web parts present on
the Web page by selecting the edit mode from the DropDownList control.
2. Create the consumer Web part as a custom control that derives from the WebPart
class and defines a connection point in the form of a method to which the
ConnectionConsumer attribute has been applied.
3. Add the Web parts to the Toolbox.
4. Add the Web part controls from the Toolbox to a Web parts page and assign an ID
and title to each of the two controls.
5. Add the connection information to the WebPartManager control by opening the Web
parts page in the Source view and adding a <staticConnections> element inside the
<asp:WebPartManager> element, as shown in the following example:
<StaticConnections>
<asp:WebPartConnection ID="wpCon" ProviderID="Provider1"
ProviderConnectionPointID="Color" ConsumerID="Consumer1"
ConsumerConnectionPointID="Color" />
</StaticConnections>
Note
SOA is software architecture, which is essentially a collection of services communicating
with each other. It was developed for enabling the development of loosely-coupled distributed
applications.
Note
Coupling refers to the interrelatedness and interdependency between two or more
components of a Web application. In loosely-coupled distributed applications, it is possible to
change one component without affecting other components.
Web services allow integration of applications developed in different languages and running
on different platforms. This integration and interoperability in Web services is made possible
with the use of XML. Web services communicate by using a standard protocol called SOAP.
SOAP defines a standard way of passing the XML-encoded data.
Developing ASP.NET Web services starts by creating an .asmx file and hosting it on a Web
server, such as IIS. Once hosted or published on the server, a Web service can be consumed
by any client. The client can be a Web application, desktop application, console application,
or another Web service based on .NET or other platforms such as Java.
The client, who has to consume a Web service, locates the service by adding a Web
reference. This adds a proxy class on the client side, which exposes the methods, parameters,
and return types of the methods contained in the Web service. After adding the proxy class,
the client application creates an instance of the proxy class and accesses the methods
provided by the Web service through the instance.
The client requests are then handled by the proxy class. It transforms the method calls of the
client into the SOAP message format, which can be transmitted over HTTP to the server.
After processing the request, the response is also sent as a SOAP message to the proxy. The
proxy then converts this SOAP message into method return value, which is returned to the
client.
ASP.NET Web Services (ASMX): It provides support and interoperability with Web
services running on non-Windows platforms.
WSE: It provides end-to-end standards-based security for Web services.
System.Messaging: It is a namespace in the .NET Framework that provides managed
APIs to Microsoft Message Queues (MSMQ), enabling developers to build
asynchronous reliable distributed applications.
Enterprise Services: It provides managed APIs to COM+. COM+ provides
component-based programming for functionality such as transactions.
Remoting: It exposes the Common Language Runtime (CLR) type system remotely
and provides location transparency for objects. Remoting is designed for tightly
Note
In tightly coupled applications, the components are interconnected with each other such that
any change in one component will lead to changes in other components as well.
Note
A WCF Service is a program that exposes a collection of Endpoints. An Endpoint is used for
communicating with other services and applications. An Endpoint has an Address, a Binding,
and a Contract. An Endpoint address is the address where the service listens. The Endpoint's
Binding specifies how the Endpoint communicates with other services and applications. The
Endpoint's Contract specifies what the Endpoint communicates. A WCF Endpoint can be
configured by using the <system.serviceModel> element.
The design goals for building WCF services are:
Summary
In this chapter, you learned that:
A Web part is a modular unit that can contain any type of Web-based information.
The advantages of using Web parts on a website are:
o Web parts enable users to personalize the content of a Web page.
o Web parts can be assigned role-based access, thereby determining which Web
parts can be shared by all users or which should be hidden for certain roles.
o Web parts can be connected to each other.
The different types of display modes of a Web part are:
o Browse mode
o Edit mode
o Design mode
o Catalog mode
o Connect mode
A Web page that is composed of Web parts is known as a Web parts page.
A Web parts page is divided into zones that provide the structure for placing Web
parts.
A Web service is a self-describing Web component that exposes its functionality to
the consumers through open standards such as XML and Simple Object Access
Protocol (SOAP).
Windows Communication Foundation (WCF) aims at providing encoding, hosting,
messaging patterns, networking, security, and interoperability in a single
infrastructure.
Reference Reading
Implementing Web Parts in a Web Application
Refer Reference Reading: URLs
ence
Read
ing:
Book
s
Pro
ASP.
NET
3.5 in
C#
2008
by
Matt
hew
Mac
Dona
ld,
Mari
http://www.hotscripts.com/Detailed/79303.html
http://books.google.co.in/books?q=Implementing+Web+Parts+in+a+Web+Applicat
ions+in+ASP.NET+3.5&source=in&sa=X&oi=book_group&resnum=11&ct=title&
cad=bottom-3results
o
Szpus
zta
Consuming Web Services in a Web Application
Referenc Reference Reading: URLs
e
Reading:
Books
Beginnin
g
ASP.NET
3.5: In
C# and
VB by
Imar
Spaanjaa
rs
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-webservices/
http://www.codedigest.com/Articles/ASPNET/52_ASPNET_35_AJAX_and_WebS
ervices__.aspx
Chapter 10
Objectives
In this chapter, you will learn to:
Explain the AJAX framework
Identify the ASP.NET AJAX server controls
Identify the ASP.NET AJAX client life-cycle events
Consume Web services in AJAX-enabled applications
The user interaction with the application is interrupted every time a postback is made
by the server.
The user has to wait during each postback.
The full page is rendered and transferred to the client after each postback, which is
time consuming and traffic intensive.
and the server becomes asynchronous. This allows users to interact with the Web application
while waiting for a response from the server. In addition to this, AJAX implementation
enables partial updates in Web applications. This means that instead of sending the entire
page, only the portion that needs to be updated is sent to the server.
Understanding AJAX
AJAX is a Web development technique that is used to create dynamically interactive
applications. It enables Web applications to retrieve data from the server, asynchronously in
the background, without interfering with the display and behavior of the existing page. To
understand the concept of AJAX, you need to understand the relevance of the following
terms:
To understand the behavior of a Web application that implements AJAX, you need to
understand the role of AJAX in a Web application and how it helps the server to quickly
respond to the client.
Quick response to a users request. This is due to partial-page updates feature that
refreshes only those parts of a Web page that have changed or updated. In addition,
partial-page updates feature enables an application to use less bandwidth because only
the those parts of a Web page that have changed or updated are sent to the server.
Asynchronous communication that allows a user to interact with the rest of the Web
page while the application is processing the changed or updated parts of the Web
page.
Auto-generated proxy classes that are used to call Web service methods from client
script such as JavaScript.
Support for the widely used Web browsers such as Microsoft Internet Explorer,
Mozilla Firefox, and Apple Safari.
AJAX-enabled Web applications also have a few limitations. Some of them are:
Browser Integration: The AJAX-enabled Web application does not register the
dynamically-created Web page in the Web browsers history engine. This restricts a
user to view the previous look of the page when he or she triggers the back button of
the Web browser. In addition, a user is not able to bookmark a particular state of the
Web application.
You can create AJAX-enabled Web applications by using the .NET Framework. The .NET
Framework enables you to create rich and intuitive websites by providing support for AJAX
features. It provides a set of extensions to ASP.NET for implementing AJAX functionality.
This set of extensions is known as ASP.NET AJAX. To create AJAX-enabled Web
applications by using the .NET Framework, you need to understand the ASP.NET AJAX
architecture.
Components
Browser compatibility
Networking
Core services
Components
The client components enable a Web application to render dynamic behavior to the Web
browser without requiring a postback to the Web server. There are various client components
such as non-visual objects and controls. Non-visual objects, such as a timer object,
encapsulate the code that needs to be repeated after a fixed interval.
Browser Compatibility
The browser compatibility feature provides compatibility for client scripts with major Web
browsers, such as Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari. This
feature makes your Web application browser-independent.
Networking
The ASP.NET AJAX client architecture provides the networking layer between the client and
the server. This layer is used to handle the communication of scripts with the Web services
and the application services. It is also used to handle asynchronous calls to the methods or
services at the remote locations.
The networking layer automatically handles partial-page updates for the UpdatePanel control
in your Web application. It also allows Web applications to access the server-based forms
authentication, role information, and profile information in a client script. The Web
applications that are not created by using ASP.NET can also use the networking layer if they
have access to the Microsoft AJAX library.
Core Services
The ASP.NET AJAX client architecture provides various core services, such as JavaScript
base class extensions, support for JavaScript libraries, debugging, error handling, and
globalization. The JavaScript libraries are either embedded in the assemblies or provided as
standalone JavaScript files with the .js extension.
The core services also include the Sys.Debug class to handle debugging in your Web
application. In addition to the Sys.Debug class, the core services also include the Error object
for handling errors in your Web application. The Error object provides support for the release
mode and the debug mode of the Web application.
Note
In the debug mode, the debug information is generated, which is used for rectifying the errors
in the code. It is used at the time of development of an application. In the release mode, the
debug information is not generated. It is used at the time of deployment of an application
because it is much faster than the debug mode.
Server-Based AJAX Features for ASP.NET
The ASP.NET AJAX server architecture provides the functionality for the following serverbased AJAX features:
Script support
Web services
Application services
Server controls
Script Support
AJAX features in an ASP.NET application can be implemented with the support of client
scripts. These client scripts are sent from the Web server to the Web browser when the
application is requested for the first time. These client scripts provide the following features:
You can also create your own custom client scripts for the AJAX-enabled Web applications.
The custom client scripts can be saved as static files or can be embedded in an assembly with
.js extension.
Web Services
An AJAX-enabled Web application can call ASP.NET Web services (.asmx) and WCF
services (.svc) by using client scripts. An AJAX-enabled Web application can call the Web
services without a postback. When a user requests for a Web page for the first time, the proxy
class is automatically generated by the server and downloaded to the browser at the page-load
time. This proxy class can be used to call the corresponding Web service methods.
Application Services
The application services are the predefined Web services that are based on certain features
provided by ASP.NET such as forms authentication, roles, and user profiles. The ASP.NET
forms authentication is performed to verify credentials, such as login id and password, of the
users. The ASP.NET roles are used to group multiple users under one role, such as grouping
all the heads of each department in an administrator role. The profile of a user consists of the
information such as background and foreground colors of the application that is set when the
user logs on to the application.
The application services can be called by various clients, such as a client script in an AJAXenabled Web page, a WCF-compatible client, or a Windows application.
Server Controls
The ASP.NET AJAX server controls consist of server-side script as well as client-side script.
This allows a Web application to provide rich client behavior. A Web page that consists of
AJAX server controls sends supporting client script to a Web browser while it is rendered to
a user to provide AJAX functionality on the Web page. The AJAX functionality include
partial-refreshing of the Web page, asynchronous communication between the Web browser
and the Web server, and faster response to the user.
ScriptManager control
ScriptManagerProxy control
UpdatePanel control
UpdateProgress control
Timer control
The custom scripts that you need to send to the Web browser to enable asynchronous
communication with the Web service and partial-page refreshes.
The JavaScript classes that are used to access the ASP.NET application services for
forms authentication, roles, and user profiles.
The JavaScript proxy classes that are used to call Web service methods from the
client script.
The ScriptManager control can be added to a Web page by using the following markup:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
Description
AsyncPostBackErrorMessage
AsyncPostBackTimeout
EnablePageMethods
EnablePartialRendering
Description
Scripts
Services
The preceding markup adds an UpdatePanel server control with a unique ID UpdatePanel1 to
the Web page.
The following table describes some properties of the UpdatePanel control.
Property
Description
ChildrenAsTriggers
UpdateMode
RenderMode
Description
AssociatedUpdatePanelID
status of update.
DisplayAfter
DynamicLayout
Periodical updates of one or more UpdatePanel controls without refreshing the entire
Web page.
Execution of the code at the server each time the Timer control causes a postback.
When the tick event of the Timer control is raised, it causes a postback and the code
written under the tick event handler is executed. For example, a part of a website that
displays the score of a cricket match is updated after every one minute. The code for
updating the score can be written under the tick event handler of a timer control so
that it executes after the set time interval.
Synchronous postback of the entire Web page to the Web server at predefined time
intervals.
The Timer control embeds a JavaScript component into the Web page. The JavaScript
component initiates the postback from the Web browser to the Web server, every time the
predefined time interval has lapsed. When the postback is initiated, the Timer control raises
the Tick event on the server. To handle the Tick event, you can add an event handler that
performs certain predefined actions in response to the event.
You can place multiple Timer controls on a Web page. You can associate each Timer control
with a different UpdatePanel control. However, you can also place one Timer control on the
Web page and associate it with all the UpdatePanel controls.
You can add a Timer control to a Web page by using the following markup:
<asp:Timer ID="Timer1" runat="server"> </asp:Timer>
The preceding code adds a Timer server control with a unique ID Timer1 to the Web page.
Description
Enabled
Interval
you to bind the events to the controls and provide handlers for those events. For example,
when an UpdatePanel control is added to a Web page, the events of the
PageRequestManager class are raised. These events can be used to cancel postback or to
provide preference to one postback over the other. These events can also be used to animate
the UpdatePanel control when the content in the control is refreshed.
Description
Sys.Application.init
Sys.Application.load
Sys.Application.unload
Sys.Component. propertyChanged
Description
Sys.WebForms.PageRequestManagerpageLoading
Sys.WebForms.PageRequestManagerpageLoaded
Sys.WebForms.PageRequestManagerendRequest
Note
An executor is a component that functions as an interface between a client Web request and
the network or other media. You can write your own executor that plugs into the
asynchronous communication layer.
Inline script
External java script file
Script embedded as a resource in an assembly
Inline Script
An inline script can be created as a script block in a Web page. A script block is defined in a
Web page as an HTML markup. The following code snippet shows how you can define a
script block in a Web page:
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="Default.aspx.cs"
function HelloWorld()
{
alert(Hello World!);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Hello"
onclick="HelloWorld()" />
</div>
</form>
</body>
</html>
In the preceding code snippet, a script block is defined that consists of a function,
HelloWorld. When a user clicks the Hello button on the Web page, the HelloWorld
function is called and an alert box showing the Hello World! Message is displayed.
An inline script is not registered in an AJAX-enabled ASP.NET application because the
script block is defined in a Web page only.
External Java Script File
You can also add a reference of an external java script file in an AJAX-enabled ASP.NET
application. To add the reference, you need to add the java script file in your Web
application. After adding the java script file, you need to set the src attribute of the script
element of the Web page to the name of the java script file.
The following code snippet is written in a java script file, JScript.js:
function HelloWorld()
{
alert(Hello World!);
}
In the preceding code snippet, a function HelloWorld is created and an alert message, Hello
World!, is defined.
The highlighted part of the following code snippet shows how you can set the src attribute of
the script element of the Web page to a java script file:
<%@ Page Language="C#" AutoEventWireup="true"
Inherits="_Default" %>
CodeFile="Default.aspx.cs"
</form>
</body>
</html>
In the preceding markup, a java script file, JScript.js is specified in the src attribute of
the script element of the Web page. When a user clicks the Hello button, the function
HelloWorld defined in the java script file is called and an alert message box showing the
message, Hello World!, is displayed.
Script Embedded as a Resource in an Assembly
You can also add a custom client script in a web page by using the ScriptManager control.
Such a client script consists of a java script file that is embedded as resources in an assembly.
The java script that is embedded in an assembly acts as a Web resource. For example, you are
creating a custom control that consists of a java script file. This file can be embedded as a
Web resource in the assembly of the custom control.
To access such a java script file, an HTTPhandler WebResource.axd is used by the ASP.NET
application. This handler retrieves assembly resources and serves them to a Web browser. To
access the assembly resources using a ScriptManager control, you need to add the reference
of the assembly and the java script file as shown in the following markup:
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<scripts>
<asp:ScriptReference Assembly="ClassLibrary"
Name="ClassLibrary.JScript1.js" />
</scripts>
</asp:ScriptManager>
In the preceding markup, a ScriptManager control is defined. A reference of the assembly and
the java script file is added in the scripts tag of the ScriptManager control.
Most client-side code is added at design time. However, it can also be generated and added in
the Web page at run time by using the System.Web.UI.ClientScriptManager class.
Consider the following code snippet:
protected void Page_Load(object sender, EventArgs e)
{
string str="return confirm(Do you want to submit the
page?)";
ClientScript.RegisterOnSubmitStatement(this.GetType(),"ABC",
str);
}
To manage, register, and add a script to a Web page, you need an object of the
ClientScriptManager class. In the preceding code snippet, the ClientScript property of
the Page object has been used to obtain a ClientScriptManager object. The
RegisterOnSubmitStatement method registers an OnSubmit statement with the Page
object.
In RegisterOnSubmitStatement (Type type, String key, String script) method:
The type parameter defines the type of the control that is registering the OnSubmit
statement.
The key parameter defines a key that uniquely identifies the script statement.
The script parameter defines the script literal for the OnSubmit statement.
Note
A custom client script can also be used to add AJAX functionality into a server control. To
provide AJAX functionality in a server control, you need to embed the JavaScript file as a
resource in the assembly that is created when the server control is precompiled.
Summary
In this chapter, you learned that:
AJAX enables Web applications to retrieve data from the server, asynchronously in
the background, without interfering with the display and behavior of the existing
page.
AJAX includes the following terms:
o
o
o
ScriptManager control
ScriptManagerProxy control
UpdatePanel control
UpdateProgress control
Timer control
Client events are raised when a user interacts with an ASP.NET AJAX-enabled
application.
Client events are raised by the classes present in the Microsoft AJAX Library.
The two main Microsoft AJAX Library classes that raise events are:
o
o
Browser Integration
Dependency on JavaScript
Asynchronous communication
JavaScript
XML
Application
PageRequestManager
Inline script
External java script file
Script embedded as a resource in an assembly
Reference Reading
Explaining the AJAX Frameworkn
Reference
Reading:
Books
ASP.NET
AJAX
Programmer
s Reference:
With
ASP.NET 2.0
Or ASP.NET
3.5 by
Shahram
Khosravi
http://blogs.sun.com/enterprisetechtips/entry/building_an_ajax_enabled_we
b
Pro
ASP.NET
3.5 in C#
2008 by
Matthew
MacDona
ld
http://www.asp.net/AJAX/Documentation/Live/overview/PartialPageRenderingO
verview.aspx
http://www.dcs-media.com/desdev/dotNet/aspnet-ajax-client-life-cycleevents.aspx
Chapter 11
Objectives
In this chapter, you will learn to:
Implement internationalization
Implement accessibility
Implementing Internationalization
Web applications are accessed by people from different countries, cultures, and regions.
These people may want the information on the websites to be in their native language and
formats. This would make it easy for them to understand the content given on the site. To
enable the people from different countries, cultures, and regions to access your Web
application, you need to implement internationalization in the application. The process of
making an application ready for international users is called internationalization.
Consider the scenario of an organization that has a chain of hotels in various countries. The
organization is maintaining the information about the hotels through a website. This website
is accessed by people from various countries.
The website has a limitation. The information provided by the website is in English and the
currency is set to United States Dollar (USD). This poses problems for the non-English
speaking people because they are unable to understand the information given on the website.
As a result, people from the countries where the currency is other than USD have to calculate
the fares according to their currency. These problems are affecting the popularity of the
website.
To accommodate users from different countries and enable them to use the website
efficiently, the organization decides to implement internationalization in the application.
Implementing internationalization on the website would enable people from various countries
to have the information on the website in their native language and formats. This would help
users to easily understand the information given on the website.
To target the wide range of audience and to enable them to browse through your website,
your Web application must be designed to accommodate users from various countries and
cultures. This can be done by implementing internationalization in the application.
International applications should be customizable according to the preferences of users
belonging to different nations, cultures, or regions. User preferences refer to the language,
currency, and formats. To make an international application customizable, you need to
understand the following phases that are involved in developing an internationalized
application:
Note
Locale is a combination of a language and a country. It includes information about the
formats used for representing time and date, symbols, and conventions used for representing
currency, and the character encoding scheme being used.
Language issues
Formatting issues
String-related issues
User-interface issues
Language Issues
Languages around the world differ in display, alphabets, grammar, and syntactical rules. For
example, some languages such as Arabic are written from right-to-left, whereas other
languages are written from left-to-right. Some languages include uppercase and lowercase
characters, whereas others do not even have the concept of uppercase and lowercase.
Languages differ in the number of characters, storage requirements, keyboard layouts, and
code representations. This diversity makes it difficult to share data between cultures. It is
even more difficult to create a multilingual user interface.
Formatting Issues
Formatting is the main source of differences in applications designed for multiple languages
or cultures. Formatting differences may arise in the addresses, currency, dates, numerals,
telephone numbers, time, and units of measure of various languages.
String-Related Issues
When developing international applications, programmers must consider issues related to
strings. When strings are translated from one language to another, the translated strings may
be longer than the original strings. In strings, the order of alphabets varies in different
languages. This causes major problems in sorting and comparison of strings. Issues also arise
when strings are concatenated because these strings may convey different meanings in
different languages.
User-Interface Issues
Various user interfaces are associated with the design of an international application. The size
of user interface elements should be larger than that required for accommodating English
strings. This is because strings in other languages are usually longer than strings in the
English language. When messages grow in size as a result of translation to another language,
they should be allowed to wrap to subsequent lines. You should also ensure that all the
access-key and shortcut-key combinations are available on international keyboards. This is
because every language has a different keyboard layout, and some characters do not exist on
all keyboards.
Data block: Contains user-interface resources, such as the text on Label controls that
are to be translated into various languages. This block is locale-specific, and each
locale will have one data block.
Code block: Contains the application code or the executable part of an application
that is applicable to all cultures/locales. This block will remain same for all locales.
The separation of culture/locale specific and culture/locale independent parts allows a user to
dynamically switch the user interface to a localized version.
The data block of a Web application consists of a set of resource files. Each application has a
default resource file that contains the resources in the default language/culture. For each
additional language/culture that your website needs to support, you need to create a separate
resource file, called a localized resource file.
Information is stored in resource files as a set of key/value pairs. For example, if you want to
display a welcome message on a Web page, you can create a key named WelcomeText. The
resource files for each language/culture can then specify a different value to the key
depending on the language/culture.
The .NET Framework represents different cultures across the world by using a culture code.
A culture code consists of two parts, a two-letter language code and an optional two-letter
country/region code.
The general format of the culture code is:
<Language code>-<Country/Region code>
The following table lists some culture codes and their descriptions.
Culture Code
Description
En
en-CA
fr-FR
De
Zh-CN
de-DE
Culture code snippets that only specify a language are called neutral cultures, whereas culture
code snippets that specify a language as well as a region are called specific cultures.
To implement globalization in an application, you need to include the
System.Gloablization namespace in your application. The System.Gloablization
namespace provides classes that define culture-related information, such as the language,
country, calendars, and formats. Two important classes included in the
System.Gloablization namespace are:
CultureInfo
RegionInfo
The CultureInfo class provides information about a specific culture. The information
includes details such as the name of the culture, the formatting styles used, and the calendar
used.
The following table lists some of the commonly used properties of the CultureInfo class.
Property
Description
CurrentCulture
CurrentUICulture
Name
IsNeutralCulture
NumberFormat
Description
CreateSpecificCulture
GetCultureInfo
GetCultures
GetFormat
You can set two culture values for an ASP.NET application, the Culture and UICulture
properties. These values determine the types of resources loaded for an application and the
formatting options for various fields like currency, numbers, and dates. The resources loaded
are determined by the UICulture property and the formatting options are determined by the
Culture property.
You can set the Culture and UICulture properties for all pages on a website by using the
globalization section of the web.config file, as shown in the following example:
<globalization UICulture=fr culture=fr-FR>
You can set the Culture and UICulture properties for individual pages by using the @Page
directive of the page, as shown in the following example:
<%@ Page UICulture=fr Culture=fr-FR>
If you want to set the UICulture and Culture values to the first language specified in the
current browser settings, you need to set the UICulture and Culture values to auto.
However, you should not rely exclusively on the browser settings to determine the UI culture
for a page because users frequently use browsers that are not set to their preferences.
Therefore, you must provide users a method to explicitly select a language/culture for their
page.
You can set the UICulture and Culture values for a page programmatically by overriding
the InitializeCulture method and using any of the following methods in the overridden
method:
Set the UICulture and Culture properties of the page to the desired values.
Set the CurrentUICulture and CurrentCulture properties of the current thread to
the desired UI culture and culture, respectively.
Consider the following example that demonstrates how to use both the methods:
protected override void InitializeCulture()
{
if (Request.Form["ListBox1"] != null)
{
String language = Request.Form["ListBox1"];
UICulture = language;
Culture = language;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(language);
}
base.InitializeCulture();
}
The code given in the preceding example allows users to select their preferred language from
a drop-down list and sets the UICulture and Culture properties accordingly.
The RegionInfo Class
The RegionInfo class contains information about a country/region. The following table lists
some properties of the RegionInfo class.
Property
Description
CurrencySymbol
CurrentRegion
IsMetric
Description
Equals
GetType
The resource files allow you to specify the text appearing on a website in different languages.
However, if you want to change the format of date, time, or currency values depending on the
current culture, you need to specifically write code for implementing the same.
Suppose you want to use different formats for displaying a date on a Label control, depending
upon the current culture. Dates can be displayed in various formats. Each format has a format
character associated with it.
The following table lists some date formats, and their corresponding format characters.
Date Formats
The preceding table specifies the pattern of date/time in the en-US culture. Other cultures
may have slightly different patterns for each date format.
The following code snippet demonstrates how to use a different format for displaying a date
depending on the current culture:
protected void Page_Load(object sender, EventArgs e)
{
DateTime dt = DateTime.Now;
CultureInfo USCulture = new CultureInfo("en-US");
CultureInfo FrenchCulture = new CultureInfo("fr-FR");
if (CultureInfo.CurrentCulture.Equals (FrenchCulture))
Label2.Text = dt.ToString("d", FrenchCulture);
else
Label2.Text = dt.ToString("d", USCulture);
}
In the preceding code snippet, the ToString() method of the DateTime object is used to
convert the date to the Short Date format, as specified by the first parameter of the
ToString() method. The second parameter specifies the culture to be used for the short date
format.
At run time, if the users browser settings specify French (France) as the preferred language,
the date will be displayed in the format, dd/MM/yyyy. However, if the preferred language is
set to any other value, the date will be displayed in the US format, MM/dd/yyyy.
Implementing Accessibility
When you develop a Web application, you want the application to be used by as many users
as possible. Your Web application may be used by users with some disabilities. These users
may not be able to interact with your Web application properly because of their disabilities.
As a Web developer, you need to take care of all such issues and design the Web application
in such a way that it can be accessed easily by most of the users. This can be done by
implementing accessibility.
Accessibility refers to the degree of ease with which an application can be used by a variety
of people. Implementing accessibility in a Web application helps people having disabilities as
well as enables other users to interact with the application more efficiently. ASP.NET
provides some guidelines that you should consider while designing your Web application to
achieve high accessibility.
Flexible input and output features: Flexible input features refer to numerous ways
in which a user can interact with an application. All features should be accessible
through keyboard with the same degree of ease as while using mouse. Three-click rule
should always be followed, which states that all functionality should be accessible in a
maximum of three clicks. Flexible output features refer to the numerous ways in
which a user can retrieve information from an application. It is a good accessibility
practice to keep a wide range of output options such as text, images, sound, and
graphics.
Simple and Intuitive: The user interface should be simple and easy to understand,
regardless of a user's experience, knowledge, language skills, or current concentration
level. Any unnecessary complexity should be eliminated. Each object on the screen
should be assigned a unique and descriptive label to assist users who cannot see its
context on the screen.
The application should interact with other applications in a standard manner. For example,
the application should provide a standard mechanism for importing data from and exporting
data to other applications.
Standardize font styles: While deciding the font style, you should keep in mind that
users having diminished eyesight may also access your website. Therefore, you need
to select the font style and the color for the background and foreground such that the
text is easily readable. Some of the important guidelines for designing a website that
can be used by the users having diminished eyesight are:
o Font size should be greater than 12 points. However, the font size may differ
depending upon the font style.
o Text should not be italicized.
o Important points should be in bold.
o Decorative fonts should be avoided.
o Text color and background color should be selected in such a way that the text
can be easily read.
Support keyboard navigation: Keyboard navigation in an application can be
provided by using the TAB key. The TAB key navigation direction should be from
top to bottom and left to right. The navigation order while using the TAB key should
be correct. All navigation links should have tool tip that explains the use of the link.
All controls should be assigned keyboard shortcuts. ASP.NET provides the following
properties that are set for the controls used in a Web page so as to enable a user to
navigate properly by using the Tab key:
o TabIndex: You can specify the TabIndex property of a control to set tab
order for proper navigation.
o DefaultButton: You can specify default button for a form or a panel by
setting its DefaultButton property. The DefaultButton property specifies
that a user can cause a postback by pressing the ENTER button in an input
control in the form such as a text box.
o AccessKey: Keyboard shortcuts can be assigned to each control by using the
AccessKey property of the control.
o ToolTip: Tool tips can be displayed for each control by using the ToolTip
property of the control.
o AssociatedControlID: You can associate a Label control to another control
by setting the AssociatedControlID property of the Label control to the ID of
the relevant control. You can then use the properties of the Label control to set
some properties of the associated control. For example, you can use the Text
and AccessKey properties of the Label control to provide the caption and
short-cut key for the associated control.
Standardize the use of images: When you use images in the form of buttons, links,
or image maps in your application, you should provide a meaningful text for the
images to enable user to understand its functionality. ASP.NET allows you to do this
by setting the following properties of controls:
o AlternateText property: You can specify the AlternateText property of the
image to provide a meaningful text to the image.
o GenerateEmptyAlternateText: You can specify the
GenerateEmptyAlternateText property to true if the image does not provide
any functionality or does not convey information relevant to the context of the
Web page and is used for enhancing the UI of a Web page.
In addition, controls such a TreeView and Menu controls display images or links. For
example, the TreeView control displays images for the expand and the collapse button
for each node in the TreeView control. The TreeView control generates alternate text
for these images based on the text of the node. By default, the alternate text for the
image of the expand button that has the text as Start is rendered as Expand Start on a
Web page. You can also specify your own alternate text by setting the
ExpandImageToolTip and CollapseImageToolTip properties for the TreeView
control.
Standardize the use of tables on a Web page: You use tables in your Web
application to place each control in a well-organized and structured manner. While
creating a table, you should specify the caption to help assistive technologies such as
screen readers to identify the purpose of the table by setting its caption property.
Minimize the use of style sheets: The layout of a form should not be affected when it
is displayed in a browser that does not support style sheets. For this, you need to
provide an alternate page that does not make use of style sheets for every page that
uses a style sheet.
Use controls properly: While using controls at the time of designing an application,
you should consider the following points:
o Do not use ActiveX controls as some browsers may not support them. If you
are using an ActiveX control on a Web page, it should have an alternate page
that does not contain the ActiveX control.
o Use either LABEL or TITLE tags to specify the name of each control.
Note
An ActiveX control can be automatically downloaded and executed by a Web browser.
ActiveX is a set of rules for how applications should share information. Programmers can
develop ActiveX controls in a variety of languages, including C, C++, Visual Basic, and
Java.
Braille and Refreshable Braille: Braille is a system using six to eight raised dots in
various patterns to represent letters and numbers that can be read by the fingertips.
Braille system is used by blind people. Braille consists of an 8-dot version that has
been developed to allow all ASCII characters to be represented on a Web browser.
Refreshable Braille offers mechanical display where the dots are raised and lowered
dynamically that allows a Braille character to be displayed on a Web browser.
Refreshable Braille displays can be incorporated into portable Braille devices with the
capabilities of small computers, which can also be used as interfaces to devices, such
as information kiosks.
Scanning Software: Scanning software is adaptive software used by individuals with
some physical or cognitive disabilities that highlights or announces selection choices
such as menu items, links, or phrases one at a time. A user selects a desired item by
hitting a switch when the desired item is highlighted or announced.
Screen Magnifiers: Screen magnifier is software used primarily by individuals with
low vision that magnifies a portion of the screen that allows them to easily view a
Web application on a Web browser. Screen magnifiers make presentations larger, and
reduce the area of the document that can be viewed by removing surrounding context.
Some screen magnifiers offer two views of the screen, one magnified and one default
size for navigation.
Screen Readers: Screen reader is software that is used by individuals who are blind
or who have dyslexia. It interprets what is displayed on a screen and directs it either to
speech synthesis for audio output or to refreshable Braille for tactile output. Some
screen readers use the document tree such as the parsed document code as their input.
In addition, the screen readers use linearization process for interpreting the text in
each column of each row of a table on your Web page. It reads all the text in the first
cell of row one, the second cell, the third, and so on until it runs out of cells. It then
moves on to the second row.
Speech Recognition: Speech recognition is used by people with physical disabilities
or temporary injuries to hands and forearms. It is used by them as an input method in
a voice browser that allows voice-driven navigation. Applications that have full
keyboard support can be used with speech recognition.
Visual Notifier: Visual notifier is an alternative feature of some operating systems
that allows hearing impaired users to receive a visual alert of a warning or error
message that might otherwise be issued by sound.
Summary
In this chapter, you learned that:
CultureInfo
RegionInfo
Reference Reading
Implementing Internationalization
Reference Reading:
Books
http://wiki.asp.net/page.aspx/55/internationalization/
by Celeste M. Brody,
James Wallace
Managing Across
Cultures by Susan C.
Schneider, Jean-Louis
Barsoux
Implementing Accessibility
Referen Reference Reading: URLs
ce
Reading
: Books
Pro
http://www.globalknowledge.com/training/course.asp?pageid=9&courseid=1134
ASP.NE 5&catid=184&country=United+States
T 3.5 in
C# 2008
by
Matthe
w
MacDo
nald,
Mario
Szpuszta
Chapter 12
Objectives
In this chapter, you will learn to:
Identify the ASP.NET security process
Configure an ASP.NET Web application for security
Whenever a user requests for a Web application, the request is received by IIS. After
receiving the request, IIS tries to authenticate the user who has requested for the application
by using a specific type of authentication. The type of authentication depends on how the
security for Web applications is configured on IIS. Therefore, you first need to configure
security on IIS to authenticate users before they are permitted access to a Web application.
IIS provides the following different types of authentications to control access to your Web
application:
Note
A sniffing attack is a security threat in which an attacker gains access to the network
communication. The attacker can extract the message transmitted over a network. This
increases the risk of private information being misused.
You can configure the preceding authentication types in IIS for a Web application by using
the Internet Services Manager.
The initial check for user authentication is done by IIS. After the user is authenticated, IIS
sends the Web request to ASP.NET to perform a second level checking. ASP.NET uses its
own security mechanism to authenticate the user.
ASP.NET first authenticates the user by using the authentication settings defined in the
web.config file of the application. If the user is authenticated, it checks whether the user has
the right to access the requested resource of the Web application. All this requires you to
configure the security settings in the web.config file of the Web application. These security
settings include configuring authentication, authorization, and impersonation for accessing
resources in your application.
Configuring Authentication
Authentication is the process of validating the identity of a user before granting access to a
restricted resource. When ASP.NET receives a Web request from IIS, it tries to authenticate
the user. This authentication is based on the settings defined in the web.config file of the Web
application. These settings enable ASP.NET to determine which user is authenticated to
access the Web application.
Authentication in a Web application can be configured by using the <authentication>
element in the web.config file. The <authentication> element specifies the authentication
type that is used by an application to authenticate the user. The authentication type can be
specified by using the mode attribute of the <authentication> element. The mode attribute
can have the following values:
Windows: This mode specifies that the authentication is performed by IIS by using
Basic, Digest, or Integrated Windows authentication.
Forms: This mode specifies that the user will be authenticated by using form-based
authentication method. This method displays a logon form to verify the users
credentials.
Passport: This mode specifies that the user will be authenticated by using Microsoft
Passport authentication method. Passport authentication relies on cookie-based
authentication and single signing authentication service provided by Microsoft.
None: This mode specifies that no authentication mechanism is set and that any
anonymous user can access the Web application.
This type of authentication is best suited to an intranet environment where a set of known
users are already logged on to a network. For example, if you are creating a Web application
that is to be used within an organization, you can use the Windows authentication mode to
authenticate the users. This is because the existing users already have their accounts in the
database of the Web server. A Web application that implements Windows authentication
rejects a users request that is not an authenticated user or has an invalid user name or
password.
Implementing Forms Authentication
When you implement Forms authentication to a Web page, you have to create an HTMLbased Web page for collecting users credentials and then authenticate the user. When a user
enters his or her credentials and gets authenticated to view a Web page, ASP.NET generates a
cookie that is served as an authentication token to the user. The browser uses this cookie for
the future requests made by the user, allowing the application to validate the requests. This
cookie can be encrypted by a private key located on the Web server to identify that the
request is sent by the same user.
To authenticate users by using Forms authentication, you need to create and store the user
credentials in a data source. You can create and manage users in ASP.NET by using the
membership management service. The membership management service is used to
authenticate the users who require access to Web pages. This service provides an API suite
and some server controls such as CreateUserWizard to manage users in an ASP.NET Web
application.
To configure an ASP.NET Web application for forms authentication, you first need to change
the mode attribute of the <authentication> element to Forms, as shown in the following
markup:
<authentication mode="Forms" />
If a user tries to access a restricted page without first logging on, the user should be redirected
to the logon page. You are required to specify the settings to redirect anonymous users to the
logon page. These settings are specified by using the <forms> element in the web.config file.
The <forms> element has the following four attributes:
name:
It specifies the HTTP cookie that will be used for authentication. .ASPXAUTH is
the default value of this attribute.
loginUrl: It specifies the URL to which the user requests are redirected for logon
when no valid authentication cookie is found. The default value is default.aspx.
protection: It specifies the type of protection that a Web application uses to protect
the HTTP cookie. The valid values of this attribute are All, None, Encryption, and
Validation. The default value of this attribute is All.
timeout: It specifies the life span of the cookie that is used for authentication. After
the time specified in the timeout attribute, the cookie expires. The value of the
timeout attribute is specified in minutes.
path: It specifies the path of the cookie.
Note
When a user visits your website without logging in or providing his/her credentials, the user
is called anonymous user.
The following markup shows a web.config file that is configured for forms authentication:
<configuration>
<system.web>
<authentication mode="Forms">
<forms
name=".AuthenticationCookie"
loginUrl="~/mylogin.aspx"
timeout="5"/>
</authentication>
</system.web>
</configuration>
In the preceding markup, the name of the HTTP cookie is AuthenticationCookie and URL
to which the user will be directed for logon is mylogin.aspx. The life span of the cookie is 5
minutes.
After configuring the Web application for forms authentication, you are required to add users
to the ASP.NET membership management service. You can add users by using the following
methods:
When you add users to the membership management service by using either of the preceding
methods, the user information is stored in the ASPNETDB.MDF file. The user information stored
in the ASPNETDB.MDF file is made available to the membership management service by the
membership provider.
The membership provider specifies the type of database that will be used to store the
membership information. The default provider uses a Microsoft SQL Server database,
ASPNETDB. You can also choose to use Active Directory or specify a custom provider to store
membership information.
Note
In addition to the preceding methods, Visual Studio provides the following methods to add
users to the ASP.NET membership management service:
The <credentials> element is defined within the <forms> tag in the web.config file. It
contains the <user> tag to specify the user credentials, as shown in the following markup:
<configuration>
<system.web>
<authentication mode="Forms">
<forms
name=".AuthenticationCookie"
loginUrl="/login.aspx"
protection="All"
timeout="60"
path="/">
<credentials passwordFormat="Clear">
<user name="John" password="P@ssw0rd"/>
<user name="Tom" password="123_P@ss"/>
</credentials>
</forms>
</authentication>
</system.web>
</configuration>
used to specify the format in which the password is stored in the web.config file. The
passwordFormat attribute is set to Clear which means the password is stored as plain text.
Other options available with passwordFormat attribute are MD5 and SHA both of which are
encryption algorithms.
After specifying the user credentials, you are now required to create the login form. You can
create the login form either manually or by using the login controls provided by ASP.NET. If
you use login controls, you are not required to write any code to validate users, the users are
validated automatically by using the credentials stored in the membership management
service. However, if you create the login form manually, you are required to perform the
validation programmatically. ASP.NET provides you with the FormsAuthentication class
that helps you validate the users programmatically.
The FormsAuthentication class is defined in the System.Web.Security namespace and is
used to implement form authentication when the configuration file is used to store user
credentials. The following table lists some commonly used methods of the
FormsAuthentication class.
Method
Description
Authenticate
RedirectFromLoginPage
SignOut
else
{
Response.Write("Sorry! Login failed");
}
}
In the preceding example, the user name and the password are authenticated by using the
Authenticate function of the FormsAuthentication class. If the user is authenticated, the
message Welcome <username> is displayed on the Web form. However, if the user is not
authenticated, the message Sorry! Login failed is displayed on the Web form.
When adding users by using the <credentials> element in the web.config file, you need to
add all the users at design time. In addition, if you want to modify or delete a user, you need
to manually remove or modify the users in the web.config file. However, if you want to add,
modify, or delete users at run time, you need to use the Membership class. To implement the
Membership class, you need to use the System.Web.Security namespace. The Membership
class has various static methods that allow you to manage users at run time. The following
table lists some useful static methods.
Method
Description
CreateUser
DeleteUser
GetUser
identifier .
GetAllUsers
UpdateUser
ValidateUser
In the preceding example, the code within the AddUser_Click event handler is written to
create a user. If the user gets created successfully, the method ShowAllUsers is invoked. This
method is used to retrieve all the users and display them in the GridView control. However, if
any exception is thrown by the code, the error message is displayed on the Web form.
Once created, you can change the user details by using the methods of the Membership class.
For example, you have created a user with the name user1. Now, you want to change the
password for the user. For this, you need to write the following code snippet:
MembershipUser currentUser = Membership.GetUser("user1");
if (currentUser.ChangePassword("OldPassword", "NewPassword"))
{
Label1.Text = "Your password is successfully changed";
}
else
{
Label1.Text = "Your password could not be changed";
}
Note
When you modify user details such as the e-mail address, you need to use the UpdateUser
method of the Membership class after modifying the details. The UpdateUser method takes
the MembershipUser class object as an argument.
You can customize the membership settings, if required, by configuring the membership
provider.
Configuring Membership Provider
You can configure the membership provider to customize the membership settings, such as
specify the database for storing the user credentials and change the default password policy.
To configure the membership provider, you need to add the <membership> element to the
web.config file. All the custom settings are defined inside the <membership> element as
shown in the following example:
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add
name="CustomMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MySqlServer"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0"
passwordFormat="Hashed"/>
</providers>
</membership>
In the preceding example, the membership provider is configured. The <add> element in the
preceding example contains the following attributes:
Name:
type:
connectionStringName:
Configuring Authorization
Authorization is the process of verifying whether an authenticated user has the privilege to
access a requested resource. After creating users that can access your Web application by
using the membership management service, you need to specify authorization rules for the
users.
You need to grant different permissions to different users to provide accessibility to the Web
pages on your website. For example, on an online shopping website, the users are able to
view the product catalog. They cannot make changes to the products being displayed on the
website. However, the administrator of the website can add or remove any product from the
website. This requires providing different levels of permission to different users of the
website.
Maintaining a different set of settings for each user is a complex task. Therefore, the users are
assembled into groups called roles and the permissions are defined on these roles. In
ASP.Net, you can provide authorization by using the role management service. The role
management service enables you to create roles, assign users to each role, and then restrict
user access based on these roles.
To use role-based authorization in your Web application, you need to enable it by using the
<roleManager> element in the web.config file, as shown in the following markup:
<configuration>
<system.web>
<roleManager enabled="true" />
...
</system.web>
...
</configuration>
In the preceding markup, setting the value of the enabled attribute to true will enable rolebased authorization for the Web application.
Creating and Assigning Roles
After you have enabled the role management service, you need to create roles, such as Users,
Administrator, and Guest. You can then assign users to one or more roles.
ASP.NET provides you with the Roles class to help you create roles. The Roles class
contains a number of methods that help you modify role information. The following table
lists the various methods of the Roles class and their description.
Methos
Description
CreateRole
DeleteCookie
DeleteRole
FindUsersInRole
GetRolesForUser
In the preceding code snippet, the user Peter is added to the Admin role. You can get a list of
all the users in a particular role. For this you need to write the code as shown in the following
example:
In the preceding example, all the users are retrieved and the names of those users who have
assigned the Manager role are displayed on the label control.
users:
A Web application contains certain Web pages that can be accessed only by specific users.
For example, there are certain Web pages that should be accessed only by the administrator.
For restricting access to such Web pages, these Web pages need to be stored in a separate
subdirectory. After storing the Web pages in the subdirectory, you need to add a Web.config
file to that subdirectory. Then, you need to use the following markup in the web.config file to
restrict users having roles other than Admin to access the Web pages:
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
The preceding markup specifies that the users who have been assigned to the Admin role are
allowed to access the Web pages stored in the subdirectory. All users having roles other than
the Admin role are denied access on these Web pages.
Configuring Impersonation
When a user requests an ASP.NET application, the request goes to IIS. IIS authenticates the
user and forwards the request to ASP.NET. If ASP.NET impersonation is disabled,
irrespective of the user who has logged on, the ASP.NET application will be executed by
using a fixed machine-specific account. In Windows XP, this account is automatically created
by ASP.NET and is named as ASPNET.
The ASPNET account has permissions such as code compilation and viewing information in
any database or files in your application that you would not want to grant to a user. For
example, if a user visits the current account page, you need to make sure that the user is able
to view the information only for his\her account. To allow users to access the ASP.NET
application according to the permissions granted to them, you need to use impersonation.
Impersonation is the process of executing code under the authenticated user identity and not
under the ASPNET account. When a user tries to access a Web application, the first step is to
check whether impersonation is enabled for the application.
Impersonation involves the following steps:
1. When a request from a remote client is received, IIS carries out authentication. If the
client is authenticated, it passes the request to the ASP.NET application.
2. The application impersonates the client and uses the authentication given by IIS to
access the restricted resources.
3. If authorized to access resources, the ASP.NET application returns the requested
resources to the client through IIS.
By default, impersonation is disabled in ASP.NET and unless overridden, all applications
inherit this setting. When impersonation is disabled, the account used for executing ASP.NET
resources is controlled by the <processModel> element in the machine.config file. However,
you can enable impersonation in an ASP.NET application by adding the following markup in
the <system.web> section of the web.config file:
<identity impersonate="true" />
In the preceding markup, impersonation is enabled for the Web application. Therefore, the
application uses the user credentials authenticated by IIS to provide access to the requested
resources.
You can also enable your Web application to run under a specific users identity. For this,
you need to specify the user credentials for that specific user in the web.config file, as shown
in the following markup:
<identity impersonate="true" userName="user1" password="Password" />
In the preceding markup, impersonation defines a single specific user account, user1.
Therefore, no matter which user accesses the application, all the Web requests will be granted
access according to the permissions of the user1 account.
Summary
In this chapter, you learned that:
The ASP.NET security model provides restricted levels of access to secure website
information from unauthorized access.
IIS provides the following different types of authentication to control access to your
Web application:
o
o
o
o
Anonymous
Basic
Digest
Integrated Windows
Authentication is the process of validating the identity of a user before granting access
to a restricted resource.
Authentication in a Web application can be configured by using the
<authentication> element in the web.config file.
Authorization is the process of verifying whether an authenticated user has the
privilege to access a requested resource.
Impersonation is the process of executing code under the authenticated user identity
and not under the ASPNET account.
Reference Reading
Identifying the ASP.NET Security Process
http://msdn.microsoft.com/en-us/magazine/cc301387.aspx
http://www.springerlink.com/content/q6w220jt19065733/
Chapter 13
Objectives
In this chapter, you will learn to:
Configure a Web server for deployment
Deploy a Web application
images, user controls, and data source files of your application. This directory is known as a
virtual directory.
A virtual directory is created so that the user does not get direct access to the Web application
folder residing on the host computer. This helps in maintaining the security of the Web
application and the host computer because a remote user or a client cannot manipulate any
data.
A virtual directory exposes the components of a Web application to the remote clients and
allows them to access your Web application through Web browsers. When a client requests a
Web page in a virtual directory, the Web server searches the page in the corresponding
physical directory that exists on the host computer. After locating the page, the server sends it
back to the client.
For example, your Web application exists in a directory named D:\MusicMania on the host
computer. To allow remote users to access the application through their browsers, you need
to deploy it on a Web server as a virtual directory. The virtual directory can either have the
same name as the name of the Web application or a different name. When the user requests a
page in a virtual directory, for example, http://172.23.3.203/MusicMania/AboutUs.aspx, the
Web server searches for the file in the corresponding physical directory, D:\MusicMania\
AboutUs.aspx and renders it to the user.
Low (IIS Process): The applications that are configured to run under this application
protection run in Inetinfo.exe. The Inetinfo.exe hosts IIS core processes. Therefore, if
the application fails, it might stop the functioning of the Web server.
Medium (Pooled): The applications that are configured to run under this application
protection share an instance of dllhost.exe and do not run in Inetinfo.exe. If the
applications fail, the Web server does not get affected. However, other application
running under this application protection share may get affected. It is the default
option.
High (Isolated): The applications that are configured to run under this application
protection are isolated from both the Inetinfo.exe and dllhost.exe. Therefore, if the
application fails, it will not affect any other application or the Web server.
A URL is the location of a file on the Web. It is unique for every application. To access a
Web application, users type the URL for that application in the address bar of a Web browser.
The Web browser sends this request to the Web server. The Web server searches for the
application mapped to that URL and sends it back to the browser.
Consider a scenario where an airline company sells airline tickets through their Web
application. The passengers can book their tickets, check the booking status, and see the
flight schedules through the airline website. Users can access the website by using the
following URL:
http://172.23.3.203/MyWebApp/default.aspx
In the preceding URL, 172.23.3.203 is the IP address of the Web server and MyWebApp is
the virtual directory residing on the Web server. To access the Web application through its IP
address, users need to remember the IP address. However, it is difficult to remember IP
addresses. Therefore, instead of using an IP address, Web applications are accessed by using
a unique name known as the domain name. For example, the airlines Web application can be
accessed by using the domain name, as specified in the following URL:
http://www.MyFlight.com/MyWebApp/default.aspx
In the preceding statement, www.MyFlight.com is the domain name for the airline website.
Note
IP address is a unique 32-bit number and is typically written as four numbers in the range of
0 to 255 separated by periods (as in 172.23.3.203).
Note
A domain name is the address that is used by users to access a Web application. A domain
name is registered by companies so that it can be used by its users to access the companys
website.
A Web application can be configured to use any version of the .NET Framework that is
installed on the computer. To configure a Web application to use a particular version, you
need to register a script map in the Internet Information Services (IIS). A script map is a path
to the ASP.NET ISAPI version used by the application. It associates a file extension and
HTTP verb with the appropriate ISAPI for script handling.
When a user requests for a particular Web page, the script map for the application directs IIS
to forward the requested file to the ASP.NET ISAPI for processing. Therefore, when you
need to use a particular version of the .NET Framework, you need to update the script maps
so that they direct the request for a Web page to the appropriate version of the ASP.NET
ISAPI.
To update the script map, you need to use the ASP.NET registration tool called
aspnet_regiis.exe, as shown in the following figure.
Note
The aspnet_regiis command can be used with several options. You can check all the available
options by typing aspnet_regiis/? at the command prompt.
The application loads slowly initially because it is compiled when it is accessed for
the first time.
It provides faster response time because the Web application does not need to be
compiled the first time it is accessed.
It helps in identifying the bugs that can occur when a Web page is requested. These
bugs are rectified at the time of compiling the Web application. Then, the compiled
and error-free Web application is deployed on to the server and is rendered to a user.
It hides and secures the source code of a Web application from the users accessing the
application.
You can precompile a Web application by using the aspnet_compiler.exe command-line tool.
This tool compiles source files such as Web pages, user controls, resources, and utility
classes into assemblies and creates output in the form of an executable version of the
application. The compiler removes all source and markup from the output. The output
consists of the compiled files of each of the .aspx file with the .compiled extension. These
compiled files contain pointers to the appropriate assembly for that page. Assemblies are the
.dll files that contain the compiled version of .aspx.cs file.
Note
All source code on an ASP.NET Web form is dynamically compiled into intermediate
language. When the intermediate language code is executed on a machine it gets compiled
just-in-time (JIT) into native machine code and then executes.
To compile a website, you need to execute the aspnet_complier command, as shown in the
following figure.
Description
-v
-p
-u
-c
performed.
Options Used with aspnet_compiler.exe
When you use the aspnet_merge tool, without any options, and only specify the target folder
name, as shown in the following figure, output assemblies are created for each Web user
interface content folder.
To create a single assembly that combines all assemblies on a precompiled website, you need
to use the -o switch with the aspnet_merge tool and specify a name for the merged assembly,
as shown in the following figure.
Summary
In this chapter, you learned that:
A virtual directory exposes the components of a Web application to the remote clients
and allows them to access your Web application through Web browsers.
An Application pool can contain one or more applications and allows you to
configure the level of isolation between different Web applications.
A URL is the location of a file on the Web. It is unique for every application.
Precompilation involves compilation of the source code of the Web application into
DLL assemblies before deployment. Precompiling a Web application provides the
following advantages:
o It provides faster response time because the Web application does not need to
be compiled the first time it is accessed.
o It helps in identifying the bugs that can occur when a Web page is requested.
These bugs are rectified at the time of compiling the Web application. Then,
the compiled and error-free Web application is deployed on to the server and
is rendered to a user.
o It hides and secures the source code of a Web application from the users
accessing the application.
The compilation tool of ASP.NET, aspnet_compiler.exe, compiles the source files and
creates separate assemblies for each source file.
Reference Reading
Configuring a Web Server for Deployment
Reference Reading:
Books
http://msdn.microsoft.com/en-us/library/aa244279(VS.60).aspx
http://e-docs.bea.com/wls/docs81/webapp/deployment.html
http://www.beansoftware.com/ASP.NET-Tutorials/DeployASP.NET.aspx
Chapter 14
Objectives
In this chapter, you will learn to:
Implement tracing in Web applications
Monitor Web applications
Implementing Tracing
Page Level
Application Level
Page-Level Tracing
Page-level tracing is used to generate diagnostic information at the end of page rendering.
This diagnostic information includes all the information about the requests made to the page
and their responses. This information is used to diagnose problems on the page. For example,
suppose the processing of your Web page is taking too long. You can use the trace
information to check which of the Web page methods or events are taking too long to
execute. Once you are able to determine the reason for delayed processing of your Web page,
you can easily resolve the problem.
To enable page-level tracing, you need to perform the following steps:
1. Include the following directive at the top of the page:
2.
If you enable tracing on a Web page of your Web application, the tracing information is
displayed at the end of the Web page, as shown in the following figure.
Request Details: It displays some basic information, such as current session ID, the
time when the request for the Web page was made, the request and response
encodings, the request type, and the return status code.
Trace Information: It displays performance-related information about the Web page
life-cycle events. The events are displayed under the Message column. The Category
column displays the category of the message. The From First(s) column displays the
running time from the instant when the page request started. The From Last(s) column
shows the elapsed time since the previous event. You can use this information to
determine which of the Web page events are taking too long to execute.
Control Tree: It displays information about each control on the Web page, such as
the size of the rendered controls. You can use this information to be aware of the
number of bytes that each control on the Web page uses. This will help you keep a
check on the overall weight of the Web page.
Session State: It displays information about all the session variables, their types, and
values.
Application State: It displays information about all the application variables, their
types, and values.
Request Cookies Collection: It displays information about all the cookies that were
sent by the Web browser with the request for this Web page.
Response Cookies Collection: It displays information about all the cookies that were
returned by the Web server with the response.
Headers Collection: It displays information about all the headers that are sent to the
Web server as part of the request from the Web browser. It includes information about
the browser making the request, the types of content it supports, and the language it
uses.
Response Headers Collection: It displays information about all the headers that are
sent to the client as part of a response from the Web server. It includes details such as
the version of ASP.NET and the type of content being sent (text/html for Web pages).
Form Collection: It displays the list of values that are posted back to the Web server.
It includes all the values that are submitted by Web controls, such as hidden field
values, the text in a textbox, and the current selection in a list box.
Querystring Collection: It displays the list of values included in the query string.
You can also view this information in the Web page URL. However, if the query
string contains a lot of information, it is easier to review the individual items in the
trace display.
Server Variables: It displays all the server variables and their values at the time of
Web page request.
Application-Level Tracing
When you enable tracing at the page-level, the tracing information is displayed at the end of
the Web page. As a result, every visitor to the website will see the tracing output at the
bottom of the Web page. This is not a good approach to display Web pages on a website. To
view the tracing output for all the Web pages on the website, you need to enable tracing for
every Web page if you are using page-level tracing. These limitations can be overcome by
enabling tracing for the entire Web application.
Application-level tracing is used to trace information for every Web page in a Web
application. A special page named trace.axd is used to view this trace information. This page
should ideally be accessible to the website administrator only. To use the trace.axd page, you
have to first enable application-level tracing within the Web.config file for your application.
You can use the following attributes of the <trace> element to change the tracing settings of
your website:
enabled: Indicates whether tracing is enabled for the application. The default value is
false.
requestLimit: Stores tracing information for a maximum number of HTTP requests.
pageOutput:
For example, you can make the necessary settings to enable application-level tracing in the
web.config file, as shown in the following code snippet:
<configuration>
<system.web>
<trace
enabled="true"
requestLimit="100"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
mostRecent="false" />
</system.web>
</configuration>
In the preceding code snippet, the trace information will be displayed for the first 100 Web
requests as specified by the requestLimit and mostRecent attributes. The trace information
will be sorted by time as specified by the traceMode attribute. It is only available to the local
clients as specified by the localOnly attribute.
You can open the trace.axd page in the Web browser just by replacing the page name in the
URL with trace.axd, as shown in the following figure.
When a Web application is in the development stage, you often use several Response.Write
statements in the program code to display debugging information. This information is used to
troubleshoot the application. However, these statements need to be removed once your
application is ready for deployment because the messages displayed using Response.Write
statements are required for debugging and should not be displayed to an end user.
Tracing resolves this problem by allowing you to insert debugging code within an application
such that the debugging code does not need to be removed at the time of deployment. This is
because you can disable tracing to prevent the debug information from being displayed as
trace information.
The Trace property of the Page class returns a Trace object, which can be used to write
custom trace statements. The Trace object is an instance of the TraceContext class. The
Trace object provides a set of methods and properties that help you trace the execution of
your application.
The properties of the Trace object are:
IsEnabled:
TraceMode:
You can use the Trace object to write custom trace statements when tracing is enabled for a
page or an application. You can use the Write and Warn methods of the TraceContext class
to write trace statements to the trace log. The only difference between these two methods is
that the Warn method displays the statements in red while the Write method displays the
statements in black color. The Write and Warn methods are overloaded methods and have
three versions. These three versions differ in the number of arguments passed to them. The
syntax of the overloaded methods of the Write and Warn methods are:
public void [Warn | Write](String message)
public void [Warn | Write](String category, String message)
public void [Warn | Write](String category, String message, Exception
errorInfo)
The arguments used in the preceding versions of the Write and Warn methods are:
message:
section.
category:
For example, you can write the following code in the Page_Load event of your Web page:
int i = 30;
int j = 0;
try
{
int z = i / j;
Response.Write(z);
}
catch(DivideByZeroException exp)
{
Trace.Write("Errors","Testing the limits of infinity?",exp);
Response.Write("A numeric value divided by zero gives result as
infinity.");
}
In the preceding code snippet, an exception is raised in the try block. This exception is caught
in the catch block. Then, a message, A numeric value divided by zero gives result as infinity,
is displayed to a user. The information of the execption caught in the catch block is displayed
in the Trace.axd file in the browser, as shown in the following figure.
To enable a trace listener, you need to add it to the Listeners collection. All the three types
of trace listeners receive the same trace output when included in the Listeners collection but
each of them then redirects this output to a different target.
Adding a Trace Listener
A trace listener is added in the web.config file within the <listeners> tag of the trace
element. The <listeners> tag is a collection of all the trace listeners. To add a trace listener
in the web.config file, you need to include the following code snippet in the web.config file:
<configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="MyListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="D:\myListener.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
In the preceding code snippet, a listener, MyListener is added to the <listeners> tag. The
MyListener listener writes the trace information to a file, myListener.txt. The
autoflush attribute of trace element specifies whether the trace listener automatically
flushes the output buffer each time it writes to a text file.
To enable ASP.NET to route tracing information to a System.Diagnostics listener, you
need to include the following entry in the web.config file:
<system.web>
<trace writeToDiagnosticsTrace = "true" />
<customErrors mode="off" />
</system.web>
<configuration>
<system.diagnostics>
<trace>
<listeners>
<remove name="MyListener"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
In the preceding code snippet, the trace listener, MyListener is removed by using the
<remove> element within the <listeners> element.
Trace Switches
Trace switches allow you to enable, disable, and filter tracing output even after the
application has been deployed on the server. This can be done by configuring the trace
switches through the web.config file. The .NET Framework provides the following types of
switches:
BooleanSwitch:
In the preceding code snippet, an object of TraceSwitch class is created and initialized. The
System.Diagnostics.TraceSwitch class takes two parameters, name and description of
trace switch.
In the preceding code snippet, the value attribute of the switch MySwitch is set to 2 to
display the warning and error messages.
Health Monitoring
Performance Monitoring
Health Monitoring
ASP.NET health monitoring system enables you to monitor the status of the deployed Web
applications. It is used to track system events and errors, which can hamper the performance
of a Web application.
Health monitoring system enables you to get the detailed run-time information about
ASP.NET resources used by a Web application. It is useful in scenarios where you want to
monitor an application and be notified when a critical error occurs. For example, you can use
health monitoring system to monitor events such as start and end of an application, successful
and failed logons, and unhandled exceptions. If you detect any unhandled exception in your
Web application, you can make appropriate changes so that it does not occur again.
The ASP.NET health monitoring system is implemented by using the
System.Web.Management namespace. This namespace contains classes and interfaces for
managing and monitoring the health of Web applications. This namespace includes Web
events responsible for packaging health-status data of the Web application. You can capture
Web events by using built-in event providers. For example, there is a provider to capture
events and send e-mail notifications, a provider to log events to SQL Server, and a provider
to drop events into an event log.
Configuring Health Monitoring
You can configure applications to use built-in or customized monitoring providers. These
providers process the health-monitoring information and report on the health status and the
performance characteristics of a Web application. To use the health monitoring system, you
need to perform the following configuration jobs:
The following code snippet shows how you can configure health monitoring by using the
<healthMonitoring> element in the web.config file:
<healthMonitoring
enabled="true|false"
heartbeatInterval="time interval">
<bufferModes>...</bufferModes>
<providers>...</providers>
<eventMappings>...</eventMappings>
<profiles>...</profiles>
<rules>...</rules>
</healthMonitoring>
Description
enabled
heartbeatInterval
Description
bufferModes
eventMappings
profiles
providers
rules
WebBaseEvent: It acts as a base class for all the other Web events.
WebBaseErrorEvent: It acts as a base class for all Web events related
to errors in the
system.
compilation time.
You need to enable the Web events by connecting them to the event providers.
Event Providers
The event providers are used to listen for Web events that are raised by a Web application.
These providers process the event information either by logging the information or by
notifying the system administrator. ASP.NET provides you with several built-in event
providers that you can use to capture Web events raised by the Web application. Some of the
built-in providers are:
The following example shows how to use the EventLogWebEventProvider in the web.config
file to log Web events in the Windows event log:
<healthMonitoring enabled="true" heartbeatInterval="0">
<rules>
<add name="Default Success Audits" eventName="Success Audits"
provider="EventLogProvider" profile="Default"
minInterval="00:02:00"/>
</rules>
</healthMonitoring>
In the preceding example, a <rule> child element is created under the <healthmonitoring>
element of the web.config file. Then, a rule, Default Success Audits, is created to handle
success audit events.
Performance Monitoring
Performance is an important factor in making a Web application or project successful. You
need to monitor a Web application to troubleshoot any performance-related issues. For
example, a user request may not be processed because of insufficient server resources. You
need to keep track of such errors to improve the performance of your Web application.
ASP.NET provides you with several performance counters, such as Application Restarts,
Requests Queued, and Errors Total to help you keep track of the execution of your Web
application. These performance counters are valuable in determining the performance-related
problems in Web applications.
For example, you can determine the number of requests that are in queue for your Web
application. A large number of Web requests in the queue may indicate that the application is
not efficient enough and needs to be tuned. By monitoring the Requests Queued performance
counter, you can track the number of requests waiting for service in the queue. If it is
affecting the performance of the application, you can make the necessary changes in the
configuration file of the application to improve its performance. You can use the System
Monitor (PerfMon) with ASP.NET applications to track the performance counters affecting
the performance of applications.
Performance Counters for ASP.NET
ASP.NET supports the following groups of performance counters:
System performance counters are displayed in the Windows Performance monitor in the form
of the ASP.NET performance counter object.
The following table lists some of the system performance counters.
System Performance Counter
Description
Application Running
Requests Disconnected
Description
Anonymous Requests
Anonymous Requests/Sec
Debugging Requests
Summary
In this chapter, you learned that:
TextWriterTraceListener
EventLogTraceListener
DefaultTraceListener
ASP.NET provides you with the following features for monitoring a Web application:
o
o
Warn
Write
IsEnabled
TraceMode
Page Level
Application Level
Health Monitoring
Performance Monitoring
o
o
Reference Reading
Monitoring Web Applications
Reference Reading: Books
http://www.mailarchive.com/mumbaiusergroup@groups.msn.com/msg15921.html
http://www.ajaxline.com/health-monitoring-in-asp-net-3-5
Chapter 15
Objectives
In this chapter, you will learn to:
Create mobile Web pages
Render content on mobile Web pages
Form
Command
PhoneCall
List and ObjectList
DeviceSpecific
SelectionList
StyleSheet
TextView
Form Control
Mobile devices have small display areas. Therefore, it is difficult to display complex Web
pages, containing multiple controls, on a mobile device. To display such complex Web pages
on a mobile device, you can break these pages into a collection of forms by using the Form
control. A Form control is a container control that provides the capability to group controls
together. Each Form control can hold a group of logically related controls. These Form
controls can be displayed by setting the ActiveForm property of the Web page, as shown in
the following example:
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<mobile:Form id="Form1" runat="server">
runat="server" />
<mobile:Command ID="Button1" text="Click Me" runat="server"
OnClick="Button1_Click" />
</mobile:Form>
In the preceding example, when the application starts, the default form control Form1 is
displayed. When the user clicks the Button1 button control in the Form1 control, the Form2
Form control is displayed.
ASP.NET Web pages can contain more than one Form controls. However, a mobile Web
application can display only one Form control at a time. When a user browses a mobile Web
page, by default, the first form appears on the page.
Note
A mobile Web page must contain at least one Form control. Form controls cannot be nested.
Command Control
The Command control is similar to the Button Web server control. It combines the
functionality of the normal Button, ImageButton, and LinkButton controls. The Command
control can be added to a mobile page by using the <Command> element, as shown in the
following example:
<mobile:Command ID="Button1" text="Click Me" runat="server"
OnClick="Button1_Click" />
In the preceding example, a Command control, Button1, is added to a Form control. The
Text property of the Command control is set to Click Me and the event handler
Button1_Click is attached with the Click event of the Command button.
PhoneCall Control
A PhoneCall control is used to enable applications to initiate telephone calls if the user's
mobile device supports that capability. If the mobile supports the capability, the phone
number specified by using PhoneNumber property of the PhoneCall Control is displayed as
hyperlink, selecting which a user can initiate a telephone call.
However, if the mobile device does not support the capability of placing phone calls, the
PhoneCall control displays the phone number as text. The PhoneCall control can be added to
a mobile page by using the <PhoneCall> element, as shown in the following example:
<mobile:PhoneCall ID="Phone1" PhoneNumber="9999037202" runat="server"/>
In the preceding example, a PhoneCall control with the PhoneNumber property set to
9999037202 is added to a Form control.
To use a PhoneCall control, you need to add the control onto a Form or Panel control or
inside a control's template on an ASP.NET mobile Web page. After adding the control, you
need to specify the Text and the PhoneNumber properties. You can optionally use the
AlternateUrl property, which is set to the URL of the page that the application will
navigate to when running on devices that cannot initiate phone calls.
Note
The PhoneNumber property must be set, to use the PhoneCall control. If the PhoneNumber
property is not set, the application will throw an error.
List and ObjectList Controls
Mobile Web controls do not include the DataList and Repeater controls. Instead of these
controls, the mobile Web controls include the List control. The List control includes the
functionality that is provided by the DataList and Repeater controls. The List control can be
added to a mobile page by using the <List>> element, as shown in the following example:
<mobile:List ID="List1" Runat="server">
<Item Text="Sam" />
In the preceding example, a List control, List1, is added to a form control. The list control
has three items.
Similarly, in place of the DataGrid control, the mobile Web controls include the ObjectList
control. The ObjectList control includes the functionality that is provided by the DataGrid
control. The ObjectList control can be added to a mobile page by using the <ObjectList>>
element, as shown in the following example:
<mobile:ObjectList ID="ObjectList1" Runat="server"/>
The following code nippet binds the ObjectList control with a dataset:
ObjectList1.DataSource = ds;
ObjectList1.DataBind();
DeviceSpecific Control
The DeviceSpecific control is used to specify a choice among multiple content alternatives.
The DeviceSpecific control allows you to specify one or more choices, each containing
attributes that specify how to evaluate the choice against target device capabilities. During
run time, each choice specified in the DeviceSpecific control is evaluated in order, and the
first choice that is successfully evaluated is used.
The DeviceSpecific control is used to specify template sets and override properties. For
example, you can use the DeviceSpecific control to specify device-specific images for the
Image control, as shown in the following example:
<mobile:Image runat=server>
<DeviceSpecific>
<Choice Filter="isColor" ImageURL="colorImg.gif" />
<Choice Filter="isWML11" ImageURL="myImage.wbmp" />
</DeviceSpecific>
</mobile:Image>
In the preceding example, if the device is colored as specified by the isColor value of the
Filter attribute, the colorImg.gif image will be displayed. For WML device,
myImage.wbmp image will be displayed.
SelectionList Control
The SelectionList control provides different visual representations for a list of selectable
items. It combines the functionality of the CheckBox, CheckBoxList, DropDownList,
ListBox, RadioButton, and the RadioButton Web server controls. You can use the
SelectType property of the SelectionList control to define the type of selection list button to
render.
For example, if you set the SelectType property of the SelectionList control to CheckBox,
the item passed to the control as the value of its DataSource property are displayed as check
boxes. You can set the SelectType property of the SelectionList control as shown in the
following code snippet:
SelectionList sl = new SelectionList();
sl.SelectType = ListSelectType.DropDown;
StyleSheet Control
The StyleSheet control enables you to use styles in the ASP.NET mobile Web Forms. It has
no visual representation. The StyleSheet control can only be attached to ASP.NET mobile
Web forms or to mobile user controls. There can be only one style sheet for a page or a
control.
Each style sheet can contain one or more styles. A control can use the styles defined in the
StyleSheet control by using the StyleReference property. The following example shows
how to define styles by using the StyleSheet control:
<mobile:StyleSheet ID="MyStyle" Runat="server">
<mobile:Style Name="Style1" ForeColor="#ff0066"
Font-Size="Large"/>
<mobile:Style Name="Style2" ForeColor="#009900"
Font-Size="Normal"/>
</mobile:StyleSheet>
The preceding example defines two styles, Style1 and Style2. To use these styles for a
control, you need to set the StyleReference property of the control as shown in the
following example:
Label1.StyleReference = "Style1";
TextView Control
The TextView control is used to display large quantities of text. The TextView control
supports device filters for overriding property values. This enables the TextView control to
customize its appearance according to the capabilities of the device on which it is rendered.
The TextView control can be added to a mobile page by using the <TextView> element, as
shown in the following example:
You need to map the mobile Web control with its adapter through the browser definition
files. The browser definition files have a .browser extension. It contains information about the
browser capabilities. ASP.NET uses the .browser files to determine the capabilities of the
browser, and to decide how to render markup to that browser.
The browser definition file, in addition to the mapping control adapters, is used to populate
the HttpBrowserCapabilities class. This class contains information about the capabilities
of the browser, such as name, type, and version of the browser. You can determine the
capabilities of the browser by accessing the HttpBrowserCapabilities class through the
Request.Browser property.
The following table lists some commonly used Request.Browser properties with their
description.
Property
Description
Request.Browser.Browser
Request.Browser.Version
Request.Browser.Type
Request.Browser.IsColor
Request.Browser.IsMobileDevice
Request.Browser.CanInitiateVoiceCall
The preceding code is written within the Page_Load event handler of the home page that is
created for the desktop computers. It is the default startup page for the application. When the
page is requested by any computer, the type of the device is checked. If the request is from a
desktop computer, the default home page is returned. However, if the request comes from a
mobile device, the Mobile/Home.aspx page is returned.
Note
You can check the browser capabilities by declaring a HttpBrowserCapabilities type
variable as shown in the following code snippet:
HttpBrowserCapabilities browser = Request.Browser;
Response.Write(browser.ActiveXControls);
Note
Some mobile controls require you to use fully qualified redirects. For converting relative
paths into fully qualified paths, you need to use the <httpRuntime> element as shown in the
following example:
<system.web>
<httpRuntime useFullyQualifiedRedirectUrl="true" />
</system.web>
The ability to render a control based on the type of the device is known as device-specific
rendering. This requires you to set the properties of the controls based on the capabilities of
the mobile devices by using device filters. You can customize a mobile Web page for specific
types of devices by defining a set of device filters for the page.
ASP.NET allows you to specify device filters for each type of device by using the
<DeviceSpecific><Choice> tags. You can insert the <DeviceSpecific> tag as a child
element of any mobile control on the Web page. This tag acts as an outer container for
holding a number of choices defined by the <Choice> tag.
The <Choice> tag represents device characteristic/value pairs, where the device characteristic
is drawn from a number of sources. A control can contain only one <DeviceSpecific> tag.
However, it can contain many <Choice> tags. Choices are evaluated in the order in which
they appear in the DeviceSpecific/Choice construct. Each <Choice> tag contains:
A Filter attribute that specifies the devices that this choice applies to.
Additional property values that override the properties of the original control when
the device specified by the Filter attribute is used.
Consider a scenario wherein you need to control the display of an image by using the
<DeviceSpecific><Choice> tags. For this, you need to use the
<DeviceSpecific><Choice> tags as shown in the following example:
<mobile:Image runat=server>
<DeviceSpecific>
<Choice Filter="isColor" ImageURL="colorImg.gif" />
<Choice Filter="isWML11" ImageURL="myImage.wbmp" />
<Choice ImageURL="monoImage.gif" />
</DeviceSpecific>
</mobile:Image>
In the preceding example, if the device is colored as specified by the isColor value of the
Filter attribute, the colorImg.gif image will be displayed. For WML device,
myImage.wbmp image will be displayed. The third <Choice> tag does not have any Filter
attribute. Therefore, it is the default choice and will be evaluated if the preceding two choices
are not matched.
Note
WML devices are those devices that support Wireless Markup Language (WML) intended for
displaying Web pages on mobile devices. Currently, in place of WML, Extensible HyperText
Markup Language (XHTML) is used in mobile devices.
The Filter attribute in each <Choice> tag either specifies the name of a method on the
mobile form or associated .ascx file, or the name of a device filter defined in the
<deviceFilters> element of the web.config file.
Using the Name of a Method as Filters
When the name of a method is used as a filter, the choice is applied on the basis of the
Boolean value returned by the method.
The filter method must conform to the following signature:
public bool methodName(
System.Web.Mobile.MobileCapabilities capabilities,
string optionalArgument);
Comparison filter: Comparison filters make comparisons that are generally based on
a Boolean argument. In comparison filter, you need to provide the name of a
capability and the value that you want the filter to compare. The following markup
shows a comparison filter:
<system.web>
<deviceFilters>
<filter name="TestIsColor" compare="IsColor" argument="true" />
</deviceFilters>
</system.web>
In the preceding markup, TestIsColor is the name of the filter and
IsColor is the capability that is to be compared against the value,
true.
<deviceFilters>
<filter
name="TestIsColor"
type="CustomFilter"
method="checkColor" />
</deviceFilters>
</system.web>
In the preceding markup, TestIsColor is the name of the filter, CustomFilter is the
name of the class, and checkColor is the method that is called at run time to test the
evaluator. You need to write and compile the class containing the method that is used
to test the evaluator.
Note
In addition to device-specific rendering by using the <DeviceSpecific> element, you can
use the XhtmlTextWriter and ChtmlTextWriter classes to provide additional adaptive
rendering capabilities to the controls.
Summary
In this chapter, you learned that:
A Web page created for desktop browsers cannot be properly displayed on mobile
devices because mobile devices have small display area and low bandwidth.
ASP.NET provides you with the System.Web.Mobile namespace that is used
specifically for mobile Web development.
Mobile Web pages have some specific controls. These are:
o Form
o Command
o PhoneCall
o List and ObjectList
o DeviceSpecific
o
o
o
SelectionList
StyleSheet
TextView
Device emulators are software programs that simulate the environment of a cell phone
or PDA on the desktop of your PC.
A control adapter is used for device-specific rendering of mobile Web controls instead
of using the control's default rendering logic.
To customize the behavior of Web controls, you need to specify an object of the
ControlAdapter class.
The ControlAdapter class is an abstract class that defines the basic functionality for
all adapters.
The ability to render a control based on the type of the device is known as devicespecific rendering.
Reference Reading
Creating Mobile Web Pages
Reference Reading:
Books
http://msdn.microsoft.com/en-us/library/8htez1ds.aspx
http://en.wikipedia.org/wiki/Mobile_browser
http://msdn.microsoft.com/en-us/library/7s9fybz5.aspx