14 Aspnet
14 Aspnet
14 Aspnet
NET
Tirunelveli
ASP.NET
i
CONTENTS
Syllabus 270
YZ
Lecture 1
Introduction to ASP.NET
Objectives
In this lecture you will
learn the following
+ Knowing about Webserver & Virtual Directory
+ Features of ASP.NET
+ Advantages of ASP.NET
+ Advantages of ASP.NET
Coverage Plan
Lecture 1
1.1 Snap Shot
• A computer on a network that sends files to or runs applications for other computers on the network
• A software that runs on the server computer and performs the work of serving files or running
applications
• A code that exchanges information with another upon request
ASP.NET
ϕ Web Server is a program to server content
over the Internet using HTML
ϕ Web server accepts requests from browser
and then returns the appropriate HTML
documents
ϕ Every computer on the Internet that contains
a web site must have a web server program
ϕ Web servers are available for both Internet
and Intranet related programs
Web server is a server to serve content over the Internet using the Hypertext Markup Language (HTML).
The Web server accepts requests from browsers like Netscape and Internet Explorer and then returns the
appropriate HTML documents. Every computer on the Internet that contains a web site must have a Web
server program.
Client machine running a web browser Server machine running a web server
Figure 1.1
When the client asks for information such as a file, the Web server gets the file and sends it to the client. In
most cases, the Web server does not read or process this file, but sends it to the client.
A number of Server-Side technologies can be used to increase the power of the server beyond its ability to
deliver standard HTML pages, which include:
• CGI scripts
The most popular Web servers are Microsoft’s Internet Information Server (Internet Information Server),
which comes with the Windows NT server, Netscape FastTrack and Enterprise servers and Apache server,
a Web server for UNIX-based operating systems. Other Web servers include Novell’s Web Server for
users of its NetWare operating system and IBM’s family of Lotus Domino servers, primarily for IBM
customers.
Web servers are available for both Internet and Intranet related programs. Some of the functionalities
include:
• Serving E-Mail
Considerations in choosing a Web Server include the ability to work with the operating system and other
servers. Selection should also be based on the ability to handle Server-Side programming, publishing,
search engine, and site building tools that accompany it.
Web Page
Web page is a World Wide Web document. A Web page typically consists of an HTML file, with
associated files for graphics and scripts, in a particular directory on a particular computer (and thus
identifiable by a URL). Web pages can be classified as static or dynamic web pages.
A static web page is a page whose content is changed before being sent over the Internet to the user’s
computer. Such pages appear to the user to be static. An example of this kind of a web page is a page
that is created by a search engine. The static web page will not have any animation or lively user
interactions.
A dynamic web page is a page that contains animated GIFs, Java applets, ActiveX Controls, or DHTML. It
is a Web page created automatically based on information provided by the user, or generated with ASP.
ASP.NET
All the documents of a web site are stored in directories. The Web server cannot publish documents that
are not within these specified directories. The first step in deploying a web site is to determine how the
files need to be organized.
If a special directory is not created to store the documents, there is a default home directory in which all
the documents can be published by copying the Web files into the default home directory.
Home directory is the root directory for a web site, where the content files are stored. It is also called as a
document root or Web root. In Internet Information Services, the home directory and all its subdirectories
are available to users by default. Normally, the home directory for a site contains the home page.
A Virtual directory is created in order to publish from any directory not contained within the home
directory. A virtual directory is not contained in the home directory but appears to client browsers as
though it were. A virtual directory has an alias, a name that Web browsers use to access that directory.
Since an alias is usually shorter than the path of the directory, it is more convenient for users to type the
alias.
ASP.NET
Creating a Virtual Directory
As seen in the previous section, if the web site contains files that are located on a drive different from the
home directory, or on other computers, virtual directories must be created to include those files in the web
site. To use a directory on another computer, the directory’s Universal Naming Convention (UNC) name
must be specified and the user must be provided with a user name and password for access permission.
• In the Internet Information Services snap-in, select the web site or FTP site to which a directory has to
be added
• Click the Action button, and then point to New, and select Virtual Directory
• Use the New Virtual Directory Wizard to complete the task
Note : While using NTFS, a virtual directory can be created by right-clicking a directory in the Windows
Explorer, clicking Sharing, and then selecting the Web Sharing property sheet.
Figure 1.2
The key component of the new .NET framework has the potential to save organizations time and money
by allowing them to establish object-oriented frameworks for the web applications. Microsoft has done an
excellent job by automating common web development tasks. But more importantly they have created a
tool that gives developers the ability to handle any business problem.
What is ASP.NET?
ASP.NET
What is ASP.NET?
ASP.NET is a revolutionary new programming framework that enables the rapid development of
powerful web applications and services. Part of the emerging Microsoft .NET Platform, it provides the
easiest and most scalable way to build, deploy and run distributed web applications that can target any
browser or device.
ASP.NET has been designed to work seamlessly with WYSIWYG HTML editors and other programming
tools, including Microsoft Visual Studio.NET. Not only does this make Web development easier, but also
provides all the benefits that these tools have to offer, including a GUI that developers can use to drop
server controls onto a Web page, as well as fully integrated debugging support.
Web Clients
.NET Framework
Figure 1.3
As shown, all Web clients communicate with ASP.NET applications through IIS. IIS deciphers the request,
authenticates, and finds the requested resource (such as an ASP.NET application). If authorized, it returns
the appropriate resource to the client. In addition to the built-in ASP.NET security features, an ASP.NET
application can use the Common Language Runtime low-level security features.
This release of ASP.NET uses IIS 5.0 as the primary host environment. When considering ASP.NET
authentication, the interaction with IIS authentication services must be understood.
There are three different kinds of authentication in IIS 5.0: Basic, Digest, and Integrated Windows
Authentication. The type of authentication used can be set in the IIS administrative services. If a URL
containing an ASP.NET application is requested, both the request and information about authentication
get handed over to the application. ASP.NET provides two additional types of authentication: Cookie
authentication and Passport authentication.
Cookie-Based Authentication
Cookie authentication is a process that allows the application to collect credentials directly from the client
requestor (usually name and password), and determine their authenticity. IIS authentication is not used
by the application however, the IIS authentication settings are important to the ASP.NET cookie
authentication process. Unless the IIS “Anonymous Access” setting is enabled, requests that do not meet
the criteria for IIS authentication will be rejected and never reach the ASP.NET application.
Passport Authentication
Passport authentication is a centralized authentication service provided by Microsoft that offers a single
sign-in and core profile services for member sites.
ASP.NET
Major features of the ASP.NET
• Server Controls • Session State
• Form Validation • Web Services
• User Control • Registration of Components
• Mobile Control • Data Access
• Error Handling • User Authentication
and debugging • Server caching
• Configuration • Global.asax File
Details
Server Controls
ASP.NET introduces the concept of Server Controls, which enable the values of the controls to be
manipulated on the Server-Side.
An amazing feature of the Server-Side controls is the ability of these controls to fire Server-Side events.
Thus, the control appearing at the client, with runat attribute set to server can fire Server-Side events. This
is particularly useful when validating and dynamically generating forms.
The Server-Side controls can be subdivided into the following categories based on the functionalities that
they offer.
Intrinsic Controls
These controls create HTML elements on the client browser with the added capability of maintaining the
state.
List Controls
These Controls are used to display a wide variety of lists on the Client-Side.
Rich Controls
These are used to output HTML in a rich format to the client. The calendar control is an example of this
category.
Validation Controls
These make the art of Server-Side validation a cakewalk.
Session State
In ASP.NET, the Session state is automatically maintained by using a hidden field called view state.
Further, ASP.NET offers the flexibility to turn the Session state on or off at both the page level as well as
the control level. It is also possible to store the Session state directly in the SQL Server database and
retrieve at a later time.
Form Validation
ASP.NET offers a rich set of server controls to achieve the task of Form Validation. These controls are
popularly known as Validators or validation controls and can be used to validate all types of validations.
Web Services
ASP.NET offers a new concept called Web Services by which a web application can expose its
functionality to others on the Internet by employing a protocol such as Simple Object Access Protocol
(SOAP) and in XML format. This is entirely a new concept. Web Services can be employed for displaying
news headlines, weather reports etc.
User Controls
ASP.NET offers code reusability by introducing the concept of “User Controls.” A User Control is a
pseudo control, wrapped with common code that can expose properties, methods and events. These can
be employed for opening and closing a database connection, which happen quite frequently in all the
pages. User Controls can be employed to wrap up the most frequently used HTML code and reuse it
across several Web pages.
Registration of Components
In web development, it is a common practice to apply the business logic as COM Components. This
concept has been received very well by the developers, as there is a performance boost when such
business objects are employed. This performance boost is due to the fact that the components are
compiled. But the maintenance poses a great problem. If a component has to be unregistered from use by
the web server, the server has to be restarted.
ASP.NET has the solution for this problem. If a component is to be registered in ASP.NET, it has to be
copied in the web application’s “bin” directory. The file has to be deleted to unregister the component.
Mobile Controls
ASP.NET is in tune with M-Commerce by providing .NET Mobile Web SDK that allows applications to be
built covering a wide range of mobile devices ranging from cellular phones to Personal Digital Assistants.
Data Access
ASP.NET has introduced the next generation of ADO known as ADO.NET with respect to data access.
ADO.NET places more emphasis on disconnected recordsets by employing XML as a medium of
communication between these recordsets and the DataStore.
ASP.NET offers a cleaner approach to error handling and debugging as compared to its predecessor ASP.
It is now possible to specify individual error pages for each ASP.NET page by employing the new
ErrorPage directive.
In the above example, if any error occurs on the page, the user is directed to myErrorPage.aspx. This type
of error handling enables developers to circumvent the IIS error pages altogether.
User Authentication
ASP.NET offers several kinds of authentication for checking the validity of the users accessing a web site.
In addition to support for Basic, Digest and Windows NT(NTLM), ASP.NET also supports Passport
authentication (explained later).
Server-Side Caching
The process of retaining most frequently visited web pages in memory is called caching. Caching of
ASP.NET Page leads to an increase in its performance. ASP.NET supports the following two types of
caching
• Output caching
• Data Caching
Output caching is the process of caching the entire page, this kind of caching is advisable for sites with
heavy traffic. Data caching is the process of caching a part of the page that includes objects and data.
Configuration Details
ASP.NET maintains all the configuration details pertaining to a web application in a file called Config.web
which is in a human readable format (XML). The whole range of configuration details including which
request to handle on specific situation, tracing options etc.
Global.asax File
In ASP.NET it is possible to specify the event-handlers that need to be invoked on the occurrence of
particular events. These event-handlers are defined in a global file by name Global.asax. The Global.asax
file of ASP.NET has a provision for the following event-handlers
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
10
Introduction to ASP.NET
• Application_OnStart
• Application_OnEnd
• Session_OnStart
• Session_OnEnd
• Application_BeginRequest
• Security_OnAuthenticate
Finally, ASP.NET provides a powerful framework for developing and deploying Next Generation Web
Applications. ASP.NET will have a significant impact on the web application development in future.
ASP.NET
Major benefits of ASP.NET
ϕ Complied Pages
ϕ More Scripting Choice
ϕ Improved IDE and Debugger
ϕ Server Controls
ϕ Platforms Independence
ϕ Separation of Logic
ϕ Backwards Compatibility
The greatly improved ASP.NET runtime handles many routine tasks in the code. Although there are
major benefits of ASP.NET, here are some that will prove beneficial to the majority of the development
tasks.
Compiled Pages
A page is compiled into a .NET class when it is requested the first time. The runtime engine will detect if
any changes have been made to the source code and recompile it if necessary. The user can optionally
specify a class file with the page, otherwise it will be created by the ASP runtime.
The entire .NET family shares the same IDE and debugging tools. The user will benefit from the feature
rich debugging tools of ASP.NET.
Server Controls
Server-Side components automate many common development tasks. These controls can detect the
version of the browser and generate the proper HTML and JavaScript code.
Browser Independence
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
11
ASP.NET
The ASP.NET runtime is capable of detecting the browser type of the requesting client and generate the
proper HTML or JavaScript code. This has the potential of making ASP.NET applications browser
independent.
Separation of Logic
ASP.NET has been designed to separate business logic and presentation by utilizing ASP and COM. The
task of encapsulating the logic from the user’s presentation has been made easier. Application separation
is the key to productivity. By creating .NET components and class files, the user can maximize code re-use.
Backward Compatibility
Organizations will be able to leverage their existing investments in COM and COM+. ASP.NET
applications can interact with legacy COM objects.
ASP.NET
Dataflow in ASP.NET
2. IIS receives the request, and if the requestor is authenticated by IIS - or if IIS “Anonymous Access” is
enabled, it is passed on to the ASP.NET application. Because the authentication mode in the
ASP.NET application is set to “cookie”, any IIS authentication is not used.
3. ASP.NET checks to see if a valid authentication cookie is attached to the request. If the identity’s
credentials have been confirmed previously, the request is tested for authorization. The authorization
test is performed by ASP.NET and accomplished by comparing the credentials contained in the
request’s authorization cookie with the authorization settings in the application configuration files
(config.web). If the user is authorized, access is granted to the protected resource - or the application
may require an additional test of the credentials before authorizing access to the protected resource,
depending on the design of the application.
Client Requests
IIS
ASP.NET
Authenticate
Credentials
Yes Authenticated?
Attach Cookie
Test Authorization
Authorized? Yes
Yes
4. If there is no cookie attached to the request, ASP.NET redirects the request to a login page (the path
of which resides in the application’s configuration file) where the client user enters the required
credentials (usually a name and password).
5. The application code checks the credentials to confirm their authenticity (usually in an event
handler) and if authenticated, attaches a cookie ticket containing the credentials to the request. If
authentication fails, the request is usually returned with an “Access Denied” message.
6. If the user is authenticated, ASP.NET checks authorization as in step 3, and can either allow access to
the originally requested, protected resource or redirect the request to some other page, depending on
the design of the application. It can otherwise, direct the request to a custom form of authorization
where the credentials are tested for authorization to the protected resource. Usually if authorization
fails, the request is returned with an “Access Denied” message.
Practice 1.1
<HTML>
<HEAD>
<TITLE>ASP Script</TITLE>
<script language=”C#” runat=”server”>
void Page_Load(Object s,EventArgs x)
{
Response.Write(“Welcome to Radiant”);
}
</script>
</HEAD>
</HTML>
Save this file as Simple.aspx in the Inetpub\wwwroot directory, which is the home directory. (If no
alteration has been made in the Internet Information Server’s Service Manager, this will be the home
directory for the default web site).
(or)
Place the Simple.aspx file in any desired directory, and create a virtual directory (see Creating a Virtual
Directory) to map to the physical directory in which the Simple.aspx file has been stored.
Open Simple.aspx in the Web browser by specifying its URL as in the following:
http://machine_name/ Simple.aspx
As it can be seen from the above output, the application is saved in a virtual directory called “aspvir”.
• Web server is a program that is used to serve content over the Internet using the Hypertext Markup
Language (HTML)
• When the client asks for information such as a file, the Web server gets the file and sends it to the
client
• Web servers are available for both Internet and Intranet related programs
• A Web page typically consists of an HTML file with associated files for graphics and scripts in a
particular directory on a particular computer (and thus identifiable by a URL)
• A static web page is a page whose content is changed before being sent over the Internet to the user’s
computer. Such pages appear to the user to be static
• A dynamic web page is a page that contains animated GIFs, Java applets, ActiveX Controls, or
DHTML
• Home directory is the root directory for a web site, where the content files are stored
• The major features of the ASP.NET are server control, session state, form validation, web services,
user control, mobile control, data access, error handling and debugging, user authentication and
server- side caching etc.
• The various advantages provided by the ASP.NET environment are compiled pages, more scripting
charges, server controls, platform independence and separation of logic etc.
• There are different ways of securing ASP.NET applications, depending on the preferences of the
designer
• An ASP.NET application can be saved either in the Home directory or Virtual directory
YZ
Lecture 2
Objectives
In this lecture you will
learn the following
+ Basic coding in ASP.NET
Coverage Plan
Lecture 2
2.1 Snap Shot
ASP executes components on the server and generates sections of the page that are returned to the user.
This concept is extended in ASP.NET through server controls. The requirement to convert an HTML
element into a server control is the addition of an extra attribute: runat=“server”. Any HTML element in a
page can be marked using this method and ASP.NET processes the elements on the server and generates
output which is suitable to a specific client.
One of the most tedious tasks in creating interactive Web sites and applications is managing the values
passed to the server from HTML form controls, and maintaining the values between page requests. Hence,
one of the aims of ASP.NET is to simplify this programming task that involves no extra effort on the part
of the programmer, and works well with any browser that supports basic HTML.
ASP.NET
Most of the existing ASP pages use either VBScript or Jscript. Since both of these are being interpreted
languages, they are no longer supported by ASP.NET.
ASP.NET, currently offers built-in support for three languages: C#, Visual Basic, and JScript.NET.
Component-based applications can be created using any of the Visual Studio .NET languages: Managed
Extensions (produced using Visual C++ .NET), Visual Basic, and C#.
An ASP.NET page is restricted to code written in a SINGLE language. The default language is C#, but any
other compliant language can be declared as the default for the page through a directive like:
The language may also be declared within <script> blocks as shown below:
If different languages are declared in separate script blocks on the same page, an error will be thrown.
“Render functions” are not supported in ASP.NET. It is possible to insert literal HTML within a
procedure body in the earlier versions of ASP:
<script runat=server>
Sub SomeProcedure()
Response.Write(“<H3> Render this line in bold text.</H3>”)
End Sub
</script>
Postback events
A Web page must be static to be viewed through the widest range of browsers. This means any interaction
with the user (such as updating the display in response to a button click) must be resolved by calling the
Web server and sending a new page.
The simplest way of implementing a request-response dialog is through the HTML form element. When a
form is submitted, it invokes its target URL, sends the page and data from its data entry controls. A well-
written ASP page submits the form to it, using hidden fields to cache the data needed to reconstruct the
current state in the refreshed client display.
A postback event occurs on the client, but handled by the code in a copy of the page running on the
server. For example, in an ordinary page a pushbutton can have an OnClick event, which is handled by
the client-side code. In ASP.NET pushbutton can have an OnServerClick event, which causes a round-trip
back to the server. When accessed by the server- side event handler, the values of the form’s control
properties reflect the data submitted by the client-side form, and any updates performed by the handler
are reflected in the refreshed client display. Postback events are the key to the advanced features of
DataGrid and DataList controls. They simplify development by hiding the difficulties of the stateless
HTTP model.
Practice 2.1
The following code shows a simple ASP.NET application.
<HTML>
<HEAD>
<TITLE>ASP Script</TITLE>
<script language=”C#” runat=”server”>
void Page_Load(Object sender,EventArgs e)
{
Response.Write(“Welcome to Radiant”);
}
</script>
</HEAD>
<HTML>
In the above program, the Response.Write method is used in Page_Load to display the message in the
browser.
Page Directives
ASP.NET
In the previous versions of ASP, a single page can contain only one page directive. The directive is
generally used to define the script language that is used to code. For example,
<%@Language=”JScript”%>
The transition state for the page, the character encoding and several other properties can also be set by
using this directive. In ASP.NET, it is possible to accept multiple directive statements in a page. The
default directive has the name Page.
<%@Page Language=”JScript”%>
The above directive supports the existing ASP attributes like Transition=“Required”. The other directives
supported are listed in Table 2.1.
CONTENTTYPE Any content type string HTTP content type for the output.
INHERITS Page-derived COM+ class “Code-behind” class for the page to inherit from.
LANGUAGE VB, JScript, C# or {other} Language used when compiling all <%…%>
blocks in the page.
Table 2.1
In order to maintain backward compatibility, the directive statements in a page having no recognized
directive name like Page, Register etc. will be considered as the Page directive statement. For example,
<%@Language=”JScript”%>
is taken as
<%@Page Language=”JScript”%>
Server controls are specifically designed to work with Web Forms. They differ from Windows controls
since they work within the ASP.NET framework. Due to this, server controls feature unique design
considerations. The different types of controls are:
z HTML Server Controls - HTML elements are exposed to the server. They expose an object model that
maps very closely to the HTML elements that they render
z ASP.NET Web Controls - Controls having more built-in features than HTML server controls.
ASP.NET server controls include controls like buttons, text boxes and also special-purpose controls
like calendar. ASP.NET server controls does not necessarily reflect HTML syntax
z Validation Controls - Controls that incorporate logic to test the user input. A validation control is
attached to an input control to test data entered by the user for that input control. Validation controls
allows to check for a required field, to test against a specific value or pattern of characters, between
ranges, and so on
z User Controls - Controls that are created by the user as Web Forms pages. Web Forms User Controls
can be embedded in other Web Forms pages and hence menus, toolbars, and other reusable elements
can be created easily
HTML controls offer Web developers the power of the Web Forms page framework while retaining the
familiarity and easier use of HTML elements. These controls look exactly like HTML, except they have a
runat=”server” attribute/value pair in the opening tag of an HTML element. For example, the following
HTML would not only create a text box on a Web page, but would also create an instance of the
HtmlInputText server control:
Note: The runat and id properties are mandatory to all the HtmlServerControls.
Without runat=”server”, this line of HTML would be parsed into a standard text box. This model allows
developers to import an HTML page authored by a Web designer and program against selected elements
on the page. In addition, once an element is converted to a control, a Microsoft .NET Framework class is
created for the element and its attributes are exposed as properties on the HTML control.
To enable programmatic referencing of the control, developers can include a unique id attribute. In the
above example, the id=”myTextBox” defines this programmatic ID, allowing developers to manipulate
the contents of this text box with events and other code that they write.
ASP.NET offers direct object model support for the most commonly used HTML elements. For those
elements that are not directly supported, there is the HtmlGenericControl, which supports the <span>,
<div>, <body>, and <font> elements, among others.
In addition, HTML controls offer the following features:
• A set of events for which handlers can be written in much the same way as it is done in a client-based
form, except that the event is handled in the server code
• The ability to handle events in client script
• None of them emit ECMAScript to the client when responding to a request
• Automatic management of the values of the form’s controls. If the form makes a round trip to the
server, HTML controls are automatically populated with the values they had when the form was
submitted to the server
• Interaction with validation controls helps to verify that a user has entered appropriate information
into a control
• Databinding to a single field, property, method, or expression (simple data binding) or a collection
(list databinding)
• Support for HTML 4.0 styles
• Pass-through of custom attributes. The required attributes can be added to HTML control. The Web
Forms framework will read them and render them without any change in functionality. This allows
the user to add browser-specific attributes to the controls
• All controls that post back events must be nested within an HtmlForm control. For example, the
following input elements would be parsed correctly as HTML server controls:
<form runat=”server” id=”myForm”>
<input type=”text” id=”myTextBox” runat=”server”>
<input type=”submit” id=”mySubmitButton”
OnServerClick=”SubmitBtn_Click” runat=”server”>
</form>
• All HTML controls must be well formed and should not overlap. Unless noted, elements must be
closed, either with an ending slash within the tag, or with a closing tag. For example,
<span id=”mySpan” runat=”server”/>
or
<span id=”mySpan” runat=”server”>Span text to be displayed here</span>
System.Object
System.Web.UI.Control
HtmlControl
HtmlInputButton HtmlAnchor
HtmlInputCheckBox HtmlButton
HtmlInputFile HtmlForm
HtmlInputHidden HtmlGenericControl
HtmlInputImage HtmlSelect
HtmlInputRadioButton HtmlTable
HtmlInputText HtmlTableCell
HtmlTableRow
HtmlInputButton Control
ASP.NET
ϕ Allows to program against the HTML <input
type=button>, <input type=submit>, and
<input type=reset> elements
When a user clicks on HTML Input Button control, input from the form that contains the embedded
control is posted to the server. The processing is done in the server and a response is sent back to the
requesting browser.
The HtmlInputButton is used in conjunction with the HtmlInputText and HtmlTextArea controls to create
user input or authentication pages that can be processed on the server.
Syntax
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
24
HTML Server-Side Controls
<input
type=button | submit | reset
runat=”server”
id=”programmaticID”
OnServerClick=”OnServerClickhandler”
>
• id is the id of the button
• OnServerClick is the handler for the button click event
Practice 2.2
The following program displays a text box and a button and displays a message when the button is
clicked.
<html>
<head>
<script language=”C#” runat=”server”>
void Button1_Click(object Source, EventArgs e)
{
Span1.InnerHtml= Name.Value + “ clicked the button”;
}
</script>
</head>
<body>
<h5><font face=”Arial”>Enter name and click the button</font></h5>
<form runat=server>
<p> Name:<input id=”Name” type=text size=40 runat=”server”><br>
<input type=button value=”Click Me” OnServerClick=”Button1_Click”
runat=”server”>
<span id=Span1 runat=server />
</form>
</body>
</html>
The above program displays a text box and a button using the input tag. When the button is clicked after
entering the text in the textbox, the Button_Click1 function is called and the text is displayed using span.
HtmlInputFile Control
The HtmlInputFile control is used to design a page that allows uploading a file to a directory designated
on the Web Server. The control allows to program against the HTML <input type=file> element. This
control allows uploading of a binary or text file from a browser to the server. File upload is enabled in
HTML.
Syntax
<input
type=file
runat=”server”
id=”programmaticID”
accept=”MIMEencodings”
maxlength=”maxfilepathlength”
size=”widthoffilepathtextbox”
postedfile=”uploadedfile”
>
• type is the file type (text, binary, etc)
• postedfile is the name of the file that is uploaded
• maxlength is the maximum length of the file path
Practice 2.3
The following program illustrates how to upload a file to the Web server.
<html>
<head>
<script language=”C#” runat=”server”>
void Button1_Click(object Source, EventArgs e)
{
if (Text1.Value == “”)
{
Span1.InnerHtml = “Please enter a file name”;
return;
}
if (File1.PostedFile != null)
{
try
{
File1.PostedFile.SaveAs(“d:\\files\\”+Text1.Value);
Span1.InnerHtml = “File uploaded successfully to
<b>c:\\temp\\”+Text1.Value+”</b> on the web server”;
}
catch (Exception exc)
{
Span1.InnerHtml = “Error saving file
<b>c:\\temp\\”+Text1.Value+”</b><br>”+ exc.ToString();
}
}
}
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
26
HTML Server-Side Controls
</script>
</head>
<body>
<form enctype=”multipart/form-data” runat=”server”>
Select File to Upload: <input id=”File1" type=file runat=”server”>
<p> Save as filename (no path): <input id=”Text1" type=”text”
runat=”server”>
<p> <span id=Span1 style=”font: 8pt verdana;” runat=”server” />
<p> <input type=button id=”Button1" value=”Upload”
OnServerClick=”Button1_Click” runat=”server”>
</form>
</body>
</html>
The above program prompts the user to select a file to upload to the Web server. It requires a new
filename and if it is not entered, an error message is displayed. The program also displays an error
message if there is a problem in saving the file. When the file is uploaded successfully a message is
displayed.
HtmlInputImage Control
The HtmlInputImage control allows to program against the HTML <input type=image> element. This
control is used in conjunction with the HtmlInputText, HtmlTextArea, and other controls to construct
user input forms. Since this control is run on the server, it offers the same customizations for the button
like HTML. This control offers greater support for earlier browsers than the HtmlButton control.
Syntax
<input
type=image
runat=”server”
id=”programmaticID”
src=”imagepath”
align=”imagealignment”
alt=”alttext”
OnServerClick=”OnServerClickhandler”
width=”borderwidthinpixels”
>
• alt is the alternate text that has to be displayed in case the image file is absent in the specified path
Practice 2.4
The following program displays two images and responds to the mouse move and mouse click events.
<head>
<script language=”C#” runat=”server”>
void Button1_Click(object Source, ImageClickEventArgs e)
{
Message.InnerHtml=”You clicked image1";
}
void Button2_Click(object Source, ImageClickEventArgs e)
{
Message.InnerHtml=”You clicked image2";
}
</script>
</head>
<form runat=”server”>
<p><input type=image id=”InputImage1" src=”d:/images/one.bmp”
OnServerClick=”Button1_Click” runat=”server”>
<p><input type=image id=”InputImage2" src=”d:/images/one.bmp”
onmouseover=”this.src=’d:/images/two.bmp’;”
onmouseout=”this.src=’d:/images/one.bmp’;” OnServerClick=”Button2_Click”
runat=”server”>
<p><span id=”Message” runat=”server”/>
</form>
In the above program, two images are loaded using the Html-input control. When the mouse cursor is
moved over the second image, the image changes to another image using the onmouseover. When the
mouse is moved out of the second image, the original image is loaded using onmouseout. When either of
the images is clicked, a message is displayed indicating the image that is clicked. This is handled by the
OnServerClick event.
HtmlInputText Control
ASP.NET
This control can be used in conjunction with the HtmlInputButton, HtmlInputImage, or HtmlButton
control to process user input on the server. Values can be assigned and retrieved to the properties
HtmlInputText MaxLength, Size, and Value.
Syntax
<input
type=text | password
runat=”server”
id=”programmaticID”
maxlength=”max#ofcharacters”
size=”widthoftextbox”
value=”defaulttextboxcontents”
>
z type specifies whether the input characters are for an ordinary field or for a password field. If set to
password, then an asterisk (*) is displayed instead of the character which is typed to preserve secrecy
z maxlength attribute specifies the maximum length of the text that can be typed in the text box
Practice 2.5
<head>
<script language=”C#” runat=”server”>
void SubmitBtn_Click(object Source, EventArgs e)
{
if (Password.Value == “ASP.NET”)
Message.InnerHtml=”Access Granted”;
else
Message.InnerHtml=”Access Denied”;
}
</script>
</head>
<body>
<form runat=”server”>
<table cellpadding=5>
<tr>
<td>Login: </td>
<td><input id=”Name” runat=”server”></td>
</tr>
<tr>
<td>Password: </td>
<td><input id=”Password” type=password runat=”server”></td>
</tr>
<tr>
<td colspan=2 align=”center”><input type=submit value=”Enter”
OnServerClick=”SubmitBtn_Click” runat=”server”> </td>
</tr>
</table>
<p><span id=”Message” runat=”server”/>
</form>
</body>
In the above program, two text boxes are displayed to enter the user name and password. If the password
entered is ASP.NET, then the message Access Granted is displayed, otherwise the message Access
Denied is displayed.
HtmlForm Control
The HtmlForm control allows to program against the HTML <form> element. All Web Form controls,
whether HTML, Web, pagelet or custom, must be nested between well-formed opening and closing tags
of the HtmlForm control in order to take advantage of the page framework’s postback services.
Note: More than one HtmlForm control cannot be included on a single Web Forms page.
By default, the method attribute of the HtmlForm control is set to POST, and the action attribute is set to
the URL of the source page. These attributes can be customized to suit the needs of an individual.
However, this can break the built-in view state and postback services provided by the Web Forms Page
Framework.
Syntax
<form
runat=”server”
id=”programmaticID”
method=POST | GET
action=”srcpageURL”
>
Other controls, input forms, and so on.
</form>
• method is the way in which the form is displayed
• action is the URL source
Practice 2.6
<head>
<script language=”C#” runat=”server”>
void Button1_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml=”Submit clicked”;
}
void Button2_OnClick(object Source, EventArgs e)
{
Span2.InnerHtml=”Cancel clicked”;
}
</script>
</head>
<body>
<div class=”header”><h3>HtmlForm</h3></div>
<form id=ServerForm runat=”server”>
<p><button id=Button1 runat=”server” OnServerClick=”Button1_OnClick”>
Submit</button>
<span id=”Span1" runat=”server” />
<p><button id=Button2 runat=”server” OnServerClick=”Button2_OnClick”>
Cancel</button>
<span id=Span2 runat=”server” />
</form>
</body>
The above program displays two buttons in a form that has the id ServerForm. The form has two buttons
namely Submit and Cancel. When the buttons are clicked, the appropriate messages appear on the right
side of the button.
HtmlSelect Control
ASP.NET
Syntax
<select
runat=”server”
id=”programmaticID”
OnServerChange=”onserverchangehandler”
DataSource=”databindingsource”
DataTextField=”fieldtodatabindoptionttext”
DataValueField=”fieldtodatabindoptionvalue”
MultipleItems=”collectionofoptionelements”
SelectedIndex=”indexofcurrentlyselecteditem”
Size=”#ofvisibleitems”
Value=”currentitemvalue”
>
<option>value1</option>
<option>value2</option>
</select>
Practice 2.7
The following program creates a selectable drop-down list and allows to choose an option.
<head>
<script language=”C#” runat=”server”>
}
void AddToList_Click(object Source, EventArgs e)
{
ColorSelect.Items.Add(Text1.Value);
}
</script>
</head>
<body>
<form runat=”server”>
<p>Select a color:
<select id=”ColorSelect” runat=”server”>
<option>SkyBlue</option>
<option>LightGreen</option>
<option>Blue</option>
<option>Yellow</option>
</select>
<input type=”button” runat=”server” Value=”Apply”
OnServerClick=”Apply_Click”>
<p>Add new colors<br>
<input type=”text” id=”Text1" runat=”server”>
<input type=”button” runat=”server” Value=”Add to List”
OnServerClick=”AddToList_Click”>
<p><span id=”Message” runat=”server”> See the background color change here.
</span>
</form>
</body>
The above program displays a listbox of colors. On selecting an option from the list and clicking the
Apply button, the color of the text at the bottom of the page is changed. If a new color is to be added to the
list, the name is typed in the text box and the Add to List button is clicked.
HtmlTable Control
The HtmlTable control allows to program against the HTML <table> element. A table control can be
dynamically bound to add rows and cells to the table using the methods provided by the
HtmlTableRowCollection and HtmlTableCellCollection.
Syntax
<table runat=”server”
id=”accessID”
align=left | center | right
bgcolor=”bgcolor”
border=”borderwidthinpixels”
bordercolor=”bordercolor”
cellpadding=”spacingwithincellsinpixels”
cellspacing=”spacingbetweencellsinpixels”
height=”tableheight”
rows=”collectionofrows”
width=”tablewidth”
>
</table>
HtmlTableCell Control
The HtmlTableCell control allows programming against the HTML <td> and <th> elements. Cell can be
added dynamically to an HtmlTableRow control, in response to control events or by binding an
HtmlTable control to the entries in a data source.
Syntax
<td or th
runat=”server”
id=”programmaticID”
align=”alignmentofcontentincell”
bgcolor=”bgcolor”
bordercolor=”bordercolor”
colspan=”#ofcolscellspans”
height=”tableheight”
nowrap=”True | False”
rowspan=”#ofrowscellspans”
valign=”vertalignmentofcellcontent”
width=”cellwidth”
>
CellContent
</td or /th>
HtmlTableRow Control
Creates a table row control. The HtmlTableRow control allows you to program against the HTML <tr>
element. Rows can be dynamically added to an HtmlTable control, whether in response to control events
or through binding an HtmlTable control to the entries in a data source.
Syntax
<tr runat=”server”
id=”accessID”
align=”tablecontentalignment”
bgcolor=”tablebgcolor”
bordercolor=”bordercolor”
height=”tableheight”
cells=”collectionoftablecells”
valign=”verticalalignmentofrowcontent”
>
<td>cellcontent</td>
</tr>
Practice 2.8
The following program illustrates the use of table, tablecell and tablerow.
<head>
<script language=”C#” runat=”server”>
<body>
<div class=”header”><h3>Create Table</h3></div>
<div align=”center”>
<form runat=”server”>
<table>
<tr>
<td>Rows:</td>
<td>
<select id=”Select1" runat=”server”>
<option Value=”2">2</option>
<option Value=”3">3</option>
<option Value=”4">4</option>
</select></td>
<td>Columns:</td>
<td>
<select id=”Select2" runat=”server”>
<option Value=”2">2</option>
<option Value=”3">3</option>
<option Value=”4">4</option>
</select></td></tr>
</table>
<p><input type=”submit” runat=”server” value=”Generate Table” > </form>
<p><table id=”Table1" runat=”server” CellPadding=4 Border=2 /></p>
</div>
</body>
</html>
The above example uses the Add function to add cells and rows to a table dynamically. The number of
rows and columns of the table are selected from the two drop down list boxes, one for the number of rows
of the table and the other for the number of columns.
HtmlTextArea Control
ASP.NET
Syntax
<textarea
runat=”server”
id=”programmaticID”
cols=”numberofcolsintextarea”
name=”namepassedtobrowser”
rows=”numberofrowsintextarea”
OnServerChange=”onserverchangehandler”
>
textareacontent
</textarea>
Practice 2.9
The following program displays a text area.
<head>
<script language=”C#” runat=”server”>
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.InnerHtml= TextArea1.Value;
}
</script>
</head>
<H3>Customize the message in your e-card</H3>
<body>
<form runat=”server”>
<p>Your message</p>
<textarea id=”TextArea1" runat=”server” cols=40 rows=4 />
<p><input type=submit value=”Send Card” runat=”server”
OnServerClick=”SubmitBtn_Click”>
<p><span id=”Message” runat=”server” />
</form>
</body>
In the above program, a text area is displayed along with a button. On clicking the button, after entering
text in the text area, the typed text is displayed below the button.
HtmlInputCheckBox Control
ASP.NET
When checked, its Checked property returns true. HtmlInputCheckBox is typically used with other user-
input controls, such as the HtmlInputButton control, to determine whether a check box is selected. This is
done by evaluating the Checked property on this control.
Syntax
<input type=”radio”
runat=”server”
id=”accessID”
checked
name=”radiobuttongroup”
>
The HtmlCheckBox control does not have an event that notifies the server when a user has selected the
control. Checkbox can be used with one of the button controls — such as the HtmlInputButton,
Practice 2.10
HtmlInputImage, or HtmlButton — to cause a postback that will allow to program the HtmlCheckBox
control itself.
The following example illustrates the use of HtmlInputCheckBox control. When a user clicks the input
button included on the form, the button’s click event handler evaluates the value of the
HtmlInputCheckBox control’s Checked property, then displays a message in a span control that depends
on the value of the property.
<head>
<script language=”C#” runat=”server”>
void Button1_Click(object Source, EventArgs e) {
if (Check1.Checked== true) {
Message.InnerHtml=”Checkbox is checked!”;
}
else {
Message.InnerHtml=”Checkbox is not checked!”;
}
}
</script>
</head>
<form runat=”server”>
<input id=”Check1" type=checkbox runat=”server”> CheckBox1
<input type=button id=”Button1" value=”Enter”
OnServerClick=”Button1_Click” runat=”server”>
<p><span id=”Message” style=”color:#600" runat=”server” />
</form>
In the above program a check box and a button are used. In the OnServerClick event of the button, we
check, whether the checkbox is checked or not. It also prints whether the checkbox is checked or
unchecked.
HtmlInputRadioButton
The HtmlInputRadioButton control creates a single radio button input field. By default, each individual
radio button can be selected.
Syntax
<input type=”radio”
runat=”server”
id=”controlID”
checked
name=”radiobuttongroup”
>
This control does not require an opening and closing tag. The HtmlRadioButton control does not have an
event that notifies the server when a user has selected one of the buttons.
A set of radio buttons can be grouped together in cases where only one button from the set of options
needs to be selected. This is done by setting a common value for the Name attribute on each radio button
in the group. For example, the following block of code creates a group of radio buttons in which only one
radio button may be selected.
However, the selected state must be tested on the individual radio buttons. HtmlInputRadioButton
allows to program against the HTML <input type=radio> element.
Practice 2.11
The sample given below illustrates the use of HtmlInputRadioButton control.
<form runat=”server”>
<h3>RADIO Input Box Example</h3>
<input type=”radio” id=”Red” name=”Mode” runat=”server”/>Red<br>
<input type=”radio” id=”Green” name=”Mode” runat=”server”/>Green<br>
<input type=”radio” id=”Blue” name=”Mode” runat=”server”/>Blue
<p><input type=button id=”Button1" value=”Enter”
OnServerClick=”Button1_Click” runat=”server”>
<p><span id=”Message” runat=”server” />
</form>
<script language=”C#” runat= “server”>
void Button1_Click(object Source, EventArgs e) {
if (Red.Checked== true)
Message.InnerHtml=”Red is checked”;
else if (Green.Checked== true)
Message.InnerHtml=”Green is checked”;
else if (Blue.Checked==true)
Message.InnerHtml=”Blue is checked”;
}
</script>
To respond to user selection of radio button controls, a set of radio button controls are declared. A button
control causes postback when clicked by the user. A span control is used here to render the postback
message. Event-handling code is included to process the information gathered from the radio button
group.
HtmlAnchor Control
ASP.NET
The HtmlAnchor control is used to navigate from the client page to another page, or to another location
within the same page.
This control can be generated by using a data source. Control events can be used dynamically to generate
this control.
Syntax
<a runat=”server”
id=”accessID”
href=”linkurl”
name=”bookmarkname”
OnServerClick=”OnServerClickhandler”
target=”linkedcontentframeorwindow”
title=”titledisplayedbybrowser”
>
linktext
</a>
Target values must begin with a letter, except when mentioning the following special values that begin
with an underscore: _blank, _self, _parent, and _top. This control requires an opening and closing tag.
Note: Remember to embed the HtmlAnchor control inside the opening and closing tags of an HtmlForm
control.
The hyperlinks can be generated on a Web Forms page by binding the HtmlAnchor control to a data
source.
Practice 2.12
The following example shows how to include an HtmlAnchor control and to bind the address of the links
(URLs), as well as to link the text in order to display for the controls.
<html>
<head>
<title>Simple HtmlAnchor Sample</title>
<script language=”C#” runat=server>
void Page_Load(Object sender, EventArgs e)
{
anchor1.HRef=”/”;
}
</script>
</head>
<body>
<h3>Simple HtmlAnchor Sample</h3>
<form runat=server>
<p><a id=anchor1 runat=”server”>Home</a>
</form>
</body>
</html>
In this example the anchor control is used to load another page. The HRef refers to Index.html and when
the anchor is clicked, the index.html page is loaded in the browser.
<form runat=”server”>
<p><a id=anchor1 runat=”server”>Home</a>
</form>
An event-handling code that assigns a URL to the HtmlControl HRef property has to be writen. The
following code generates a URL that will let the user navigate the site’s home page when the Page_Load
event occurs.
HtmlGenericControl
The HtmlGenericControl provides a server control implementation for all other HTML server control tags
that are not directly represented by a specific HTML server control. These include the <span>, <body>,
<div>, and <font> elements, among others.
Syntax
<span | body | div | font | others
runat=”server”
id=”accessID”
>
element content here
</span | body | div | font | others>
An HtmlGenericControl is created on the server in response to tags that include the runat=“server”
attribute in elements that do not map directly to a specific HTML control. The control maps the name of
the tag of the particular element to be used as an HTML control to the page framework through the
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
44
HTML Server-Side Controls
TagName property. This control inherits the functionality from the HtmlContainerControl class, which
allows to dynamically change the inner content of HTML control tags.
Practice 2.13
The following example shows how an HtmlGenericControl is used to modify a background color of the
page. The sample also demonstrates how to use the AttributeCollection class to programmatically access
the attributes that can be declared on any HTML control, in this case, the HTML BODY element.
<html>
<head>
<script language=”C#” runat=”server”>
void SubmitBtn_Click(object Source, EventArgs e) {
Body.Attributes[“bgcolor”]=ColorSelect.Value;
}
</script>
</head>
<body id=Body runat=”server”>
<div class=”header”><h3>HtmlGenericControl Sample</h3></div>
<form runat=”server”>
<p>Select a background color for the page: <p>
<select id=”ColorSelect” runat=”server”>
<option>White</option>
<option>Wheat</option>
<option>Red</option>
<option>Green</option>
</select>
<input type=”submit” runat=”server”
Value=”Apply” OnServerClick=”SubmitBtn_Click”>
</form>
</body>
</html>
The above program uses an HtmlGenericControl to display a list box and a button. When a color is
selected and the Apply button is clicked, the background color of the form changes accordingly.
HtmlImage Control
ASP.NET
The HtmlImage control allows to program against the HTML <img> element. This control allows to
dynamically set and retrieve image attributes that include the src, width, height, border, alt, and align
attributes.
The HtmlImage server control renders an image file specified by its Src property. The HtmlImage control
allows to program against the HTML <img> element, enabling developers to dynamically set and retrieve
image attributes, including the image file’s src, width, height, border, alt, and align attributes.
Practice 2.14
The following example shows how to dynamically change a displayed image in a Web Forms page based
on the choice of the user.
<html>
<head>
<script language=”C#” runat=”server”>
void SubmitBtn_Click(object Sender, EventArgs e) {
Image1.Src=”d:/myprog/asp.net/Images/” + Select1.Value;
}
</script>
</head>
<body>
<form runat=”server”>
<img ID=”Image1" src=”d:/myprog/asp.net/images/bobcat.jpg” runat=”server”/>
<p>Select image file: </p>
<select id=”Select1" runat=”server”>
<option Value=”Bobcat.jpg”>Bobcat</option>
<option Value=”Cheetah.jpg”>Cheetah</option>
<option Value=”Leopard.jpg”>Leopard</option>
<option Value=”Lynx.jpg”>Lynx</option>
<option Value=”Tiger.jpg”> Tiger</option>
</select>
<input type=”submit” runat=”server” Value=”Apply”
OnServerClick=”SubmitBtn_Click”>
</form>
</body>
</html>
This example shows how to change a displayed image based on the choice of the user. The example uses
the click event of the HtmlInputButton control to trigger a handler that specifies the path of the image file
to be displayed, in this case, from the application’s images directory. Notice that the SubmitBtn_Click
event handler is simple, specifying the d:/.../images directory as the source path for the images to be
displayed. An HtmlSelect control provides the list of option for the user. The selected value in the
HtmlSelect control in the Web Forms page determines which image to display from the absolute path
specified.
• In ASP.NET, all the functions and subroutines must be placed within the <script> section
• Tables can be dynamically bound to add rows and cells to the table using the methods provided by
the HtmlTableRowCollection and HtmlTableCellCollection
• HtmlAnchor is used to navigate from the client page to another page, or to another location within
the same page
• The HtmlGenericControl provides implementation for other HTML server control tags not directly
represented by a specific HTML server control
• The HtmlImage server control renders an image file specified by the SRC property
YZ
Lecture 3
Objectives
In this lecture you will
learn the following
Coverage Plan
Lecture 3
3.1 Snap Shot
Web controls are Server-Side controls, which can be used in the same way as HTML controls. The only
difference is that they must have the runat = ”server” attribute set. This attribute makes the control
available for server-side programming. Each ASP.NET Server Control is capable of exposing an object
model containing properties, methods and events. This object model can be utilized by the ASP.NET
developers to modify and interact with the Web page.
ASP.NET
Web controls are nothing but the server controls with an abstract, strongly-typed object model. Web
controls include not only form-type controls such as buttons and text boxes, but also special-purpose
controls such as a calendar. Web controls are more abstract than HTML controls. In web controls, the
object model does not necessarily reflect the HTML syntax. There are some common properties shared by
all the Web controls which are as follows.
• AccessKey - This is the control’s keyboard accelerator key. It specifies a single letter or number that
the user should use while pressing ALT. For example, if the user wants to press ALT+K to access the
control, “K” should be specified. Access keys are not supported on all browsers
• Attributes - Attributes denote the complete set for the control’s persistent format. This property is
only used while programming and cannot be set while declaring the control
• BackColor - This property indicates the color behind the text of the control
• CSS Style - This is a collection of text attributes that will be rendered as a CSS style attribute on the
outer tag of the control. This property is only used while programming and cannot be set while
declaring the control
• Enabled - This property enables the control if set to true (the default) or disables when it is set to
false
• ForeColor - ForeColor is the text color of the control. This property may not work in some of the
earlier version browsers
• TabIndex - This property sets the order of the control when the user tabs between controls. If it is not
set, the control’s index is zero. Controls with the same tab index will be navigated in the order in
which they are declared in the content
• ToolTip - ToolTip is indicated in the form of the text that appears when the mouse is placed on the
control. ToolTip does not work in all browsers
It is possible to develop a custom Web control by extending an existing Web control, by combining
existing Web controls, or by creating a control that derives from the base class
System.Web.UI.WebControls.WebControl.
ASP.NET
Web Controls
The following figure shows the Web Controls Hierarchy in the System.Web.UI.WebControls namespace.
Figure 3.1
Button
The Button Web control causes the Web Forms page to be posted back to the server.
Syntax
<asp:Button runat=”server”
id=”accessID”
Text=”label”
Command=”command”
CommandArgument=”commandArgument”
OnClick=”OnClickMethod”
/>
The properties of the button control are given below.
• Command - This property will be invoked when a button embedded in a container control is clicked
• CommandArgument - This is an optional command argument that is used in combination with the
value of the Command property
• Text - This is the button caption
This control has only one event:
• OnClick - This event will be raised when the user clicks the button. This event always causes the page
to be posted to the server
Practice 3.1
The following example shows the code for displaying a button.
<HTML>
<TITLE> ASP.NET </TITLE>
<HEAD>
<form runat=”server”>
<p><asp:button id=”Button1" text=”Click Me” runat=”server” />
</form>
</HEAD>
</HTML>
In the above example a button control is created. The id of the button is Button1 and the text “click me” is
the caption that appears on the button.
Label
This control allows to display static text to be displayed on the page and to manipulate it
programmatically.
Syntax
<asp:Label runat=”server”
id=”accessID”
Text=”label”
/>
The main property of the Label control is given below:
Textbox
This control generates single- and multi-line text boxes.
Syntax
<asp:TextBox runat=”server”
id=accessID
AutoPostBack=”True|False”
Colums=”characters”
MaxLength=”characters”
Rows=”rows”
Text=”text”
TextMode=”Single | Multiline | Password”
Wrap=”True|False”
OnTextChanged=”OnTextChangedMethod”
>
</asp:TextBox>
The properties of this control are:
• AutoPostBack - If this property is used in the control, it will automatically cause a postback to the
server when it is true; otherwise false. The default is false
• Columns - The column width of the control is in characters. This property differs from the Width,
which sets the absolute width of the control independent of the character spacing
• MaxLength - The maximum number of characters are allowed within the text box. This property has
no effect unless the TextMode property is set to SingleLine or Password
• Rows - Rows indicates the number of rows within the text box. This property has no effect unless the
TextMode property is set to MultiLine
• Text - Implies the text that the user has entered into the box
• TextMode - Indicates whether the text box is in single-line, multi-line, or password mode. Possible
values are Single, MultiLine and Password
• Wrap - Indicates whether text should wrap around as users type text into a multi line control. This
property has no effect unless the TextMode property is set to Multi line
• OnTextChanged - This event is raised on the server when the contents of the text box change. This
event does not cause the Web Forms page to be posted to the server unless the AutoPostBack
property is set to true.
Practice 3.2
<html>
<title> ASP.NET </title>
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
56
ASP.NET Web Controls - I
<head>
<script language=c# runat=server>
void button_click(Object sender,EventArgs e)
{
label1.Text=text1.Text;
label2.Text=text2.Text;
label3.Text=text3.Text;
}
</script>
<body>
<form runat=server>
Enter the name : <asp:Textbox id=text1 runat=server/> <br>
Enter the address : <asp:Textbox id=text2 runat=server/> <br>
Enter the Contact no: <asp:Textbox id=text3 runat=server/> <br>
<asp:Label id=”label1" runat=server/> <br>
<asp:Label id=”label2" runat=server/> <br>
<asp:Label id=”label3" runat=server/> <br>
<asp:button OnClick=”button_click” text=”submit” runat=server/>
</form>
</body>
</html>
In the above example, Textbox, label, button controls are used. It can be seen from the above example that
the names entered in the textboxes are displayed in the label controls when the submit button is clicked.
CheckBox
This control creates a check box on a Web Forms page, allowing users to set a true or false value for the
item associated with the control.
Syntax
<asp:CheckBox runat=”server”
id=”accessID”
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
57
ASP.NET
AutoPostBack=”True|False”
Text=”label”
TextAlign=”Right|Left”
Checked=”True|False”
OnCheckedChanged=”OnCheckedChangedMethod”
/>
The properties of the CheckBox are:
• Checked - This is true if the check box is checked, otherwise false. The default is false
• TextAlign - TextAlign is the position of the caption. The possible values are Right and Left. The
default is Right
• OnCheckedChanged - This event is raised when the user clicks the checkbox. It does not cause the
Web Forms page to be posted to the server unless the AutoPostBack property is set to true
Practice 3.3
The following example illustrates the usage of the CheckBox Control.
<html>
<title> ASP.NET </title>
<head>
<script language=”C#” runat=”server”>
void SubmitBtn_Click(Object Sender, EventArgs e) {
if (Check1.Checked == true && Check2.Checked == true )
{
Label1.Text = “Both the Check boxes are checked!”;
}
else if(Check1.Checked == false && Check2.Checked == true )
{
Label1.Text = “Check box 2 is checked!”;
}
else if(Check1.Checked == true && Check2.Checked == false )
{
Label1.Text = “Check box 1 is checked!”;
}
else
{
Label1.Text = “Both are not checked!”;
}
}
</script>
</head>
<body>
<h3><font face=”Verdana”>CheckBox Example</font></h3>
<form runat=server>
<asp:CheckBox id=Check1 Text=”CheckBox 1" runat=”server” />
In the above example it can be seen that controls such as button, checkbox and labels are used. When the
user checks the check box and clicks the “submit” button, a message is displayed in the label depending
on the number of checks boxes that are checked.
RadioButton
This control creates a single radio button on a Web Forms page.
Syntax
<asp:RadioButton runat=”server”
id=”accessID”
AutoPostBack=”True|False”
Checked=”True|False”
GroupName=”GroupName”
Text=”label”
TextAlign=”Right|Left”
OnCheckedChanged=”OnCheckedChangedMethod”
/>
The properties of the RadioButton are as follows:
• AutoPostBack - This returns true if client-side changes in the control automatically cause a postback
to the server; otherwise false. The default is false
• Checked - This returns true if the radio button is checked, otherwise false. The default is false
• GroupName - The name of a group to which the radio button belongs. Radio buttons with the same
group name are mutually exclusive
• TextAlign - This property indicates the position of the caption. The possible values are Right and Left.
The default is Right
• OnCheckedChanged - This event will be raised when the user clicks the radio button and does not
cause the Web Forms page to be posted to the server unless the AutoPostBack property is set to true
Practice 3.4
<html>
<title> ASP.NET </title>
<head>
<script language=”C#” runat=”server”>
void Button1_Click(Object sender, EventArgs e)
{
if (Radio1.GroupName==”Dark”)
{
if (Radio1.Checked==true)
{
Span1.Style[“background-color”] = Radio1.Text;
}
else if (Radio2.Checked==true)
{
Span1.Style[“background-color”] = Radio2.Text;
}
}
}
</script>
</head>
<body>
<h3><font face=”Verdana”>Option Button Example</font></h3>
<form runat=server>
<asp:RadioButton id=”Radio1" GroupName=”Dark”
Text=”DarkRed” BackColor=”DarkRed” runat=”server”/>
<p>
<asp:RadioButton id=”Radio2" GroupName=”Dark”
Text=”DarkSlateGray” BackColor=”DarkSlateGray” runat=”server”/>
<p>
<asp:Button id=”Button1" OnClick=”Button1_Click”
Text=”Click” runat=”server”/>
<pre>
<span id=Span1 runat=server > This will affect the Text </span>
</pre>
</form>
</body>
</html>
This program uses two radio buttons and a button control. When the user selects one of the Options and
clicks the “Click” button, the corresponding color will be the background color of the text area.
• Web controls are more abstract than HTML controls, in that their object model does not necessarily
reflect in the HTML syntax.
• All Web controls (except Repeater) derive directly or indirectly from the base class System.Web.UI.
WebControls.WebControl.
• The Button Web control causes the Web Forms page to be posted back to the server.
• Label Web control allows to display static text on the page and manipulate it programmatically.
• Check box control creates a check box on a Web Forms page, allowing users to set a true or false
value for the item associated with the control.
• Radio button control creates a single radio button on a Web Forms page.
YZ
Lecture 4
Objectives
In this lecture you will
learn the following
+ Knowing about Image Controls & List Controls
Coverage Plan
Lecture 4
4.5 Panel
4.6 AdRotator
4.7 Calendar
The ASP.NET list controls enable the users to choose one or more items from a list of items. The Panel is a
container for other controls. The AdRotator control is used to display randomly selected advertisement
banners on Web pages. The Calendar control displays a one-month calendar on the Web page, which can
be used to view and select dates.
ASP.NET
Web Controls
The Image control is a replacement for the standard HTML image control. It is used to display and
manage images on a Web page. The syntax for using the Image control is:
• ImageUrl- The ImageUrl property specifies the URL of the image to be loaded into the image control
• AlternateText - The AlternateText property specifies the text to be displayed if the image referenced by
the ImageUrl property is not available
• ImageAlign - The ImageAlign property specifies the alignment of the image with the text
surrounding it.
Practice 4.1
The following example displays one of the four images, based on the user’s selection.
<html>
<head>
<script language=”C#” runat=”server”>
void Btn_Click(Object sender, EventArgs e) {
string s = “”;
if (Radio1.Checked)
s = “web.gif”;
else if (Radio2.Checked)
s = “warning.gif”;
else if (Radio3.Checked)
s = “print.gif”;
else
s = “mmc.gif”;
Img.ImageUrl=”G:/Inetpub/wwwroot/” + s;
}
</script>
</head>
<body>
<form runat=server>
Select an image from the list and click on the button to display the image:
<br><br>
<asp:Image ID=”Img” ImageUrl=”G:/Inetpub/wwwroot/web.gif”
AlternateText=”Sample Images” runat=”server”/>
<br><br>
<asp:RadioButton id=Radio1 Text=”Web” Checked=”True” GroupName=”Group1"
runat=”server” /><br>
<asp:RadioButton id=Radio2 Text=”Warning” GroupName=”Group1"runat=”server”/> <br>
<asp:RadioButton id=Radio3 Text=”Print” GroupName=”Group1" runat=”server” />
<br>
<asp:RadioButton id=Radio4 Text=”MMC” GroupName=”Group1" runat=”server”/>
<br>
<asp:button text=”Display” OnClick=”Btn_Click” runat=server/>
</form>
</body>
</html>
The example uses four radio buttons to enable the user to select his/her option. Since the default option is
“Web”, the corresponding image is displayed. When the user selects one of the four options and clicks the
button “Display”, the “OnClick” event of the button invokes the method “Btn_Click”. This method checks
which one among the four radio buttons is selected and based on this, it displays the corresponding
image.
ImageButton
ASP.NET
ImageButton
The ImageButton control enables trapping of user-clicks within an image. This is similar to the image map
of HTML. The syntax for using the ImageButton is:
• ImageUrl - The ImageUrl property specifies the URL of the image to be displayed on the Web page
• Command - The Command property denotes the command to be executed when the button
contained in a container control is clicked
• CommandArgument - The CommandArgument property is used along with the Command property
if a value has to be supplied to the command invoked by that property
Practice 4.2
The following example displays an ImageButton and when the user clicks on the button, it displays the
coordinates of the image at which the user has clicked.
<html>
<head>
<script language=”C#” runat=”server”>
void ImgBtn_Click(object Source, ImageClickEventArgs e)
{
Label1.Text=”You clicked the image button at the coordinates:
(“ + e.X.ToString() + “, “ + e.Y.ToString() + “)”;
}
</script>
</head>
<body>
<form runat=”server”>
<asp:label id=”Label1" BackColor=”Pink” runat=”server”/>
<asp:ImageButton id=”imgbtn” runat=”server”
AlternateText=”Windows 2000 Logo”
ImageAlign=”left”
ImageUrl=”g:/Inetpub/wwwroot/win2000.gif”
OnClick=”ImgBtn_Click”/>
</form>
</body>
</html>
The example contains an ImageButton and a Label. When the user clicks on any part of the ImageButton,
the OnClick event of the ImageButton is invoked. This event calls the method “ImgBtn_Click” that
displays the message “You clicked the image button at the coordinates:” followed by the x and y
coordinates of the point at which the user has clicked on the ImageButton.
ASP.NET
The ASP.NET List controls include ListBox, DropDownList, CheckBoxList and RadioButtonList. The items
for the list controls are accessed through the Items collection. The Items collections can be used to add
items, remove items, etc., from any control that uses the collection. Processes like adding items,
determining the selection, setting the selection and responding to the changes are common to all the list
controls. So, these processes will be explained after introducing these controls.
ListBox
The ListBox control is used to allow the user to select one or more items from a specified list. It displays
more than one item at the same time. The number of controls that should be visible can be set for the
control. Each item of the list has the properties Text, Value and Selected. The Text property denotes the
text to be displayed in the list and the Value property denotes the value associated with it. Selected takes
a boolean value that denotes whether the item is selected or not. The following is the syntax for using the
ListBox:
where AutoPostBack and selected can take one of the values “true” or “false”.
• SelectionMode – This property can either be “Single” or “Multiple” depending on whether the user
wants to select a single item or multiple items. If it is set to “Single” then the SelectedItem property
returns the selected item. If SelectionMode is set to “Multiple”, then the SelectedItems property is
used to retrieve the selected items
• DataSource – This property denotes the object that supports ICollection Interface
• DataTextField - The DataTextField property denotes the source of the Text property of the items
• DataValueField – The DataValueField property denotes the source of the Value property of the
items
• Rows - The Rows property determines the number of rows to be visible in the list
The event OnSelectedIndexChanged(Object sender, EventArgs e) is raised on the server when the
selection of the ListBox is changed.
DropDownList
The DropDownList control enables users to select from a single-selection drop-down list. It is similar to
the ListBox control, but it shows only the selected item. The syntax, properties and event for the
DropDownList are similar to those of the ListBox except that DropDownList does not support multiple
selection.
CheckBoxList
The CheckBoxList control contains a group of checkbox controls. The syntax for using the CheckBoxList
control is:
• CellPadding – The CellPadding property determines the spacing between the controls
• RepeatColumns – The RepeatColumns property determines the number of columns in which the
controls will be displayed
• RepeatDirection – The RepeatDirection property determines the direction in which the controls are
to be displayed and can be either “Vertical” or “Horizontal”
• RepeatLayout – The RepeatLayout property determines whether the control renders in-line (when it
takes the value “Flow”) or in a table (when it takes the value “Table”)
• TextAlign – TextAlign determines the position of the text with respect to the control and it can take
one of the values “Right” or “Left”. The default alignment is Right
RadioButtonList
The RadioButtonList control provides a radio button group that can be dynamically generated through
databinding. The radio buttons in the group are mutually exclusive, i.e., only one of them can be selected
at a time.
• Create a new object of ListItem and set its Text and Value properties
• Add the new object to the Items collection through its Add method
For instance, to add a new item to a ListBox named list1, the following lines of code are written:
ListItem it = new ListItem();
it.Text = “New item”;
it.Value = “10”;
list1.Items.Add(it);
If the control allows single-selection, then the value of SelectedIndex will denote the index of the item that
is selected. If nothing is selected then the value of SelectedIndex is –1. The contents of the selected item are
retrieved using the SelectedItem property that returns an object of ListItem. The Text and Value
properties of the ListItem are used to get the details about the item.
If the control allows multi-selection, then the Selected property of each item in the collection is checked to
see if it is true. If it is true then its contents can be accessed through its Text and Value properties.
The following part of a code checks the items of a list box named list1 to see if they are selected and
displays the text of the selected items.
To set a single selection, set the SelectedIndex property of the control to the index of the item to be
selected. If the SelectedIndex property is set to –1 then no item is selected from the list. To set multiple
selections, the Selected property of those items is set to true. It must be noted that multiple items can be
selected only if the control’s SelectionMode is set to Multiple.
The following line of code selects the second item in a list box named list1:
list1.SelectedIndex = 1;
Practice 4.3
The following example moves items that are selected by the user from the “Store Shelf” ListBox to the
“Shopping Basket” ListBox.
<html>
<head>
<Script language=”c#” runat=”Server”>
void addCart(Object sender,EventArgs e)
{
if (Store.SelectedIndex > -1)
{
shoppingBasket.Items.Add( new ListItem(Store.SelectedItem.Value ) );
Store.Items.Remove( Store.SelectedItem.Value );
}
}
</Script>
</head>
<body>
<form runat=”server”>
<table cellpadding=”10">
<tr>
<td valign=”top”>
<h3>Store Shelf</h3>
<asp:listbox id=”Store” width=”200" runat=”server”>
<asp:listitem>Ice Cream</asp:listitem>
<asp:listitem>Mars Bars</asp:listitem>
<asp:listitem>Chips</asp:listitem>
<asp:listitem>Soda Pop</asp:listitem>
<asp:listitem>Pickles</asp:listitem>
</asp:listbox>
<br>
<asp:button id=”add2Cart” text=”Add to Cart” OnClick=”addCart”
runat=”server”/>
</td>
<td valign=”top”>
<h3>Shopping Basket</h3>
<asp:listbox id=”shoppingBasket” width=”200" runat=”server” />
</td>
</tr>
</table>
</form>
</body>
</html>
The above example contains two ListBoxes “Store Shelf” and “Shopping Cart” and a Button “Add to
Cart”. When the user selects an item from the first ListBox and clicks on the Button, the OnClick event of
the Button gets fired. This event calls the method “addCart”. This method checks if any item is selected
from the first ListBox by checking if its SelectedIndex is greater than –1. If any item has been selected in
the ListBox, then the corresponding item is added to the second ListBox and then removed from the first.
4.4 LinkButton
ASP.NET
LinkButton
The LinkButton control creates hyperlink-style buttons that post back to the page from which they were
created. The syntax for using a link button is:
• Text – This property denotes the text that will be displayed in the link. It can also be specified
outside the tag
• Command – The Command property denotes the command to be executed when the button
contained in a container control is clicked
• CommandArgument – This property is used along with the Command property if a value has to be
supplied to the command invoked by the Command property
The OnClick(Object sender, EventArgs e) event is raised when the user clicks the button and
causes the page to be posted to the server.
Practice 4.4
The following example uses LinkButton to enable the user to navigate to Microsoft’s home page.
<html>
<head>
<script language=”C#” runat=”server”>
void LinkBtn_Click(Object sender, EventArgs e) {
Page.Navigate(“http://www.microsoft.com”);
}
</script>
</head>
<body>
<form runat=server>
<asp:LinkButton Text=”Click Here” onclick=”LinkBtn_Click” runat=”server”/>
</form>
</body>
</html>
The example displays a LinkButton with the text “Click Here” displayed on the screen. When the user
clicks on the LinkButton, the OnClick event of the LinkButton is invoked. This event calls the
“LinkBtn_Click” method that directs the user to the home page of Microsoft.
4.5 Panel
ASP.NET
Panel
ϕ Panel
ϕ Container for other controls
ϕ Used to group controls on a page
ϕ Can be used to create controls at run time
The Panel is a container for other controls. It is used to group controls on a page. It enables the user to
execute a command only on one group or certain groups of controls on a page. It can be used to create
controls at run time.
• BackImageUrl – The BackImageUrl property specifies the URL of the image to be displayed as a
background of the panel
• HorizontalAlign – The HorizontalAlign property specifies the alignment of the panel with respect to
the surrounding text. It can take one of the values “Center”, “Justify”, “Left”, “NotSet” and “Right”
• Wrap - The Wrap property can be set to either “True” or “False”. If it is set to “True” then the content
can be wrapped. The default value is “True”
Practice 4.5
The following example sets the background for a panel and adds a textbox to it, when the user clicks the
corresponding buttons.
<html>
<head>
<script language=”c#” runat=”server”>
void Btn1_Click(Object sender, EventArgs e)
{
Panel1.BackImageUrl = “G:/Inetpub/wwwroot/win2000.gif”;
}
void Btn2_Click(Object sender, EventArgs e)
{
TextBox t = new TextBox();
t.ID = “Text1”;
t.Text=”Hai”;
t.Width=50;
Panel1.Controls.Add(t);
}
</script>
</head>
<body>
<form runat=server>
<asp:Panel id=”Panel1" Height=120 Width=450 BackColor=”Gainsboro”
Wrap=”True” HorizontalAlign=”Right” runat=”server”/>
<br>
<asp:Button id=”Btn1" OnClick=”Btn1_Click” Text=”Set the label back
ground” runat=”server”/>
<asp:Button id=”Btn2" OnClick=”Btn2_Click” Text=”Create a
TextBox” runat=”server”/>
</form>
</body>
</html>
The above example consists of a Panel and two Buttons. When the first Button, namely “Set the label
background” is clicked, its OnClick event is invoked that calls the method “Btn1_Click”. This method sets
the BackImageUrl property of the Panel to display the “Windows 2000 logo”. When the second Button,
namely “Create a Text Box” is clicked, its OnClick event is invoked that calls the method “Btn2_Click”.
This method creates a new TextBox and places it in the right top of the Panel.
4.6 AdRotator
ASP.NET
AdRotator
The AdRotator control is used to display randomly selected advertisement banners on Web pages.
• AdvertisementFile - The AdvertisementFile property (a required property) specifies the path to the
XML file containing the information about the advertisement
• KeywordFilter – This property indicates the category filter to pass to the source of advertisements
• Target – This property specifies the name of the browser in which the advertisement will be
displayed
The only event of the AdRotator control is OnAdCreated(Object sender, AdCreatedEventArgs e). This
event is raised on the server once per round trip, after the control is created and before the page is
rendered. When an AdvertisementFile is specified, this event is raised after an advertisement is selected
from the XML file.
The source of the advertisement is specified in an XML file using the following syntax:
<Advertisements>
<Ad>
<ImageUrl> url </ImageUrl>
<TargetUrl> url </TargetUrl>
<AlternateText> toolTip </AlternateText>
<Keyword>filter </Keyword>
<Impressions> relativeWeight </Impressions>
</Ad>
</Advertisements>
• ImageUrl - The ImageUrl property contains the URL of the image file
• TargetUrl - The TargetUrl property contains the URL of the page that should be displayed when the
user clicks on the ad
• AlternateText - The AlternateText property contains the text that will be displayed if the image is not
loaded
• Keyword - The Keyword property specifies the category for the advertisement
• Impressions - The Impressions property denotes the weight of the advertisement with respect to the
other ads in the file. It determines how often the advertisement will be displayed. The higher the
value of Impressions, the more the importance given to the advertisement
Practice 4.6
The following example uses AdRotator to display two advertisements. When the user clicks on an
advertisement, he/she is directed to the corresponding Web page.
<Advertisements>
<Ad>
<ImageUrl>nat1.bmp</ImageUrl>
<NavigateUrl>http://www.kodaihotels.com</NavigateUrl>
<AlternateText> Click here to book a hotel at Kodaikkanal</AlternateText>
<Keyword>websites </Keyword>
<Impressions>10</Impressions>
</Ad>
<Ad>
<ImageUrl>nat2.bmp</ImageUrl>
<NavigateUrl>http://www.udagamandal.com</NavigateUrl>
<AlternateText> Click here to book a hotel at Ooty </AlternateText>
<Keyword>websites </Keyword>
<Impressions>10</Impressions>
</Ad>
</Advertisements>
The example consists of an AdRotator control that is centered in the form using the <Center> tag. The
Width of the AdRotator is set to be 80% of the width of the page. The AdvertisementFile property
specifies the XML file that has to be referred by the ASPX file in order to display the advertisements. The
XML file specifies the image to be used, its alternate text, etc.
4.7 Calendar
ASP.NET
Calendar
ϕ Displays a one-month calendar
ϕ Used to view, select and manipulate dates
ϕ By default current date is highlighted
ϕ Based on DateTime object
ϕ Can be used to display any date in the range
0 to 9999 A.D
ϕ Rendered as a HTML table
ϕ User can select a single for a range of dates
or to disable date selection
The Calendar control displays a one-month calendar on the Web page. It can be used to view and select
dates. By default the current date is highlighted. The Calendar control can be used to display details of
each day, like the daily schedule, appointments, etc. It is based on the DateTime object of the .NET
framework and can be used to display any date in the range between 0 to 9999 A.D. It is actually rendered
as a HTML table on the Web page. Therefore, its properties are similar to that of the table.
The user can change the current date, navigate to another month or year, and select a single date, week or
month. The user can also select a range of dates using this control. By default, the control allows the user
to select a single date. The settings can also be changed to disable the selection of the date. If day selection
is enabled, each date acts as a LinkButton and raises an event when clicked. If the week or month selection
is enabled, a column of links is added to the left side of the Calendar so that the user can select an entire
week or month. The appearance of the Calendar control like its color, font, borders etc., can be modified
using the style objects.
Property Description
CellSpacing Determines the space between the border of a cell and the text contained in the
cell.
DayNameFormat Determines the format of the name of the days. The value can be one of “Full”,
“Short”, “FirstLetter” or “FirstTwoLetters”. The default is “Short”.
FirstDayOfWeek Determines the day that will be displayed in the first column. The week will be
set to start from this day. The default value depends on the local settings of the
server.
NextMonthText Determines the text that will be displayed in the hyperlink for the next month.
This requires the ShowNextPrevMonth property to be set to true.
NextPrevFormat Specifies the format in which the next month and previous month links are
displayed. The default value is “Custom”.
PrevMonthText Determines the text that will be displayed in the hyperlink for the previous
month. This requires the ShowNextPrevMonth property to be set to true.
SelectedDate Specifies the date that will be highlighted. The default value is the value of the
TodaysDate property.
SelectionMode Specifies whether the user can select a day, week or month. It can take one of the
values “None”, “Date”, “DateWeek” or “DateWeekMonth”. The default value is
“Date”. Setting this property to “None” disables date selection.
SelectMonthText Represents the text to be displayed for month selection in the selector column if
SelectionMode is set to “DayWeekMonth”.
SelectWeekText Represents the text to be displayed for week selection in the selector column if
SelectionMode is set to “DayWeek” or “DayWeekMonth”.
ShowDayHeader Determines whether or not the names of the days of the week are displayed.
ShowGridLines Specifies whether or not the border is displayed around each day.
ShowNextPrevMonth Specifies whether or not next and previous month hyperlinks are displayed.
TitleFormat Specifies the format of the month in the title bar. The default value is “Month”.
VisibleDate Specifies the month to be displayed. The date can be any day within the month.
Table 4.1
The events of the Calendar control are raised on the server. They are:
• OnDayRender(Object sender, DayRenderEventArgs e) – Raised when the cell for each day is
created
Practice 4.7
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
80
ASP.NET Web Controls - II
Width=”500px”
/>
</form>
An important point to be noted in the above example is that the Calendar control is enclosed within the
Form tag. This enables the navigation between months. If the control is not embedded in the form, it will
not be submitted to the server and thus will not support the navigation between months. The example
illustrates how the control can be customized by setting many of its properties.
• The Image control is a replacement for the standard HTML image control. It is used to display and
manage images on a Web page
• The ASP.NET List controls include ListBox, DropDownList, CheckBoxList and RadioButtonList.
The items for the list controls are accessed through the Items collection
• The LinkButton control creates hyperlink-style buttons that post back to the page from which they
were created
• The Panel is a container for other controls. It is used to group controls on a page and perform some
action only to one group or certain groups of controls on a page
• The AdRotator control is used to display randomly selected advertisement banners on Web pages
• The Calendar control displays a one-month calendar on the Web page. It can be used to view and
select dates
• The Web controls provide additional support for styles by adding properties for commonly used style
settings
5. Which property of the AdRotator is used to specify the importance of an advertisement with respect
to other advertisements?
6. Which property of the Calendar control is used to set the Text for the hyperlink for the next month?
YZ
Lecture 5
Validation Controls
Objectives
In this lecture you will
learn the following
Coverage Plan
Lecture 5
5.1 Snap Shot
This session focusses on how input validation can be added to WebForms by means of validation controls.
It also discusses the various validation controls available in ASP.NET. An important aspect of creating
Web Forms pages for user is to enable Validation of user-input. The Web Forms framework provides a set
of validation controls that provide an easy-to-use but powerful way to check for errors, and if necessary,
display messages to the user. This session introduces to the validation controls in broader prospective.
Let us consider a typical web-based form wherein users have to provide their names and ages. A visitor to
the page types his name properly, but say types in “twenty-four” for his age instead of the number “24”.
When the user presses the Submit button on the form, his name and age (“twenty-four”) are sent to the
Web server, where there is a program waiting for his input. The program expects to get proper data from
the user to add it to the database. But instead, it gets a string of alphabetic characters for the age. So the
Web server creates an HTML page that asks the user to enter a valid age and sends this page to the user’s
browser. The user might complete the field correctly the second time and send the data back to the server.
This whole process may take just half a second, or several seconds, depending on several factors such as
the speed of the user’s connection, the speed of the Net, the Web server’s load, and so on. These trips to
the server for simple validations are a waste of resources.
Moving these simple validation tasks from the server to the client is a simple task and a big advantage of
client-side scripting. If the above Web page had a simple validation script, then the user would be
immediately notified of his data entry error. More importantly, the page would not have been sent to the
server until it was validated and complete.
ASP.NET
Validation in ASP.NET
Validating user input can be a time-consuming and tedious process. ASP.NET provides developers with a
set of pre-built validation controls that will help in speeding up and simplifying the task of validation.
This session provides a brief overview of using the Validation controls.
Input validation can be added to WebForms by using validation controls. Validation controls provide an
easy-to-use mechanism for all common types of standard validations — (eg. testing for valid dates or
values within a range.) Moreover, these controls can be used to provide custom-written validations. In
addition, validation controls allow to completely customize the display of error information to the user.
Validation controls can be used with any control that is processed in a Web Form’s class file, including
both HTML and ASP.NET server controls.
User input validation can be enabled by adding validation controls to the form. There are controls for
different types of validation, such as range-checking or pattern-matching.
Each validation control references an input control (a server control) elsewhere on the page. When the
user’s input is being processed (for example, when the form is submitted), the page framework passes the
user’s entry to the appropriate validation control or controls. The validation controls test the user’s input
and set a property to indicate whether the entry has passed the test or not. After all validation controls
have been called, a property on the page is set; if any of the controls show that a validation check has
failed, the entire page is set to invalid.
The state of the page and that of the individual controls can be tested by the code. For example, the state of
the validation controls have to be tested before updating a data record with information entered by the
user. If an invalid state is detected, the the update has to be bypassed. Typically, if any validation check
fails, all the processing is skipped and the page is returned to the user. Validation controls detect errors
and then produce an error message that appears on the page.
Generally speaking, each validation control performs only one test. (eg. to establish that a field is required
and limited to accepting dates within a specific range.) More than one validation control can be attached
to an input field on a form. In that case, the tests performed by the controls are resolved using a logical
AND. The data input by the user must pass all the tests in order to be considered as valid.
In some instances, several different entries might be valid. For example, if the code prompts for a phone
number, the users may be allowed to enter a local number, a long-distance number, or an international
number. This situation arises primarily where checking for specific patterns of numbers or characters. To
perform this type of test, the pattern-matching validation control is used to specify the multiple valid
patterns within the control.
Validation controls are normally not visible in the rendered form. However, if the control detects an error,
it produces error message text. The error message can be displayed in a variety of ways, as listed in the
following table.
In place Each validation control can individually display an error message or appear in place
(usually next to the control where the error occurred).
Summary Validation errors can be collected and displayed in one place, for example, at the top of
the page. (This strategy is often used in combination with displaying the error message
next to the input fields with errors.) If the user is working in a browser that supports
DHTML, the summary can be displayed in a pop-up message box.
Custom Create custom error display by capturing the error information and designing user-
defined output.
Note : If in-place or summary display options are used, the error message text can be formatted using
HTML.
Validation controls perform input checking in server code. When the user submits a form to the server, the
validation controls are invoked to review the user’s input, control by control. If an error occurrs in any of
the input controls, the page itself is set to an invalid state. Hence, validity has to be tested before the code
runs.
If the user is working with a browser that supports DHTML, the validation controls can also perform
validation using client script. This can substantially improve response time in the page Errors are detected
immediately and error messages are displayed as soon as the user leaves the control containing the error.
If client-side validation is available, the user has greater control over the layout of error messages and can
display an error summary in a pop-up message box.
The page framework performs validation on the server even if the validation controls have already
performed it on the client, so that the test for validity can be within the server-based event-handling
methods. In addition, it helps prevent users from being able to bypass validation by impersonating as
another user or a pre-approved transaction.
Types of Validation
ASP.NET
ASP.NET offers a number of Server Controls to
enable input validation. They are as follows:
5.3 RequiredFieldValidator
The RequiredField Validator is used to ensure that the user does not leave a field blank. For fields where it
does not matter as to what type of data the user enters, as long as they enter something, this is the
validator to use. This is actually one of the most widely used validation controls. This validation ensures
that the user does not skip an entry.
Validation can be managed by a Page directive. This overrides the automatic client-side validation
process. The directive:
Note : “UpLevel” directive will force the client to attempt to use Client-side script for the validation –
even if it doesn’t support this technique.
Practice 5.1
Here is an example using RequiredField Validator, a name is required from the user as input.
<html>
<body>
<h3>RequiredFieldValidator Example</h3>
<form runat=server>
Name: <asp:textbox id=text1 runat=”server” />
<asp:button id=”Button1" runat=”server” text=”Validate” />
<p><asp:requiredfieldvalidator id=”RequiredFieldValidator1"
controltovalidate=”Text1"
font-size=”11pt”
forecolor=”#600" runat=”server”>
Entry required!
</asp:requiredfieldvalidator>
</form>
</body>
</html>
The RequiredFieldValidator checks if the user has made any entry. It ensures that the user is not allowed
to move further without entering the field. So the attribute control to Validate is set to text1. When the
control shifts from text1, the RequiredFieldValidator checks if there is any entry for the field and if there
is no entry it prints the error message “Entry Required!”.
5.4 CompareValidator
The Compare Validator is used to compare the data entered by a user with a constant or other field on the
web form. The most common use of this Validation control is with respect to the password field. Typically
Web Forms would ask the user to enter a password and to confirm it . These two fields must be identical
for the form to be processed. The Compare Validator would be used in this case.
Display Property
The display property indicates how the validation controls output will be rendered in the page. The value
“static” tells the control to reserve sufficient space in the page for the text content so that the page layout
does not change when this content is displayed.
The value “dynamic” indicates that the control will only take up space in the page when the error text
string is displayed. In this case, the layout of the page might change. However, this is useful when there
are more than one validation control is attached to a control on the form. The value “none” tells the
control that no inline output will be displayed, even if the input value is invalid. Instead, the
ValidationSummary control can be used to detect if there was an error, and display the contents of the
errorMessage property elsewhere in the page.
Practice 5.2
Given below is a typical example of using the compare validator control. Two text controls are used to
get the password from the user and if there is a difference in the password it is reported by the
comparison control.
<HTML>
<SCRIPT LANGUAGE=”c#” RUNAT=”server”>
void submit_Me(Object sender,EventArgs E)
{
if (Page.IsValid==true)
{
Result.Text=”Successful Login.”;
}
}
</SCRIPT>
<BODY bgcolor=”wheat”>
<FORM RUNAT=”server”>
<h4>Example for CompareValidator Control</h4>
<br>
<asp:label id=Result runat=”server”/> Enter your name :
<INPUT TYPE=”text” id=”UserName” Runat=”server” />
<asp:RequiredFieldValidator id=”regUserName”
runat=”server”
ControlToValidate=”UserName”
errormessage=”Please Enter User Name”
display=”static”>
</asp:RequiredFieldValidator>
<br><br>
Enter New Password :
<INPUT TYPE=”text” id=”Password” Runat=”server” />
<asp:RequiredFieldValidator id=”reqPassword”
runat=”server”
ControlToValidate=”Password”
errormessage=”Please Enter Password”
display=”static”>
<--
</asp:RequiredFieldValidator>
<br><br>
Retype Password :
<INPUT TYPE=”text” id=”vPassword” Runat=”server” />
<asp:RequiredFieldValidator id=”reqvPassword”
runat=”server”
ControlToValidate=”vPassword”
errormessage=”Please Verify Password”
display=”static”>
<--
</asp:RequiredFieldValidator>
<asp:CompareValidator id=”reqMatch”
runat=”server”
ControlToValidate=”Password”
errormessage= “Passwords do not match”
ControlToCompare = “vPassword”
type = “string”
operator = “Equal”
display=”static”>
<--
</asp:CompareValidator>
<asp:ValidationSummary id=”sumErrors”
runat=”server”
showSummary = true
displayMode = “BulletList” />
<asp:button text=”Submit” RUNAT=”server” onClick=”submit_Me” />
</FORM>
</BODY>
</HTML>
In the above program, three text boxes are created for Name, New Password and Retype password. The
New password is for entering the new password and the retype password is used to check if the password
has been typed without typographical errors. Normally, the password will be masked and it will not be
visible. Here the password has not been masked to enable us to view the text.
The RequiredFieldValidator is used to check if the username, password and vpassword have any entry. If
the user leaves them blank it shows the user that some entry is required for the field. The
CompareValidator which checks if both the password and vpassword entries are identical. If they are
not identical, the error message “Passwords do not match is displayed” otherwise “Successful Login” is
displayed.
5.5 RangeValidator
The Range Validator checks if the data that a user enters falls within a given range of values. The
minimum and maximum values can be set to constant values or they can be set to other fields on the web
form.
Practice 5.3
Now let us see an example usng RangeValidiator which checks whether the given input is within the
specified range.
<html>
<script language=”c#” runat=”server”>
void btnclick(object sender,EventArgs e)
{
if (Page.IsValid==true)
{
Result.Text=”Successful Entry.”;
}
}
</script>
<title> Range Validator</title>
<body>
<form runat=”server”>
<h4>Example for Range Validator</h4>
<br>
<h3>Enter Your Age</h3>
<asp:textbox id=”textval” text=” “ runat=”server”/>
 
</table></center>
<br>
<center><asp:button id=”checkbtn” text=”click” runat=”server”
Onclick=”btnclick” /></center>
</form>
</body>
</html>
In the below example a text box control is used to get the age of the user. RangeValidator is used to check
if the age falls within a range. So the attribute control to validate is set to textval. When the control shifts
from the textval the RangeValidator checks for the range and if there is an error, prints the error message
even before the user clicks the click button. The color of the error message is set to red to enable the user
easily notice the error message. When the button is clicked it checks for the validation of the page and if it
is valid, prints “Successful Entry!”.
5.6 RegularExpressionValidator
The RegularExpression Validator evaluates the data that a user enters against a regular expression. This
allows for complex formatting restrictions on the field data. A popular example of this kind is the email
address. A RegularExpression Validator can check if there is at least one character, followed by the ‘@’
symbol, followed by at least one character, followed by a period, which is followed by either ‘com’, ‘org’,
‘net’ or any other valid email extension. This enables the developer to force the user to enter a valid email
address.
Practice 5.4
Here is an example with RegularExpression validator which validates if a specific number of digits have
been entered.
<html>
<head>
<script language=”C#” runat=server>
void ValidateBtn_Click(Object Src, EventArgs E)
{
if (Page.IsValid)
{
lblMessage.Text=”Page is Valid!”;
}
}
</script>
</head>
<body>
<div class=”header”><h3>Simple RegularExpressionValidator Sample</h3></div>
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
94
Validation Controls
<form runat=”server”>
<center>
<table bgcolor=”#eeeeee” cellpadding=6>
<tr valign=”top”>
<td colspan=3> <asp:label id=”lblMessage” text=”Enter a 6 digit Pin code”
font-name=”Verdana” font-size=”10pt” runat=”server”/>
</td>
</tr>
<tr>
<td colspan=3><b>Personal Information</b></td></tr>
<tr>
<td align=right>
PIN Code:</font>
</td>
<td>
<asp:textbox id=”TextBox1" runat=server /></td>
<td> <asp:regularexpressionvalidator id=”RegularExpressionValidator1"
runat=”server”
controltovalidate=”TextBox1"
validationexpression=”^\d{6}$”
display=”Static”
font-name=”verdana”
font-size=”10pt”>
PIN code must be 6 numeric digits
</asp:regularexpressionvalidator>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:button text=”Validate” OnClick=”ValidateBtn_Click” runat=server />
</td>
<td></td></tr>
</table>
</center>
</form>
</body>
</html>
In the above example, the text box control textbox1 is used to get the PIN Code from the user.
RegularExpressionValidator is used to check the validity of the PIN Code. So the attribute control to
validate is set to textbox1. The color of the error message is set to red so that the user can easily notice the
error message. (When the control shifts from the textbox, the RegularExpressionValidator checks for the
validity of the PIN Code and if there is an error prints the error message even before the “Validate” button
is clicked. It checks if all the entries are numeric and that there are six significant digits. When the
“validate” button is clicked, it checks for the validation of the page and if it is valid prints “Page is Valid!”.
5.7 CustomValidator
The Custom Validator allows the developer to create user-defined criteria for validation. The Validation
can be defined at two funcions which they determine. The developer can place any logic he or she wants
in these functions to determine if the data is acceptable. A common use of this Validator is to check for a
username against the usernames in a database, to see if the person is a registered user. Credit Card
number validation is also a very common use of the Custom Validator.
Practice 5.5
Given below is a typical example of using the custom validator control. A text control is used to get an
user input and if the input exceeds 9 digits the custom validator prints an error message.
<html>
<title>Custom Validation</title>
<script language=”c#” runat=”server”>
bool ServerValidate(object sender,String value)
{
if (value.Length <= 9)
return true;
else
return false;
}
</script>
<body>
<h3>Custom Validator Example</h3>
<form runat=server>
<table>
<tr>
<td> <asp:label id=”label1" text=”Enter a Number” runat=”server”/> </td>
<td> <asp:textbox id=”text1" runat=”server” /> </td>
In the above example, the text box control text1 is used to allow the user to enter a number.
CustomerValidator checks the validity of the number entered. So the attribute control to validate is set to
text1. When the control shifts from text1, the CustomValidator checks for the validity of the number and
if there is an error, prints the error message even before the click button is clicked. The color of the error
message is set to red so that the user can easily notice the error message. This checks if all the entries are
numeric and that the number of digits are less than or equal to 9. If it is greater than 9, it prints the error
message “Greater than nine Digits”.
Practice 5.6
In this example four validation controls are used. All the controls are managed by the
ValidationSummary control.
<html>
<title>Summary Validator </title>
<script language=”C#” runat=server>
void ValidateBtn_Click(Object Src, EventArgs E)
{
if (Page.IsValid == true)
{
lblMessage.Text=”Page is Valid!”;
}
}
</script>
<body>
<h3>Summary Validator Example </h3>
<form runat=”server”>
<asp:label id=”label1"
text=”Enter the Boiling point of water : “
runat=”server” />
<asp:textbox id=”text1"
runat=”server”/>
<asp:label id=”lblMessage” runat=”server”/>
<asp:regularexpressionvalidator
id=”RegularExpressionValidator1"
runat=”server”
controltovalidate=”Text1"
validationexpression=”^\d{3}$”
display=”Static”
Errormessage = “Boiling point of water is a three digit numeric value” >
</asp:regularexpressionvalidator>
<asp:comparevalidator id=”compboilpt”
controltovalidate=”text1"
Type=”Integer”
ValueToCompare=100
Operator=”Equal”
display=”static”
Errormessage=”Wrong Value”
runat=”server”>
</asp:comparevalidator>
<asp:requiredfieldvalidator
id=”RequiredFieldValidator1"
controltovalidate=”Text1"
runat=”server”
Errormessage = “Should Enter a Value”>
</asp:requiredfieldvalidator>
<asp:ValidationSummary
id=”sumErrors”
runat=”server”
showSummary = true
displayMode = “BulletList”>
</asp:ValidationSummary >
<br>
<asp:button text=”Click” OnClick=”ValidateBtn_Click” runat=server />
</form>
</body>
</html>
In the above example, the text box control text1 is used to get the boiling point of water.
RegularExpressionValidator, CompareValidator, RequiredFieldValidator are used to check the validity of
the figure entered. So the attribute controltovalidate is set to text1 for all the validators. When the control
shifts from text1, the RegularExpressionValidator checks for the validity of the number entered for the
boiling point of water and if there is an error, prints the error message even before the “click” button is
clicked. The RegularExpressionValidator checks for the number of digits that are entered, if it is less than
or greater than 3 an error message is displayed. The ComparisonValidator checks whether the entry is
exactly equal to 100. The RequiredFieldValidator checks if there is an entry in the text box. The
ValidationSummary control lists all the errors as bulleted list.
• The CustomValidator control lets the user define custom validation criteria
8. What are the different ways in which error messages ca nbe displayed?
YZ
Lecture 6
HtttpRequest
Objectives
In this lecture you will
learn the following
+ About HTML Forms
Coverage Plan
Lecture 6
6.1 Snap Shot
6.4 Cookies
The Request object is responsible for retrieving information from the Web browser. The Request object is
filled with various types of collection, properties, and methods that provide many ways to retrieve
information from the user. The HttpRequest class is used to gain access to the HTTP request data elements
that are supplied by a client.
ASP.NET
To interact with the user, HTML recognizes a few special tags that insert controls on a Form, besides the
universal hyperlinks. A control can be used to collect information from the user for registration purpose,
take orders over the Internet, or let the user specify selection criteria for record retrieval from database.
Before placing any controls on a page, a Form must be created, with the Form tag. All controls must
appear within a pair of Form tags:
The NAME attribute is optional, but it is advisable to have Form names. The FORM tag also accepts two
more attributes namely METHOD and ACTION that determine how the data will be submitted to the
server and processed. The METHOD attribute can have the value POST or GET. The ACTION attribute
specifies the script that will process the data on the server.
The values entered by the user on the Form’s controls are sent to the server using the Submit button.
Every Form has a Submit button that extracts the ACTION attribute from the <FORM> tag. The values of
the controls create a new URL and send it to the server.
The values of the various controls can be retrieved through the Request. Form collection. The Form
collection has one member for each control on the Form and individual control’s value can be accessed by
name. For example, if the Form contains a control named “UserValue”, its value can be accessed with the
expression Request.Form (“UserValue”).
Note : The Form collection contains the values of form elements when an HTML form is submitted with
the POST method. When an HTML Form is submitted with the GET method, the values of the form
elements are placed in the QueryString collection.
Practice 6.1
The following code accepts details from the user and submits it to the .aspx file.
html file
<html>
<head><title>Simple HTML Form</title></head>
<body>
<form method=”post” action=”result.aspx”>
<b>Enter name: </b>
<input name=”username” type=”text” size=30>
<p>
<b>Enter Comments: </b>
<br><textarea name= “comments” cols=40 rows=5></textarea>
<p>
<input type=”submit” value=”Send”>
</form>
</body>
</html>
result.aspx
<%@Page Language=”C#”%>
<%
string username=””;
string comments=””;
username = Request.Form [“username”];
comments= Request.Form [“comments”];
%>
<head><title>Result</title></head>
<body>
User Name : <%=username%>
<p>
Comments : <%=comments%>
</body>
In the above program the user is prompted to enter a user name and comments. When the user clicks the
button labeled Send, the contents of the form are submitted to result.aspx. The Form collection can be
accessed using the Request object inside the result.aspx file is then passed to the browser.
When the Send button is clicked after entering the name (Yashoda) and comments (Excellent), the
result.aspx file is called which displays the output as shown below:
Practice 6.2
The following program displays a confirmation form after the submitted details are processed.
html file
<html>
<head><title>Simple HTML Form</title></head>
<body>
<form method=”post” action=”confirm.aspx”>
<b>Enter name: </b>
<input name=”username” type=”text” size=30>
<p>
<b>Enter Comments: </b>
<br><textarea name= “comments” cols=40 rows=5></textarea>
<p>
<input type=”submit” value=”Send”>
</form>
</body>
</html>
confirm.aspx
<%@Page Language=”C#”%>
<%
string username=””;
string comments=””;
username = Request.Form [“username”];
comments = Request.Form [“comments”];
%>
<head><title>Result</title></head>
<body>
<form method= “post” action= “result.aspx”)
<p>Do you really want to send this information?</p>
<p>User Name:
<br><input name= “username”
type= “text” value= “<%=(username)%>”>
<p>Comments:
<br><textarea name= “comments” cols=40 rows=5>
<%=(comments)%></textarea>
<p>
<input type=”submit” value=”Send”>
</form>
</body>
When the Send button is clicked after entering the details, the confirm.aspx file is invoked and the
confirmation form is displayed. The user can make further changes and submit the form by clicking the
Send button.
ASP.NET
Some of the properties of the HttpRequest
class are
ϕ Application
ϕ Browser
ϕ ClientCertificate
ϕ ContentType
ϕ FilePath
ϕ RawUrl
ϕ Url
ϕ Cookies
Application Path
This property gets the virtual path to the currently executing server application.
Practice 6.3
The following example illustrates the usage of the ApplicationPath property.
<head>
<title> ApplicationPath </title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
String apath;
apath=Request.ApplicationPath;
Info.InnerHtml=apath;
}
</script>
</head>
<form runat=”server”>
<span id=”Info” runat=”server”/>
</form>
In the above example, it can be seen that the property ApplicationPath is used to get the virtual path. As
in the case of the above example the virtual directory is aspvir .
Browser
The Browser property gets the virtual path of the currently executing server application.
Practice 6.4
The following example illustrates the usage of the Browser property.
<head>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
HttpBrowserCapabilities bcap = Request.Browser;
Response.Write(“<p>Browser Capabilities:</p>”);
Response.Write(“Type = “ + bcap.Type + “<br>”);
Response.Write(“Name = “ + bcap.Browser + “<br>”);
Response.Write(“Version = “ + bcap.Version + “<br>”);
Response.Write(“Platform = “ + bcap.Platform + “<br>”);
Response.Write(“Supports Cookies = “ + bcap.Cookies + “<br>”);
}
</script>
/head>
This Browser property is used here to get the browser details namely, the browser type , name, version
and the platform on which the browser is running and whether the browser supports cookies.
ClientCertificate
This property gets information on the current request’s client security certificate.
Practice 6.5
The following example illustrates the usage of the ClientCertificate property.
<head>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
HttpClientCertificate cert = Request.ClientCertificate;
Response.Write(“ClientCertificate Settings:<br>”);
Response.Write(“IsPresent = “ + cert.IsPresent + “<br>”);
}
</script>
</head>
<form runat=”server”>
</form>
</head>
As it can be seen from the above example, the information about the client certificate settings details can
be found using the ClientCertificate property.
ContentType
This property indicates the Multipurpose Internet Mail Extensions (MIME) content type of the incoming
request. This property is read-only.
contype = Request.ContentType;
Response.Write (contype);
FilePath
This property indicates the virtual path of the current request. It is read-only.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
109
ASP.NET
Practice 6.6
<head>
<title> FilePath</title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
String fiPath;
fiPath = Request.FilePath;
Message.InnerHtml=fiPath;
}
</script>
</head>
<form runat=”server”>
<span id=”Message” runat=”server”/>
</form>
RawUrl
This property indicates the raw URL of the current request.
Practice 6.7
<head>
<title> RawUrl </title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
String Rurl;
Rurl = Request.RawUrl;
Info.InnerHtml=Rurl;
}
</script>
</head>
<form runat=”server”>
<span id=”Info” runat=”server”/>
</form>
The Raw URL of the above request is aspvir/furl.aspx as shown in the above output. It is obvious that
aspvir is the virtual directory and furl is the file name.
Url
This property gets information regarding the URL of current request.
Practice 6.8
The following example gives information about the URL of the current request.
<head>
<title> URL Info </title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
HttpUrl objUrl = Request.Url;
Response.Write(“URL Port: “ + objUrl.Port + “<br>”);
Response.Write(“URL Protocol: “ + objUrl.Protocol + “<br>”);
}
</script>
</head>
<form runat=”server”>
</form>
The above example shows that by using the Url property, the port and protocol information can be
obtained.
6.4 Cookies
Cookies are small pieces of information, which can be sent to a browser by a server program and stored by
the web browser. The web browser will then pass the cookie back to the server every time it makes a
request from that server. This facility is particularly useful for allowing authentication.
For example, when a user logs into a password restricted system, a cookie containing that users
login/password details can be set with those details, so that the user does not have to re-type their
password for every new page they wish to download.
It is important to know that the client’s web browser could be configured to refuse cookies and that some
browsers manage cookies incorrectly. When a cookie was sent, the server can retrieve it in a successive
client’s connection. This strategy makes it is possible to track the history of client’s connections.
The cookie property gets a collection of the client’s cookie variables. Cookies can be seen elaborately in the
following session.
ASP.NET
Other properties of the HttpRequest class are
ϕ Path
ϕ PhysicalPath
ϕ PhysicalApplicationPath
ϕ Headers
ϕ ServerVariables
ϕ Form
ϕ QueryString
Path
ϕ Params
Path
This property indicates the virtual path of the current request and it is read-only.
Practice 6.9
The following example illustrates the usage of the Path property.
<head>
<title> PathInfo </title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
String vpath;
vpath = Request.Path;
Info.InnerHtml=vpath;
}
</script>
</head>
<form runat=”server”>
<span id=”Info” runat=”server”/>
</form>
As shown from the above example, the Path property is used to get the virtual path of the current request.
ServerVariables
This property gets a collection of Web server variables.
Practice 6.10
As it can be seen from the output the various server variables information can be obtained by selecting the
required property in the list box.
Form
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
114
HttpRequest
Practice 6.11
The example illustrates the use of Form property to retrieve Form variables.
<html>
<title> Form Info </title>
<head>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
if(IsPostBack){
int ctr1;
NameValueCollection nvc;
nvc=Request.Form; // Load Form variables into NameValueCollection
variable.
String[] arr1 = nvc.AllKeys; // Get names of all forms into a string
array.
for (ctr1 = 0; ctr1 < arr1.Length; ctr1++) {
Response.Write(“Form: ” + arr1[ctr1] + “ : ” +
nvc.Get(arr1[ctr1])+ “<br>”);
}
}
}
</script>
</head>
<body>
<form runat=“server”>
<input type=“text” id=”text1" runat=”server”>
<input type=”submit” id=”sbt1" value=”Click” runat=”server”>
</form>
</body>
</html>
The above code first loads all the form variables into the NameValueCollection variable. Then using a for
loop the contents of the collection are displayed in the browser.
QueryString
This property gets the collection of QueryString variables.
Practice 6.12
The example uses QueryString to retrieve form variables.
<html>
<title> QueryString </title>
<head>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
if(IsPostBack){
int ctr1;
NameValueCollection nvc;
nvc=Request.QueryString; // Load Form variables into
NameValueCollection variable.
String[] ary1 = nvc.AllKeys; // Get names of all forms into a string array.
for (ctr1 = 0; ctr1 < ary1.Length; ctr1++) {
Response.Write(“Form: “ + ary1[ctr1] +” : “ +
nvc.Get(ary1[ctr1])+ “<br>”);
}
}
}
</script>
</head>
<body>
<form runat=”server” method=”Get”>
<input type=”text” id=”text1" runat=”server”>
<input type=”submit” id=”sbt1" value=”Click” runat=”server”>
</form>
</body>
In the above code the variables of the form are retrieved using the Request.QueryString property. The
values are then displayed in the browser.
HttpRequest Method
MapPath Method
ASP.NET
Syntax
• HttpRequest class is used to gain access to the HTTP request data elements supplied by a client
• The Browser property gets the virtual path of the currently executing server application
• ClientCertificate property gets information on the current request’s client security certificate
• FilePath property indicates the virtual path of the current request. This property is read-only
YZ
Lecture 7
HttpResponse
Objectives
In this lecture you will
learn the following
Coverage Plan
Lecture 7
7.1 Snap Shot
The Response object provides access to all the responses sent to the user. The Response object is
responsible for sending the output from the server to the client. The methods and properties of this object
control the way in which information is sent from the Web server to a Web browser.
ASP.NET
⊥ Used to set the characteristics of information
delivered by the server
⊥ Used between the browser and server to enable
communication
⊥ Properties are?
y BufferOutput y StatusDescription
y SupperssContent y Cookies
y Charset y IsClientConnected
y ContentType y StatusCode
y ContentEncoding
HttpResponse has different properties that are used to set the various characteristics of the information
delivered by the server. The characteristics are used between the browser and server to provide a
communication mechanism between the information provider and the information consumer. The
properties include:
BufferOutput
The BufferOutput gets or sets a value indicating whether the HTTP output is buffered or not. This
property takes the value true if the output to client is buffered and false otherwise. The default value is
true.
Practice 7.1
The following program checks if the output is buffered.
<head>
<title>BufferOutput</title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
if (Response.BufferOutput == true)
Message.InnerHtml=”The output is Buffered”;
}
</script>
</head>
<form runat=”server”>
<span id=”Message” runat=”server”/>
</form>
The BufferOutput property in the above program checks if the output is buffered and displays a message
in the browser.
SuppressContent
The SuppressContent property gets or sets a value indicating that the HTTP content will not be sent to the
client. The property returns true if the output is to be suppressed and false otherwise.
Response.SuppressContent = false;
Charset
The Charset property gets or sets the HTTP charset of the output.
Cookies
Cookies are used for session tracking, and user preferences. Cookies may also be used to determine how
long the users view a Web page, content (e.g., advertising), the link, and other services. The cookies
property gets the HttpCookie collection that is sent by the current request.
The following code takes the current cookie collection and fills a string array with the names of cookies.
IsClientConnected
The IsClientConnected property gets a value that indicates whether the client is still connected to the
server or not. The value of the property will be true if the client is currently connected and false
otherwise.
StatusCode
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
122
HttpResponse
The StatusCode property gets or sets the HTTP status code of the output returned to the client. The return
value is an integer code that represents the status of the HTTP output that is returned to the client. The
default value is 200. Some StatusCode values and their corresponding meaning are given in Table 7.1
Code Meaning
200 OK. The operation has been finished successfully
302 Redirection
Table 7.1
ASP.NET
⊥ Used to control information flow from the server to the
browser
⊥ Methods are:
y AppendToLog y Write
y Clear y End
y Flush y Redirect
The methods are used to control the HTTP header information, non-textual content such as binary images,
and Web server log files. In addition, the methods control the buffering mechanism happening in the
server and page redirection.
AppendToLog
The AppendToLog method adds custom log information to the IIS log file.
Syntax
public void AppendToLog( string param );
where,. param is a string that contains the text to be added to the log file.
The following code appends the text Page delivered to the IIS log file.
Response.AppendToLog(“Page delivered”);
Write
The Write method writes the values to an HTTP output content stream.
Syntax
Practice 7.2
The following program adds two input textboxes and a submit button.
<head>
<title>Response.Write</title>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
Response.Write(“<H3>Login Screen</H3>”);
Response.Write(“<b>User Name: </b>”);
Response.Write(“<input type=text id=user /> “+”<br><br>”);
Response.Write(“<b>Password : </b>”);
Response.Write(“<input type=password id=user /> “);
Response.Write(“<input type=submit value=Submit />”);
}
</script>
</head>
The above program uses the Response.Write method and displays two textboxes – to enter the user name
and password. A Submit button is also displayed.
Clear
The Clear method clears all headers and content output from the buffer stream.
Syntax
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
124
HttpResponse
End
The End property sends all the currently buffered output to the client and then closes the socket
connection.
Syntax
public void End();
The following code closes the socket after sending the buffered output to the client.
Response.End();
Flush
The Flush method sends the currently buffered output to the client. The method can be called multiple
times during request processing.
Syntax
public void Flush();
The following code sends the buffered output to the client.
Response.Flush();
Redirect
The Redirect method redirects a client to a new URL.
Syntax
public void Redirect( string url );
where, url is the new target location.
Practice 7.3
As it can be seen from the above output, the program redirects the client to another Web Site called
Radiant Software.
• The BufferOutput property gets or sets a value that indicates if the HTTP output is buffered
• Cookies are used for tracking the session. The cookies property is used to retrieve the HttpCookie
collection that is sent by the current request
• The IsClientConnected property is used to check if the client is connected to the server
• The End property closes the socket connection after sending the currently buffered output to the
client
YZ
Lecture 8
Objectives
In this lecture you will
learn the following
+ Knowing about HttpApplication
Coverage Plan
Lecture 8
8.1 Snap Shot
8.2 HttpApplication
8.3 Session
8.4 Cookies
Active Server Pages can be thought in terms of traditional programming. A single Active Server Page is
similar to a procedure or subroutine. When related Active Server Pages are grouped together they form an
application. One of the greatest challenges faced in constructing a full-featured web application is keeping
track of user-specific information when a user navigates the site. Sessions are used to store visitor’s
preferences and to keep track of the habits and interests of the visitors. This information can be used for
advertising purposes, to improve the design of the Web site.
8.2 HttpApplication
ASP.NET
The HttpApplication class defines the methods, properties and events common to all HttpApplication
objects within the ASP.NET Framework.
An ASP.NET application is defined as a collection of files, pages, handlers, modules and executable code
that can be invoked in the scope of a given virtual directory and its subdirectories on a Web Application
Server. All the types of ASP.NET programming models can be included within any application (Web
Forms, and Web Services). The only condition is that they must coexist in a single virtual directory
structure.
Every ASP.NET application on the Web Server is executed within a unique .NET runtime Application
Domain. ASP.NET maintains a collection of HttpApplication instances of a Web application’s lifetime and
automatically assigns an instance to process the incoming HTTP request. An HttpApplication instance
manages the entire lifetime of the request, and is re-used only after completing the request.
Creating an Application
An ASP.NET application is created by placing a simple .aspx page in the virtual directory and executing it
in the browser. Then an appropriate code can be added to use the Application object, for example to store
objects with application scope. Various event handlers can be defined by creating a Global.asax file
(discussed later).
fired. An HttpApplication instance processes the request until the last instance is present. When there are
no more instances the Application_End event is fired.
Managing Applications
The Application object is a built-in object in ASP.NET. The HttpApplication is used to control and
manage all the items that are available to all the users of an Active Server application. The Application
items can be variables that are necessary for the application, or they can be instantiated objects providing
special server-side functionality.
An application variable contains data that is used in all the web pages and by the users of an application.
Application variables can contain different types of data, including arrays and objects. The common uses
of application variables are:
To display transient information on every Web page. For example, Tip of the day or a daily news update on
every Web page
To record the number of times a banner advertisement on the Web site has been clicked
To store data that is retrieved from a database, which can then be displayed easily on multiple pages
without frequently accessing the database
To count the number of visitors to a particular Web site
An application variable helps in communicating with the users of the Web site. For example, application
variables can be used to create multi-user games or multi-user chat rooms.
To create a new application variable, the name of the new variable is passed to the HttpApplication.
Practice 8.1
The following program illustrates the use of the application variable.
<HTML>
<HEAD><TITLE>Application Variable</TITLE></HEAD>
<BODY>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
Application [“var”] = “Radiant”;
Response.Write (Application[“var”].ToString());
}
</script>
</BODY>
</HTML>
The above example creates a new application variable named var and assigns the value Radiant. Then, the
value of the variable var is displayed in the browser. After assigning a value to an application variable, it
can be displayed on all the pages in an application.
Global.asax
The Global.asax file (ASP.NET application file) is a file that contains the syntax for coding the server-side
application object. The Global.asax file is stored in the root directory of an ASP.NET application. The file
handles the application events like Application_Start, Application_End, Session_Start, Session_End, etc.
The Global.asax is parsed and compiled by ASP.NET into a .NET Framework class when a request is
made for the first time within its application namespace. The Global.asax file itself is configured so that
direct URL request is automatically rejected. i.e. users are not allowed to view or download the code.
The ASP.NET Global.asax file is fully compatible with the ASP Global.asa file. A Global.asax file can be
created either in a WYSIWIG HTML designer, Notepad, or as a compiled class that is deployed in the
application’s \bin directory as an assembly.
Note: The Global.asax file is not mandatory; if not defined, the ASP.NET framework assumes that there is
no definition for application or session event handlers.
The Global.asax provides more than 15 events. The following table describes the different events in the
Global.asax.
Table 8.1
Events in the Global.asax can have different event method prototypes. The following is an example of how
the BeginRequest event signature can vary:
ApplicationState
ASP.NET
Earlier versions of ASP had a single instance of the Application object for each application running in the
machine. The values and object references are valid as long as the application is running. However, the
Application object is destroyed when changes are made to the Global.asax file or if the last client Session
object is destroyed.
Global information can be shared across applications using the HTTPApplicationState class that exposes
a key-value dictionary of objects that can be used to store both .NET Framework object instances and
scalar values across multiple web requests from multiple clients.
An instance of the HTTPApplicationState class is created when the client requests a URL resource from
within a particular ASP.NET Application virtual directory namespace for the first time. This is the case for
each application that is stored in the computer. This instance can be manipulated through the Application
property of the HTTPContext object that is provided to all IHTTPModules and IHTTPHandlers during a
given Web request.
The important thing to be noted is that objects instantiated at the application-level scope can handle
multiple concurrent access. The limitation while using an HttpApplication is that it is not maintained
across a Web-farm or in a Web-garden. A Web-farm is where more than a single server handles the
requests for the same application and a Web-garden is where the same application runs in multiple
processes within a single, multi-processor machine.
An easy to use state facility that is compatible with ASP that works with all .NET languages and is
consistent with other .NET Framework APIs.
The application state dictionary is available to all request handlers invoked within an application
whereas in ASP it has restricted access only to pages.
Application state values are accessible only from code running within the context of the originating
application and not from other applications running on the system.
Application state variables are also global variables for a given ASP.NET application. The impact of
creating global variables must be considered before creating them. The points to be considered when
using application state variables are:
The memory occupied by application state variables will not be released until the value is either
removed or replaced. For instance, storing 10Mb recordsets that is never used in application state
permanently is not the best use of system resources
The concurrency and synchronization implications of storing – and later correctly accessing – a global
variable within a multi-threaded server environment. Multiple running threads within an application
can access application state variables simultaneously. Care must be taken to ensure that either the
application-scoped object is free-threaded and contains built-in synchronization support, or an
application-scoped object is not free-threaded and explicit synchronization methods are coded to
avoid deadlocks. Hence, explicit use the “Lock” and “Unlock” methods provided on the
HTTPApplicationState class must be used to avoid problems
Since locks that protect global resource are themselves global, the code running on multiple threads
that accesses global resources will ultimately battle on these locks. This causes the OS to block the
worker threads until the lock becomes available. In a server environment with high load this can
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
133
ASP.NET
cause severe “thread thrashing” on the system. In multi-processor systems it can lead to processor
under-utilization (since all the threads are waiting for a shared lock) and significant drops in overall
scalability
Global data stored in application-state is not stable, since it will be lost when the host containing it is
destroyed. To avoid such failures, the state has to be stored either in a database or on some other
durable store
Since the application-state is not shared across either a Web-farm or a Web-garden, variables stored
in application-state in these scenarios are global only to the particular process that the application is
running
Note: For performance reasons all the built-in .NET collections do not contain built-in synchronization
support.
Properties
The properties of the application state are as follows:
All
The All property returns all application state objects as an array of objects.
AllKeys
The AllKeys property retrieves all application state object names in a collection.
Contents
The Contents property returns “this”. This property is included for compatibility with ASP.
Count
The count property gets the number of item objects in the application state collection.
Item
The item property is used to add, remove, or update an application state object. This property is the
indexer for the HttpApplicationState class.
Item Property (String) - Enables a user to add/remove/update a single application state object. This
property is the indexer for the HttpApplicationState class.
Item Property (Int32) - Enables user to retrieve an application state object by index. This property is
the indexer for the HttpApplicationState class.
StaticObject
The StaticObject property exposes all objects declared through the <object runat=server></object> tag
within the ASP.NET application file.
Collection
A collection represents a logical storage unit that helps to manage information.
Keys
The Keys collection represents a collection of the System.String keys of a collection. This class is used
exclusively to implement the NameObjectCollectionBase.Keys property, which allows different methods
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
134
Application, Session State Management and Cookies
for accessing each key in the NameObjectCollectionBase.Keys property by using an index, an array or a
Get method.
Methods
The methods of the application state are discussed below:
Clear
The Clear method removes all objects from the application state collection.
Remove
The Remove method removes an object from the application state collection by specifying a name.
Syntax
public void Remove(string name);
name is the object name
RemoveAll
The RemoveAll method removes all objects from the application state collection.
Lock
The Lock method locks access to all application state variables and hence facilitates access
synchronization.
UnLock
The Unock method unlocks access to all application state variables. This also facilitates access
synchronization.
8.3 Session
ASP.NET
A session keeps track of user-specific information when a user navigates the site without asking the users
identity for every request from the server. The different information to be maintained are a user’s
identification and security. In certain advanced applications, customization to the web site must also be
maintained. A separate session is assigned for each visitor to the Web site.
Usage of Session
A Session can store the user’s preferences like the preferred background color of the Web page, whether to
use frames etc. Sessions can also be used to create a virtual shopping basket. Whenever a user selects an
item to buy, the item is automatically added to a shopping basket. When the user is ready to quit, he/she
can purchase the items in the shopping basket at once. All the item information in the shopping basket can
be stored in a session. Sessions can also be used to keep track of the habits and interests of the visitors.
This information can be used for advertising purposes, to improve the design of the Web site, or to satisfy
the Webmasters’ curiosity.
Managing Sessions
Session variables are similar to application variables and can be used in multiple ASP.NET pages.
However, unlike an application variable, separate copies of a session variable are created for each visitor
to the Web site.
In order to store data that will persist throughout a user session, the data has to be stored in a collection of
the Session object. This is illustrated in the following example:
Practice 8.2
<HTML>
<HEAD><TITLE>Session Variable</TITLE></HEAD>
<BODY>
<script language=”C#” runat=”server”>
void Page_Load(Object Source, EventArgs e)
{
Session [“svar”] = “Radiant Software”;
Response.Write (Session[“svar”].ToString());
}
</script>
</BODY>
</HTML>
The first line in this script assigns the text Radiant Software to a session variable named svar. The next
line in the script displays the text on the screen.
If the same user requests another page the same text is displayed again. For example, consider the
following code:
Note: Session variables exist only in relation to a particular user. The values assigned to a session variable
in one user session does not affect the values of the session variables in another user session; i.e. the data
stored in session variables are not shared among different users.
To create a script that executes whenever a new session begins, the script has to be added to the
Session_Start section of the Global.asax file, as in the example given below:
</script>
The script assigns the value “Unknown” to two session variables named Username and UserPassword.
The Session_Start script can be used for other purposes like redirecting the visitors to a new page.
The Session_End script stores data when the user leaves a session. This information can be used to
determine the pages that are more often used to enter and exit the Web site.
When an instance of an object is created with session scope, a new instance of the object is created for each
user. In general, the objects created with session scope demand more memory than objects created with
application scope. However, there will be less access contention over the object because only one user can
access each instance of the object.
SessionState
ASP.NET
HTTP is a stateless protocol, which means that it provides no method to automatically recognize that a
series of requests are all from the same client. It does not even determine whether a single browser
instance is still actively viewing a page or site. As a result, building web applications that need to maintain
some cross-request state information (shopping carts, data scrolling, etc) can be extremely challenging
without additional infrastructure help.
Session State provides an easy, robust and scalable way to automatically identify and classify requests
coming from a single browser client into a logical application “session” on the server. It is also used to
store session-scoped data on the server for use across multiple browser requests and to raise the
appropriate session lifetime management events (Session_Start, Session_End, etc.) that can be handled in
application code. A Session state will automatically release session information if the browser does not re-
visit an application after a specified timeout period.
Cookieless
The Cookieless property indicates whether a cookie should be used as an identity key or not. The default
setting is false. When the property is set to true, ASP.NET automatically encodes cookie data in the URL
and passes it along with the request.
Count
The count attribute determines the number of items in the Cookies collection.
Collections
The various collections of the session state are as follows:
Contents
The Contents collection exposes all variable items that have been added to the session-state collection
directly through code.
Session[“Message”] = “Bar”;
StaticObject
The StaticObject collection exposes all variable items that have been added to the Session-state collection
through the <object runat=”server”> </object> tags with the “Session” scope within the global.asax file.
The StaticObjects collection cannot have objects that are added to this collection in any other place within
a .NET Application. The .NET Page Compiler automatically inserts member references to all objects stored
within the StaticObjects collection at page compilation time. This enables direct access to Session objects
at the time of page request without having to go through the Application collection.
Abandon
The Abandon method terminates a user’s session and releases the memory allocated to maintain user
information. If the user leaves the web site, the information is maintained until the session times out. If the
user returns before the session times out, the web server does not create another new Session object; it
uses the existing one. This is illustrated below:
Response.Write (Session.SessionID);
Session.Abandon();
In the above code, the session ID of the user is displayed on the screen and then the Session.Abandon
method is called. When the user requests a new page, the information in the Session object is lost and a
new ID is assigned to the session. The server treats the user as a new user after the Abandon method is
called.
The Session.Abandon method has certain special scope characteristics. When the Session.Abandon
method is called, the Web server continues to process the remaining ASP code on the page.
8.4 Cookies
ASP.NET
Cookies are special files on Windows machines and are used to store data about visitors to Web sites. A
Web server can insert information into these cookie files. Storing cookies on the client is one of the
methods used by the ASP.NET’s session state in order to associate requests with sessions. Cookies can also
be used directly to persist data between requests. However, the data is then stored on the client and sent
to the server with every request. The size of the cookie is limited to 4096 bytes by the browser.
Note : Cookies work on the majority of browsers, but fail completely when used with browsers that do not
support them, and hence the sessions will also fail.
<%
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
140
Application, Session State Management and Cookies
cookie.Expires = DateTime.MaxValue;
cookie.Domain =”.forindia.com”;
cookie.Path = “/examples”;
cookie.Secure = “True”.ToBoolean();
%>
ASP.NET
Server Object
ϕ Provides access to utility function
ϕ Property
- ScriptTimeout
ϕ Methods
- CreateObject() - Execute(Path)
- GetLastError() - HTMLEncode()
- MapPath(Path) - Transfer()
- UrlEncode()
The Server object provides access to the utility functions of the server.
The ScriptTimeout property specifies the amount of runtime in seconds for a script before it terminates.
The default value is 90 seconds.
The following code causes a script to timeout if the script takes more than 150 seconds to complete.
There is one mandatory argument ObjectID that specifies the type of object to be created.
Execute(Path)
The Execute method allows to call another ASPX page from inside an ASPX page. When the called ASPX
page completes its tasks, control is then returned to the calling ASPX page. The overall effect is very
similar to a function or subroutine call. Any text or output from the called ASPX page will be displayed on
the calling ASPX page. The Execute method is a more useful alternative to using server-side includes.
In contrast, the Transfer method allows to transfer from one ASPX page to another without returning to
the calling ASPX page.
There is one mandatory argument Path that is a string specifying either the absolute or relative path of the
ASPX page being called. The file name must be included in the path. The entire Path must be enclosed
inside a pair of quotes. The Path argument cannot include a query string, however, any query string that
was available to the calling ASPX page will be available to the called ASPX page.
// CallingAsp.aspx
<HTML>
<BODY>
Hello <%Server.Execute(“CalledAsp.aspx”)%> - Welcome to Radiant
</BODY>
</HTML>
// CalledAsp.aspx
<%
Response.Write “Anitha”
%>
GetLastError( )
HTMLEncode( )
The HTMLEncode method applies HTML encoding syntax to a specified string of ASCII characters. For
example, this allows to display a HTML tag on a web page and not have it treated as an actual tag.
MapPath(Path)
The MapPath method maps a relative or virtual path to a physical path. This method does not check for
the validity or the existence of the physical path. If the path starts with a forward or backward slash, the
method returns the path as if the path is a full virtual path. If the path does not start with a slash, then the
method returns the path relative to the directory of the ASPX file being processed.
Practice 8.3
<HTML>
<HEAD>
</HEAD>
<BODY>
The path of this file is <% Response.Write Server.MapPath(“test.aspx”)
%>
The path of file1 is <% Response.Write Server.MapPath(“test\test.aspx”)
%>
The path of file2 is <% Response.Write Server.MapPath(“\”)
%>
</BODY>
</HTML>
In the above code, the first MapPath method considers test.aspx as a page under the root directory. The
second method considers test.aspx as a page residing in the test sub-directory of the root directory. The
third method returns the path of the root directory.
Transfer()
The Transfer method allows to transfer from inside one ASPX page to another ASPX page. All of the state
information that has been created for the first (calling) ASPX page will be transferred to the second
(called) ASPX page. This transfered information includes all objects and variables that have been given a
value in an Application or Session scope, and all items in the Request collections. For example, the second
ASPX page will have the same SessionID as the first ASPX page.
When the second (called) ASPX page completes its tasks, control does not return to the first (calling) ASPX
page.
In contrast, the Execute method that allows to call another ASPX page, and when the called page has
completed its tasks, control returns to the calling ASPX page.
It has one mandatory argument namely Path, that is a string specifying either the absolute or relative path
of the ASPX page being called. The file name must be included in the path. The entire Path must be
enclosed inside a pair of quotes.
URLEncode()
The URLEncode method takes a string and converts it into a URL-encoded format. For example, it is
possible to use URLEncode to ensure that hyperlinks in Active Server Pages are in the correct format.
The following line of code illustrates the usage of the URLEncode method:
http%3A%2F%2Fwww%2Eissi%2Enet
An ASP.NET application is created when a request is made for the first time to the server
An application variable contains data that is used in all the web pages and by all the users of an
application
The global.asax file contains syntax for coding the server-side application object
A session keeps track of user-specific information when a user navigates the site without asking the
users identity for every request from the server
A session begins when a user requests a page from a Web site. A session is closed when the user
leaves the Web site
Session variables like application variables can be used in multiple ASP.NET pages
Session State provides an easy, robust and scalable way to automatically identify and classify
requests coming from a single browser client into a logical application “session” on the server
Cookies are special files on Windows machines that are used to store data about visitors to Web sites
Lecture 9
ADO.NET - I
Objectives
In this lecture you will
learn the following
Coverage Plan
Lecture 9
9.1 Snap Shot
9.2 Database
9.3 DBMS
Every organization has a pool of resources that it must manage effectively to achieve its objectives.
Although their rules differ, all resources human, financial and material share a common characteristic.
The organization that fails to treat data or information as resource and to manage it effectively will be
handicapped in how it manages its manpower, material and financial resources. In order to satisfy the
information requirements of management, the data should be stored in an organized form.
Actually data are the facts stored in the record of a database. But the processed facts are presented in a
form for usage is information.
9.2 Database
ASP.NET
Database
A database is a shared collection of interrelated data designed to meet the varied information needs of an
organization. For example, in a payroll application each person’s record has Name, Age, Designation,
Basic Pay etc as columns. So payroll database has a collection of all employee records, that are
interrelated. From the database, various reports like payslip, persons with particular designation, service
report etc can be obtained. The database acts as a media to store the data in an organized way so that it
can be managed effectively. A database has two important properties integration and sharing.
Information collected for the sake of making a statistical analysis, e.g. the national census. Operational and
administrative information required for running an organization or a commercial concern will take the
form of stock records, personnel records, customer records etc.
Because of the investment involved in setting up a database, the expectation must be that it will continue
to be useful, over years rather than months. But the relationship with time varies from one type of
information to another. An organizational database may not change very drastically in size, but it will be
subject to frequent updating (deletions, amendments, insertions) following relevant actions within the
organization itself. Ensuring the accuracy, efficiency and security of this process is the main concern of
many database designers and administrators.
ASP.NET
Benefits of Database approach
The database approach offers a number of important advantages compared to the file system. These
benefits include minimal data redundancy, consistency of data, integration of data, sharing of data,
enforcement of standards, ease of application development, uniform security, privacy and integrity
controls, data accessibility and responsiveness, data independence, and reduced program maintenance.
With the database approach, data files that were separate are integrated into a single, logical structure. So
each item is ideally recorded in only one place in the database. Hence, in a database system, the data
redundancy is controlled.
Consistency of data
By eliminating data redundancy, the consistency of data is greatly improved. If there is any change in the
data, it can be incorporated in one place unlike the traditional file system where the change has to be
incorporated manually in each and every place.
Integration of data
In a database, data are organized into a single, logical structure, with logical relationships defined
between associated data entities.
Sharing of data
9.3 DBMS
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
148
ASP.NET
DBMS
ϕ Computerized record-keeping system that stores,
maintains and provides access to information
ADO.NET - I
A DBMS (Database Management System) is a computerized record-keeping system that stores, maintains
and provides access to information. The function of the DBMS is to store, maintain and retrieve
information as required by applications, programs or users. The functions of the DBMS are listed below:
• Type Checking
• Range Checking
• Consistency Checking
In an interactive data entry system, errors should be detected immediately and recovery and re-entry
should be permitted. If the database is error bound then it will be the main cause to make the program
error prone.
Updating
Updating of data is very important otherwise it will be fruitless in future. Updating involves:
• Record Insertion
• Record Modification
• Record Deletion
Updating may take place interactively, or by submission of a file of transaction records; handling these
may require a program of some kind to be written, either in a conventional programming language or in a
language supplied by the DBMS for constructing command files.
These allow:
Report definition
Most systems provide facilities for describing how summary reports from the database are to be created
and laid out on paper. These may include obtaining:
• COUNTS
• TOTALS
• AVERAGES
• MAXIMUM and MINIMUM values
On a table over a particular Control Field the above layouts have to be found out. Also specification of
Page and Line Layout, Headings, Page-Numbering, and other narrative are required to make the report
comprehensible.
Security
The security consists of several aspects:
• Ensuring that only those authorized can see and modify the data, generally by some extension of the
password principle
• Ensuring the consistency of the database where many users are accessing and up-dating it
simultaneously
• Ensuring the existence and INTEGRITY of the database after hardware or software failure. At the
very least this involves making provision for back-up and re-loading
ASP.NET
DBMS Standardization
ϕ Eliminates duplications
Early computer applications were based on existing clerical methods and stored information was
partitioned in much the same way as manual files. But the computer’s processing speed gave a potential
for relating data from different sources to produce valuable management information, provided some
standardization could be imposed over departmental boundaries. The idea emerged of the integrated
database as a central resource emerged. Here, data is captured as close as possible to its point of origin
and transmitted to the database, then extracted by anyone within the organization who requires it.
However, many provisos have become attached to this idea in practice, it still provides possibly the
strongest motivation for the introduction of a DBMS in large organizations. The idea is that any piece of
information is entered and stored just once, eliminating duplications of effort and the possibility of
inconsistency between different departmental records. Data redundancy has to be removed as much as
possible.
Advantages
Organizational requirements change over time, and applications laboriously developed need to be
periodically adjusted. A DBMS gives some protection against change by taking care of basic storage and
retrieval functions in a standard way, leaving the application developer to concentrate on specific
organizational requirements. Changes in one of these areas need not affect elsewhere. In general, a DBMS
is a substantial piece of software, the result of many man-years of effort.
The points discussed above are probably most relevant to larger organizations using a DBMS for its
administrative functions - the environment in which the idea of databases first originated. In other words
the convenience of a DBMS may be the primary consideration. The purchaser of a small business
computer needs all the software to run it in a package form, written so that the minimum of expertise is
required to use it. The same applies to departments (e.g. Research & Development) with special needs that
cannot be satisfied by a large centralized system. When comparing database management systems it is
obvious that some are designed in the expectation that professional staff will be available to run them,
while others are aimed at the total novice.Actual monetary costs vary widely from, for instance, a large
multi-user Oracle system to a small PC-based filing system.
ASP.NET
SQL
ϕ Basic language that allows users to access
data in database management systems
ϕ Mainly classified into DDL and DML
DDL
ϕ Create Database Statement
ϕ Create Table Statement
ϕ Alter Table Statement
ϕ Drop Table Statement
Structured Query Language (SQL) is a basic language that allows users to access data in database
management systems, such as Oracle, Sybase, Informix, Microsoft SQL Server, Access by allowing users to
describe the data the user wishes to see. SQL also allows users to define the data in a database, and
manipulate that data.
SQL is mainly classified into Data Definition Language (DDL) and Data Manipulation Language (DML).
Note: The Create Database statement is not supported by all SQL implementations
The Create Table statement creates a table and adds it to the database:
The columnName is unique to a table. The columnType identifies the type of data that will be stored in
the table. Common data types are
Practice 9.1
The following is an example of a Create Table statement which creates a table named Customers
containing columns CustName,Company, Cust_rep, Credit_limit:
The Alter Table statement is used to add a row to an existing table or to change the table definitions.
Practice 9.2
ASP.NET
DML
ϕ Insert Statement
ϕ Update Statement
ϕ Delete Statement
One of the primary uses of SQL is to update the data contained in a database. There are SQL statements
for inserting new rows into a database, deleting rows from a database, and updating existing rows.
INSERT Statement
Practice 9.3
The following is an example of the preceding form of the INSERT statement:
(1 row(s) affected)
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
153
ASP.NET
The preceding statement adds a row to the Customer table. All columns of this row are filled in.
An alternative form of the INSERT statement may be used to insert a partial row into a table. The
following is an example of this alternative form of the INSERT statement:
The values of columnName 1 through columnName m are set to value 1 through value m. The value of
the other columns of the row are set to NULL.
Practice 9.4
(1 row(s) affected)
The preceding statement adds a row to the Customer table with CustName - Smith and Company -
Radiant. The other columns of the table are set to null.
DELETE Statement
If WHERE clause is omitted, all the rows of the table are deleted.
Practice 9.5
(1 row(s) affected)
The preceding statement deletes the row which has CustName as Smith from the Cutomers table.
UPDATE Statement
Practice 9.6
The following statement is an example of the UPDATE statement:
(1 row(s) affected)
The preceding statement changes the Credit Limit of the company Radiant with the new Credit Limit of
Rs12,00,000.
ASP.NET
Select Statement
The most important use of SQL for many users is for retrieving data contained in a database. The SELECT
statement specifies a database query:
Note: An asterisk (*) may replace columnList1 to indicate that all columns of the table(s) are to be
returned.
Practice 9.7
The following is an example for select statement.
Where Clause
The WHERE clause is a Boolean expression consisting of column names, column values, relational
operators, and logical operators. For example, suppose there are columns such as Department, Salary, and
Bonus. The following WHERE clause could be used to find all employees in the Engineering department
whose salaries are over 100,000 and bonus are less than 5,000.
ASP.NET
WHERE clause can be based on some relational
and logical comparisons
ϕ Comparison Test
ϕ Range Test
ϕ Set Membership Test
ϕ Pattern Matching Test
ϕ Null Value Test
ϕ Compound Search Conditions
Comparison Test
= equal to
<> not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Range Test
This test is used to test whether the value lies within the range or not. The keyword are:
• BETWEEN … AND
• NOT BETWEEN … AND
Practice 9.8
The following statement selects rows from the Customers table subject to the condition that the credit
limit lies between 10000 and 50000.
The preceeding example selects rows from Customers table that satisfy the condition that the Credit_limit
is between 10000 and 50000.
This is to test whether the value is present in the list of values. The keyword is IN.
Example
SELECT * FROM CUSTOMERS WHERE CUST_REP IN (10, 15, 20, 25)
The above query selects the rows for which the Cust_Rep takes one of the values 10, 15, 20 or 25.
The Pattern matching test is employed to select rows from a table based on a field whose values match a
given pattern. The keywords LIKE, %, _ are the wildcard characters used in the pattern matching test. %
is equivalent to * in DOS. _(Underscore) is equivalent to ? in DOS. The $ is used to remove the above
special meaning of % and _.
Example
SELECT * FROM CUSTOMERS WHERE CUSTNAME LIKE ‘S%H’
The above query searches for the customers whose first character is S and the last character is H.
This is used to test whether the column contains null value. The keyword is IS NULL.
This is used to test for more than one condition. The keyword AND/OR/NOT is used.
ASP.NET
ϕ Order by clause
- Used to order result set by specified
column(s) of a table
ϕ Union
- Used to combine two or more tables
ϕ Joins
- Used when results of two or more queries
have to be combined
Order By
The ORDER BY clause is used to order the result set by the specified column(s) of a table. Each of the
column names in the column list may be followed by the ASC or DESC keywords. If DESC is specified,
the result set is ordered in descending order. Otherwise, the result set is ordered in ascending order. The
following query retrieves the rows of the Customers table ordered by the CustName field.
Union
It is used to combine two or more tables. The necessary criteria are:
• The tables must contain the same number of columns
• Data type of each of the columns of one table should match that of the other
When the keyword UNION ALL is used, all the rows of both the tables are displayed. When the keyword
UNION is used, only distinct rows from both the tables are displayed.
Example:
SELECT * FROM A
UNION (SELECT * FROM B
UNION SELECT * FROM C)
ORDER BY NAME
The preceeding statement produces a combined output from tables A,B and C. The output is arranged in
the ascending order of Names.
Joins
Joins are used when the results of two or more queries have to be combined. This session discusses two of
the joins namely, Equi joins and Non-Equi joins.
Equi-join
An equi-join is a join with a join condition containing an equality operator. An equi-join combines rows
that have equivalent values for the specified columns.
Practice 9.9
The following example performs an equi-join with Order and Customer tables where both the tables are
described below:
Ordernum
order_date
cust_rep
qty
amount
Non-Equi-join
A non-equi-join is a join with a join condition containing any operator other than the equality operator.
Example
The following query selects the order number, amount and credit limit of the Customer table where
cust_rep of Order table is not equal to cust_rep of Customer table.
ASP.NET
ϕ Functions
- Used to compute against a column or columns of
data returned from a query
ϕ Group by
- Gather all rows that contain data in specified
column(s)
ϕ Having
- Allows to specify conditions on rows for each
group
ϕ Distinct
- Returns information from table columns without
repetition
Functions
Functions are used to compute against a column or columns of data returned from a query. Some of the
important functions are
Example
SELECT CUST_REP, SUM(AMOUNT) FROM ORDERS ORDER BY CUST_REP
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
159
ASP.NET
The above query displays the number of each salesperson and the total sum of orders for each of them.
Group by
The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and
will allow aggregate functions to be performed on the one or more columns.
Example:
SELECT company, SUM(credit_limit)
FROM customer
GROUP BY company
This query select the sum of credit_limit from customer table for each company.
Having
The HAVING clause allows to specify conditions on the rows for each group - in other words, which rows
should be selected will be based on the conditions specified in the Having clause. The HAVING clause
should follow the GROUP BY clause if used.
Example:
Distinct
The SQL SELECT statement with Distinct keyword returns information from table columns without
repetition.
A special type of client/server architecture consisting of three well-defined and separate processes, each
running on a different platform is as follows:
• The user interface, which runs on the user’s computer (the client)
• The functional modules that actually process data. This middle tier runs on a server and is often called
the application server
• A Database Management System (DBMS) that stores the data required by the middle tier. This tier
runs on a second server called the database server
To accomplish the task of connecting to data sources that are open to many applications, the application
and the database must agree on a common method of accessing the database. This agreement is
implemented using a complete set of API calls and a complete SQL syntax set.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
160
ADO.NET - I
The database side of this open connectivity is provided by drivers. These drivers will transform the API
functions into function calls supported by the particular data source being used. Similarly, the drivers
transforms the SQL syntax into syntax accepted by the data source. These drivers were originally
produced by the manufacturers of the databases, but now there are many third-party vendors as well.The
main benefit of this API is that many database formats can now be accessed by applications as their own
native databases.
ASP.NET
ADO.NET
ADO.NET is the latest of the database access technologies that began with the Open Database
Connectivity (ODBC) application programming interface (API). Microsoft introduced open data base
connectivity with the promise of creating a singular common access methodology for databases. ODBC
has come a long way since those early days. Almost every major database in use today suports ODBC
drivers, and third party developers provide optimized driver versions.The primary focus of the ODBC is
to provide a consisitent interface to database data sources.
As time passed by COM landed at the database territory and started a colonization process that
culminated with OLE DB. OLE DB is a set of COM-based interfaces that exposes data from a variety of
sources. OLE DB interfaces provide applications with uniform access to data stored in diverse information
sources, or data stores. These interfaces support the amount of DBMS functionality appropriate to the data
store, enabling the data store to share its data.
With .NET, Microsoft is offering a general-purpose framework—the Framework Class Library—that will
cover all the existing Windows API and more. In particular, it will include a number of frequently used
libraries now available through separate COM objects. The XML and ADO object models have been
integrated in a subtree of classes called ADO.NET
• ADO.NET is the base that will form the foundation of data-aware .NET applications
• Unlike ADO, ADO.NET has been purposely designed for more general, and less database-oriented,
guidelines
• ADO.NET gathers all the classes that allow data handling. Such classes represent data container
objects that feature typical database capabilities—indexing, sorting, views
• ADO.NET is the definitive solution for .NET database applications, it shows off an overall design that
is not as database-centric as the ADO model
• ADO.NET is quite different from ADO. It is a new data access programming model that requires full
understanding, commitment, and a different mindset
• ADO.NET is not ADO adapted to fit into the .NET infrastructure. This is apparent when looking at
ADO.NET in terms of syntax, code design, and migration
• Information is data that have been processed and refined and then given in the format that is
convenient for decision making or other organizational activities
• A database is a shared collection of interrelated data designed to meet the varied information needs of
an organization
• SQL also allows users to define the data in a database, and manipulate that data
• SQL is mainly classified into Data Definition Language (DDL) and Data Manipulation Language
(DML)
• One of the primary uses of SQL is to update the data contained in a database
• Functions are used to compute against a column or columns of data returned from a query
• ADO.NET is the latest among of the database access technologies that started with the ODBC API
1. What is a database?
3. What is a DBMS?
4. What is SQL?
6. What is a function?
YZ
Lecture 10
ADO.NET - II
Objectives
In this lecture you will
learn the following
+ What is meant by Managed Provider?
Coverage Plan
Lecture 10
10.1 Snap Shot
10.5 DataReader
The Managed Provider acts as an intermediate between the client and the data source. The Connection
object is used to connect to the data source. The Command object is used to create and execute commands
against the data source so that the data is retrieved in an useful form to the client. The DataReader is a
forward-only stream which is used to store the retrieved data, for use in the application.
ASP.NET
Managed Provider
The Managed Provider is an intermediate between the client and the data source. It responds to queries
from the client and returns data from the data source in a usable form. The .NET Framework provides two
types of Providers:
• ADO
• SQL
The ADO Provider is used to connect to any data source, whereas the SQL Provider is specially designed
for use with the SQL database. The support for the ADO Provider is given by the System.Data.ADO
Namespace. The support for the SQL Provider is given by the System.Data.SQL Namespace.
• SQLCommand
• SQLConnection
• SQLDataReader
• SQLDataSetCommand
• SQLError
• SQLErrors
• SQLException
• SQLParameter
• SQLParameters
The usage of the above classes will be dealt with while discussing the corresponding objects.
The following figure (Figure 10.1) shows the object model of ADO.NET
Figure 10.1
ASP.NET
Parameter object
ϕ Represents and parameter or argument associated
with a Command object
ϕ Enables reuse of command
Property object
ϕ Contains metadata and setting for a property in an
ADO data source
ADOException
ϕ Instance created when ADO encounters a situation
that it cannot handle
The parameter object represents a parameter or argument associated with a Command object based on a
parameterized query or stored procedure. The parameter object enables reuse of the same command, by
altering only the values passed to it. For example, by using the parameter object, an insert statement can
be reused by changing the values of the fields passed as parameters to the command. The property object
contains the metadata and settings for a property in an ADO data source. When ADO encounters a
situation that it cannot handle, it creates an instance of the ADOException class. Any operation involving
the objects in ADO.NET can generate one or more provider errors. Whenever such errors occur, the ADO
creates an instance of the ADOError class. These instances are created and managed by the ADOErrors
class which in turn is created by the ADOException class.
The following paragraphs deal with the Connection, Command and DataReader objects.
ASP.NET
ADO Connection object
ϕ Used to connect to database
ϕ Represents a unique session with a data source
ϕ Used to
- Define information needed by ADO
- Define transactional capabilities of session
- Allow creation and execution of commands
- Provide information about design of underlying
data source
There are four basic operations involved in creating an ADO application. They are: retrieving data,
examining data, editing data and updating data. To get the data from the database, a connection has to be
established. The connection to the database is established using the ADOConnection object. A connection
object represents a unique session with a data source. It is used to:
• Define the information needed by the ADO to communicate with data sources and create sessions
• Define the transactional capabilities of the session
• Allow the creation and execution of commands against the data source
• Provide information about the design of the underlying data source
The properties of the ADOConnection class are:
• ConnectionString – Indicates the string to be used to open a data store which includes the username,
password etc.
• ConnectionTimeout – Denotes the time to wait to establish a connection, before terminating the
attempt and generating an error
• DataSource – Represents the source of the data to which the connection has to be established
• Provider – Indicates the name of the provider to be used for connecting to the data source
ASP.NET
The SQLConnection class also shares the above properties except the Provider property. The SQL Server
Managed Provider uses the private protocol called tabulardata stream to communicate with SQL Server. It
does not use OLEDB, ADO or ODBC. So, the Provider property is not present in this class.
Instead, the SQLConnection class contains two more properties listed below:
• ServerVersion – Denotes the version of the SQL Server to which the connection has been established
• TransactionLevel – Specifies the transaction level
An instance of the ADOConnection class can be created using one of the following two constructors:
• SQLConnection(string dataSource, string userID, string password) – Creates a new instance of the
SQLConnection to the specified dataSource, using the specified user ID and password
• SQLConnection(string dataSource, string userID, string password, string database) – Creates a new
instance of the SQLConnection to the specified database in the specified dataSource using the
specified user ID and password
Some of the important methods common to both the classes are listed below:
The following part of code illustrates how to connect to a database using the SQLConnection class:
Note: While using SQLConnection, the provider need not be specified since the default SQL Provider will
be used. But, while using ADOConnection, the provider needs to be specified.
Practice 10.1
The following example uses the SQLConnection object to connect to the master database.
In the above code, when the user clicks on the “Get Connection” button, its Onclick event is fired. The
event calls the Connect method that in turn establishes the connection with the SQL Server database
named master that is present in the same system as the client as the user sa. All these are specified in the
connection string when an instance of SQLConnection is created. The Open method of the connection
object actually establishes the connection.
ASP.NET
Command Object
ϕ Used to request any type of operation from
the provider
Once a connection to a database has been established, the queries have to be sent and the results retrieved.
This is achieved through the Command object. The Command object can be used to request any type of
operation from the provider, if the provider understands the command string properly. It is not necessary
for a command to be executed only through the Command object. The command object is very useful
when a command is to be reused or needs to receive input parameters.
The following are the properties of the Command object common to both the ADOCommand and
SQLCommand classes:
In addition to the above methods, the ADOCommand class contains the following methods:
There are five constructors in the SQLCommand class that can be used to create a command object. They
are:
The ADOCommand class contains five similar constructors to create an ADOCommand object. The fifth
constructor alone contains an additional boolean parameter that determines whether or not the command
uses named parameters. The constructor is shown below:
The lines above create a command with the query string “select * from emp” and with the connection
object “conn”.
Practice 10.2
The following example uses the SQLCommand object to insert a record into the emp table of the master
database.
<html>
<title> Example for Command </title>
<script language=”C#” runat=”server”>
SQLConnection myConnection;
protected void Page_Load(Object Src, EventArgs E)
{
myConnection = new SQLConnection
(“server=localhost;uid=sa;pwd=;database=master”);
}
try
{
myCommand.ExecuteNonQuery();
lb.Text = “Record Added”;
}
catch (SQLException e)
{
if (e.Number == 2627)
lb.Text = “ERROR: A record already exists with
the same primary key”;
else
lb.Text = “ERROR: Could not add record, please ensure
the fields are correctly filled out”;
}
myCommand.ActiveConnection.Close();
}
</script>
<body style=”font: 10pt verdana”>
<form runat=”server”>
<h3>Add a New Employee:</h3>
ID: <input type=”text” id=”eid” value=”0" runat=”server”> <br>
Name: <input type=”text” id=”ename” value=”” runat=”server”> <br>
Sal: <input type=”text” id=”esal” value=”0" runat=”server”><br>
<input type=”submit” OnServerClick=”AddEmp” value=”Add Employee”
runat=”server”>
<asp:label id=”lb” runat=”server” />
</form>
</body>
</html>
The above example receives the employee ID, name and salary from the user to adds a new record to the
emp table of the master database. The connection object is created when the page is loaded. When the user
enters the required information and clicks the “Add Employee” button, its OnServerClick event is fired.
This event invokes the AddEmp method. It checks if any of the input values is empty. If so, it prints out an
appropriate message and returns without inserting the record. If not, a command object is created using
the connection defined in the Page_Load event. Values are passed to the object using the Parameters
collection. Then the command is executed and the record is added to the table.
10.5 DataReader
ASP.NET
DataReader
ϕ A read-only, forward-only stream returned from the
database
ϕ At a time, only one record is held in memory
ϕ Every time a record is read, internal cursor points
to next record
ϕ A series of Get methods enable user to access
field values
ϕ An instance is created through Execute method
ϕ Fully utilizes the corresponding connection object
Data can be retrieved from the database and held in memory for usage by the application. But when a
large amount of data is retrieved, maintaining the memory used by the data for a long time will be
inefficient. In this case it is useful to make use of the DataReader. The DataReader can also be used when
the user has to iterate over the stream of data retrieved from the database.
The DataReader is a read-only, forward-only stream returned from the database. At a time, only one
record is held in memory. Every time a record is read, the internal cursor will automatically point to the
next record. A series of Get methods provided by the DataReader enable the user to access the field
values.
An instance is created for ADODataReader through the Execute method of the ADOCommand class and
not through its constructor. Further, when the ADODataReader is being used, the corresponding
ADOConnection is fully utilized by it. So, no other operation (except the Close operation) can be
performed using the connection until the ADODataReader is closed. The same holds true for
SQLDataReader.
The ADODataReader class contains one more property named RowFetchCount that indicates the number
of rows to be retrieved at one time.
Practice 10.3
The following example uses DataReader to retrieve and display the records of the table emp in the master
database.
</html>
The above example establishes a connection with the master database. It then executes a select command
to retrieve rows from the emp table and stores the retrieved rows in the SQLDataReader dr. Then it reads
each row from it and displays in a table.
• The parameter object represents a parameter or argument associated with a Command object based
on a parameterized query or stored procedure
• The property object contains the metadata and settings for a property in an ADO data source
• When the ADO encounters a situation that it cannot handle, it creates an instance of the
ADOException class
• The Command object can be used to request any type of operation from the provider, if the provider
understands the command string properly
• The DataReader is a read-only, forward-only stream returned from the database. It is useful when
the user has to iterate over the stream of data retrieved from the database
3. What are the kinds of commands that can be executed using the Command object?
4. What is a DataReader?
5. When an ADODataReader is open, can the corresponding Connection object be used to execute some
other command?
YZ
Lecture 11
ADO.NET - III
Objectives
In this lecture you will
learn the following
Coverage Plan
Lecture 11
11.1 Snap Shot
11.2 DataSet
11.3 DataTable
11.4 DataView
This session introduces the user to DataSet, DataRelation, DataTable and DataView.
The DataSet is designed to handle the actual data from a data store and provides access to multiple tables,
rows and columns. Each DataSet can contain multiple tables and maintain the relationship between
them.The advantage of the DataSet is that since it is designed for disconnected data, multiple tables can be
simultaneously passed around the tiers of a Web application, along with the relationships.
DataView is a custom view of data table, whose prime purpose is to aid in data binding. DataView is the
equivalent of ADO RecordSet.
Note: A DataSet is not a RecordSet. In terms of analogies, a DataView is more like a RecordSet.
11.2 DataSet
ASP.NET
Data set
The centerpiece of any software solution using ADO.NET is the DataSet. A DataSet is an in-memory copy
of the database data. A DataSet contains any number of data tables, each of which typically corresponds to
a database table or view. A DataSet constitutes a “disconnected” view of the database data. That is, it
exists in memory without an active connection to a database containing the corresponding tables or views.
This disconnected architecture enables greater scalability by only using database server resources when
reading or writing from the database.
The DataSet class resides in System.Data namespace. The DataSet object model is shown in Figure 11.1.
DataSet
Relation Collection
Extended Properties
Tables Collection
Rows
ChildRelations
ParentRelations
Constraint
Columns
PrimaryKeys
Figure 11.1
TablesCollection object
An ADO.NET DataSet is a collection of one or more tables represented by DataTable objects. The
TablesCollection object contains all the DataTable objects in a DataSet. A DataTable is defined by
System.Data and represents a single table of memory-resident data. It contains a collection of columns
represented by the ColumnsCollection object, which defines the schema and rows of the table. It also
contains a collection of rows represented by the RowsCollection object, which orders the data in the table.
Along with the current state, a DataTable object retains its original state and tracks all changes that occur
to the data. The DataSet is able to persist and reload its contents through XML.
RelationsCollection object
ExtendedProperties
The ExtendedProperties object contains customized user information, such as a password or the time
when data should be refreshed for a DataSet object.
ASP.NET
Working with DataSets
At run time, data will be passed from the database to a middle-tier business object and then down to the
user interface. To accommodate the exchange of data, ADO.NET uses an XML-based persistence and
transmission format. That is, to transmit data from one tier to another, an ADO.NET solution expresses
the in-memory data (the DataSet) as XML and then sends the XML to the other component.
• An existing database management system, such as SQL Server can be used to fill tables in the DataSet.
In this method, one SQLDataSetCommand can be used per table to fill the DataTable object with data.
However, the DataRelation objects should be created between each table
• A DataSet can be programmatically created, DataTable objects can be added to it, and then
DataRelation objects can be created to link each table
On the client application, the data is displayed using a combination of controls, such as the DataGrid. The
user can add, delete, or edit the data. After the user finishes working with the data, the DataSet is again
converted into an XML document for transmitting back to the server component. DataSet, the middle tier
component, is created using an adapter. The DataSet is then converted into an XML document for
transport back to the requester.
The DataSet stores data using COM+ types. The COM+ decimal type allows a maximum of 28 significant
digits, while the SQL decimal type allows 38 significant digits. Currently, the FillDataSet method throws
an exception if it encounters a valid SQL decimal with more than 28 significant digits. Currently there are
currently no ways to get a SQL decimal of greater than 28 significant digits into a DataSet object. If the
application requires the added precision, a SQLDataReader object can be used. The GetSQLNumeric
method can then be called to get the SQL decimal value.
Figure 11.2
Constructors of DataSet
There are two constructors for a DataSet.
The first constructor initializes a new instance of the DataSet class, as shown below:
public DataSet();
The second constructor initializes a new instance of a DataSet class with the given name, as given below:
public DataSet(string);
Practice 11.1
The following application performs a select query from a SQL database bounded to a DataGrid.
<html>
<script language=”C#” runat=”server”>
void Page_Load(Object Src, EventArgs E)
{
SQLConnection con = new SQLConnection
(“server=localhost;uid=sa;pwd=”);
In the above example, the connection object con is created in the Page_Load event. A
SQLDataSetCommand object com is also created with the query to retrieve all the records from the
emptab table. The command is executed and the DataSet ds is filled with the resulting rows using the
FillDataSet() method. Then, the DataSource property of the DataGrid is set to the DataSet. Finally, the
DataBind() method is called to populate the DataGrid with the values.
Practice 11.2
The following application executes a select query from a database using ADOConnection and
ADODataSetCommand classes and displays the data in a listbox.
</script>
<asp:Listbox id=l runat=server/>
</html>
In the above example, a connection with the database has been created using ADOConnection. The Query
has been passed to ADOSetCommand. The DataSet is populated with the results from the query using the
FillDataSet method. The result is then viewed in a listbox using the foreach statement. The result can also
be viewed by binding it to a DataGrid.
Methods of DataSet
ASP.NET
ϕ Important Methods of DataSet:
- AcceptChanges( )
- Clear( )
- Copy( )
- Dispose( )
- Equalst( )
- GetChildRelations( )
- GetContainer( )
- GetParentRelations( )
- Merget( )
- ReadXml( )
- WriteXml( )
• AcceptChanges() - Commits all the changes made to this DataSet since it was loaded or the last time
AcceptChanges was called
• Clear() - Clears the DataSet of any data by removing all rows in all tables
• Clone() - Clones the structure of the DataSet, including all DataTable schemas, relations, and
constraints
• Copy() - Copies both the structure and data for this DataSet
• Dispose() - Disposes of the Component
• Equals() - Determines whether the specified Object is the same instance as the current Object
• GetChanges() - Returns a copy of the DataSet containing all changes made to it since it was last
loaded, or since AcceptChanges was called
• GetChildRelations() - Gets the collection of child relations which belong to a specified table
• GetContainer() - Returns the IContainer that contains the Component
• GetHashCode() - Serves as a hash function for a particular type, suitable for use in hashing algorithms and data
structures like a hash table
• GetParentRelations() - Gets the collection of parent relations which belong to a specified table
• GetType() - Gets the Type of the Object
• Merge() - Merges this DataSet with a specified DataSet
• ReadXml() - Reads XML schema and data into the DataSet
• ReadXmlData() - Reads data from the specified XML source and maps the data into the DataSet object’s
schema
• ReadXmlSchema() - Reads an XML schema into the DataSet
• ToString() - Returns a String that represents the current Object
• WriteXml() - Writes the current schema and data for the DataSet[cref, System.Data] to an XML
document
• WriteXmlData() - Overloaded. Writes the data contained in the DataSet to an XML document
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
187
ASP.NET
Properties of DataSet
ASP.NET
ϕ Important properties of DataSet:
- DataSetName
- DefaultView
- ExtendedProperties
- NameSpace
- Relations
- Tables
- Xml
- XmlData
• CaseSensitive - gets or sets a value indicating whether string comparisons within datatable objects
are case-sensitive
• Datasetname - gets or sets the name of the dataset
• Defaultview - gets a custom view of the data contained by the dataset, one that allows filtering,
searching, and navigating through the custom data view
• Extendedproperties - gets the collection of custom user information
• Haserrors - gets a value indicating whether there are errors in any of the rows in any of the tables of
the dataset
• Locale - gets or sets the locale information used to compare strings within the table
• Relations - get the collection of relations that link tables and allow navigation from parent tables to
child tables
• Tables - gets the collection of tables contained in the dataset
• Xml - gets or sets the xml data for the dataset
• Xmldata - gets or sets the xml data for the dataset
Events of DataSet
ASP.NET
MergeFailed
- Public event MergeFailedEventHandler Merge
Failed;
PropertyChanged
- public event PropertyChanged EventHandler
PropertyChanged
MergeFailed - Occurs when a target and source DataRow have the same primary key value, and
EnforceConstraints is set to true. Its syntax is as follows:
DataSet Constraints
ASP.NET
DataSet constraints
ϕ ForeignKeyConstraint
ϕ UniqueConstraint
ForeignKeyConstraint
UniqueConstraint
The UniqueConstraint can be enforced to a DataTable when it is essential that all the values of a column
must be unique. It can be added either to a single column or to an array of columns of the same DataTable.
Constraints are not enforced unless the EnforceConstraints property is set to true. When a DataSet is
merged with a second DataSet, constraints are not enforced until all merges are completed.
DataRelation
ASP.NET
DataRelation
The DataRelation represents a parent/child relationship between two tables. The DataSet represents a
complete set of data including related tables, constraints, and relationships among the tables. A typical
dataset contains relationships contained by the RelationsCollection object. A relationship, represented by
the DataRelation object, associates rows in one table to the rows in another table. It is similar to the
foreign-key relationship in a relational database. A DataRelation identifies matching columns in two
tables of a DataSet.
A DataSet can contain either related or unrelated data. It can be thought of as a document of Data. In fact,
an XML data document is similar to it except for the fact that it is based on a hierarchical paradigm. Since
data is often stored in relational databases, the DataSet can handle both hierarchical relationships and
foreign key relationships. Relationships can also have different types of enforcement. By default, deletions
and updates are cascaded. A DataSet contains a Relations collection. It is easy to add a relationship to this
collection using the column or columns (in a multi-column key) of the related tables.
Practice 11.3
The example given below presumes that two DataTable objects exist in the DataSet. Both tables have a
column named “CustomerID” which serves as the link between the two tables. The example adds a single
DataRelation to the Relations collection of the DataSet object. The first argument (“CustOrders”) specifies
the name of the relationship. The second and third arguments are the DataColumn objects that link the
two tables.
orders”, con);
ds = new DataSet();
com1.FillDataSet(ds,”Customers”);
com2.FillDataSet(ds,”Orders”);
DataRelation dr;
dr = new DataRelation( “CustOrders”,ds.Tables[“Customers”].
Columns[“CustomerId”],
ds.Tables[“Orders”].Columns[“CustomerId”]);
ds.Relations.Add(dr);
Response.Write(“Relationship Established”);
}
</script>
</html>
The example above constructs an instance ds of a DataSet and fills data into it from two
SQLDataSetCommand objects com1 and com2. Then a DataRelation dr is added to the Relations collection
specifying its name, and the appropriate DataColumn objects as arguments. It adds a relation between the
CustomerId Key on the Customers table and the CustomerId foreign key on the Orders table in the
DataSet.
Data can be retrieved from the relationship defined in the example above using the lines:
A primary function of the DataRelation is to allow navigation from one table to another within the
DataSet. In practice, this allows us to retrieve all the related DataRow objects in one table when given a
single DataRow from a related table. The above example gives a DataRow from the Customers table. All
the orders for a particular customer can be retrieved from the Orders table.
11.3 DataTable
ASP.NET
DataTable class
The DataTable class is present in the System.Data namespace. It represents a table of in-memory data. The
DataTable is a central object in the ADO.NET library. Other objects which use the DataTable include the
DataSet and the DataView.The DataTable contains a collection of Constraint objects that can be used to
ensure the integrity of the data.
Syntax
Public Class DataTable Inherits Component Implements IListSource,
ISupportInitialize
Practice 11.4
This program displays the properties of a table such as its column names, types and column properties. It
displays the result in a listbox.
The example above creates a connection with database using the ADOConnection object con and passes a
query in an ADOSetCommand object com. It then populates the DataSet ds with the results from the
query using the FillDataSet method. Then it displays the table properties such as its column names, types
and column properties in the listbox l using the foreach statement. The Unique, AutoIncrement and
AllowNull properties return a boolean value.
11.4 DataView
ASP.NET
DataView
ϕ Represents a databindable, customized view of a
DataTable
ϕ Allows data binding on both Windows forms and
Web Forms
ϕ Can be customized to present a subset of data
from DataTable
ϕ Components of DataRows of a DataTable within a
given DataView
The DataView represents a databindable, customized view of a DataTable for sorting, filtering, searching,
editing, and navigation. A major function of DataView is to allow data binding on both Windows Forms
and Web Forms. A DataView can be customized to present a subset of data from the DataTable. This
capability allows to have two controls bound to the same DataTable, but showing different versions of the
data. For example, one control may be bound to a DataView showing all the rows in the table, while the
second control may be configured to display only the rows that have been deleted from the DataTable.
The DataTable also has a DefaultView property, which returns the default DataView for the table.
The DataRows of a DataTable within a given DataView have three components: what the data was (the
original state), what the data is now (the current state), and what the value of the data is going to be (the
proposed state). When changes are made to the data, it affects the current state or proposed state, but its
original state is left unaffected until it is changed explicitly by using the DataRow.AcceptChanges method.
Syntax
Public Class DataView Inherits Component Implements ILiveList, IList,
ICollection, IEnumerable, _ ISortedList, IIndexedList, ITypedList
Practice 11.5
The following example creates a single DataTable with three columns and five rows using DataView.
<html>
<script language=”C#” runat=”server”>
void Page_Load(Object Src, EventArgs E)
{
SQLConnection con = new SQLConnection(
“server=localhost;uid=sa;pwd=”);
SQLDataSetCommand com = new SQLDataSetCommand(“select * from
emptab”, con);
DataSet ds = new DataSet();
com.FillDataSet(ds, “emptab”);
DataView dv = new DataView(ds.Tables[“emptab”]);
s.InnerHtml = dv.Table.TableName;
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
194
ADO.NET - III
d.DataSource = dv;
d.DataBind();
}
</script>
<body>
<h3><font face=”Verdana”>Example for DataView <span runat=”server”
id=”s”/></font></h3>
<ASP:DataGrid id=”d” runat=”server”
Width=”250"
BackColor=”#ccccff”
BorderColor=”black”
CellPadding=3
Font-Name=”Verdana”
Font-Size=”8pt”
HeaderStyle-BackColor=”#aaaadd”
/>
</body>
</html>
A SQLConnection object con is created to perform a select query on the emptab table of the SQL database.
A SQLDataSetCommand object com that contains the query statement is then constructed. A DataSet
object is created and populated with the results from the query through the FillDataSet method. The
DataView dv represents a subset of data from the DataTable. Finally, the output is displayed by binding
the DataView with the DataGrid d.
• The DataSet is designed to handle the actual data from a data store and provides access to multiple
tables, rows and columns
• The TableCollection object, RelationsCollection object and ExtendedProperties are the three major
parts of the DataSet object model
• The DataTable contains a collection of Constraint objects that can be used to ensure the integrity of the
data
• The DataView represents a databindable, customized view of a DataTable for sorting, filtering,
searching, editing, and navigation. A major function of the DataView is to allow data binding on both
Windows Forms and Web Forms
Lecture 12
Objectives
In this lecture you will
learn the following
+ Learning about Databinder
Coverage Plan
Lecture 12
12.1 Snap Shot
12.2 Databinder
In the previous sessions, we have learnt how to use ASP.NET controls. This session deals with binding the
controls to the data source, that is, associating the control with the datasource so that the data for the
control is supplied by the data source. In ASP.NET, the data source can be a database, an XML file, a
control etc. The Web Forms page enables the user to bind any control’s property to the information in any
kind of data store.
ASP.NET
• Controls like textbox, label, checkbox etc., can be bound to the data source
• Controls like DataGrid, DataList etc., that are primarily designed for the usage of data binding can
be used
• Programmer can write code explicitly to retrieve the data from the data source and display it in the
controls
The Web Forms pages access data in the form of classes that expose data as properties and define methods
for updating the underlying data source. The simple controls like radio button, checkbox etc., bind to a
single value. They can bind to the public property of the page or any of its controls. Complex controls like
Repeater, DataList and DataGrid can bind to any structure that implements the ICollection interface.
A control can be bound to the data by using either of the following steps:
The expression is evaluated only when the DataBind method is called. This method is generally called at
two instances: when the page is loaded or when an event-handling method has changed the data set. The
DataBind method can be called for each control or for the whole page. When it is called for the whole
page, it is cascaded down to each control on the page. Similarly, when it is called on a parent control, it is
cascaded to all of its child controls.
12.2 Databinder
ASP.NET
Databinder
ϕ Makes code simpler and more readable
ϕ Eval()
- Static method that evaluates data binding
expressions against Container object at runtime
- Optionally formats result as a string
- Useful when data binding against controls in a
templated list
Syntax = Eval(Object container, string expression,
string format) n not be used
The DataBinder class is provided by ASP.NET to make code simpler and more readable. The static
method Eval() of this class evaluates data binding expressions against the Container object at runtime and
optionally formats the result as a string. This method is particularly useful when data binding against
controls in a templated list. It can take one of the two forms:
ASP.NET
ϕ Public variables
ϕ Properties of the page
ϕ Properties of other controls on the page
The ASP.NET data binding syntax supports binding to public variables, properties of the page and
properties of other controls on the page. The following example illustrates binding to public variables and
simple properties on the page.
Practice 12.1
The following example binds four properties to display the details of an employee.
<html>
<head>
<script language=”C#” runat=”server”>
void Page_Load(Object sender, EventArgs e) {
Page.DataBind();
}
int EmpID {
get {
return 101;
}
}
string EmpName{
get {
return “Sandhya”;
}
}
string Dept{
get {
return “ICG”;
}
}
int Salary{
get {
return 10000;
}
}
</script>
</head>
<body>
<form runat=server>
Employee ID: <b><%# EmpID %></b><br>
Employee Name: <b><%# EmpName %></b><br>
Department: <b><%# Dept %></b><br>
Salary: <b><%# Salary %></b>
</form>
</body>
</html>
The above example uses the databinding expression to bind four properties namely, EmpID, EmpName,
Dept and Salary to the corresponding elements of the page. The DataBind() method is present in the
Page_Load event so that the data is displayed as soon as the page is loaded.
Binding to a DataBase
ASP.NET
The controls like ListBox, DropDownList, CheckBoxList and RadioButtonList can be used to display data
from a database. They can display one field from the source and use another field as the item value. The
DataSource property of the control should be set to the source of the data. The DataTextField property
denotes the name of the field whose value is displayed in the list. The DataValueField property is the
name of the field to be used for the Value property of each list item.
Practice 12.2
The following example uses the ListBox control to display the list of publisher names from the Publishers
table.
DataSet ds;
SQLConnection conn;
SQLDataSetCommand cmd;
string connStr, query;
connStr=”server=localhost;uid=sa;database=pubs”;
conn = new SQLConnection(connStr);
The above example binds the listbox to the database in the Page_Load event. It creates a connection object
named conn using the connection string connStr. A command object cmd is then created using this
connection and the query string query. The command is executed and the results are retrieved in the
DataSet ds. Then the DataSet is linked to the listbox through the properties DataSource and
DataTextField.
ASP.NET
Repeater Control
The Repeater control is used to display the data items in a repeating list. The layout of the control’s
content is defined using templates.
A template is a set of HTML elements and controls that make up the layout for a particular portion of a
control. Templates allow the programmer to specify both the contents and appearance of controls like the
Repeater, DataGrid and DataList. Each of these controls support a slightly different set of templates that
specify layouts for different portions of the control such as the header, footer, item and selected item. The
type of template is specified as the NAME attribute of the template element. Templates can be created
directly in the .aspx file containing the control which uses the template. Since the template also specifies
the content to be displayed, the databinding expressions can be specified inside the template.
• HeaderTemplate – This defines the layout of the elements to be rendered once before all the data-
bound rows are displayed
• ItemTemplate – This defines the layout of the elements to be rendered once for each row in the
Repeater control. This template is used to bind one or more ASP.NET server controls to a data source.
This template is mandatory
• AlternatingItemTemplate – This is similar to the ItemTemplate, but it is rendered for every alternate
row in the Repeater control
• SeparatorTemplate – This defines the layout of the elements to be rendered between each row, such
as line breaks, lines etc
• FooterTemplate – This defines the layout of the elements to be rendered once after all the data-bound
rows are displayed
The Repeater control is bound to the data source through its DataSource property. It can bind to any class
that supports the ICollection or IEnumerable interface.
Practice 12.3
The following example uses the Repeater control to retrieve the rows whose country is USA, from the
Publishers table.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
204
Data Aware Controls
</script>
</head>
<body bgcolor=”#FFFFFF”>
<ASP:Repeater id=”rep” runat=”server”>
<template name=”headertemplate”>
<table >
<tr align=left >
<th width=80> Pub. ID </th>
<th width=180> Name </th>
<th width=100> City </th>
<th> State </th>
</tr>
</template>
<template name=”itemtemplate”>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, “pub_id”)%> </td>
<td> <%# DataBinder.Eval(Container.DataItem, “pub_name”)%></td>
<td> <%# DataBinder.Eval(Container.DataItem, “city”)%> </td>
<td> <%#DataBinder.Eval(Container.DataItem, “state”)%></td>
</tr>
</template>
<template name=”footertemplate”>
</table>
</template>
</ASP:Repeater>
</body>
</html>
The above example binds the Repeater control to the database in the Page_Load event. It creates a
connection object named conn using the connection string connStr. A command object cmd is then
created using this connection and the query string query. The command is executed and the results are
retrieved in the DataSet DS. Then the DataSet is linked to the repeater through the properties DataSource.
The itemtemplate of the repeater defines how the data of each row has to be displayed.
• The Web Forms pages access data in the form of classes that expose data as properties and define
methods for updating the underlying data source
• The property of a control can be bound to a datasource using the databinding expression. The
databinding expression is evaluated only when the DataBind method is called
• The ASP.NET data binding syntax supports binding to public variables, properties of the page and
properties of other controls on the page
• List server controls like ListBox, DropDownList etc., use a collection as a datasource
• The controls like ListBox, DropDownList, CheckBoxList and RadioButtonList can be used to display
a single field from a table
YZ
Lecture 13
Objectives
In this lecture you will
learn the following
+ Knowing about DataGrid Server Control
Coverage Plan
Lecture 13
13.1 Snap Shot
DataGrid Server control displays information in tabular form with columns. It Provides mechanisms that
allow editing and sorting. DataList Server control is similar to Repeater control, but with more formatting
and layout options, including the ability to display information in a table. The DataList control also allows
to specify editing behavior.
ASP.NET
ϕ Allows to add specific functionality, including
selecting, editing, sorting, and paging data
ϕ Must be bound to a data source through its
DataSource property
ϕ The grid displays one row, one item for every row
in the data source
ϕ 0
By default, the DataGrid control generates a bound
column for each field in the data
The DataGrid ASP.NET sever control is a multi-column, data-bound grid that displays tabular data. The
control allows to define various types of columns, both to lay out the contents of the grid and to add
specific functionality, including selecting, editing, sorting, and paging the data.
The DataGrid ASP.NET server control must be bound to a data source via its DataSource property or it
will not be accompflished on the page.
When data binding, a data source is specified for the DataGrid control as a whole. The grid displays one
row, one item for every row in the data source. By default, the DataGrid control generates a bound
column for each field in the data source. When the page runs, the controls DataBind method is called to
load the grid with data. The method can be called each time the page makes a round trip to the server (for
example, in an event-handling method) to refresh the grid.
A simple datagrid
Practice 13.1
<html>
<title> Simple DataGrid </title>
<script language=”C#” runat=”server”>
ICollection CreateDataSource() {
DataTable dtbl = new DataTable();
DataRow drow;
drow[0] = i;
drow[1] = “prd 00” + Int32.ToString(i);
dtbl.Rows.Add(drow);
}
</script>
<body>
<form runat=server>
</form>
</body>
</html>
The above example shows a simple DataGrid control which shows Serial No and Product No. These two
Columns has been created using Datacolumn object in Datatable.Similarly rows has been inserted using
Datarow object in Datatable.
DataGrid Columns
The DataGrid control allows to specify the columns it displays in a variety of ways. By default, the
columns are generated automatically based on the fields in the data source. However, in order to
manipulate the content and layout of columns more precisely, the following types of columns can be
defined:
• Bound columns
This columns allow to specify which database fields to be displayed and in what order it must be
displayed and allow to specify the format and style of the display.
• Hyperlink columns
This columns display information as hyperlinks. A typical use is to display data (such as Area
number or Area name) as a hyperlink that users can click to navigate to a separate page that provides
details about that information.
• Button columns
These columns allow to display buttons next to each item in the grid and define custom functionality
for the buttons. For example, a button might be created and labeled as “Add to Shopping Cart” that
runs the custom logic when users click it.
• Template columns
These columns allow to create combinations of HTML text and server controls to design a custom
layout for a column. The controls within a template column can be data bound. Template columns
provide the ultimate flexibility in defining the layout and functionality of the grid contents.
Note: To execute the following program, an MSAccess database named sample.mdb with a table
Employee has to be created with the fields EmployeeID, FirstName, Salary.
ASP.NET
There are two ways to edit the contents of individual rows in a grid item. They are:
This is the easiest method of allowing editing. A special column can be included in the grid with buttons
labeled “Edit”. When users click the edit button, the control automatically redisplays the current row with
editable fields for all columns (for example, text boxes for characters and numbers and checkboxes for
Boolean data). The column with the edit button is redisplayed with update and cancel buttons.
It is possible to create columns that display the data in editable controls. This approach allows to
manipulate very precisely the columns that can be edited and allows to choose how the user can edit the
data. When a template column is used, the items in the grid typically do not switch between edit and
display modes. Instead, the items are always in edit mode. In either approach, a custom logic must be
added to the page to update the data source with the user’s edits.
The DataGrid ASP.NET server control provides a way to add sorting to the grid using the following
methods:
• Default sorting
All columns in the grid are sortable. The header for each column contains a LinkButton control
(hyperlink) that users click to sort by that column.
• Custom sorting
It is possible to define which column to support sorting and what type of button in the column
heading user click to sort.
In either case, the grid does not sort the rows. Instead, it notifies the sort request by raising an event. Then
sorting is performed in the code, usually by passing rebinding to the data source with new sort
parameters.
Data in a grid is commonly sorted by clicking the header of the column. This is enabled by setting
AllowSorting=true. When enabled, the grid will render LinkButtons in the header for each column. When
the button is clicked, the grid’s OnSortCommand event is thrown. Since DataGrid always displays the
data in the same order it occurs in the datasource, the typical logic sorts the datasource, then rebinds the
data to the grid.
Practice 13.2
if (!IsPostBack)
BindGrid(“EmployeeID”);
}
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}
</script>
</head>
<form runat=”server”>
<h4> Sorting Datagrid Control </h4>
<asp:Datagrid id=”DataGrid1" onsortcommand=”dbsort” allowsorting=”true”
runat=”server” autogeneratecolumns=”true”/>
</form>
</body>
</html>
The above example shows how to do sorting in datagrid.When we click any one of the header column the
rows will be sorted in ascending order.The sortfield has been used to set the field to be sorted.Set the
Dataview s sort property to the sortfield so that dataview will sort it out.
Paging in DataGrid
ASP.NET
The DataGrid ASP.NET server control provides a way to add paging to the grid using the following
methods:
It is possible to provide own paging controls and manually set which page is to be displayed. This
option allow to move any number of pages at a time, jump to a specific page, and so on.
The page displayed by the grid is determined by its CurrentPageIndex property. The built-in controls set
this property automatically; if custom navigation controls are provided it has to be set. After the
CurrentPageIndex is set, the grid should be re-bound to the data source. The grid will recreate the entire
data set and automatically move to the appropriate place in the data set. It then displays enough rows to
make up one page of the grid.
In case of working with a large data set, recreating the entire data set each time users navigate to a new
page can require too many overheads. In that case, we might prefer to get data in page-size “chunks”, that
is, retrieving just a page worth of records at a time. To allow that, turn off the automatic paging feature of
the grid so that it doesn’t assume that it is working with the entire data set. Then correct number of rows
should be retrieved manually to fill the grid.
Accessing a Database
ASP.NET
ϕ SQL Connection class gets or sets the name of the
current database or the database to be used once a
connection is open
ϕ Accessing a Database using DataGrid is achieved
with the following steps:
- Establish a connection
- Execute a query and retrieve the sesults in a
DataView, DataReader or DataSet
- Blind the DataView, DataReader or DataSet to the
DataGrid through the DataSource property
SQLConnection class gets or sets the name of the current database or the database to be used once a
connection is open.
• Establish a connection
• Bind the DataView, DataReader or DataSet to the DataGrid through the DataSource property
The following example shows how a DataGrid is used to access the data in the SQL Server database.
<html>
<script language=”C#” runat=”server”>
void Page_Load ( Object src, EventArgs e)
{
DataSet DS;
SQLConnection MyConnection;
SQLDataSetCommand MyCommand;
string strconn, strSQL;
strconn=”server=saravanan;uid=sa;database=pubs”;
MyConnection = new SQLConnection(strconn);
strSQL=”select * from Publishers”;
MyCommand = new SQLDataSetCommand(strSQL,MyConnection);
DS = new DataSet();
MyCommand.FillDataSet(DS, “publishers”);
MyDataGrid.DataSource = DS.Tables[“Publishers”].DefaultView;
MyDataGrid.DataBind();
}
</script>
<body>
<form runat=server>
<ASP:DataGrid id=”MyDataGrid” runat=”server”
BorderColor=”black”
BorderWidth=”1"
GridLines=”Both”
CellPadding=”3"
CellSpacing=”0"
Font-Name=”Verdana”
Font-Size=”8pt”
HeaderStyle-BackColor=”#aaaadd” />
</form>
</body>
</html>
In the above example, data from the Publishers table are displayed in the DataGrid. When the “Show
Values” button is clicked, the records are displayed as shown.
ASP.NET
The DataList control displays database information in a format that can be controlled very precisely using
templates and styles. The DataList control is useful for displaying rows of database information. The
DataList control displays rows of data as items in the list. It is possible to use templates to define the layout
of the items by including HTML text and controls.
• ItemTemplate
This template defines the content and layout of items within the list.
• AlternatingItemTemplate
If this template is defined, this determines the content and layout of alternating items. If it is not
defined, ItemTemplate is used.
• SelectedItemTemplate
If this template is defined, this determines the content and layout of the selected item. If it is not
defined, ItemTemplate is used.
• EditItemTemplate
This defines the layout of an item when it is in edit mode. This template typically contains editing
controls, such as TextBox controls.
This text defines the text and controls to render at the beginning and end of the list.
• SeparatorTemplate
This defines the elements to render between each item. A typical example might be a line (using an
<HR> element).
A Simple DataList
DataList supports directional rendering through the RepeatDirection property. This means that it can
render its items horizontally or vertically. Since page width is the dimension that the developer must
control in Web UI, DataList permits the developer to control the number of “columns” that are rendered
(RepeatColumns), regardless of whether the items are rendered horizontally or vertically.
Practice 13.4
</asp:DropDownList><br>
<asp:LinkButton id=Button1 Text=”Refresh DataList”
OnClick=”Button1_Click” runat=”server”/>
</font>
</form>
</body>
</html>
Above example shows a simple DataList control. As it can be seen from the above program a table is
created using DataTable class and the rows are added using NewRow method. RepeatDirection property
is used to render the items horizontally or vertically. With the help of RepeatColumns property, the
number of columns to be repeated can be shown.
It is possible to customize the content and appearance of the selected item via the SelectedItemTemplate
property. The SelectedItemTemplate is controlled by the SelectedIndex property. By default the value of
SelectedIndex is -1, meaning none of the items in the list is selected. When SelectedIndex is set to a
particular item, that item is displayed using the SelectedItemTemplate.
Accessing a Database
SQLConnection class represents an open connection to a SQL Server data source. SQLDataSetCommand
represents a set of data commands and a database connection which are used to fill the DataSet and
update the data source. DataBinder Class provides design-time support for Rapid Application Designers
(RAD) designers to generate and parse DataBinding expression syntax.
• Establish a connection
• Execute a query and retrieve the results in a DataView, DataReader or DataSet
• Bind the DataView, DataReader or DataSet to the DataList through the DataSource property
Practice 13.5
The following example shows how a DataGrid is used to access the data in the database.
As seen from the above example, a connection to the database is created using a Connection object. SQL
query is passed to the SQLDataSetCommand object mycom. The FillDataSet method executes the
command and populates the DataSet DS with the result. The DataSource property of the DataList is used
to bind the DataList to the DataSet. Then the DataBind method is used to list out the values in the
DataList.
• The DataGrid ASP.NET server control must be bound to a data source via its DataSource property
• The DataGrid control allows to specify the columns it displays in a variety of ways
• The types of columns that can be defined in DataGrid are Bound columns, Hyperlink columns,
Button columns, Edit command columns and Template columns
• The two ways to edit the contents of individual rows in a grid item are Allow in-place editing and
Create a custom editing layout with a template column
• Data in a grid is commonly sorted by clicking the header of the column and is enabled by setting
AllowSorting=true
• The DataGrid provides the means to display a group of records from the datasource
• SQLConnection class gets or sets the name of the current database or the database to be used once a
connection is open
• The DataList control displays database information in a format that can be controlled very precisely
using templates and styles
• It is possible to customize the content and appearance of the selected item through the
SelectedItemTemplate property
3. What are the two ways to edit the contents of individual rows in a grid item?
YZ
Lecture 14
Objectives
In this lecture you will
learn the following
+ Compare the tracing in ASP and ASP.NET
Coverage Plan
Lecture 14
14.1 Snap Shot
14.2 Tracing
14.3 Error-Handling
14.4 Debugging
Debugging is used to find and correct the logical errors that keep the application or stored procedures
from running correctly. Tracking down problems in the code can be confusing without the appropriate
tool support. Fortunately, the compiled nature of ASP.NET means that debugging Web applications is no
different from debugging any other managed application and the .NET Framework SDK includes a
lightweight visual debugger that is perfectly suited for this task.
14.2 Tracing
Tracing with ASP
In an ASP application, the Response.Write() statement is used to dissect a troublesome section of code.
<%
On Error Resume Next
Response.Write(“About to do data access...”)
Set objDB = Server.CreateObject(“Custom.DataAccess”)
objDB.Open(“PersonalizationData”)
user = objDB.Get(“username”)
Response.Write(“Done calling data access. Value of username is:” + user)
%>
It is evident from the Response.Write() calls in the code given above that an error has occurred in the
behavior of the code. The error is not necessarily an application or system error, such as a failure to load
the object, but rather a coding error in which the code executes as expected but does not return the
expected value. Of course, debugger can also be used, but sometimes it is just faster to get a output to find
out what the code is doing or to simply know how a particular section of code is being executed. Although
Repsonse.Write() statements do make it easy to debug the application rather quickly, they introduce
unnecessary code into an application that can result in real bugs that break deployed applications. The
same functionality of Response.Write() statements is supported within ASP.NET.
ASP.NET
Trace
Trace feature is used to track particular types of actions in a deployed application as they occur (for
example, database connections), and can thus monitor the application’s efficiency. As another example, a
developer might write a program that must connect to the Internet in order to obtain updates to a file. The
developer could include tracing code in the program to record what steps are being used to accomplish
the task of connecting to the Internet. After the program is deployed in production, if a problem occurs
during the connection process, the end user can turn on a Trace switch to enable the tracing options that
the developer coded.
The new tracing features of ASP.NET allow to simulate Response.Write() statements. The users need not
worry about removing the statements before deploying the applications. Instead of using
Response.Write(), Trace.Write() is used. The Trace object is an intrinsic page object, similar to Request,
Response, Server, etc. It is accessible directly with the page code.
Trace class
Trace is exposed as a public property within ASP.NET pages. When the Trace property is used, an
instance of the TraceContext class is defined in the System.Web namespace. Trace class provides a set of
methods and properties that help to trace the execution of code. Instrumentation allows to monitor the
health of the application running in real-life settings. Tracing helps to isolate problems and fix them
without disturbing a running system.
• In C# or Managed Extensions for C++, the /d:TRACE flag can be added to the compiler command
line. In Visual Basic, the /d:TRACE=True flag can be added to the compiler command line
• The #define TRACE can be added to the top of the file. This syntax is compiler specific. If the user is
using a compiler other than the ones specified above, the compiler’s documentation has to be
referred to enable conditional compilation
Trace Methods
• Assert() - Checks for a condition, and displays a message if the condition is false
• Close() - Flushes the output buffer, and then closes the Listeners so that they no longer receive
debugging output
• GetHashCode() - Serves as a hash function for a particular type, suitable for use in hashing
algorithms and data structures like a hash table
• Equals() - Determines whether the specified Object is the same instance as the current Object
• Warn() - Writes trace information, along with optional exception data, to the trace log. All warnings
appear as red text. It has two forms. The first form writes trace information to the trace log including
any user defined categories. Its syntax is:
The second form writes trace information to the trace log including any user defined categories,trace
messages and error information. Its syntax is:
Practice 14.1
<html>
<script Language=C# runat=server>
public int Add(int a , int b)
{
Trace.Write(“Inside Add() a: “, a.ToString());
Trace.Write(“Inside Add() b: “, b.ToString());
return a + b;
}
</script>
<body>
Call the Add routine: 4 + 5 = <%=Add(4,5)%>
</body>
</html>
Here the Add() method is called. However, unlike the Repsonse.Write() statements, the Trace.Write()
statements do not appear within the resulting output. To view the results of the Trace.Write() statements,
we need to enable tracing for this page or for the application.
Practice 14.2
Here the warn method writes trace information, along with optional exception data, to the trace log. All
warnings appear as red text. If Write method is used instead of Warn method, all warnings appear in
black.
Trace Properties
The TraceContext class supports two public properties: IsEnabled and TraceMode.
IsEnabled
It indicates whether tracing is enabled on the page or for the application. This property can be set to true
for a page by including a trace=”true” attribute in the @Page directive. For an entire application this
property can be set to true in the application’s config.web file.
Note : If this property is set to true for an entire application, then for any page in that application for
which the tracing information need not be displayed, this property must be explicitly set to false for that
page.
TraceMode
It sets or returns the sorting mode that tracing is using. It indicates the order in which trace messages
should be output to a requesting browser. Trace messages can be sorted in the order in which they are
processed, or alphabetically by user-defined category.
Tracing Levels
ASP.NET
ϕ Page-Level Tracing
ϕ Application-Level Tracing
Page-level Tracing
ASP.NET aids the debugging and testing process by providing a trace capability that does two things
when enabled:
Tracing messages are appended to the HTML output stream that is sent to the requesting browser. This
information helps to clarify errors or undesired results as the framework processes a page request.The
trace capability is encapsulated in the TraceContext class, which is exposed as the Page.Trace property.
Essentially, there are two steps involved in viewing trace statements in a page, irrespective of whether
they are generated from a code-behind file or in an HTML editor. The first is to write the statements to be
included to the trace log, and the second is to enable the page to display those messages and other trace
information.
At the page-level, developers can use the TraceContext instrinsic to write custom debugging statements
that appear at the end of the client output delivered to the requesting browser. ASP.NET also inserts some
helpful statements regarding the start/end of lifecycle methods, like Load() and Dispose() as well as the
inputs and outputs to a page, such as Form and querystring variables or headers, and important statistics
about the page’s execution (control hierarchy, session and application state). Because tracing can be
explicitly enabled or disabled for a page, these statements may be left in the production code for a page
with no impact to the page’s performance. Each statement is associated with a user-defined category for
organizational purposes, and timing information is automatically collected by the ASP.NET runtime. The
resulting output may be ordered by either time or category.
Page directives are special instructions that ASP.NET uses when processing a request for an ASP.NET
resource. Page directives can be used to override or apply configuration settings for an ASP.NET page.
A directive must be the first element on a page. It is declared using the following syntax:
<%@ Directive Attribute=”[Value]” %>
Using the above syntax, in ASP.NET the page can be enabled as:
<%@ Page Trace=”true” %>
Example
The above page directive is added to the sample code Practice – 1. The output changes as shown in the
following figure:
Tracing is enabled by setting the Page directive to true. The tracing output is added to the bottom of the
page. Trace output is always added at the end of the page.
Application-Level Tracing
Application level tracing provides a view of several requests to an application’s pages at once. Like page-
level tracing, it also displays inputs and outputs to a page, such as Form and querystring variables or
headers, as well as some important statistics about the page’s execution (control hierarchy, session and
application state). Application-level tracing is enabled via the ASP.NET configuration system, and
accessed as a special mapped URL into that application (“trace.axd”). When application tracing is enabled,
page-level tracing is automatically enabled for all pages in that application.
ASP.NET uses XML configuration files to set configuration settings for ASP.NET applications. Every
ASP.NET installation installs a configuration file in the
[systemdrive]\WinNt\Microsoft.NET\Framework\[version]\ directory named config.web.
The configuration file sets the default ASP.NET configuration, and is currently known as the root
configuration file. Changes made within this file affect all the ASP.NET Web application. The
configuration files can also be used in Web applications to add or remove settings acquired from the
default config.web.
Note : If tracing is enabled at the application level, it is automatically enabled for each page in the
application. However, to view trace information on a page the PageOutput attribute must be used in the
config.web file.
Trace section
ASP.NET
<configuration>
<trace
enabled=”false”
requestlimit=”10"
pageoutput=”false”
tracemode=”SortByTime”
/>
</configuration>
There are four attributes for the trace element:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
233
ASP.NET
• enabled = “[true/false]”— The enabled option can be set to true or false. Tracing is either enabled at
an application level, or it is disabled at the application level. If enabled is set to false, page tracing is
still supported using the Trace directive discussed earlier
• requestlimit = “[int]”—Indicates the total number of trace requests to keep cached in memory on a
per-application basis. Tracing exposes a special resource Trace.axd, that is used to view trace output
when pageoutput is set to false
Trace.axd
ASP.NET
Trace.axd
ϕ An Http Handler
ϕ Can be used to request application trace details
Trace.axd is an Http Handler. An Http Handler is a coding option that allows request/responses to be
handled at the most basic level. Http Handlers are the equivalent of ISAPI extensions. However, unlike
ISAPI, they can be authored using any .NET language. Trace.axd is an Http Handler that can be used to
request application trace details. When requested, a trace log of the last n requests are given; n is
determined by the value set by requestlimit=”[int]” in the configuration file.
To use trace.axd, it can be requested from the same application directory from where the request for the
sample application has been made, as shown in Figure 14.1:
Figure 14.1
The screen shot, presents a list of traces that can be viewed (Figure 14.2). These trace views are identical to
the details that trace would add to the page, without the output from the page included:
Figure 14.2
• Request details—This is basic information, such as the session id, time of the request, the Http
request type, and the Http response status code
• Trace information—This section provides a table view of categories and messages. If Trace.Write()
statements are used in the code, the two parameters that Trace.Write() accepts are used as the
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
235
ASP.NET
Category and Message values, respectively. Additionally, it provides the time taken to trace from the
first to the last byte
• Control tree—ASP.NET uses server controls to allow users to declaratively build applications. The
Control Tree section provides information about controls within a page. The id, type, render size,
and view state size of the control as provided. This information gives an idea of the controls that are
being used, as well as the associated cost (render size and viewstate)
• Cookies collection—Any cookies that the client sends in the request headers are parsed, and their
names, values, and sizes are displayed
• Headers collection—Http headers presented by the client to the server are provided in this section. It
is a simple table that lists Name/Value pairs
• Server variables—The server variables section presents a Name/Value pair table of server variables
Using Tracing
Tracing is a powerful new ASP.NET feature designed to make the development of Web applications
easier. However, it is worthwhile to know the siruations for which tracing should be used.
• Deployed Applications
Tracing adds additional overhead to requests and should not be enabled for deployed applications.
Trace.Write() statements, however, can be retained because they are ignored when tracing is not
enabled
The classes found in the System.Diagnostics namespace are used to capture data for deployed
applications. These classes allow to write directly to the Windows event log. Tracing can be used
when an application is built, but it should be disabled when the application is deployed
• Disabling Trace.axd
<configuration>
<add verb=”*”
path=”trace.axd”
type=”System.Web.Handlers.TraceHandler” />
<remove verb=”*” path=”trace.axd”/>
</configuration>
Note : The entire <add/> entry can be removed, but the <remove> option is better because it leaves the
code in the configuration file and accomplishes the same goal by disabling trace.axd.
14.3 Error-Handling
ASP.NET
ASP.NET
ASP.NET error messages are more descriptive and visually appealing when compared to ASP.
ASP.NET files are compiled, and not interpreted like ASP files. Interpreted scripts process a file
one line at a time and send data to the client as each line is being processed.
One of the new features of ASP.NET is its rich support for handling and tracking runtime
errors. ASP.NET also provides administrators with additional information or notifications
about problems that occur on production sites.
ASP.NET will generate an html error page in the event that either a runtime or compile time
error occurs on a server. Unlike ASP, however, ASP.NET ensures that the “secure” information
is not leaked as a result of the occurence of errors.
or
• Modify the configuration settings within the machine’s or application’s config.web file to
enable remote access
<configuration>
<customerrors mode=”off” />
</configuration>
In the event, where an unhandled error occurs during the processing of a request, ASP.NET displays the
user’s “custom error page”. This in turn displays the user’s own branding and the required error message.
Custom error support can be added into the ASP.NET application very easily. Initially, web page must be
authored (it can be any type of file: .htm, .aspx, .asp etc). Then modify the configuration settings within
the application’s config.web file to point to the ASP file.
<customerrors> Section
The <customerrors> section defines custom error messages for an ASP.NET application.
Syntax
<customerrors defaultredirect=”[url]” mode=”[on/off/remote]”>
<error statuscode=”[statuscode]” redirect=”[url]” />
</customerrors>
The defaultredirect attribute (optional) indicates the default url that a browser should be redirected to if
an error occurs. The mode tag attribute indicates whether or not custom errors are enabled, disabled, or
only shown to remote machines.
The <customerrors> section tag supports multiple <error> sub-elements that each supports two attributes:
Directive Description
Statuscode Indicates an error status code that should cause a browser to be directed to a non-
default error page.
Type The URL to which the browser should be redirected in the event when an error occurs.
Example
<configuration>
<customerrors defaultredirect=”genericerror.htm” mode=”remote”>
<error statuscode=”500" redirect=”InternalError.htm”/>
</customerrors>
</configuration>
The ErrorPage directive will redirect an ASP page to a custom error page. The following directive will
redirect any ASP.NET page to any custom error page for any error.
Example
<%@page Errorpage = “/custom_error.aspx”%>
Practice 14.3
The following example shows how the configuration settings override two specific http status codes, and
then falls back to a default page for custom error.
//default.aspx
<html>
<head>
</head>
<body>
<form method=”post” action=”eventlog2.aspx” name=”form1" id=”number”>
<asp:Button id=”abutton” type=”submit” text=”Click Me to generate an
error”runat=”server” />
</form>
</body>
</html>
//eventlog2.aspx
<html>
<script language=”C#” runat=server>
void Page_Load(Object sender,EventArgs e)
{
int x,y,z;
x = 1;
y = 0;
z = x/y;
}
</script>
<body>
Stuff was added to the event log
</body>
</html>
//403page.aspx
<html>
<head>
</head>
<body>
<h1>403 Error page</h1>
</body>
</html>
//404page.aspx
<html>
<head>
</head>
<body>
<h1>404 Error page</h1>
</body>
</html>
//customerrorpage.aspx
<html>
<head>
</head>
<body>
<h1>custom error page</h1>
</body>
</html>
//config.web
<configuration>
<customerrors mode=”On” defaultredirect=”customerrorpage.aspx”>
<error statuscode=”404" redirect=”404Page.aspx”/>
<error statuscode=”403" redirect=”403page.aspx”/>
</customerrors>
</configuration>
When the button is submitted, it links to the custom error page since unpredictable error (ie infinity)
appears in eventlog2.aspx file.
Custom error support can be added into an ASP.NET application very easily. Web page can be any type of
file: .htm, .aspx, .asp, etc. The configuration settings can be modified within the application’s config.web
file to point to this file. The “defaultredirect” attribute of the <customerrors> tag defines the “default”
page that a user will be redirected to in the event of an error. Optionally, the default value with alternative
pages is used to redirect depending upon the http status code of the response (for example: redirect to a
special “file not found” error page, “illegal access” error page, “server crash” error page, etc).
Custom error pages are very useful for production scenarios. It can often be difficult to deal with custom
error pages during development. Since bugs are expected during development, the developer would want
to see the actual error message. To help with this, the <customerrors> tag supports a “mode” attribute
with three values:
• Off - Indicates custom error page is never sent out (you always see the original error message)
• Remoteonly – Indicates custom error page is only sent out when remote browsers hit the site
(developers hitting the site on the actual machine see the detailed error message)
ASP.NET
Global.asax file
ϕ Located at the root of a Web application’s Virtual
directory tree
ϕ Provided with services to handle higher level
application events
ϕ Parsed and dynamically compiled by ASP.NET
ϕ Configured so that any direct URL request is
automatically rejected
The “application level” logic and event handling code can be added into the Web applications. This code
is responsible for handling higher-level application events - Application_Start, Application_End,
Session_Start, Session_End, etc. The Global.asax file that is being located at the root of a particular Web
application’s Virtual directory tree provides these services. ASP.NET automatically parses and compiles
this file into a dynamic .NET Framework class - that extends the HttpApplication base class.
The Global.asax file is parsed and dynamically compiled by the ASP.NET into a .NET Framework class for
the first time when any resource or URL within its application namespace is activated or requested. The
Global.asax file itself is configured so that any direct URL request is automatically rejected.
• The first step is to modify the config.web file to route the users of the Web application to a friendly
error page. The following line should be added to the config.web file of the Web application:
<configuration>
<customerrors mode=”on” defaultredirect=”error.aspx” />
</configuration>
• The second step is to build the error.aspx page that user will be re-directed for an exception
<%@ Page Language=”C#” %>
<%
Response.Write(“custom error page”);
%>
• The third step is to build a global exception handler in which an event handler is added to the
global.asax file to capture all exceptions that occur in the Web application
EventLog.WriteEntry(“Test Web”,
“MESSAGE: “ + ex.Message +
“\nSOURCE: “ + ex.Source +
“\nFORM: “ + Request.Form.ToString() +
“\nQUERYSTRING: “ + Request.QueryString.ToString() +
“\nTARGETSITE: “ + ex.TargetSite +
“\nSTACKTRACE: “ + ex.StackTrace,
EventLogEntryType.Error);
}
</script>
There are three methods by which a reference can be obtained to the exception that occurred in
ASP.NET page.
• Context.Error.GetBaseException()
• Server.GetLastError().GetBaseException() or
• Context.ApplicationInstance.LastError.GetBaseException()
WriteEntry() method of the EventLog class accepts three parameters. The first parameter is the
source of the error. It will appear in the “Source” field of the Windows 2000 Event Log Viewer.
The second parameter is the log data itself. The third and final parameter to the WriteEntry()
method is an enumeration of type EventLogEntryType.
throw(ex);
}
}
</script>
<form runat=”server”>
<asp:textbox id=”textbox1" text=”foobar” runat=”server” />
<asp:button id=”button1" onclick=”button1_click”
text=”click me” runat=”server” />
</form>
The code above defines a Web Form with a textbox and a button. When the button is clicked, it
fires the button1_click event handler. Generate a DivideByZeroException intentionally which
will be caught by the catch block. throw(ex) is called to pass the exception to the global
exception handler in order to be logged in the Windows 2000 Event Log. The defaultredirect
attribute sets in the config.web file re-directs to the error.aspx page to display the custom error
page.
14.4 Debugging
ASP.NET
Debugging tool in ASP.NET
ϕ Provided with support for local and remote
debugging
ϕ Accomplished through tracing
ϕ DebugMode has to be included in Compilation
sectin of conig.web
ϕ Should be enabled during debugging
ϕ Breakpoints can be set
ASP.NET is supplied with a full-featured debugging tool, optimized for use with ASP.NET. It is also
provided with support for local and remote machine debugging – including the setting of breakpoints and
the ability to single-step through a code.
Figure 14.3
Setting Breakpoints
A breakpoint can be set in the page, by clicking the left-hand margin on a line containing an executable
statement or function/method signature. A red dot will appear where the breakpoint is set. The
breakpoint ensures that it is appropriately mapped to the correct application instance in the xspwp.exe
process. The request to the page has to be re-issued from the browser. The visual debugger will stop at the
breakpoint and gain the current window focus. From here it sets variable watches, view locals, stack info,
disassembly, etc. The intrinsic objects on the Page, like Request, Response, and Session can be viewed by
using “this” (C#) or “Me” (VB) in the watch window, as shown in Figure 14.4 below:
Figure 14.4
• Search same path as assembly (this is the normal location for pdb files). For local assemblies, place the
symbols (.pdb files) in the application’s /bin directory along with the dlls.
Practice 14.4
</html>
To execute the above example, the debugger has to be run. The debugger is present in the path “Program
files/microsoft.net/frameworkSDK/guidebug/dbgurt.exe” in the drive where the .NET Framework is
installed. The file trace4.aspx has to be opened from the debugger and the “Processes” option of the
“Debug” menu should be selected. A dialog box is opened in which there is a list box and two check
boxes. The checkbox “Show system processes” should be selected. From the list, xspwp.exe (which
executes the ASPX files) should be selected. On clicking OK, the dialog box is closed. A break point should
be set at the point where debug has to be carried out. On executing the trace4.aspx file, the output is not
visible initially. It will be visible only when the code is run in the debugger. The Application Trace can be
viewed by giving the path “http://localhost/trace.axd” and Request details are viewed by clicking
ViewDetails (which is in application trace).
• Tracing the execution of an ASP.NET page can be done easily by using its methods Warn() and
Write()
• Page-level tracing is enabled using a Trace=”true” attribute on the top-level Page directive
• Application-level tracing is enabled using a “trace” section in the configuration file at the application
root directory
• Details for a series of requests may be accessed by requesting “trace.axd” from the application root
• The .NET Framework SDK visual debugger supports manual-attach debugging of processes on a
local development computer. DebugMode is enabled by setting <compilation debugmode=”true”/>
in the application root’s config.web file
YZ
Lecture 15
Objectives
In this lecture you will
learn the following
+ Knowing about the User Controls
Coverage Plan
Lecture 15
ASP.NET
User controls
ϕ Custom controls created by programmer for use in other
programs
ϕ Aid in partitioning and reuse of simple, common user interface
functionality across a Web application
ϕ Compiled on demand and cached in server memory
ϕ Do not contain <html>, <body>, or <from> elements
ϕ Must have .ascx file extension
ϕ @Page must be changed to @Control
ϕ @OutputCache cannot be used
User controls are custom controls created by the programmer for use in other programs. ASP.NET enables
creation of user controls. User controls aid in partitioning and reuse of simple, common user interface
functionality across a Web application. They are compiled on demand and cached in server memory. User
controls do not contain <html>, <body>, or <form> elements. These elements should be included in the
page in which the user control is present. User controls must have .ascx file extension. If the page contains
an @ Page directive, then it must be changed to @ Control directive. All the attributes (except the Trace
attribute) supported by the @ Page directive are supported by the @ Control directive. Also, the @
OutputCache directive cannot be used in a user control.
User controls developed using different languages can be used in the same Web Forms page. For example,
if one developer uses Microsoft Visual Basic to create a user control that imports data from an XML file,
and another developer uses Microsoft C# to create a control that contains a login form, both the controls
can be included in the same Web Forms page.
ASP.NET
Given below is the procedure to create a user control that receives the name, age and designation from the
user.
• Create a code block that exposes the properties of the text boxes and the list box declared in the
previous step so that they can be manipulated programmatically when they are inserted as a user
control into a Web Form. This makes it possible to manipulate these properties declaratively or
dynamically in any Web Forms page in which it is included
set {
age.Text = value;
}
}
If a Web Forms page has to be converted into a user control so that its functionality can be used
throughout another application, then the following alterations should be made to it:
• All <html>, <body> and <form> elements have to be removed from the page
• If there is an @Page directive in the Web Form it should be replaced with an @Control directive
• The control must be given a meaningful name and the file extension must be changed from .aspx to
.ascx
ASP.NET
To include a user control in a Web Forms page
ϕ @Register directive should be included
- Associates aliases with namespaces and
class names
- Consists of attributes Tagprefix, Tagname,
Namespace and Src
ϕ A custom server control tag should be declared in
desired location on the page containing user
control
The following steps should be carried out in order to include a user control in a Web Forms page.
− The Tagprefix:Tagname pair will be used when an instance of the control is declared on another
page
For example, the following code registers a control defined in the file user1.ascx, which has been given the
tag prefix User and the tag name Info.
<html>
<body>
<form runat=”server”>
<User:Info id=”FirstUser” runat=”server”/>
</form>
</body>
</html>
The following example creates and uses a simple user control.
Practice 15.1
This example creates a user control containing two text boxes, one to enter the user’s name and another to
enter the user’s age. The user control is inserted into a page which also contains a button.
The Web Forms page should be run and not the user control file.
The above example creates a simple user control and saves it in the file named ctrl.ascx. The Web Forms
page registers the control using the @Register directive, assigning the TagPrefix as user and TagName as
c1. Then an instance of the control is created with the id c, along with an ASP button server control, and
displayed.
ASP.NET
To manipulate user control property values declaratively, the property name and a value have to be
declared as an attribute/value pair in the ActiveX control tag. The value has to be assigned as the same
type for the property as declared on the control. For example, the following code establishes default
settings for the properties created on the User:Info user control:
ASP.NET
Handling events in user controls is almost similar to handling events from any other control in Web Forms
pages. The event handler can be included either in the page containing the control, or in the user control
itself. In both the cases the event-handling code is the same, but there are a few precautions that should be
taken care of before including event handlers in the user control.
While the user control’s properties are exposed on the page containing the user control, the user control
cannot access properties of other controls on the page. So all the functionality must be included within the
user control for it to work as intended.
To handle the event in the page containing the user control, a code declaration block has to be included in
the head of the Web Forms page in which the user control is included and an event-handling code has to
be written to interact with the form.
To handle the event in the user control itself, a code declaration block has to be included in the user
control that contains event-handling code for the form. All the controls involved in the event should be
included in the control itself.
The following example creates a user control, handles the event in the control and uses it in a Web Forms
page.
ASP.NET
To add a user control programmatically, either in a code-behind file or in a code declaration block in an
.aspx file, a control instance has to be created, the property values have to be assigned as necessary, and
the control has to be added to the Controls collection for the particular instance of the Page class.
For example, in the following code, MyUserCtrl.ascx is instantiated with its BackColor property set to
yellow.
Control c = LoadControl(“UserCtrl.ascx”);
((UserCtrl_ascx)c).BackColor = “beige”;
Page.Controls.Add(c);
Practice 15.2
The following example adds a user control programmatically to a Web Forms page.
<asp:ListItem>Asst. Manager</asp:ListItem>
<asp:ListItem>Clerk</asp:ListItem>
<asp:ListItem>Cashier</asp:ListItem>
</asp:ListBox>
<head>
<script runat=”server” language=”C#”>
</script>
</head>
<body>
<form runat=”server”>
<asp:label id=”title” Text=”Click on the button beside to create the user
control” runat=”server” />
<asp:button id=”create” OnClick=”Ctrl” Text=”Create the control”
runat=”server” />
</form>
</body>
In the above code, when the user clicks the “Create the control” button, its OnClick event is fired. This
event calls the method Ctrl. This method creates an instance of the user control programmatically through
the LoadControl method. Then it initializes the properties UserName, UserAge and UserDesg of the
control. Then it adds the control to the Controls collection of the page.
Lecture 16
ASP.NET Components
Objectives
In this lecture you will
learn the following
+ Knowing about the disadvantages of COM
Coverage Plan
Lecture 16
ASP.NET
Disadvantages of COM
ϕ Registration is troublesome
ϕ New versions overwrite earlier versions
ϕ Cross-language support is not full-fledged
Com Vs .NET
ϕ .Net components
- self-contained units of functionality
- do not require any registration
Even though COM is the most successful technology to development components, it has its own
shortcomings.
• Registration: Registration is the most troublesome part while using COM components. Every COM
component stores information about it in Windows registry. The information is basically about
GUIDs, CLSIDs, Path etc. Even though a COM component is to be used by only one application, this
information is made available machine wide
• Versioning: Another problem with COM components is compatibility of version. Many times the
newer versions of COM component overwrite its earlier version and breaks old applications
• Cross-language Support: It is said that the COM components developed in one language can be used
for any other COM compatible tool. However, components developed in VB cannot be used easily in
VC++
For a component to be called as COM compatible, it must support IUnknown interface. This interface is
responsible for reference counting of the component. A COM component stores all the information about
various methods and their parameters in a ‘Type Library’ (In case of VB type library information is
embedded in the resulting EXE or DLL itself). To use COM component successfully, this information
must be available along with some registration information.
In contrast, .NET components are very different. The component do not itself keep track of reference
count. It is the responsibility of the CLR. Moreover, .NET components store all the information about the
component along with the assembly itself. This information is called as MetaData. .NET components are
self-contained units of functionality that do not require any registration.
ASP.NET
Component
Component is a reusable piece of code. Each CLR image carries the metadata for declarations,
implementations, and references specific to that image, the image-specific metadata is referred to as
component metadata, and the resulting component is said to be self-describing. Collections of CLR
components and other files are packaged together for deployment into assemblies.
Every assembly has a manifest that declares the components that make up (or are allowed to make up)
the assembly, the types to be exported, how type references are resolved, how assembly references are
resolved, configuration rules, etc. An assembly may carry an explicit manifest or the manifest may be
implicit.
ASP.NET attempts to solve the problems of previous versions by allowing components to be placed in a
/bin directory, which is automatically found at run-time.
• No Registration Required
When any part of an ASP.NET application is changed (for example, replacing a .dll in /bin), new
requests immediately begin the execution against the changed file(s). The Web server does not
require a restart when the application is changed, even when replacing compiled code.
• No Namespace Conflicts
Each assembly loaded from /bin is limited in scope to the application in which it is running. This
means that peer applications could potentially use different assemblies with the same class or
namespace names, without conflicting.
• Managed Execution
Codes that executes under the control of ASP.NET are called as managed codes. The memory
consumed by such a code is reclaimed automatically by CLR through garbage collection mechanism.
COM components are not under the control of .NET CLR and hence are treated as unmanaged code.
Tasks like automatic memory management are not available to such components.
ASP.NET
System architecture
ϕ Defines
- Interaction between piece
- Functionality of each piece
ϕ Three types
- Single-tier
- Two-tier
- n-tier
One of the key elements of any application design is the system architecture. The system architecture
defines how pieces of an application interact with each other, and the functionality of each piece. There
are three main classes of application architecture. They can be characterized by the number of layers
between the user and the data. Each layer generally runs on a different system or in a different process
space on the same system than the other layers.
Single-tier WebForm
The monolithic application consists of a single application layer that supports the user interface, the
business rules, and the manipulation of data. The data itself could be physically stored in a remote
location, but the logic for accessing it is part of the application. Microsoft Word is an example of a
monolithic application. The user interface is an integral part of the application. The business rules, such as
how to paginate and hyphenate, are also part of the application. The file access routines, that manipulate
the data of the document, are also part of the application. Even if there are multiple DLLs that handle the
different functionality, it is still a monolithic application.
Two-tier WebForm
In the first type, the business rules and user interface remain as part of the client application. The data
retrieval and manipulation is performed by another separate application which is usually found on a
physically separate system. This separate application could be SQL Server or Oracle, which functions as a
data storage device for the application. This type of application is widely used in the traditional client-
server types of applications. PowerBuilder or Visual Basic with Oracle as backend are examples of tools
that can be used to create client-server systems.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
263
ASP.NET
In the second type of two-tier application, the business rules are executed on the data storage system. This
is the case in applications that use stored procedures to manipulate the database. A stored procedure is a
database function that is stored in the database server. It can be executed in one of the two ways. A client
application can explicitly call a stored procedure, which would then be run on the server. Alternatively
trigger can also execute a stored procedure, which is the occurrence of a specific event in the data.
Three-tier WebForm
With three-tier applications, the business rules are removed from the client and are executed on a system
in between the user interface and the data storage system. The client application provides user interface
for the system. The business rules server ensures that the business processing which includes validation of
user input is done correctly. It serves as an intermediary between the client and the data storage. In this
type of application, the client would never access the data storage system directly. This type of system
allows for any part of the system to be modified without having to change the other two parts. Since the
parts of the application communicate through interfaces, and then as long as the interface remains the
same, the internal workings can be changed without affecting the rest of the system.
ASP.NET
ϕ Copying
ϕ Xcopying
ϕ FTPing
An assembly can be deployed into an application’s local assembly cache by simply copying, xcopying, or
FTPing the appropriate file(s) into a directory that has been marked as an “assembly cache location” for
that particular application. No additional registration utility is needed to run, once the appropriate files
are copied and no reboot is necessary. By default, an ASP.NET application is automatically configured to
use the “bin” sub-directory which is located immediately under the application root as its local assembly
cache. The bin directory is also configured to deny any browser access .
ASP.NET applications are identified by a unique URL and live in the file system of the Web server.
ASP.NET can use shared assemblies, which reside in the global cache, and application-specific assemblies,
which reside in the “bin” directory of the application’s virtual root. ASP.NET applications run in the
context of Application Domains, which provide isolation and enforcement of security restrictions. Classes
can be dynamically referenced through “classname, assemblyname”. ASP.NET uses shadow-copies of
assembly files to avoid locking and monitors the files, so that changes are picked up immediately.
Practice 16.1
//comp2.cs
namespace comp2 {
using System;
using System.Text;
//comp2app.aspx
<html>
<body >
<h3>A Simple Component</h3>
<div id=”d” runat=”server”/>
</body>
</html>
Practice 16.2
The following example is a two-tier Web Form that uses a component to connect to the database and
execute a given query.
//comp1.cs
using System.Data;
using System.Data.SQL;
namespace comp1
{
public class SQLRecords
{
string cst;
string sst;
//comp1app.aspx
The component contains two properties namely SQLConnectionString and SQLStatement and two
methods conmethod() and getrecords() in the SQLRecords class. The conmethod() creates and returns a
SQLConnection object using the SQLConnectionString property. The getrecords() method uses the
conmethod() to get the ConnectionString, establishes the connection, executes the query represented by
the SQLStatement property and fills the DataSet ds with the results and returns the DefaultView of the
DataSet.
In the Page_Load event of the Web Form, an instance of the SQLRecords class is created and the two
properties SQLConnectionString and SQLStatement are assigned values. Then the getrecords() method
is called to populate the DataGrid d.
• The three types of application architecture are single-tier (or monolithic), two-tier and n-tier, where n
can be three or more
4. What are the advantages of three-tier Web applications over two-tier applications?
YZ
MS 3.2 ASP.NET
Lecture 6 HttpRequest
HTML Form -HttpRequest Properties -Application Path - Browser -Client Ceritficate -ContentType
- FilePath -RawUrl -Url - Cookies -Form - Query String
Lecture 7 HttpResponse
HttpResponse Properties -BufferedOutput-SuppressContent -Charset -ContentType -
ContentEncoding -StatusDescription -Cookies -IsClientConnected - StatusCode -Httpresponse
Methods
Lecture 8 Application, Session State Management and Cookies
HttpApplication -Managing Application - Global.asax -Applicatin Events in Global.asax -
Application State -Session - Cookies - How to Create Cookie? - Server Object
Lecture 9 ADO.NET I
Database -Benefits of the Database approach - DBMS -DBMS Standardization -Structured Query
Language -Using SQL as a DataQuery Language -Manipulation of database in ASP.NET -
Introduction to ADO.NET
Lecture10 ADO.NET II
Managed Providers -Connection Object -Command Object -DataReader