Sei sulla pagina 1di 40

Unit II: Basics of ASP.

Net

Introducing ASP .NET – Creating and deploying ASP .NET applications – Web forms –
Web controls – working with events – Rich web controls – Custom web controls –
Validation controls – Debugging ASP .NET pages.

1. History before ASP.NET

• Before .NET came into the game, tools to support Internet application
development were sort of pasted on top of the operating system and usually
produced not too clean-cut solutions.
• Active Server Pages (ASP), introduced by Microsoft around 1995, consisted of
HTML mixed with server-side script, and its goal was to dynamically build
HTML from the script. Although useful for web application development, it relied
on interpreted scripting. The business logic (script) was mixed with the
presentation logic (HTML) and the script was type-less, which reduced its
robustness.
• ASP pages offered very poor modularity. Also, a lot of redundant scripting code
had to be done for each ASP; one could not factor and reuse the repeating
boilerplate code. More importantly, ASP, although convenient for Internet apps,
was at the same time a step backwards into interpreted non type-safe, non-
structured and non object-oriented code.
• The design, debugging and maintenance of the resulting spaghetti code were
unpleasant to any developer used to traditional applications.
• Microsoft pushed forward a very attractive architecture called Windows DNA,
based on COM (Component Object Model – the Microsoft binary model for
pre-.NET components) that separates the development into 3 tiers: ASP in the
presentation layer, business objects in the middle layer, and relational data store
and engine in bottom layer. Its main weaknesses were related to:

 Understanding COM was never easy and neither programming it; although
some languages like VB did make it much easier to work with than VC++,
albeit with some loss in versatility
 Deployment of DNA applications could become a nightmare, because of the
many potential problems that can arise from version-conflicts.
 The only real problem with this effort was that architecture without a
corresponding framework and tools to support it is truly very hard to achieve,
and this was the case before .NET arrived at the scene.
2. Introducing ASP.Net

ASP.Net provides the following advantages of server-side scripting:

• ASP.Net enables to access information from the data sources, such as back-end
databases and text files that are stored on a web server or a computer that is
accessible to a web server.
• ASP.Net enables to use a set of programming code called templates to create
HTML documents. The advantage of using templates is that you can dynamically
insert content retrieved from data sources, such as back-end databases and text
files, into an HTML document before the HTML document is displayed to users.
Therefore, the information need not be changed manually as and when the content
retrieved from data source change.
• ASP.Net also enables you to separate HTML design from the data retrieval
mechanism. Therefore, changing the HTML design does not affect the program
that retrieve data from the databases. Similarly, server-side scripting ensures that
changing data sources does not require a change in HTML documents.

Features of ASP.Net

In addition to hiding script commands, ASP.Net has the following advanced features that
help develop robust web applications.

• Compiled code: Code written in ASP.Net is compiled and not interpreted. This
makes ASP.Net applications faster to execute that other server-side scripts that are
interpreted, such as scripts written in a previous version of ASP.
When you request a page for the first time, the run time compiles the code and the
page itself, and keeps a cached copy of the compiled result. When you request the
page the second time, the cached copy is used. This results in greatly increased
performance because, after the first request, the code can run from the much faster
compiled version and the content on the page does not need to be parsed again.
• Enriched Tool Support: The ASP.Net framework is provided with a rich toolbox
and designer in VS.Net IDE. Some of the powerful features are WYSYWIG
controls and automatic deployment.
• Power and Flexibility: ASP.Net applications are based on CLR. Therefore the
power and flexibility of .Net platform is available to ASP.Net application
developers. ASP.Net applications enable you to ensure that the .Net framework
class library, messaging, and data access solutions are seamlessly accessible over
the web.
• Multiple Language Support: It provides a true language-neutral execution
framework for the web application. ASP.Net is also language independent.
Therefore, you can choose any .Net language to develop you application.
• Simplicity: ASP.Net enables you to build user interfaces that separate application
logic from presentation content. In addition, CLR simplifies application
development by using managed code services, such as automatic reference
counting and garbage collection. Therefore, ASP.Net makes it easy to perform
common tasks ranging from form submission and client authentication to site
configuration and deployment.
• Manageability: ASP.Net enables you to manage Web applications by storing the
configuration information in an XML file. You can open the XML file in the
VS.Net IDE.
• Scalability: ASP.Net has been designed with scalability in mind. It has features
that help improve performance in a multiprocessor environment. A session-state
can be maintained in a separate process on a separate machine or database,
allowing for cross-server sessions.
• Security: ASP.Net provides a number of options for implementing security and
restricting user access to a web application. All these options are configured
within the configuration files. One can create form based authentication, and
create login forms.
• Classes and Namespaces: ASP.Net includes a range of useful classes and
namespaces. Namespaces are like class libraries and can make writing web
applications easier. Some of the classes included with ASP.Net are HtmlAnchor,
HtmlControl, and HtmlForm, which are included within the
System.Web.UI.HtmlControls.
• Server Controls: ASP.Net provides several server controls that simplify the tazsk
of creating pages. These server controls encapsulate common tasks that range
from displaying calendars and tables to validating user input. They automatically
maintain their selection states and expose properties, methods, and events for
server-side code, there by providing a clean programming model.
• Web Services: A web service is an application delivered as a service that can be
integrated with other web services by using Internet Standards. ASP.Net allows to
create and use web services.
For example, a company can assemble an online store by using the Microsoft
Passport service to authenticate users, a third-party personalization service to
adapt Web pages to each user’s preferences, a credit-card processing service, a
sales tax service, and package-tracking services from each shipping company, and
an in-house catalog service that connects to the company’s internal inventory
management applications.
Web services provide the building blocks for constructing distributed webbased
applications. ASP.Net files have an .aspx extension and web services have an
.asmx extension.
• Cookie-less Sessions: ASP.Net enables to use session state even with browsers
that have cookie supported disabled. Cookie-less sessions use Uniform Resource
Locators as opposed to cookies, to pass the sessionID to an ASP.Net page. A
cookie-less session involves encoding data into a URL, which is done
automatically by the browser.
• Easy configuration and deployment: Configuration and deployment are now
easier with the use of human-readable configuration files and DLLs that do not
need to recognized.
In ASP.Net, all the configuration details for all web applications are kept in
human readable files named web.config. The standard format for the
configuration files is XML, and each application inherits the settings in the
default web.config file.
With .Net, all files that a web site needs are located under the site’s root folder.
DLLs are in the /bin folder, and the web.config is in the root folder. To deploy a
web site, all you need to do is copy the site’s root folder by using file copy
commands, Microsoft front page server extensions, or File transfer protocols.

ASP.NET over ASP

ASP.NET is the answer to ASPs weaknesses. Most of its innovations are aimed at the
Web developer who doesn’t know much beyond HTML.

 ASP.NET introduces server controls, which means we can use HTML-like tags to
accomplish something that in ASP required both HTML and scripting.
 In ASP if you wanted a control to keep state between web pages when someone
refreshed a page, you’d also have to write script code. Not anymore; ASP.NET
may automatically keep track of state for us.
 In ASP one could use procedures and functions, but without calling this via
events, you were still confined to a sequential execution order. Therefore, many
developers, out of complexity or ignorance, did not give much use to structured
programming; not to mention object-oriented programming which was simply not
available.
 With ASP.NET two concepts are introduced. Code behind, comes into play when
an ASP.NET page is compiled, producing a base class from which the page
inherits. Therefore, ASP.NET pages are now objects.
 The other concept is that of user controls (custom controls derived from .NET
provided server side Web controls). Just like we could create ActiveX controls for
the user interface for traditional Windows applications, we now have the same
capability but for use in the user interface of Internet applications (i.e. browsers).
Additionally the page can make transparent use of any .NET or COM component
and it can contain methods, properties, events, attributes, etc, just like any other
object. Since these pages are now classes, it should come as no surprise that they
can be compiled (the first time a page is run) and that we can use any .NET
language to program them.
 Separating Presentation from Code: The idea of code behind, allows us to
separate the presentation aspect written basically in HTML and tags representing
Web controls from the class that represents the page. Both are tightly
interconnected by a special tag in the .aspx file (not .asp anymore). For example,
the following is the first line of an .aspx file:
<%@ Page language="c#" Codebehind="default.aspx.cs"
AutoEventWireup="false" Inherits="MyFirstWebApplication.DefaultWebForm"
trace="true" %>
3. Set up the development environment of ASP.Net

ASP.Net is based on the CLR, class libraries, and other tools integrated with the
Microsoft.Net framework. Therefore, to develop and run the ASP.Net applications, it is
required to install the .Net framework. The .Net framework is available in two forms:

(i) .Net framework SDK (software development kit)


(ii) Visual studio.Net (VS.Net)

(i) .Net framework SDK

The .Net framework SDK or VS.Net is installed on a machine that has one of the
following OS:Windows 2000, Windows NT 4.0, Windows Me, Windows 98, Windows
XP professional.

Installation of .Net framework SDK is very simple. Just run the setup program and follow
the onscreen instructions. However, the development machine must have IE5.5 or higher
available before the installation. Otherwise, you will be prompted to download it before
you install the .Net framework SDK.

Note: To develop any web application, you need Internet Information Server (IIS)
configured on either the development machine or another machine on network. The .Net
framework must be installed on the machine on which IIS is configured.

In the case of Windows 2000 Server, the IIS server is automatically installed. For
ASP.Net database applications, one must install SQL Server 7.0.

To crate ASP.Net applications by just installing the .Net framework SDK and configuring
an IIS server. In this case, text editor such as, notepad is used to write the code.

(ii) VS.Net

It comes in 4 CDs: Windows component update CD, VS.Net CD 1,2,and 3

When setup program is run from VS.Net CD1, a dialog box appears that prompts for the
following three options:

Windows component update, install visual studio.net, check for service releases

The VS.Net start page is displayed. The VS.Net window contains the solution explorer
window. The options available on the start page:

• Get started (create new project or open existing)


• What’s new (identify new features)
• Online community (contact other developers online)
• Headlines (get latest news from MSDN online)
• Search online (search web)
• Downloads (get latest product updates, SDK releases)
• Web Hosting (Post web applications and web services)
• Myprofile (set IDE with specific preferences)

4. Create and Deploy ASP.Net application

(i) Create ASP.Net application

ASP.Net web applications can be created in one of the following ways:


• Use a text editor: Write the code in a text editor, and save as ASPX file.
Files can be saved in the directory C:\inetpub\wwwroot. To display the output of
the web page in IE, simply type http://localhost/<filename>.aspx in the address
box. If IIS server is installed in some other machine, replace localhost with the
name of the server.
• Use VS.Net IDE: Use IDE of Visual studio.Net to create a web page in
WYSIWYG environment. The application is automatically created on a web
server (IIS server).

ASP.Net web pages consist of HTML text and the code. The HTML text and the code
can be separated in two different files. The code is written in VB or C#. This separate file
is called the code behind file.

At the top of the page, specify @ Page directive to define page specific attributes, such as
language. Example

<%@ Page Language = “VB” %>

To render the output, use Response.Write () method.

<% Response.Write(“Hello”) %>

For dynamic processing of a page, use <Script>. Example

<Script runat=”server” [language=codelanguage]>


code here
</Script>

(ii) Deploying ASP.Net web Application

Deployment is the process of distributing the finished applications (without the source
code) to be installed on other computers. In VS.Net the deployment mechanism is the
same irrespective of the programming language and tools used to create applications. The
steps are:
Step 1: Open the web application project.
Step 2: Select File-> Add Project -> New project dialog box
Step 3: From Project types pane, select setup and deployment projects. From the
Template pane, select Web Setup Project
Step 4: Change the default name of the project
Step 5: Click Ok to complete the process. The project is added to the solution explorer
window. Also, a File System editor window appears to the left. The editor
window has two panes. The left pane displays different items. The right pane
displays the content of the item selected in the left pane.
Step 6: Select Web Application Folder in the left pane of the File System editor window.
Then, from the Action Menu, select Add-> Project Output to open the Add
Project Output Group Dialog box.
Step 7: Verify the given project is selected in the Project drop-down list. Then select
primary output and content files from the list.
Step 8: Click Ok. The output files and content files of the given project are added to the
solution.
Step 9: Select Web Application Folder in the File system editor and select properties
window from the view menu to open the properties window.
Step 10: Set the virtual directory property to a folder that would be the virtual directory
on the target computer where you want to install the application. By default, this
property is set to name of Web Setup project that is added by user. Set the
property to DeployedApplication.
Note: Folder name is new folder name and should not already exist on target
machine.
Step 11: In the same properties window of the web application folder, set the
DefaultDocument property to WebForm1.aspx. This property is used to set the
Default web forms page for the application.
Step 12: Build the solution by selecting Build Solution from the Build Menu.
Step 13: After the solution is built successfully, a SampleVBDeploy.msi file is created in
the Debug directory of the web setup project. The default path is

\documents and settings\<login name>\MyDocuments\ Visual Studio\Projects


\SampleVB\ SampleVBDeploy\Debug\SampleVBDeploy.msi

Step 14: Copy the SampleVBDeploy.msi file to the Web server computer
C:\inetpub\wwwroot

Step 15: Double click the SampleVBDeploy.msi file on the target computer to run the
installer.
5. ASP.Net in .Net framework: Its application elements

ASP.Net, which is the .Net version of ASP, is built on Microsoft .Net framework.
Microsoft introduced the .Net framework to help developers create globally distributed
software with Internet functionality and interoperability. The following figure illustrates
the elements of an ASP.Net application and how the elements fit in the broader context of
.Net framework.

ASP.Net application elements

ASP.net page
Framework

WebFormpages Configuration file XML web service


With .aspx extension with .config files with .asmx
And corresponding extension extension
Class files

ASP.Net run time services

State Management

View state Web Security

Session State Caching

Application State

.Net Framework Base Classes

Common Language Runtime

As shown in the figure, the elements of ASP.Net application include web forms,
configuration files and XML web service files. Web forms enable to include user
interfaces, such as text box, list box controls and application logic of web applications,
and configuration files enables to store the configuration settings of ASP.Net application.
The elements of ASP.Net application also include web services to provide a mechanism
for programs to communicate over the Internet. Web forms and the state management
features of ASP.Net make the ASP.Net page framework. There are also a number of
runtime services available in ASP.Net. The ASP.Net runtime services include session and
application state management, web security, and caching mechanism of ASP.Net
applications. The runtime services of ASP.Net interact with .Net framework base
classes. .Net framework base classes in turn interact with common language runtime
(CLR) to provide a robust web-based development environment.
6. Working of an ASP.Net application

You create an ASP.Net application by using tools integrated with Microsoft.Net


framework. After creating ASP.Net application, the ASP.Net files need to be stored on an
IIS server, which is the web server for windows platform. An IIS server processes
ASP.Net files from top to bottom and then executes the scripts. Finally, the results are
sent to the web browser that requested the ASP.Net file.

The following figure describes how an IIS server processes the request for an ASP.Net
file.

An ASP.Net commands and variables are processed before


the output is sent to the client computer.

<HTML> <HTML>
<Head> <Head>
<Title> Mypage </Title> <Title> Mypage </Title>
</Head> </Head>
<Body> <Body>
<H1> welcome </H1> <H1> welcome </H1>
<Embedded ASP.Net commands you are the first person.
and variables congrats
runat=server> welcome
</Body> </Body>
</HTML> </HTML>

Client computer requests Client receives the output


An ASP.Net file as HTML content
As shown in the above figure to execute an ASP.Net file, the following steps are taken:

1. A web browser sends a request for an ASP.net file to a web server by


using URL
2. The web server IIS receives the request and retrieves the appropriate
ASP.Net file from the disk or memory
3. The web server forwards the ASP.net file to the ASP.Net script engine for
processing
4. The ASP.Net script engine reads the file from top to bottom and executes
any server-side script is encounters.
5. The processed ASP.Net file is generated as an HTML document and the
ASP.Net script engine sends the HTML page to the web server.
6. The web server then sends the HTML page to the client
7. The web browser interprets the output and displays it.

A web server generates and sends only the HTML output to the client. Therefore, it helps
in hiding the code of the ASP.Net file from users accessing an ASP.Net web page.

ASP.Net execution model:

o
ie u Parser Compiler
t
p
u
t Assembly cache
c Assembly IL
a Memory
c
h AssemblyIL
e Execute
HTTPRuntime

Client Server

Parser: The parser checks and interprets the contents of the aspx page and passes the page
to a compiler
Compiler: The run-time compiler is responsible for compiling the contents of the page
into an intermediate language
Assembly cache: Each machine on which Microsoft .Net framework is installed has
machine-wide code cache called the assembly cache. One of the functions of the
assembly cache is to hold the native code versions of pages that have been pre-compiled.
Memory: Some times that are expensive to construct can be built once and used for a
period of time before they are considered as invalid. These items are stored in memory
where they can be efficiently retrieved without incurring the cost of being reconstructed.
Output cache: The output cache is a cache for entire pages, including their objects and
data. After a page is built, it can be placed in the output cache. If a user makes another
request for the page, the request is returned from the output cache.

7. Structure of ASP.Net Page

The structure of ASP.Net web page include:

Directives, Code declaration blocks, Code render blocks, Server-side comments, and
Serverside include directives

(i) Directives:
A directive specifies how an ASP.Net page is compiled. The beginning of a directive
is marked with the characters <% @ and the end of the directive is marked with the
characters %>. The most frequently used directives are Page directive and Import
directives.

Page directives are used to specify the default programming language of a page.
Example: <%@ Page Language=”C#” %>

The Import directive is used to import additional namespace to a web application. For
example, to send an email message from ASP.Net page, you need to use Send method
of SmtpMail class. SmtpMail class is included in the System.Web.Mail namespace
which is not imported to a web application by default. To explicitly import the
namespace, the import directive as shown below:

<%@ Import Namespace=”System.Web.Mail” %?

(ii) Code declaration blocks

You can application logic in either a code-behind file or the .aspx file of a web
application. If you want to add the application logic in the .aspx file, you need to
write application logic in a code declaration block. A code declaration block contains
the application logic of an ASP.Net page and the global variable declarations,
subroutines, and functions. The <Script Runat=”Server”> tag accepts two attributes.
The first attribute, Language, enables you to specify the language that is to be used
within the <Script> tag. The second attribute, SRC, is an optional attribute, which
enables you to specify an external file that contains the code block. You specify these
attributes in the HTML mode of .aspx files as shown below:

<Script language=”C#” runat=”Server”> // beginning of code declaration block

void AddEmp() // user defined method


{
Label1.Text =”Hello welcome to SRM”;
}
</Script> // end of code declaration

(iii) Code render blocks

If you want to execute code within the HTML content of an ASP.Net page, you need
to use code render blocks. There are two types of code render blocks: Inline code and
Inline expressions. Inline code can execute a statement or a series of statements.
Inline code begins with the characters <% and ends with %>. Inline expressions
display the value of a variable or a method.

Inline expressions begin with the characters <%= and end with %>
<form runat=”Server”>
<% str=”Hello SRMIST”; %>
The value of str is:
<%=str%>
</form>

(iv) Server side comments

You can include comments in an ASP.Net page by using server-side comments.


Serverside comments begin with <%-- and end with --%>. Server side comments are
included in an ASP.net page for the purpose of documentation as shown below:

<%-- This is an example --%>


They are useful for debugging applications.

(v) Server side include directives

If you want to include an external file in an ASP.Net applications, you need to use server-
side Include directives. If the file is loaded in the same directory or in a subdirectory of
the directory in which the ASP.Net application is stored you need to use Include
directives:

<!-- #Include file=”<name of the file>” -->

You can also include the file by supplying the full virtual path. For example, if you have
a subdirectory named My_dir under wwwroot directory, you can include the file by using
the include directive:

<!-- #Include virtual=”/My-dir/<name of the file>” -->

8. Programming Models in ASP.Net

ASP.Net provides two types of programming models: Web Forms, Web Services

Web Forms enable to create user interface for web applications. You use server controls
to design the user interface of web applications and then write code, which will be
executed at the server-side, to handle events triggered by these controls.

Web services enable you to remotely access certain functionality at the server side. These
services enable the exchange of data in a client-to-server environment over the web by
using SOAP. To enable this data exchange, web services use standards such as http and
xml messaging.
9. ASP.Net Web Forms

The ASP.Net web forms technology is used to create programmable web pages that are
dynamic, fast and interactive. Creation of web forms by using ASP.Net has following
advantages:

• Web forms can be designed and programmed using RAD


• Web forms support a rich set of controls, including user-defined and third party
controls that make the application user friendly
• Web forms can be programmed using any of .Net framework languages, such as
C# or VB.Net
• ASP.Net uses the CLR of .Net framework and thus benefits from its features, such
as type safety and inheritance.

Web Forms components:

In ASP.Net web forms consist of a user interface and application logic that is applied to
the components of user interfaces.

A user interface consists of static HTML or XML elements, and ASP.Net server controls.
When you create a web application, HTML or XML elements and server controls are
saved in a file with a .aspx extension. This file is called a page file.

Application logic consists of code that is applied to the user interface elements of a web
form page. You can use any of .Net programming languages, such as VB.Net or C#, to
write the logic for a web page.

Server controls in ASP.Net

You design the user interface of a web page by using controls called ASP.Net server
controls. Server controls are different from usual windows controls because they work
within the ASP.Net framework. As soon as the client requests a web page, ASP.Net
converts these controls into HTML elements, which are displayed in the browser. These
controls support raising of events on user interaction. For example, if a user clicks a
button control, an event click is raised for the button on the client computer. However,
the browser does not process the event. Instead, the browser raises a postback event so
that the web server is alerted about the click event being raised. When the postback event
is raised by the browser for the occurrence of the click event of the button, the event
handler written for the click event is processed on the web server and the output is sent to
the client computer. The following figure illustrates handling of event raised for sever
controls.
A web browser displays Sample.aspx file that has a text box to enter username and
passwork and a button to submit.

User enters the details and click submit button.


This causes the click event to get fired

As soon as the click event gets fired, the web broser sends postback event to alert the
webserver about the click event being raised.

The web server executes the event-handler for the click event of the submit button and
the welcome text for user is set

The web page with the processed output is sent back by web server

Output

In ASP.Net, each server control is an instance of a particular class. For example, when
you a add a button control to a web page, you accurately create an instance of Button
class. The base class of all server controls is the Control class that resides in the
System.Web.UI namespace. The hierarchy of sever controls in ASP.Net is depicted:

System.Object

System.Web.UI

System.Web.UI.Control

System.Web.UI.WebControls System.Web.UI.HTMLControls

PlaceHolder
Repeater
XML
System.Web.UI.WebControls

Button AdRotator BaseDatalist


CheckBox Calendar DataGrid
RadioButton ValidationSummary Datalist
HyperLink ListControl
Image CheckboxList
ImageButton DropDownList
Label ListBox
BaseValidator –BaseCompareValidator, CompareValidator RadioButton
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
LinkButton
Panel
Table
TableCell – TableHeaderCell
TableRow
TextBox

System.Web.UI.HTMLControls:
HtmlAnchor, HtmlButton, HtmlForm, HtmlGenericControl, HtmlTable
HtmlInoutCheckBox, HtmlTableCell, HtmlTableRow

(i) ASP.Net HTML controls

ASP.Net HTML controls are server-side replicas of standard HTML tags and are
executed by aspnet_isapi.dll. The HTML tags are converted into HTML controls by using
attributes such as ID and RUNAT. After an HTML tag is converted into an HTML
control, the tag becomes a server-side object with properties, methods, collections and
events.

It is important to remember that HTML controls are included in ASP.Net for backward
compatibility. You will use HTML controls when you need to migrate an existing ASP
application to ASP.Net platform. To crate HtmlInputText control, you need to enter the
following line of code in a web form:

<Input Type = Text Runat =”server” ID=”textbox1” value=”Welcome”>

The HTML Server controls can also be included through HTML Tab in the toolbox.
(ii) ASP.Net Web controls

ASP.Net web controls include traditional form controls, such as buttons and text boxes.
They also include controls that provide functionality, such as displaying data in a grid
and selecting dates. The web controls exist in System.Web.UI.WebControls namespace
and are derived from the WebControl base class. A web control is always closed with a
trailing forward slash (/). The web controls with description:

Web Controls Description


Basic web controls These are controls that correspond to the existing HTML tags
such as TextBox, Label, Button, HyperLink, RadioButton and
CheckBox
List controls These are controls used to build lists. These lists can also be
bound to a data source. The controls included in this group are
ListBox, DropDownLIst, CheckBoxList, and RadioButtonList
Rich web controls These are controls used to render an interactive calendar and to
display banner advertisements. The controls in this group are
Calendar control and AdRotator control. There are also additional
controls, such as Toolbar, and Treeview controls that belong this
category of web controls. The Toolbar control is used to render a
toolbar in client browsers, and the Treeview control is used to
present hierarchical data to users in the windows explorer style
format
Data controls These controls are used to display data from data base table. The
controls included in this group are Datagrid, Datalist, and
Repeater.

One can decide to use HTML controls or web controls based on the requirements and
functionality of each server controls:

HTML server controls Web controls


You prefer an Html like object You prefer a VB like programming
model model
You are working with existing You are writing a page that might be
HTML pages and want to used by variety of browsers
quickly add web forms
functionality
The control will interact with When you need any specific web
client and server script controls

(iii) Validation controls


These controls are used to validate the user input. The controls in this group do not
correspond to any existing HTML tags. The validation controls can be attached to input
controls to check the values that a user enters for input controls. You can use a validation
control to perform tasks, such as checking whether a user has entered any value for a
required field, testing the entered value against a specific value or pattern of characters,
and verifying that the entered value lies within the range.

For example, you can use validation controls to check whether a user has entered a
password, whether the entered password contains a minimum of four characters and a
maximum of twenty characters and whether the entered password is combination of
letters and numbers.

Some of the validation controls are Compare Validator, Custom Validator, Range
Validator, RegularField Validator, RequiredField Validator and Validation Summary.

(iv) Custom Controls

Custom controls are compiled software components that you can create to share the same
customized controls among a number of ASP.Net applications. You can share custom
controls without having to add a separate copy of the control in each ASP.Net
applications. You can crate a custom control by using a base control class, such as
WebControl class. Custom controls encapsulate user interface and the application logic
that is applied to the user interface into reusable packages. After you crate a custom
control, you can add it to the Toolbox. When you create a custom control, you install a
single copy of custom control and share it between applications. To access custom
control, you need to place the .dll file of custom control in the bin directory of the web
application that will use it. You also need to register it.

User controls

User controls are ASP.Net pages that are converted into controls. If you want to create a
server control that encapsulates the user interface of an existing web page, you can save
the page as a user control. User controls enable you to easily reuse the same content and
application logic in multiple ASP.Net pages. For example, you can create a company
logo once and save it as a user control. You can then use the same user control in
multiple web pages. The advantages of using user controls is that you can easily update
the content if required. For example, if the company logo changes, you need to change it
only in the file that contains the user control. To build a user control, you need to save the
web page with .ascx extension.

It is important to remember that you must register a user control in a web page before you
start using it:
<%@ Register TagPrefix=”ABC” TagName=”Header” Src=”Mypage.ascx” %>
TagPrefix is an alias to associate with the namespace of user control. Tagname is an alias
to associate with the class of user control. Src is the virtual path of the file containing user
control.

Composite controls: A composite control is a type of custom control that you can create
in an ASP.Net web applications. Composite controls are compiled controls that combine
the functionality of two or more existing controls
In addition to the custom controls, you can perform the following actions with controls:
Extend the functionality of existing web form controls to meet the requirements
Develop a custom control by inheriting directly from one of the control base
classes.
.
10. Some of the web controls

(i) TextBox control

It is used to obtain information such as text, numbers, and dates for single line, password
or multiline data. The properties of text box control determine its appearance:

Text: allows to specify text to be displayed in textbox


Maxlength: number of characters that user can type
TextMode: represents single-line, multi-line or password
Rows: to set vertical size
Wrap: to set word-wrap behavior in multi-line

(ii) Label control

To display a static text in a web form. The few properties are:

Caption: text to be displayed


Text: to modify the control’s caption
Visible: to display or hide the control

(iii) CheckBox and CheckBoxList controls

Checkboxes provide independent choices or options that you can select. CheckBoxList
control is a collection of several check boxes. After you add the checkboxlist control,
you need to add a list of items to it. You can add items to a check box by performing
the following steps:

Step 1: click the ellipses button for the items property of checkboxlist control
Step 2: In the ListItem collection editor dialog box, click the Add button. A new item is
created and its properties are displayed on the right side of dialog box.
Step 3: Verify that the item is selected in the Members list, and then set the properties
of the item. Each item is a separate object and has following properties:
Text: represents the text to be displayed for item in the list
Value: represents the value associated with the item without displaying it.
Selected: a Boolean value that indicates whether or not an item selected

Some of the properties of checkbox and checkboxlist controls are:


Text: checkbox: to get or set value
TextAlign:checkbox/Checkboxlist: to set the alignment of text property
Items:Checkboxlist: used to access the individual checkboxes in the checkboxlist
control

Some of the methods:


// add items at run time
Dim CheckBoxList1 As New CheckBoxList()
Controls.Add(CheckBoxList1)
CheckBoxList1.Items.Add(“Check1”)

Dim ischk as Boolean


Ischk=CheckBox1.Checked

Dim x as integer
X = CheckBoxList1.SelectedIndex()

Dim ListItem1 As New ListItem()


ListItem1=CheckBoxList1.SelectedItem()
Dim y As String
Y=CheckBoxList1.SelectedItem.Text

(iv) RadioButton and RadioButtonList control

Radio buttons provide a set of choices or options from that you can select.
RadioButtonList control is a collection of radio buttons. Usually, you use radio buttons
in a group. A group of radio buttons provides a set of mutually exclusive options. You
can select only one radio button in a group. You can group a set of radio buttons in two
ways:

Place a set of radiobutton controls in page and assign them manually to a group.
To do so, you can use the GroupName property

Place a RadiobuttonList control in a page. The radio button in the control are
automatically grouped. After you add a RadioButtonList control, you need to add
individual radio buttons. You can do so by using Items propery.

Some of the properties of RadioButton and RadioButtonList controls are

Text:RadioButton: to get or set value


TextAlign:RadioButton/RadioButtonList: to set the alignment of text property
Items:RadioButtonList: used to access the individual checkboxes in
the checkboxlist control.

Some of the methods:


// add items at run time
Dim RadioButtonList1 As New RadioButtonList()
Controls.Add(RadioButtonList1)
RadioButtonList1.Items.Add(“Radio1”)

(v) ListBox control

ListBox control is a list of predefined items and allows user to select one or more items
from the list. The ListBox control is a collection of list items. The individual list items
can be added used the Items property. Some of the properties are:

Items: represents the collection of list items


Rows: used to set the vertical size of listbox and takes a value in number of rows.
If the control contains more than the specified number of items, the
control displays a vertical scroll bar.
SelectionMode: used to set the number of items that can be selected. To allow
users to select only one item, set the SelectionMode property to single.
To select more than one item, users can hold CTRL or Shift key while
clicking multiple items.

(vi) DropDownList control

The DropDownList control allows user to select an item from a set of predefined items,
where each item is a separate object with its own properties, such as Text, Value and
Selected. You can select only one item at a time and the list of items remains hidden until
a user clicks the drop-down list button. Some of the properties are:

Items: represents the collection of list items in dropdown list


Width: represents width of dropdownlist control and takes value in pixels
Height: represents vertical size of dropdownlist control and takes value in pixels

(vii) HyperLink control

The HyperLink Control creates links in a web page and allows users to navigate from
one page to another in an application. You can use text or an image to act as a link in a
HyperLink control. When users click of the control, the target page opens. Some of the
properties:

Text: allows to set the text displayed as a link


ImageUrl: used to display an image as a link. The image file should be stored at
the same application project.
NavigateUrl: allows to represent the URL of target page in the application project

The NavigateUrl property in program:

Dim HyperLink1 as New HyperLink()


HyperLink1.NavigateUrl=”http://www.msn.com”

(viii) Table, TableRow and TableCell Control

A table is used to display information in a tabular format. You can add a table in Web
Forms page by using the Table control. This control can display information statically
by setting rows and columns at design time. In addition, you can program the Table
control to display information dynamically at run time. Some of the properties:

Rows:Table: used to represent a collection of TableRow objects. TableRow


control represents a row in a table
Cells: TableRow: used to represent a collection of TableCell objects. A TableCell
Control represents a cell in a row in a table.
After you add a Table control to a Web Forms page, you can add items to a table cell in
each row by performing the following steps:

Step 1: Click ellipses button for rows property of Table control


Step 2: In the TableRow Collection Editor dialog box, click Add button. A new
Row is created, and its properties are displayed on right side of dialog box.
Step 3: Verify that the row is selected in the Members list, and then click the
Ellipses button of the cells property to add a cell to the row
Step 4: In TableCell collection editor dialog box, click add button. A new cell is
Created and its properties are displayed on right side of dialog box
Step 5: To add items to a particular cell, you need to have the cell selected in the
TableCell Collection Editor dialog box and specify the item name in the
Text property of selected TableCell.

The following code is associated with Click event of Button control:

‘Declare the total number of rows


Dim RowCnt As Integer
‘Declare the current row counter
Dim RowCtr As Integer

‘Declare the total number of Cells


Dim CellCtr As Integer
‘Declare the current cell counter
Dim CellCnt As Integer
‘Accept total number of rows and columns from user
RowCnt= Val(TextBox1.Text)
CellCnt=Val(TextBox2.Text)

For RowCtr = 1 to RowCnt


‘creating a TableRow object
Dim TableRowObj As New TableRow()

For CellCtr= 1to CellCnt


‘creating TableCell object
Dim TableCellObj As New TableCell()
TableCellObj.Text = “Row =” &RowCtr & “Cell=” &CellCtr
‘ Add the new TableCell object to row
TableRowObj.Cells.Add(TableCellObj)
Next

‘Add new row to a Table


Table1.Rows.Add(TableRowObj)
Next

(ix) Image control

The Image control allows user to display images in a web forms page and manage them
at design or run time. Some of the properties are:

ImageUrl: used to represent the URL of the image to be displayed in the control
ImageAlign: used to represent the alignment of an image with respect to the
surrounding text.
Alternate Text: used to specify the alternate text in the image control when the
Image is unavailable. Browsers that support the ToolTips feature
Display the text as ToolTip.

Code to setup ImageUrl in the Page_Load event

Dim Img1 as New Image()


Img1.ImageUrl=”Rose.gif”

(x) Button, LinkButton and ImageButton control

The button control in web forms page is used to submit the page to the server. You can
create three types of server control buttons:

Button: represent a standard button


LinkButton: represents a button that can act as a hyperlink in a page
ImageButton:represents a graphical button to provide a rich button appearance.
You can set the ImageUrl property to point to a specific image

Some of the properties are:

Text: Button and LinkButton: used to set the text to be displayed on the button
Enabled:Button, LinkButton and ImageButton: Whether or not the button is
available at run time.
ImageUrl: ImageButton: represents URL of the image to be displayed
AlternateText:ImageButton:represents the text that is displayed as a tooltip or
When the image cannot be loaded.

11. Build Web Forms

1. Click Start Programs Microsoft Visual Studio .NetMicrosoft Visual


Studio.Net to open start page of VS.Net IDE
2. Click FileNew  Project to open new project dialog box
3. Select VC# projects as Project types in the left pane and then select ASP.Net web
Application as the template in the right pane. Click OK
4. Select View Toolbox. Toolbox is displayed in the left pane of window
5. Using Web Forms tab of Toolbox, add all the required controls to
WebForms1.aspx, as planned.
6. Write the code to validate user input
7. Execute the application
Execute the program by selecting Start option from Debug menu. Submit the form
without entering any value and check server side script

12. Working with Events

When users interact with different web controls on a page, events are raised. It can be
raised either on client or server, but are always handled on server.

Round Trips: Most web pages require processing on the server. The type of dynamic
functionality is accomplished by handling server control events. Whenever a user
interaction requires some kind of processing on the server, the web forms page is
submitted to the server, processed, and then returned to the browser. This sequence is
called a round trip.
Browser (.aspx) Server
(.aspx.vb or .aspx.cs)
Find Item
Application Code
Submit

Find Item

10 items found
Submit

Processed form for the browser

Most of the user interactions with the server controls result in round trips. Because a
round trip involves sending the web forms page to the server and then displaying the
processed form in the browser, the server control events affect the response time in the
form. Therefore the number of events available in web forms server controls is limited,
usually to click events. The events that occur quite often, such as the OnMouseOver
event, are not supported by server controls. The events associated with different
ASP.Net server controls:

TextBox control: TextChanged Event: occurs when the content of text box is changed

RadioButton and CheckBox: CheckedChanged / Checked : occurs when the value of


the property changes

RadioButtonList, CheckBoxButtonList, ListBox, and DropDownList:


SelectedInedxChanged: Occurs when you change the selection in the list

Button, LinkButton, and ImageButton: Click: Occurs when you click the button. This
event causes the form to be submitted to the server.

By default, only click event of the Button, LinkButton and ImageButton server controls
causes the form to be submitted to the server for processing – the form is said to be
posted back to the server. The Change events associated with other controls are
captured and cached and do not cause the form to be submitted immediately. When the
form is posted back (as a result of button click), all the pending events are raised and
processed. No particular sequence exists for processing these change events, such as
TextChanged and CheckChanged on the server. The Click event is processed only after
all the change events are processed.

You can set the change events of server controls to result in the form post back to the
server. To do so, modify the AutoPostBack property to True.

Event Handlers:

When the events are raised, you need to handle them for processing. The procedures
that are executed when an event occurs are called event handlers. The event handler is
associated with the corresponding event by using WithEvents and Handles keywords.
The WithEvents keyword is used to declare the control generating an event. The
Handles keyword is used to associate the event handler with the event, which is raised
by the control.
Event Handlers are automatically created when you doubleclick the control in design
mode. For example when the Buttoncontrol Button1 is doubleclicked the code in the
event handler is:

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e as


System.EventArgs) Handles Button1.Click

………

End Sub

The procedure Button1_Click is the event handler for Click event of button. The handles
keyword associated the event with event handler. The procedure takes two arguments.
The first argument contains the event sender that can generate events. The second
argument contains the data.

Implementing events and event handlers

Consider once the login user id and password is entered and pressed button1, a new web
form page is opened to display welcome message.

1. Accepting input of userid and password is stored in WebForm1.aspx


2. Add new web form page WebForm2.aspx to display the message. Add label in the web
form 2 to display the message.
3. To implement the functionality, you need to write the following code in the event of
button1 in web form1 page:

Response.Redirect(“WebForm2.aspx?StrTextValue=” & “Hi”


&UserName.Text & “you have been successfully logged in”)

4. The label1 of WebForm2.aspx is initialized in the Init procedure of web form

Lable1.Text = Request.QueryString(“strTextValue”)
5. To provide the reset functionality code associated with ReSet button is

UserName.Text=””
Email.Text=””
USStateList.ClearSelection()

Handling post back

The web form page is posted back to the server only when the server control buttons are
clicked. After the page is posted to the server, it is processed there. To respond to a
button event
• Write an event handler for click event of button
• Write event handler for load event of web form page. The load event is
generated when the form is loaded from the server to the browser. Use
IsPostBack property in the load event to determine whether the page has
been processed for first time or by a button click.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
If ResetButton.Page.IsPostBack = True Then
Button1.Visible = False
End If
End Sub

Using View State

Whenever the web page is processed at the server, the page is created from scratch. In
traditional web applications, the server discards the page information after processing and
sending the page to the browser. Because the page information is preserved on the server,
the web pages are called stateless. However, the web forms framework works around this
limitation and can save the state information of the form and its controls. To implement
the following options are provide:

• The View State: The framework automatically saves the state of the page and its
current properties, and the state of the server controls and their base properties,
with each round trip.
• The StateBags: Every page has a state bag that stores values to be restored in the
next round trip.

The framework automatically stores and restores page information with each round trip.
The view state contains the state of all controls on page between requests sent to server.
The state information is stored as hidden form field as name-value pairs in the
System.Web.UI.StateBagObject. To view those values View Source in the browser. By
default viewstate is enabled for all server controls, but you can set
<%@ Page EnableViewState=”false” %>

13. Using Rich Web Controls

ASP.Net provides controls that can be rendering of controls on server side. This allows
server-side processing, and thus provides dynamic web pages resulting in a rich and
improved user experience. Some of the Rich Web controls are

(i) AdRotator control

AdRotator control is sued to display flashing banner advertisements in web pages. The
controls is capable of displaying advertisements randomly. Some of the properties,
events, and methods of AdRotator control is as follows:
Property:

AdvertisementFile: used to set the path to XML file that contains list of banner
advertisements to display
KeyWordFilter: used to specify filter criteria based on which advertisements of
specific categories will be displayed in a web page
Target: used to specify the name of browser window that will display the contents of
linked web page when the AdRotator control is clicked. This parameter can also take
any of the HTML frame-related keywords.

_top: loads the lined document into topmost window


_blank: loads the linked document into a new browser window
_self: loads the linked document in the same window
_parent: loads the linked document in the parent window of the window that
contains the linke

Event:
AdCreated: This event is raised after an advertisement is retrieved from the
advertisement file and before the banner advertisement is rendered in a web page

Methods:
OnAdCreated: This method is used to raise the AdCreated event

Sample Code:

Consider the AdRotator control uses an Advertisement file named Ads.Xml


The asp.net coding is:

<%@ Page Language =”VB” %>


<html>
<head>
</head>
<body>
<form runat=”server”>
<h3> <font face=”verdana”> AdRotator Example </font> </h3>
<asp:AdRotator id=”AdRotator1” runat=”server” AdvertisementFile=”Ads.xml”/>
</form>
</body>
</html>

The Ads.xml file which contains two advertisements:

<Advertisements>
<Ad>
<ImageUrl>
Saturn.gif
</ImageUrl>
<NavigateUrl>
http://www.saturnrings.com/
</NavigateUrl>
<AlternateText>
Saturn Rings website
</AtlernateText>
<Impressions>
1
</Impressions>
<Keyword>
Saturn
</Keyword>
</Ad>

<Ad>
<ImageUrl>
Moon.gif
</ImageUrl>
<NavigateUrl>
http://www.moon.com/
</NavigateUrl>
<AlternateText>
Moon explores website
</AtlernateText>
<Impressions>
1
</Impressions>
<Keyword>
Moon
</Keyword>
</Ad>
</Advertisements>

(ii) Calendar control

The calendar control is used to display a one-month calendar. Users can use this control
to view dates or select a specific day, week or month. Calendar is one of the rich web
controls available in ASP.Net. Some of the properties, events and methods of Calendar
controls are:

Properties:
DayNameFormat: used to specify the name format of days of a week
FirstDayOfWeek: used to specify the day of the week to display in the first column of
calendar control
SelectedDate: used to represent the date selected in a calendar control
SelectionMode: used to specify whether a user can select a day, a week or a month.
Default value is Day.
VisibleDate: used to specify the month to be displayed in a Calendar control. It is
updated after the visibleMonthChanged event is raised
TodaysDate: used to specify a Date Time value that sets the current date of calendar

Events:

DayRender: It is raised before each day cell is rendered on a calendar

Methods:

OnDayRender: used to raise DayRender event

Sample Code:

<%@ Page Language=”VB” %>


<html>
<head>
<script runat=”server”>

Sub OnSelectionChanged (sender as Object, e as EventArgs)


lblSelDate.Text=Calendar1.SelectedDate
End Sub
</script>
</head>
<body>
<h3> <font face=”verdana”> Calendar control demo </font></h3>
<asp:Calendar id=”Calendar1” runat=”server”
SelectionMode=”DayWeekMonth”
SelelctWeekText=”wk”
SelectMonthText=”month”
OnSelectionChanged=”OnSelectionChanged”/>
<BR>
<asp:label id=”lblSelDate” runat=”server”/>
</form>
</body>
</html>

(iii) TreeView Control


The TreeView control is used to present hierarchical data to users in the windows
explorer style format. The TreeView control is not shipped as part of the ASP.Net
framework. You need to install this control separately. In addition, when you want to use
these controls in ASP.Net page, you must explicitly import the assemblies containing
these controls. Some of the properties and events are:

Properties:

AutoPostBack: used to specify whether or not the control posts back to the server on
each client request.
AutoSelect: used to specify whether or not a tree node can be selected by pointing the
mouse to the node without clicking the node.
ImageURL: used to specify the location of an image that is to be displayed to
represent a node

Events:
Collapse: raised when a user click a tree node to collapse it
Expand: raised when a user clicks a tree node to expand it

(iv) Toolbar Control

The toolbar control is used to render a toolbar in client browser. It is a container for one
of the following controls.

ToolbarButton: represents a standard image or text button


ToolbarCheckButton: represents a button that a user can select or clear
ToolbarDropDownList: represents a drop-down list in a Toolbar container
ToolbarLabel: represents a text or image label
ToolbarSeparator: represents a separator between controls in a toolbar container
ToolbarTextbox:represents a text box in a toolbar container

Properties:
AutoPostBack: used to specify whether or not the control posts back to server
after each client request.
DefaultStyle: used to specify a default style for the toolbar

Events:
ButtonClick:raised when a user clicks to a toolbar button
CheckChange:event is raised when the state of a ToolbarCheckbutton changes

(v) TabStrip control and MultiPage control

The TabStrip control is used to present tabbed controls, which can be used along with the
MultiPage control to display varied information in a given space. The TabStrip control
renders tabs that users can click to switch between the different tabs. The MultiPage
control is used to display multipages of data in a given screen area. This control is
typically used with TabStrip control.

Some of the properties in TabStrip controls: AutoPostBack, DefaultStyle, Orientation,


SelectedIndex, TargetID

14. More about System.Web.UI.Control class

The System.Web.UI.Control class defines all the properties, events, and methods that are
common to all the WebForms controls. Some of the properties, methods and events of
control class are:

Properties:

ID: represents the control identifier to refer to the server control in programs
Parent: represents the parent control in the server control hierarchy
Visible: indicates whether or not a server control should be rendered on the page

Methods:
Dispose: cause a server control to perform final cleanup
Equals: used to check whether or not an object is the same as the current object.
FindControl: used to search a container for a specified server control.
ToString: used to return the string representation of current object

Event:
Init: is fired when a control is initialized.
Load: when the control is loaded in a page
Unload: when the control is unloaded from memory

Interfaces:
INamingContainer Interface: Provides data binding, templated control, Routes
events to its child control
IPostBackDataHandler interface: when it needs to update its state or raise events
on server after examining postback data
IPostBackEventHandler: when you want to transfer events that are generated on
the client side to server.

15. Creating and using custom controls

Consider the given simple user control

Product_ID :

Product Name:

Buy
Steps to be followed for creating custom control:

Step 1: Add a web Form to the existing project

Select the Add web form option from the project menu. Then Add new item
dialog box appears

Type the name of web form as example myweb

Click open, this will open a new webform

Step 2: Convert you web form to user control

This step involves converting a web form to user control. Add the required control to the
form using toolbox and then edit the HML code of aspx file. The HTML file cannot
contain the HTML tags that include <Head>, <body>, <HTMl> and <form> tags. Also
need to change @ Page and @ Control directives. The typical code after doing all the
changes is as follows:

<table height=90 cellspacing=0 cellpadding=0 width=361 border=0


ms_2d_layout=”TRUE”>
<tr valign=top>
<td width=14 height=15></td>
<td width=188></td>
<td width=159></td></tr>
<tr valign=top>
<td colspan=2 height=9></td>
<td rowspan=2>

<asp:TextBox id=Product_ID runat=”server”></asp:TextBox> </td></tr>

<tr valign=top>
<td height=37></td>
<td>
<asp:Label id=Label1 runat=”server”>Product_ID</asp:Label></td></tr>
<tr valign=top>
<td colspan=2 height=4></td>
<td rowspan=2>

<asp:TextBox id=Product_Name runat=”server”></asp:TextBox> </td></tr>

<tr valign=top>
<td height=25></td>
<td>
<asp:Label id=Label2 runat=”server”>Product_Name</asp:Label></td></tr>

After editing the code, save and close the file

Step 3: Change the extension of file to .ascx

This steps involves changing the extension of the file to .ascx. To rename the file you
need to do these steps:

Rightclick the user control web form file in solution explorer window and select
rename from the shortcut menu

Change the extension of file to .ascx

Steps to be followed for using a user control in web forms page

Step1: Register the user control

Steps involved in registering the user controls are:

Open the web form page in which you want to add your user control.

Write the following code:


<%@ Register TagPrefix=”Acme” Tagname=”Product” Src=”Myweb.asc” %>

Step 2: Add the user control to web forms page

This step involves adding user control to web forms page by adding the code:
<Acme:Product id=”MyProduct” runat=”Server” />

This code is to be placed in the script where you want the control to appear on the page.
Mostly it is placed in the <Body> of <Form> element

16. Validating user Input

There are totally six validation controls in ASP.Net to do validation.

(i) RequiredFieldValidator

This validation control is used to check whether a server control added to a web form
page has a value or not.

Properties:
ControlToValidate: used to specify the ID of the control that is to be validated
ErrorMessage: to specify the error message that is displayed in the validation
summary control
Text: to specify the error message displayed by the control
Display: static: each validation control occupies space even when no error
message text is visible
Display:dynamic: When layout of page changes , it causes controls to move as
error message are displayed. Validation controls cannot occupy the same space,
so you must give each control a separate location on the page.

Method:
Validate: used to perform validation and set the IsValid Property

Sample code:

<asp:textbox id=”txtname” Value=”enter name” runat=”server />


<asp:RequiredFieldValidator id=”txtNameValidator” runat=”server”
ControlToValidate=”txtName” ErrorMessage=”You must enter name”
Display=”dynamic”>
</asp:RequiredFieldValidator>

(ii) RegularExpressionValidator

This control is used to match the value entered in a web form field to a regular
expression. The regular expression can be the format of telephone number or email
address.

Properties:
ControlToValidate: used to specify the ID of the control that is to be validated
ErrorMessage: used to specify the error message that is displayed in the
Validation Summary control
ValidationExpression: used to specify the regular expression to use for validation

Methods:
Validate: used to perform validation and set the IsValid property

List of valid expressions:

Expression for Synta Description Example


Checking x
Set of chars [] Mach any one of chars within [] ValidationExpression=”P[0-5]”
Tagged expression {n} Match an expression exactly n time ValidationExpression=
”P[0-5]{4}”
Starts with letter P followed by four
digits ranging from 0 to 5
Word chars \w Any letter, numeric, or underscore ValidationExpression
=”\w{8,20}”
Any char . Any char except a line break ValidationExpression=”X.”
Any non white \S Chars except space, tables, and line “http://\S\S\S\S\S\S\S”
space char breaks
One or more chars + At least one occurrence of “\S+@\S+\.\S+”
preceding expression example: xyz@now.com
Any single char ? Match any single preceding char “programs?” ? is optional
Any white space \s Any white space char including “\sip”
char tab, space, line break space before the word ip
Any digit char \d Any digit in the range 0-9 “\d{5}”
Escape char \ Used to map backslash “\~”
to check whether the tilt(~) is entered
by user
Zero or more char * Zero or more chars in expression “P*”

Sample Code:

<asp:textbox id=”txtzip” Value=”enter zip code” runat=”server />


<asp:RegularExpressionValidator id=”txtzipValidator” runat=”server”
ControlToValidate=”txtzip” ErrorMessage=”Use the format 123-12-1234”
ValidationExpression=”[0-9]{3}-[0-9]{2}-[0-9]{4}”>
</asp:RegularExpressionValidator>

(iii) CompareValidator

This control is used to perform comparisons between a values entered with another
value.

Properties:
ControlToCompare: used to specify the Id of control that will be used to compare
ControlToValidate: used to specify the Id of the control that is to be validated
ErrorMessage: used to specify the error message that is displayed in
ValidationSummary
ValueToCompare: specify the value used when performing comparison

Methods:
Validate: used to perform validation and set the IsValid property

Sample Code:
<asp:textbox id=”txtage” Value=”enter age” runat=”server />
<asp:CompareValidator id=”txtageValidator” runat=”server”
ControlToValidate=”txtage”
ValueToCompare=”0”
Type=”Integer”
Operator=”GreaterThanEqual”
ErrorMessage=”You must enter whole a number zero or greater”>
</asp:CompareValidator>

(iv) RangeValidator
This control is used to check whether the value of a particular web form field is within
the minimum and maximum data. The data can be dates, numbers, currency amounts or
strings.

Properties:
ControlToValidate: used to specify the Id of control that is to be validated
ErrorMessage: specify error that is displayed in validation summary
MaximumValue:specify maximum value in the range of values
MinimuValue:specify the minimum value in the range of values
Type: to set as currency, date, double, integer or string
Methods:
Validate: perform validation and set the IsValid property

Sample Code:

<asp:textbox id=”txtAge” value=”enter age” runat=”server”/>


<asp:RangeValidator id=”txtAgeValidator” runat=”server”
ControlToValidate=”txtAge”
Type=”Integer”
minimumValue=”18”
maximumValue=”50”
errormessage=”applicants must be between 18 and 50”
display=”dynamic”>
</asp:RangeValidator>

(v) ValidationSummary

This control is used to summarize all errors and display the error list in a user-specified
location in the web page.

Properties:
HeadText: to set the text that will be displayed at the top of summary
ShowMessageBox: to display the error message in a pop-up messagebox
ShowSummary: used to enable or disable the summary of error messages

Sample Code:

<asp:ValidationSummary id=”valSummary” runat=”server”


headerText=”these errors were found”
Showsummary=”True”
displayMode=”List” />

(vi) CustomValidator

This control is used to perform user-define validations that cannot be performed by


standard validation controls.
Properties:
ControlToValidate: specify the ID of the control to be validated
ErrorMessage: specify the error to be displayed in validatinsummary
Events:
ServerValidate: represent the function for performing server side validation
Methods:
OnServerValidate: used to raise servervalidate event
Validate: used to perform validation and set the IsValid property

Sample Code:
<asp:textbox id=”cardno” maxlength=”16” runat=”server”/>
<asp:CustomValidator id=”cucardno”
ControlToValidate=”cardno”
ClientValidationFunction=”IsCardValid”
Display=”dynamic”
Errormessage=”invalid card number”
Runat=”server”>
</asp:CustomValidator><br>

IsCardValid function:

<script language=”javascript”>
function IsCardValid(source, value){
if (value != “5555555555”)
return false;
else
return true;
}
</script>

17. Debugging ASP.Net pages

The process of reviewing the code to identify the root cause of error and its elimination
is called debugging.

Access error:

The details of errors can be viewed from

• Access the page again from local server


• Modify the configuration settings on computer
• Modify configuration settings of applications web.config file to enable remote
access. The web.config file is
<configuration>
<system.web>
<customErrors mode=”Off” />
</system.web>
</configuration>

• Use custom error pages: The HTML error page can be displayed to a user with
the steps given:

Create web page that you want to display error message [.html or .aspx]
Modify web.config file to show Myerror.aspx
<configuration>
<system.web>
<customErrors mode=”RemoteOnly”
defaultRedirect=”MyError.aspx”/>
</system.web>
</configuration>
• Tracking errors: To ensure that the administrators and developers are also able
to track errors. It is implemented by Application_Error event. For enabling this
Import System.Dianostics in Global.asax file. And write event log to track
errors.
• Import system.Io and write the code updation in Page_Load event to throw error.

Trace the application

Page level tracing: allows to write debug message directly to web form. The
system.web.TraceContext class support the trace functionality of ASP.Net page.

Application level tracing allow to trace the entire application. Enable the <Trace >
element of <system.web> element in applications <web.config> file.

Use Debugging tools:

The debug tool bar provided by VS.Net is used. The various debugging tools can be
accessed using the debug menu item. It allows to trace and rectify an error. The two
different ways to use debug tools:

(i) By using debug menu

The different debug menu options are:


Start, continue, restart, step into (to called procedure) step out (calling
procedure), step over (skip called procedure), Run to cursor (until breakpoint)
New Breakpoint (set breakpoint by Ctrl+b).

To debug the current page, mark the page as startup page of project and Set the
breakpoint before browse the page.
To debug select Debug-> start. This option starts the application and attaches a
debugger.

When you enter values and proceeds the debugger enters break mode placed by
you.

In this mode, you can see the line at which you set the breakpoint being
highlighted. You can check the values of various variable and controls for
correctness in break mode.

You will now run through the procedure in a step wise manner to identify the
source of problem by selecting debug->step into.

To view the results in the immediate window by selecting


debug->windows->immediate and type
? lblresult.text

You can stop debugging and correct the code. To stop the debug process, select
debug->stop debugging.

(ii) By attaching the debugger to a running application

A VS.Net debugger can be attached to an already running application. It is


achieved by the given steps:

Step 1: Open the running application in Vs.Net


Step 2: select debug from menu bar and select processes from debug menu
Step 3: the processes dialog box is displayed, from that select show system
processes check box to display all the system processes
Step 4: select aspnet_wp.exe from available processes list and click attach
button. This will attach the asp.net runtime process aspnet_wp.exe to
application.
Step 5: select the common language runtime and script check boxes in the
attach to process dialog box. And then click ok.
Step 6: Click close button in the processes dialog box

Attach
Debugger

Execute Watch/alter See immediate


Program commands, variables results
During execution

Stop debugger

Repeat

Potrebbero piacerti anche