Programming Using Asp Dot Net Notes
Programming Using Asp Dot Net Notes
Programming Using Asp Dot Net Notes
UNIT-1
Asp.Net Overview:
Yes, these are the three different models of .NET Framework. Now, you might
be thinking about ASP.Net Core, and so you should know that it is the modal
of .NET Core Framework.
You can code your applications in any language compatible with the common
language runtime (CLR), including Microsoft Visual Basic, C#, JScript .NET,
and J#. These languages enable you to develop ASP.NET applications that
benefit from the common language runtime, type safety, inheritance, and so on.
ASP.NET includes:
Web Win Forms, Rapid development using a rich library of controls Mid-Level,
Forms WPF, .NET that encapsulate HTML markup Advanced RAD
MVC Ruby on Full control over HTML markup, code and markup Mid-Level,
Rails, .NET separated, and easy to write tests. The best choice Advanced
for mobile and single-page applications (SPA).
Web Classic HTML markup and your code together in the same New, Mid-Level
Pages ASP, PHP file
According to Microsoft, if we use any framework then the output will be the
same. But there is a reason behind this separation. Every Framework has its
own pros and cons
Web Pages
Web pages are preferred to build information based sites and blog-type
applications. The applications you see on the internet with (.asp) extension is
built on the top of Web Pages framework.
Web Forms
Now, let’s discuss the history of Windows before digging into web forms. In
1980’s, mostly DOS based OS was used which is like cmd in our Windows.
We used commands there to create, read, update, delete the files. But then
Microsoft launched Windows in which everything was graphical so that we can
do everything through GUI. As Microsoft was successful in GUI, it repeated
something visual once again to become successful in the programming world.
As we know already, we want button or grid we need to code for them to look
like a button or grid. But Microsoft launched Visual Studio in which every
programming language is replaced with the Visual programming language.
Like if you were working in C++ then you can use Visual C++ in which
controls are already present like buttons, menus and you need to just drag and
drop the controls and code the functionality behind it.
Microsoft does the same thing in Web Forms to separate the client side and
server side. History again repeats and Microsoft becomes very famous among
developers eventually due to this feature. Now, we can design the client side on
client side layer and we can code behind it. It was much better than the classical
Web Pages approach. Now the development becomes so much fast, we
performing event-based application development. And it is what we say RAD
(Rapid Application Development) fast development.
ASP.NET is an open-source server-side web application framework designed
for web development to produce dynamic web pages.
1. Static Website : All user who visit the same web site can see
same information.For e.g .News paper sites
2. Dynamic Website : All user who visit same web site will see
different information. or e.g.Gmail (shows logged in users
email).
Web Application
Definition
A web application is a computer program that utilizes web browsers and web
technology to perform tasks over the Internet.
Overview
The web application requires a web server to manage requests from the client,
an application server to perform the tasks requested, and, sometimes, a database
to store the information. Application server technology ranges from ASP.NET,
ASP and ColdFusion, to PHP and JSP.
1. User triggers a request to the web server over the internet, either
through a web browser or the application’s user interface
2. Web server forwards this request to the appropriate web application
server
3. Web application server performs the requested task – such as querying
the database or processing the data – then generates the results of the
requested data
4. Web application server sends results to the web server with the
requested information or processed data
5. Web server responds back to the client with the requested information
that then appears on the user’s display
Google Apps for Work has Gmail, Google Docs, Google Sheets, Google Slides,
online storage and more. Other functionalities include online sharing of
documents and calendars. This lets all team members access the same version of
a document simultaneously.
Web Server:
A web server accepts and fulfills requests from clients for static content (i.e.,
HTML pages, files, images, and videos) from a website. Web servers handle
HTTP requests and responses only.
It includes
What is IIS?
What is Apache?
Apache, or to use its full royal title The Apache HTTP web server, is an open
source Web server application managed by the Apache Software Foundation.
The server software is freely distributed, and the open source license means
users can edit the underlying code to tweak performance and contribute to the
future development of the program – a major source of its beloved status among
its proponents. Support, fixes and development are handled by the loyal user
community and coordinated by the Apache Software Foundation.
Although Apache will run on all major operating systems, it is most frequently
used in combination with Linux. These two, combined with MySQL database
and PHP scripting language, comprise the popular LAMP Web server solution.
The Web Server (IIS) role in Windows Server 2016 provides a secure, easy-to-
manage, modular and extensible platform for reliably hosting websites, services,
and applications. With IIS, you can share information with users on the Internet,
an intranet, or an extranet. IIS is a unified web platform that integrates IIS,
ASP.NET, FTP services, PHP, and Windows Communication Foundation
(WCF).
When you deploy server certificates, your Web server provides you with a
location where you can publish the certificate revocation list (CRL) for your
certification authority (CA). After publication, the CRL is accessible to all
computers on your network so that they can use this list during the
authentication process to verify that certificates presented by other computers
are not revoked.
If a certificate is on the CRL as revoked, the authentication effort fails and your
computer is protected from trusting an entity that has a certificate that is no
longer valid.
Before you install the Web Server (IIS) role, ensure that you have configured
the server name and IP address and have joined the computer to the domain.
Note
1. In Server Manager, click Manage, and then click Add Roles and
Features. The Add Roles and Features Wizard opens.
2. In Before You Begin, click Next.
Note The Before You Begin page of the Add Roles and Features Wizard is not
displayed if you have previously run the Add Roles and Features Wizard and
you selected Skip this page by default at that time.
Much of the Web’s software and code is designed to work along with
Apache’s features. Programmers working on Web applications typically
make use of a home version of Apache to preview and test code.
Apache also has a safe and secure file-sharing feature, allowing users to put
files into the root directory of their Apache software and share them with
other users.
HTTP/S is used to define how messages are formatted and transmitted across
the web, with instructions for browsers and servers on how to respond to
various requests and commands. Hypertext Transfer Protocol Secure is usually
through port 443 with the unsecured protocol being through port 80.
The Apache server is configured via config files in which modules are used to
control its behavior. By default, Apache listens to the IP addresses configured in
its config files that are being requested. This is where one of Apaches many
strengths come into play.
With the Listen directive, Apache can accept and route specific traffic to certain
ports and domains based on specific address-port combination requests. By
default, Listen runs on port 80 but Apache can be bound to different ports for
different domains, allowing for many different websites and domains to be
hosted and a single server. You can have domain1.com listening on port 80,
domain2.com on port 8080 and domain3.com on port 443 using HTTPS all on
Apache.
Apache HTTP web servers are used by over 67% of all web servers in the
world. Apache web servers are easy to customize environments, they’re fast,
reliable, and highly secure. This makes Apache web servers a common choice
by best-in-class companies.
While Apache web servers are very popular, they’re not the only web servers on
the market. Below are a number of alternatives for Apache HTTP servers.
Nginx
Apache Tomcat
Node.js
Lighttpd
Cherokee
Microsoft IIS
Appweb
Hiawatha
What is a browser?
Browser is an application, which helps us to view the Web sites and the
web content.
Web sites are located in some remote systems, which needs a special kind
of program or an application to access them, such an application is
called browser.
A browser is an application which you can use to retrieve web pages from
web sites and view.
When you type a URL in the browser, the browser will convert it into
a web request which web server can understand. Browser will send the
request to web server using the HTTP protocol.
When a web server returns a web page as a Response, the browser will
understand the response and display the body of the response to the user
in browser.
You can create your own simple browser application using C++, C#,
VB.NET or any other language you like. All you need to know is, how to
compose a request which web server can understand, how to parse and
display the response from web server and communicate with webserver
using HTTP protocol.
Even though the basic job of browser is just send requests to web server
and receive response from the server, modern browser provide several
other enhanced features including Back/Forward buttons, save viewed
files to disk so that they can be viewed later, cache images so that the
same images need not be downloaded again and again etc.
Internet Explorer, Netspace, Mozilla are some of the popular web
browsers currently available in the market.
Netscape was the most popular web browser till 4-5 years back, but
currently more than 90% of the internet users use "Internet Explorer" to
browse the websites.
There is a variety of coding languages developers choose from, and most use
the language they are most comfortable with. Their preference is formed over
time based on their experience using different languages.
Here are the most common languages and how they are used:
1. HTML
HTML makes up the layout and structure for your website. This language is
dynamic and allows you to create a beautiful website using less code. HTML is
used to create a starting point for the website and is what most of your static
pages start from. A better way to understand this language is to consider it as
the skeleton that is holding your website together.
HTML has all the features you want in a web development language.
2. CSS
CSS is the language developers can use to style a website. The style sheet
language describes how your website is presented and its layout. CSS is used
hand in hand with HTML to add colors, backgrounds, layouts, font sizes, and
more. This language is a core technology web developers use to design and
build websites.
CSS is one of the web languages which gives you massive control over web
design.
CSS, as a web developer’s language, has plenty of benefits. Here’re some you’d
want to explore.
The first version of the protocol had only one method, namely GET, which
would request a page from a server.
The response from the server was always an HTML page.- Wiki
To give you an idea of how simple the HTTP protocol started out take a look at
the Original specification which was only 1 page.
There have been several versions of HTTP starting with the original 0.9
version.
The current version is 1.1 and was last revised in 2014. See Wiki for more
details.
How It Works
Like most of the Internet protocols http it is a command and response text
based protocol using a client server communications model.
The HTTP protocol is also a stateless protocol meaning that the server isn’t
required to store session information, and each request is independent of the
other.- See this wiki
This means:
Request and response message structures are the same and shown below:
A simple CRLF (carriage return and Line feed) combination is used to delimit
the parts, and a single blank line (CRLF ) indicates end of the headers.
If the request or response contains a message body then this is indicated in the
header.
Note: the message body is not followed by a CRLF See RFC 7230 section
3.5
HTTP Requests
We saw the general request response format earlier now we will cover the
request message in more detail.
The start line is mandatory and is structured as follows:
Where
Notes:
Note: URL (uniform resource Locator) is used for web pages. It is an example
of a URI (uniform resource indicator).
The actual http request is not shown by the browser, and is only visible using
special tools like http header live (Firefox).
HTTP vs URL
Most people are familiar with entering a url into a web browser. Usually
looking like this.
The url can also includes the port which is normally hidden by the browser, but
you can manually include it as shown below:
This tells the web browser the address of the resource to locate and the protocol
to use to retrieve that resource (http).
http is the transfer protocol that transfer the resource (web page,image,video
etc) from the server to the client.
Response Status codes are split into 5 groups each group has a meaning and
a three digit code.
1xx – Informational
2xx – Successful
3xx -Multiple Choice
4xx– Client Error
5xx -Server Error
For example a successful page request will return a 200 response code and an
unsuccessful a 400 response code.
and here is a screen shot of the http request-response that happens behind the
scenes.
What is TCP/IP?
TCP is responsible for breaking data down into small packets before they can be
sent over a network, and for assembling the packets again when they arrive.
IP - Internet Protocol
TCP/IP specifies how data is exchanged over the internet by providing end-to-
end communications that identify how it should be broken into packets,
addressed, transmitted, routed and received at the destination. TCP/IP requires
little central management and is designed to make networks reliable with the
ability to recover automatically from the failure of any device on the network.
The two main protocols in the IP suite serve specific functions. TCP defines
how applications can create channels of communication across a network. It
also manages how a message is assembled into smaller packets before they are
then transmitted over the internet and reassembled in the right order at the
destination address.
IP defines how to address and route each packet to make sure it reaches the
right destination. Each gateway computer on the network checks this IP
address to determine where to forward the message.
A subnet mask tells a computer, or other network device, what portion of the IP
address is used to represent the network and what part is used to represent hosts,
or other computers, on the network.
Network address translation (NAT) is the virtualization of IP addresses. NAT
helps improve security and decrease the number of IP addresses an organization
needs.
The transport layer itself, however, is stateful. It transmits a single message, and
its connection remains in place until all the packets in a message have been
received and reassembled at the destination.
The TCP/IP model differs slightly from the seven-layer Open Systems
Interconnection (OSI) networking model designed after it. The OSI reference
model defines how applications can communicate over a network.
TCP/IP is highly scalable and, as a routable protocol, can determine the most
efficient path through the network. It is widely used in current internet
architecture.
Web browsers and servers use TCP/IP protocols to connect to the Internet.
Common TCP/IP protocols are:
HTTP takes care of the communication between a web server and a web
browser. HTTP is used for sending requests from a web client (a browser) to a
web server, returning web content (web pages) from the server back to the
client.
HTTPS takes care of secure communication between a web server and a web
browser. HTTPS typically handles credit card transactions and other sensitive
data.
IP is Connection-Less
IP does not occupy the communication line between two computers. This
reduces the need for network lines. Each line can be used for communication
between many different computers at the same time.
With IP, messages (or other data) are broken up into small independent
"packets" and sent between computers via the Internet. IP is responsible for
"routing" each packet to the correct destination.
IP Routers
The path the packet will follow might be different from other packets of the
same communication. The router is responsible for the right addressing,
depending on traffic volume, errors in the network, or other parameters.
IP Addresses
Each computer must have an unique IP address before it can connect to the
Internet.
Each IP packet must have an address before it can be sent to another computer.
In computer terms, TCP/IP uses 32 bits addressing. It uses 4 bytes. One byte
is 8 bits. One byte can contain 256 different values:
Domain Names
All over the world, DNS servers are connected to the Internet. DNS servers are
responsible for translating domain names into TCP/IP addresses.
When a new domain name is registered together with a TCP/IP address, DNS
servers all over the world are updated with this information.
E-mail programs use TCP/IP for sending and receiving e-mails. The TCP/IP
protocols for email are:
SMTP takes care of sending emails. Often emails are sent to an email server
(SMTP server), then to other servers, and finally to its destination. SMTP can
only transmit pure text. It cannot transmit binary data like pictures, sounds or
movies.
The MIME protocol lets SMTP transmit multimedia files including voice,
audio, and binary data across TCP/IP networks. The MIME protocol converts
binary data to pure text, before it is sent.
The POP protocol is used by email programs to retrieve emails from an email
server. If your email program uses POP, all your emails are downloaded to your
email program (also called email client), each time it connects to your email
server.
The IMAP protocol works much like the POP protocol. The main difference is
that the IMAP protocol will not automatically download all your emails each
time your email program connects to your email server.
The IMAP protocol allows you to look through your email messages at the
email server before you download them. With IMAP you can choose to
download your messages or just delete them. This way IMAP is perfect if you
need to connect to your email server from different locations, but only want to
download your messages when you are back in your office.
LDAP is used for collecting information about users and e-mail addresses from
the internet.
The SSL protocol is used to encrypt data for secure data transmission.
Notice the request headers are automatically inserted by the browser, and so are
the response headers are inserted by the web server.
ASP.NET:
ASP.NET is a free web framework for building great websites and web
applications using HTML, CSS, and JavaScript. You can also create Web APIs
and use real-time technologies like Web Sockets.
ASP.NET offers three frameworks for creating web applications: Web Forms,
ASP.NET MVC, and ASP.NET Web Pages. All three frameworks are stable
and mature, and you can create great web applications with any of them. No
matter what framework you choose, you will get all the benefits and features of
ASP.NET everywhere.
Each framework targets a different development style. The one you choose
depends on a combination of your programming assets (knowledge, skills, and
development experience), the type of application you're creating, and the
development approach you're comfortable with.
With ASP.NET Web Forms, you can build dynamic websites using a familiar
drag-and-drop, event-driven model. A design surface and hundreds of controls
and components let you rapidly build sophisticated, powerful UI-driven sites
with data access.
MVC
ASP.NET Web Pages and the Razor syntax provide a fast, approachable, and
lightweight way to combine server code with HTML to create dynamic web
content. Connect to databases, add video, link to social networking sites, and
include many more features that help you create beautiful sites that conform to
the latest web standards.
Single-page applications
ASP.NET Single Page Application (SPA) helps you build applications that
include significant client-side interactions using HTML 5, CSS 3 and
JavaScript. Visual Studio includes a template for building single page
applications using knockout.js and ASP.NET Web API. In addition to the built-
in SPA template, community-created SPA templates are also available for
download.
.NET Components
The architecture of .Net framework is based on the following key components;
Exception Handling – Exceptions are errors which occur when the application
is executed.
If an application tries to open a file on the local machine, but the file is
not present.
If the application tries to fetch some records from a database, but the
connection to the database is not valid.
1. Language – The first level is the programming language itself, the most
common ones are VB.Net and C#.
2. Compiler – There is a compiler which will be separate for each
programming language. So underlying the VB.Net language, there will be
a separate VB.Net compiler. Similarly, for C#, you will have another
compiler.
3. Common Language Interpreter – This is the final layer in .Net which
would be used to run a .net program developed in any programming
language. So the subsequent compiler will send the program to the CLI
layer to run the .Net application.
2. Class Library
The .NET Framework includes a set of standard class libraries. A class library is
a collection of methods and functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level
operations. So there is a method which can be used to read the text from a file.
Similarly, there is a method to write text to a file.
Most of the methods are split into either the System.* or Microsoft.*
namespaces. (The asterisk * just means a reference to all of the methods that fall
under the System or Microsoft namespace)
3. Languages
The types of applications that can be built in the .Net framework is classified
broadly into the following categories.
WinForms – This is used for developing Forms-based applications, which
would run on an end user machine. Notepad is an example of a client-based
application.
ASP.Net – This is used for developing web-based applications, which are made
to run on any browser such as Internet Explorer, Chrome or Firefox.
Microsoft always ensures that .Net frameworks are in compliance with all the
supported Windows operating systems.
3) Security – The .NET Framework has a good security mechanism. The inbuilt
security mechanism helps in both validation and verification of applications.
Every application can explicitly define their security mechanism. Each security
mechanism is used to grant the user access to the code or to the running
program.
4) Memory management – The Common Language runtime does all the work
or memory management. The .Net framework has all the capability to see those
resources, which are not used by a running program. It would then release those
resources accordingly. This is done via a program called the “Garbage
Collector” which runs as part of the .Net framework. The garbage collector runs
at regular intervals and keeps on checking which system resources are not
utilized, and frees them accordingly.
5) Simplified deployment – The .Net framework also have tools, which can be
used to package applications built on the .Net framework. These packages can
then be distributed to client machines. The packages would then automatically
install the application.
Namespace:
The namespace keyword is used to declare a scope that contains a set of related
objects. You can use a namespace to organize code elements and to create
globally unique types.
Within a namespace, you can declare zero or more of the following types:
class
interface
struct
enum
delegate
nested namespaces can be declared except in file scoped namespace
declarations
a. Cookies
b. Configuring page caching
c. Tracing Implementation
d. Retrieving Information of Web Server and client browser
We uses built-in object frequently .This namespace are very important for
ASP.net application, it is also required for User Interface , Web forms and Web
services.
a. Attribute Collection
b. BaseParser
c. BaseTemplateParser
d. AsyncPostBackTrigger etc
Syntax Highlighting
An IDE that knows the syntax of your language can provide visual cues.
Keywords, words that have special meaning like class in Java, are highlighted
with different colors.
Building Executables
Java is a compiled language. Before programs run, the source code of
a .java file must be transformed into an executable .class by the compiler. Once
compiled, the program can be run from the terminal.
This compilation process is necessary for every program, so why not have the
IDE do it for us? IDEs provide automated build processes for languages, so the
act of compiling and executing code is abstracted away, like in Codecademy
lessons.
Debugging
No programmer avoids writing bugs and programs with errors.
When a program does not run correctly, IDEs provide debugging tools that
allow programmers to examine different variables and inspect their code in a
deliberate way.
IDEs also provide hints while coding to prevent errors before compilation.
The biggest benefit to using an IDE is that it allows you to code and run Java
programs on your own computer. We recommend IntelliJ IDEA, which you can
download for macOS, Windows, or Linux.
UNIT-2
Web Forms are web pages built on the ASP.NET Technology. It executes on
the server and generates output to the browser. It is compatible to any browser
to any language supported by .NET common language runtime. It is flexible and
allows us to create and add custom controls.
Web Forms are made up of two components: the visual portion (the ASPX file),
and the code behind the form, which resides in a separate class file.
The main purpose of Web Forms is to overcome the limitations of ASP and
separate view from the application logic.
ASP.NET provides various controls like: server controls and HTML controls
for the Web Forms. We have tables all these controls below.
o Server Controls
o Master Pages
o Working with data
o Membership
o Client Script and Client Frameworks
o Routing
o State Management
o Security
o Performance
o Error Handling
Server Controls
Web Forms provides rich set of server controls. These controls are objects that
run when the page is requested and render markup to the browser. Some Web
server controls are similar to familiar HTML elements, such as buttons and text
boxes. It also provides controls that we can use to connect to data sources and
display data.
Master Pages
It allowsus to create a consistent layout for the pages in our application. This
page defines the look and feel and standard behavior that we want for all of the
pages in our application. When users request the content pages, they merge with
the master page to produce output that combines the layout of the master page
with the content from the content page.
x
Membership
Project's Account folder contains the files that implement the various parts of
membership: registering, logging in, changing a password, and authorizing
access. Additionally, ASP.NET Web Forms supports OAuth and OpenID.
These authentication enhancements allow users to log into your site using
existing credentials, from such accounts as Facebook, Twitter and Google.
We can configure URL routing of our application. A request URL is simply the
URL a user enters into their browser to find a page on our web site. We use
routing to define URLs that are semantically meaningful to users and that can
help with search-engine optimization (SEO).
State Management
ASP.NET Web Forms includes several options that help you preserve data on
both a per-page basis and an application-wide basis.
Security
Performance
We can diagnose problems that occur in our Web Forms application. Debugging
and error handling are well supported within ASP.NET Web Forms so that our
applications compile and run effectively.
Button Controls
Property Description
Text The text displayed on the button. This is for button and
link button controls only.
PostBackUrl The URL of the page that is requested when the user
clicks the button.
Text box controls are typically used to accept input from the user. A text box
control can accept one or more lines of text depending upon the settings of the
TextMode attribute.
Label controls provide an easy way to display text which can be changed from
one execution of a page to the next. If you want to display text that does not
change, you use the literal text.
Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Common Properties of the Text Box and Labels:
Property Description
ReadOnly Determines whether the user can change the text in the
box; default is false, i.e., the user can not change the text.
Columns The width of the text box in characters. The actual width
is determined based on the font that is used for the text
entry.
The mostly used attribute for a label control is 'Text', which implies the text
displayed on the label.
A check box displays a single option that the user can either check or uncheck
and radio buttons present a group of options from which the user can select just
one option.
To create a group of radio buttons, you specify the same name for the
GroupName attribute of each radio button in the group. If more than one group
is required in a single form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially
displayed, set its Checked attribute to true. If the Checked attribute is set to true
for multiple radio buttons in a group, then only the last one is considered as
true.
Basic syntax of check box:
<asp:CheckBox ID= "chkoption" runat= "Server">
</asp:CheckBox>
Basic syntax of radio button:
<asp:RadioButton ID= "rdboption" runat= "Server">
</asp: RadioButton>
Common properties of check boxes and radio buttons:
Property Description
Text The text displayed next to the check box or radio button.
List Controls
SelectedIndex The index of the currently selected item. If more than one
item is selected, then the index of the first selected item.
If no item is selected, the value of this property is -1.
SelectedValue The value of the currently selected item. If more than one
item is selected, then the value of the first selected item.
If no item is selected, the value of this property is an
empty string ("").
Property Description
The ListItemCollection
Property Description
Methods Description
Add(string) Adds a new item at the end of the collection and assigns
the string parameter to the Text property of the item.
Insert(integer, ListItem) Inserts the item at the specified index location in the
collection.
Remove(string) Removes the item with the text value same as the string.
A radio button list presents a list of mutually exclusive options. A check box list
presents a list of independent options. These controls contain a collection of
ListItem objects that could be referred to through the Items property of the
control.
Basic syntax of radio button list:
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Basic syntax of check box list:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common properties of check box and radio button lists:
Property Description
The bulleted list control creates bulleted lists or numbered lists. These controls
contain a collection of ListItem objects that could be referred to through the
Items property of the control.
Basic syntax of a bulleted list:
<asp:BulletedList ID="BulletedList1" runat="server">
</asp:BulletedList>
Common properties of the bulleted list:
Property Description
BulletStyle This property specifies the style and looks of the bullets,
or numbers.
HyperLink Control
Property Description
Image Control
The image control is used for displaying images on the web page, or some
alternative text, if the image is not available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
Property Description
Server Controls
The following table contains the server-side controls for the Web Forms.
HTML Controls
These controls render by the browser. We can also make HTML controls as
server control. we will discuss about this in further our tutorial.
Controls Description
Name
Reset Resets all other HTML form elements on a form to a default value
Button
Submit Automatically POSTs the form data to the specified page listed in
Button the Action attribute in the FORM tag
File Field Places a text field and a Browse button on a form and allows the
user to select a file name from their local machine when the
Browse button is clicked
CheckBox Gives the user a check box that they can select or clear
Radio Used two or more to a form, and allows the user to choose one of
Button the controls
ListBox Displays a list of items to the user. You can set the size from two
or more to specify how many items you wish show. If there are
more items than will fit within this limit, a scroll bar is
automatically added to this control.
Dropdown Displays a list of items to the user, but only one item at a time will
appear. The user can click a down arrow from the side of this
control and a list of items will be displayed.
ASP.NET – Directives
In this section, we will just introduce the ASP.NET directives and we will use
most of these directives throughout the tutorials.
Attributes Description
The Assembly directive links an assembly to the page or the application at parse
time. This could appear either in the global.asax file for application-wide
linking, in the page file, a user control file for linking to a page or user control.
The basic syntax of Assembly directive is:
Attributes Description
The control directive is used with the user controls and appears in the user
control (.ascx) files.
The basic syntax of Control directive is:
The Implement directive indicates that the web page, master page or user
control page must implement the specified .Net framework interface.
The basic syntax for implements directive is:
The Import directive imports a namespace into a web page, user control page of
application. If the Import directive is specified in the global.asax file, then it is
applied to the entire application. If it is in a page of user control page, then it is
applied to that page or control.
The basic syntax for import directive is:
<%@ namespace="System.Drawing" %>
The Master directive specifies a page file as being the mater page.
The basic syntax of sample MasterPage directive is:
The MasterType directive assigns a class name to the Master property of a page,
to make it strongly typed.
The basic syntax of MasterType directive is:
The OutputCache directive controls the output caching policies of a web page or
a user control.
The basic syntax of OutputCache directive is:
The Page directive defines the attributes specific to the page file for the page
parser and the compiler.
The basic syntax of Page directive is:
ClientTarget The browser for which the server controls should render
content.
ValidateRequest The Boolean value that indicates whether all input data is
validated against a hardcoded list of values.
The Reference directive indicates that another page or user control should be
compiled and linked to the current page.
The basic syntax of Reference directive is:
The Register derivative is used for registering the custom server controls and
user controls.
The basic syntax of Register directive is:
In addition, visual studio has the following features, to help produce in error-
free coding:
Dragging and dropping of controls in design view
IntelliSense feature that displays and auto-completes the properties
The properties window to set the property values directly
ASP.NET server controls with a visual aspect are derived from the WebControl
class and inherit all the properties, events, and methods of this class.
The WebControl class itself and some other server controls that are not visually
rendered are derived from the System.Web.UI.Control class. For example,
PlaceHolder control or XML control.
ASP.Net server controls inherit all properties, events, and methods of the
WebControl and System.Web.UI.Control class.
The following table shows the inherited properties, common to all server
controls:
Property Description
AccessKey Pressing this key with the Alt key moves focus to the
control.
Font Font.
TabIndex Gets or sets the tab index of the Web server control.
Method Description
AddAttributesToRender Adds HTML attributes and styles that need to
be rendered to the specified
HtmlTextWriterTag.
Example
Let us look at a particular server control - a tree view control. A Tree view
control comes under navigation controls. Other Navigation controls are: Menu
control and SiteMapPath control.
Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit
each of the nodes using the Tree view node editor as shown:
Once you have created the nodes, it looks like the following in design view:
The AutoFormat... task allows you to format the tree view as shown:
Add a label control and a text box control on the page and name them
lblmessage and txtmessage respectively.
Write a few lines of code to ensure that when a particular node is selected, the
label control displays the node text and the text box displays all child nodes
under it, if any. The code behind the file should look like this:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace eventdemo {
public partial class treeviewdemo : System.Web.UI.Page {
if(childnodes != null) {
txtmessage.Text = " ";
Execute the page to see the effects. You will be able to expand and collapse the
nodes.
ASP.NET Themes
Themes are made up of a set of elements: skins, cascading style sheets (CSS),
images, and other resources. At a minimum, a theme will contain skins. Themes
are defined in special directories in your Web site or on your Web server.
Skins
A skin file has the file name extension .skin and contains property settings for
individual controls such as Button, Label, TextBox, or Calendar controls.
Control skin settings are like the control markup itself, but contain only the
properties you want to set as part of the theme. For example, the following is a
control skin for a Button control:
Copy
<asp:button runat="server" BackColor="lightblue" ForeColor="black" />
You create .skin files in the Theme folder. A .skin file can contain one or more
control skins for one or more control types. You can define skins in a separate
file for each control or define all the skins for a theme in a single file.
There are two types of control skins, default skins and named skins:
A theme can also include a cascading style sheet (.css file). When you put a .css
file in the theme folder, the style sheet is applied automatically as part of the
theme. You define a style sheet using the file name extension .css in the theme
folder.
Themes can also include graphics and other resources, such as script files or
sound files. For example, part of your page theme might include a skin for
a TreeView control. As part of the theme, you can include the graphics used to
represent the expand button and the collapse button.
Typically, the resource files for the theme are in the same folder as the skin files
for that theme, but they can be elsewhere in the Web application, in a subfolder
of the theme folder for example. To refer to a resource file in a subfolder of the
theme folder, use a path like the one shown in this Image control skin:
Copy
<asp:Image runat="server" ImageUrl="ThemeSubfolder/filename.ext" />
You can also store your resource files outside the theme folder. If you use the
tilde (~) syntax to refer to the resource files, the Web application will
automatically find the images. For example, if you place the resources for a
theme in a subfolder of your application, you can use paths of the form
~/SubFolder/filename.ext to refer to resource files, as in the following example.
Copy
<asp:Image runat="server" ImageUrl="~/AppSubfolder/filename.ext" />
Scoping Themes
You can define themes for a single Web application, or as global themes that
can be used by all applications on a Web server. After a theme is defined, it can
be placed on individual pages using the Theme or StyleSheetTheme attribute of
the @ Page directive, or it can be applied to all pages in an application by
setting the <pages> element in the application configuration file. If
the <pages> element is defined in the Machine.config file, the theme will apply
to all pages in Web applications on the server.
Page Themes
A page theme is a theme folder with control skins, style sheets, graphics files
and other resources created as a subfolder of the \App_Themes folder in your
Web site. Each theme is a different subfolder of the \App_Themes folder. The
following example shows a typical page theme, defining two themes named
BlueTheme and PinkTheme.
Copy
MyWebSite
App_Themes
BlueTheme
Controls.skin
BlueTheme.css
PinkTheme
Controls.skin
PinkTheme.css
Global Themes
A global theme is a theme that you can apply to all the Web sites on a server.
Global themes allow you to define an overall look for your domain when you
maintain multiple Web sites on the same server.
Global themes are like page themes in that they include property settings, style
sheet settings, and graphics. However, global themes are stored in a folder
named Themes that is global to the Web server. Any Web site on the server, and
any page in any Web site, can reference a global theme.
You can specify the precedence that theme settings take over local control
settings by specifying how the theme is applied.
If you set a page's Theme property, control settings in the theme and the page
are merged to form the final settings for the control. If a control setting is
defined in both the control and the theme, the control settings from the theme
override any page settings on the control. This strategy enables the theme to
create a consistent look across pages, even if controls on the pages already have
individual property settings. For example, it allows you to apply a theme to a
page you created in an earlier version of ASP.NET.
Alternatively, you can apply a theme as a style sheet theme by setting the
page's StyleSheetTheme property. In this case, local page settings take
precedence over those defined in the theme when the setting is defined in both
places. This is the model used by cascading style sheets. You might apply a
theme as a style sheet theme if you want to be able to set the properties of
individual controls on the page while still applying a theme for an overall look.
As a rule, you can use themes to define properties that concern a page or
control's appearance or static content. You can set only those properties that
have a ThemeableAttribute attribute set to true in the control class.
Properties that explicitly specify control behavior rather than appearance do not
accept theme values. For example, you cannot set
a Button control's CommandName property by using a theme. Similarly, you
cannot use a theme to set a GridView control's AllowPaging property
or DataSource property.
Note that you cannot use expression builders, which generate code expressions
for assignment in a page at compile time, in themes or skins.
Themes are similar to cascading style sheets in that both themes and style sheets
define a set of common attributes that can be applied to any page. However,
themes differ from style sheets in the following ways:
Themes do not cascade the way style sheets do. By default, any
property values defined in a theme referenced by a
page's Theme property override the property values declaratively set
on a control, unless you explicitly apply the theme using
the StyleSheetTheme property. For more information, see the Theme
Settings Precedence section above.
Only one theme can be applied to each page. You cannot apply
multiple themes to a page, unlike style sheets where multiple style
sheets can be applied.
Security Considerations
Themes can cause security issues when they are used on your Web site.
Malicious themes can be used to:
Alter validation.
Do not expose the theme name in query data. Malicious users could
use this information to use themes that are unknown to the developer
and thereby expose sensitive information.
You can apply themes to a page, a Web site, or globally. Setting a theme at the
Web site level applies styles and skins to all the pages and controls in the site
unless you override a theme for an individual page. Setting a theme at the page
level applies styles and skins to that page and all its controls.
By default, themes override local control settings. Alternatively, you can set a
theme as a style sheet theme, so that the theme applies only to control settings
that are not explicitly set on the control.
Copy
<configuration>
<system.web>
<pages theme="ThemeName" />
</system.web>
</configuration>
Note
If an application theme has the same name as a global application
theme, the page theme takes precedence.
Copy
<configuration>
<system.web>
<pages styleSheetTheme="Themename" />
</system.web>
</configuration>
A theme setting in the Web.config file applies to all ASP.NET Web pages in
that application. Theme settings in the Web.config file follow normal
configuration hierarchy conventions. For example, to apply a theme to only a
subset of pages, you can put the pages in a folder with their own Web.config
file or create a <location> element in the root Web.config file to specify a
folder. For details, see Configuring Specific Files and Subdirectories.
Copy
<%@ Page Theme="ThemeName" %>
<%@ Page StyleSheetTheme="ThemeName" %>
The theme and its corresponding styles and skins now applies only
to the page declaring it.
Skins defined in your theme apply to all control instances in the application or
pages to which the theme is applied. In some cases, you might want to apply a
specific set of properties to an individual control. You can do that by creating a
named skin (an entry in a .skin file that has a SkinID property set) and then
applying it by ID to individual controls.
To apply a named skin to a control
Copy
<asp:Calendar runat="server" ID="DatePicker"
SkinID="SmallCalendar" />
If the page theme does not include a control skin that matches the
SkinID property, the control uses the default skin for that control
type.
UNIT-3
ASP.NET – Validators
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.
ASP.NET provides the following validation controls:
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence
they inherit its properties and methods. Therefore, it would help to take a look at
the properties and the methods of this base class, which are common for all the
validation controls:
Members Description
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty.
It is generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.
It has three specific properties:
Properties Description
Type It defines the type of the data. The available values are:
Currency, Date, Double, Integer, and String.
</asp:RangeValidator>
CompareValidator Control
Properties Description
</asp:CompareValidator>
RegularExpressionValidator
\b Matches a backspace.
\t Matches a tab.
\r Matches a carriage return.
\ Escape character.
Apart from single character match, a class of characters could be specified that
can be matched, called the metacharacters.
Metacharacters Description
Quantifier Description
</asp:RegularExpressionValidator>
CustomValidator
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in specified format.
ShowMessageBox : shows the error messages in a separate
window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
Validation Groups
Example
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server"
style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:
</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server"
RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house
name" >
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:
</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:
</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\
w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true"
HeaderText="Errors:" />
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblmsg.Text = "Thank You";
}
else
{
lblmsg.Text = "Fill up all the fields";
}
}
Validation is important part of any web application. User's input must always be
validated before sending across different layers of the application.
Validation controls are used to,
Implement presentation logic.
To validate user input data.
Data format, data type and data range is used for validation.
Validation is of two types
1. Client Side
2. Serve Side
Client side validation is good but we have to be dependent on browser and
scripting language support.
Client side validation is considered convenient for users as they get instant
feedback. The main advantage is that it prevents a page from being postback to
the server until the client validation is executed successfully.
For developer point of view serve side is preferable because it will not fail, it is
not dependent on browser and scripting language.
You can use ASP.NET validation, which will ensure client, and server
validation. It work on both end; first it will work on client validation and than
on server validation. At any cost server validation will work always whether
client validation is executed or not. So you have a safety of validation check.
For client script .NET used JavaScript. WebUIValidation.js file is used for
client validation by .NET
All validation controls are rendered in form as <span> (label are referred as
<span> on client by server)
To make this happen, simply set the CauseValidation property to true for submit
button as shown below:
RequiredFieldValidation Control
It can most commonly be used when you need to confirm password entered by
the user at the registration time. The data is always case sensitive.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="
server" Style="top: 145px;
2. left: 367px; position: absolute; height: 26px; width: 162px" Err
orMessage="password required"
3. ControlToValidate="TextBox3"></
asp:RequiredFieldValidator>
RangeValidator Control
If you don't find your desired regular expression, you can create your custom
one.
Default.aspx Design
Default.aspx Source code
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="D
efault.aspx.cs" Inherits="_Default" %>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitiona
l//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
3. <html xmlns="http://www.w3.org/1999/xhtml">
4. <head runat="server">
5. <title>Untitled Page</title>
6. </head>
7. <body>
8. <form id="form1" runat="server">
9. <div>
10. <asp:Label ID="Label3" runat="server" Style="top: 241px; left:
70px; position: absolute;
11. height: 22px; width: 128px; bottom: 282px;" Text="Enter yo
ur email id:"></asp:Label>
12. <asp:Label ID="Label1" runat="server" Style="top: 54px; left:
74px; position: absolute;
13. height: 22px; width: 128px" Text="Enter your name:"></
asp:Label>
14. <asp:TextBox ID="TextBox1" runat="server" Style="top: 54px
; left: 221px; position: absolute;
15. height: 22px; width: 128px; right: 396px;"></asp:TextBox>
16. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ru
nat="server" Style="top: 56px;
17. left: 378px; position: absolute; height: 22px; width: 128px" E
rrorMessage="RequiredFieldValidator"
18. ControlToValidate="TextBox1">name is
19. mandatory </asp:RequiredFieldValidator>
20. </div>
21. <p>
22. <asp:Button ID="Button1" runat="server" Style="top: 311px; le
ft: 267px; position: absolute;
23. height: 26px; width: 61px" Text="Submit" />
24. </p>
25. <asp:TextBox ID="TextBox3" runat="server" Style="top: 145px;
left: 217px; position: absolute;
26. height: 22px; width: 131px" TextMode="Password"></
asp:TextBox>
27. <p>
28. <asp:TextBox ID="TextBox2" runat="server" Style="top: 101p
x; left: 218px; position: absolute;
29. height: 22px; width: 131px" TextMode="Password"></
asp:TextBox>
30. <asp:Label ID="Label4" runat="server" Style="top: 105px; left:
74px; position: absolute;
31. height: 22px; width: 128px" Text="Password"></asp:Label>
32. <asp:TextBox ID="TextBox5" runat="server" Style="top: 239p
x; left: 210px; position: absolute;
33. height: 22px; width: 134px"></asp:TextBox>
34. </p>
35. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat
="server" Style="top: 98px;
36. left: 367px; position: absolute; height: 26px; width: 162px" Err
orMessage="password required"
37. ControlToValidate="TextBox2"></
asp:RequiredFieldValidator>
38. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat
="server" Style="top: 145px;
39. left: 367px; position: absolute; height: 26px; width: 162px" Err
orMessage="password required"
40. ControlToValidate="TextBox3"></
asp:RequiredFieldValidator>
41. <asp:CompareValidator ID="CompareValidator1" runat="server"
Style="top: 149px; left: 512px;
42. position: absolute; height: 26px; width: 162px" ErrorMessage="
CompareValidator"
43. ControlToValidate="TextBox3" ValueToCompare="hello"></
asp:CompareValidator>
44. <p>
45. <asp:Label ID="Label5" runat="server" Style="top: 148px; left:
71px; position: absolute;
46. height: 22px; width: 128px; bottom: 375px;" Text="Confirm
Password"></asp:Label>
47. <asp:TextBox ID="TextBox4" runat="server" Style="top: 194p
x; left: 212px; position: absolute;
48. height: 22px; width: 140px"></asp:TextBox>
49. <asp:Label ID="Label6" runat="server" Style="top: 194px; left:
71px; position: absolute;
50. height: 22px; width: 128px; bottom: 329px;" Text="Enter yo
ur age:"></asp:Label>
51. </p>
52. <asp:RangeValidator ID="RangeValidator1" runat="server" Style
="top: 194px; left: 365px;
53. position: absolute; height: 22px; width: 105px" ErrorMessage="
RangeValidator"
54. ControlToValidate="TextBox4" MaximumValue="100" Minim
umValue="18" Type="Integer"></asp:RangeValidator>
55. <asp:RegularExpressionValidator ID="RegularExpressionValidat
or1" runat="server" Style="top: 234px;
56. left: 366px; position: absolute; height: 22px; width: 177px"
57. ErrorMessage="RegularExpressionValidator" ControlToValidat
e="TextBox5"
58. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+
([-.]\w+)*"></asp:RegularExpressionValidator>
59. </form>
60.</body>
61.</html>
CustomValidator Control
You can solve your purpose with ASP.NET validation control. But if you still
don't find solution you can create your own custom validator control.
The CustomValidator Control can be used on client side and server side.
JavaScript is used to do client validation and you can use any .NET language to
do server side validation.
I will explain you CustomValidator using server side. You should rely more on
server side validation.
To write CustomValidator on server side you override ServerValidate event.
Source Code
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="D
efault.aspx.cs" Inherits="_Default" %>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitiona
l//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
3. <html xmlns="http://www.w3.org/1999/xhtml">
4. <head runat="server">
5. <title>Untitled Page</title>
6. </head>
7. <body>
8. <form id="form1" runat="server">
9. <div>
10. <asp:Label ID="Label1" runat="server" Text="User ID:"></
asp:Label>
11. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
12. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat=
"server"
13. ControlToValidate="TextBox1" ErrorMessage="User id requ
ired"></asp:RequiredFieldValidator>
14.
15. <asp:CustomValidator ID="CustomValidator1" runat="server"
OnServerValidate="UserCustomValidate"
16. ControlToValidate="TextBox1"
17. ErrorMessage="User ID should have atleast a capital, small a
nd digit and should be greater than 5 and less
18.than 26 letters"
19. SetFocusOnError="True"></asp:CustomValidator>
20. </div>
21. <asp:Button ID="Button1" runat="server" onclick="Button1_Clic
k" Text="Submit" />
22. </form>
23.</body>
24.</html>
Code behind file
1. using System;
2. using System.Configuration;
3. using System.Data;
4. using System.Linq;
5. using System.Web;
6. using System.Web.Security;
7. using System.Web.UI;
8. using System.Web.UI.HtmlControls;
9. using System.Web.UI.WebControls;
10.using System.Web.UI.WebControls.WebParts;
11.using System.Xml.Linq;
12.
13.public partial class _Default : System.Web.UI.Page
14.{
15. protected void UserCustomValidate(object source, ServerValidat
eEventArgs args)
16. {
17. string str = args.Value;
18. args.IsValid = false;
19. //checking for input length greater than 6 and less than 25 charac
ters
20. if (str.Length < 6 || str.Length > 25)
21. {
22. return;
23. }
24. //checking for a atleast a single capital letter
25. bool capital = false;
26. foreach (char ch in str)
27. {
28. if (ch >= 'A' && ch <= 'Z')
29. {
30. capital = true;
31. break;
32. }
33. }
34. if (!capital)
35. {
36. return;
37. }
38. //checking for a atleast a single lower letter
39. bool lower = false;
40. foreach (char ch in str)
41. {
42. if (ch >= 'a' && ch <= 'z')
43. {
44. lower = true;
45. break;
46. }
47. }
48. if (!lower)
49. {
50. return;
51. }
52. bool digit = false;
53. foreach (char ch in str)
54. {
55. if (ch >= '0' && ch <= '9')
56. {
57. digit = true;
58. break;
59. }
60. }
61. if (!digit)
62. {
63. return;
64. }
65. args.IsValid = true;
66. }
67. protected void Page_Load(object sender, EventArgs e)
68. {
69. }
70. protected void Button1_Click(object sender, EventArgs e)
71. {
72. }
73.}
The server side validation you write does not need to provide the exact same
validation as that of the client side validation. The client side validation can
check for the user input data for range and type and server side validation can
check for matching of data with database. Both server side and client side
validation can be used for total solution.
ValidationSummary
ASP.NET has provided an additional control that complements the validator
controls.
You can use this validation control to consolidate errors reporting for all the
validation errors that occur on a page instead of leaving this up to each and
every individual validation control.
The validation summary control will collect all the error messages of all the
non-valid controls and put them in a tidy list.
1. <asp:ValidationSummary ID="ValidationSummary1" runat="server"
If you are using ValidationSummary than only ErrorMessage and Text property
is used.
Default.aspx Design
Default.aspx Source code
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="D
efault.aspx.cs" Inherits="_Default" %>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitiona
l//EN"
3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title>Untitled Page</title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. <asp:Label ID="Label1" runat="server" Style="top: 239px; left:
75px; position: absolute;
12. height: 22px; width: 128px" Text="Enter your Age:"></
asp:Label>
13.
14. <asp:Label ID="Label2" runat="server" Style="top: 94px; left:
81px; position: absolute;
15. height: 22px; width: 128px" Text="Enter your name:"></
asp:Label>
16. </div>
17. <asp:TextBox ID="TextBox1" runat="server" Style="top: 95px; l
eft: 250px; position: absolute;
18. height: 22px; width: 128px"></asp:TextBox>
19. <p>
20. <asp:TextBox ID="TextBox4" runat="server" Style="top: 195p
x; left: 249px; position: absolute;
21. height: 22px; width: 127px"></asp:TextBox>
22. </p>
23. <p>
24. <asp:Label ID="Label3" runat="server" Style="top: 148px; left:
76px; position: absolute;
25. height: 22px; width: 128px" Text="Enter Password:"></
asp:Label>
26. </p>
27. <p>
28. <asp:TextBox ID="TextBox3" runat="server" Style="top: 146p
x; left: 249px; position: absolute;
29. height: 22px; width: 127px" TextMode="Password"></
asp:TextBox>
30. </p>
31. <p>
32. <asp:Label ID="Label4" runat="server" Style="top: 197px; left:
75px; position: absolute;
33. height: 22px; width: 128px" Text="Confirm Password:"></
asp:Label>
34. </p>
35. <asp:TextBox ID="TextBox2" runat="server" Style="top: 236px;
left: 250px; position: absolute;
36. height: 22px; width: 127px" TextMode="Password"></
asp:TextBox>
37. <asp:CompareValidator ID="CompareValidator1" runat="server"
Style="top: 197px; left: 522px;
38. position: absolute; height: 22px; width: 17px" ErrorMessage="
CompareValidator"
39. ControlToCompare="TextBox2" ControlToValidate="TextBox
3">*</asp:CompareValidator>
40. <p>
41. <asp:Button ID="Button1" runat="server" Style="top: 333px; le
ft: 248px; position: absolute;
42. height: 26px; width: 56px" Text="Submit" />
43. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ru
nat="server" Style="top: 196px;
44. left: 393px; position: absolute; height: 22px; width: 22px" Er
rorMessage="Confirm Password mandatory & should match passwo
rd"
45. ControlToValidate="TextBox3">*</
asp:RequiredFieldValidator>
46. <asp:RangeValidator ID="RangeValidator1" runat="server" Sty
le="top: 235px; left: 388px;
47. position: absolute; height: 22px; width: 156px; bottom: 288p
x;" ErrorMessage="age between 18-100"
48. ControlToValidate="TextBox4" MaximumValue="100" Min
imumValue="18" Type="Integer">*</asp:RangeValidator>
49. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ru
nat="server" Style="top: 92px;
50. left: 393px; position: absolute; height: 22px; width: 156px" E
rrorMessage="Name is required"
51. ControlToValidate="TextBox1">*</
asp:RequiredFieldValidator>
52. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" ru
nat="server" Style="top: 146px;
53. left: 391px; position: absolute; height: 22px; width: 156px" E
rrorMessage="Password mandatory"
54. ControlToValidate="TextBox2">*</
asp:RequiredFieldValidator>
55. </p>
56. <asp:ValidationSummary ID="ValidationSummary1" runat="serv
er" Style="top: 390px;
57. left: 44px; position: absolute; height: 38px; width: 625px" />
58. </form>
59.</body>
60.</html>
Output of ValidationSummary program
ADO.NET Introduction
All the ADO.NET classes are located into System.Data.dll and integrated with
XML classes located into System.Xml.dll.
ADO.NET has two main components that are used for accessing and
manipulating data are the .NET Framework data provider and the DataSet.
These are the components that are designed for data manipulation and fast
access to data. It provides various objects such as Connection, Command,
DataReader and DataAdapter that are used to perform database operations.
We will have a detailed discussion about Data Providers in new topic.
There are two approaches to work with XML and ADO. First, you can use
ADO.NET to access XML documents. Second, you can use XML and
ADO.NET to access XML. Additionally, you can access a relational database
using ADO.NET and XML.NET.
In ADO.NET, you can access the data using the DataSet class. The DataSet
class implements methods and properties to work with XML documents. The
following sections discuss methods that read XML data.
In the following example, create a new DataSet object and call the DataSet.
ReadXml method to load the books.xml file in a DataSet object:
ds.ReadXml("books.xml");
Once you've a DataSet object, you know how powerful it is. Make sure you
provide the correct path of books.xml.
Note: Make sure you add a reference to System.Data and the
System.Data.Common namespace before using DataSet and other common data
components.
ds.ReadSchema(@"c:\books.xml");
The following example reads the file XmlReader and uses XmlTextReader as
the input of ReadXmlSchema:
ds.ReadXmlSchema(myXmlReader);
myXmlReader.Close();
Writing XML using Data Set
Not only reading, the DataSet class contains methods to write XML file from a
DataSet object and fill the data to the file.
The WriteXml method writes the current data (the schema and data) of a
DataSet object to an XML file. This is overloaded method. By using this
method, you can write data to a file, stream, TextWriter, or XmlWriter. This
example creates a DataSet, fills the data for the DataSet, and writes the data to
an XML file.
using System;
using System.IO;
using System.Xml;
using System.Data;
namespace XmlAndDataSetsampB2
class XmlAndDataSetSampCls
try
ds.Namespace = "StdNamespace";
stdTable.Columns.Add(col1);
stdTable.Columns.Add(col2);
ds.Tables.Add(stdTable);
stdTable.Rows.Add(newRow);
newRow = stdTable.NewRow();
newRow["Address"] = "NewYork";
stdTable.Rows.Add(newRow);
newRow = stdTable.NewRow();
stdTable.Rows.Add(newRow);
ds.AcceptChanges();
System.IO.StreamWriter(@"c:\stdData.xml");
ds.WriteXml(myStreamWriter);
myStreamWriter.Close();
catch (Exception e)
return;
}
}
You wouldn't believe the WriteXml method does for you. If you see the output
stdData.xml file, it generates a standard XML file that looks like listing 6-27.
<DS xmlns="StdNamespace">
<Student>
<Name>Mahesh Chand</Name>
</Student>
<Student>
<Name>Mike Gold</Name>
<Address>NewYork</Address>
</Student>
<Student>
<Name>Mike Gold</Name>
<Address>New York</Address>
</Student>
</DS>
using System;
using System.IO;
using System.Xml;
using System.Data;
namespace XmlAndDataSetsampB2
class XmlAndDataSetSampCls
ds.Namespace = "StdNamespace";
stdTable.Columns.Add(col1);
stdTable.Columns.Add(col2);
ds.Tables.Add(stdTable);
stdTable.Rows.Add(newRow);
newRow = stdTable.NewRow();
newRow["Address"] = "NewYork";
stdTable.Rows.Add(newRow);
ds.AcceptChanges();
ds.WriteXmlSchema(writer);
Console.ReadLine();
Console.ReadLine();
return;
}
XmlData Document and XML
As discussed earlier in this article, the XmlDocument class provides DOM tree
structure of XML documents. The XmlDataDocument class comes from
XmlDocument, which is comes from XmlNode.
Figure-6.10.gif
The xmlData Documet class has property called DataSet. It returns the attached
DataSet object with XmlDataDocument. The DataSet property provides you a
relational representation of an XML document. Once you've a DataSet object,
you can do anything with it such as attaching to a DataGrid.
You Can use all XML read and write methods of the DataSet object through the
DataSet property such as ReadXml, ReadXmlSchema, WriteXml, and
WriteXml schema. Refer to the DataSet read write methods in the previous
section to see how these methods are used.
You can use either the Load method or the LoadXml method to load an XML
document. The Load method takes a parameter of a filename string, a
TextReader, or an XmlReader. Similarly, you can use the LoadXml method.
This method passes an XML file name to load the XML file for example:
doc.Load("c:\\Books.xml");
A DataSet object has methods to read XML documents. These methods are
ReadXmlSchema and LoadXml. You use the Load or LoadXml methods to load
an XML document the same way you did directly from the
XMLDataDocument. Again the Load method takes a parameter of a filename
string, TextReader, or XmlReader. Similarly, use the LoadXml method to pass
an XML filename through the dataset. For example:
doc.DataSet.ReadXmlSchema("test. Xsd");
Or
xmlDatadoc.DataSet.ReadXml("c:\\ xmlDataDoc.xml");
dataGrid1.DataSource = xmlDatadoc.DataSet.DefaultViewManager;
Listing 6-29 shows the complete code. As you can see from Listing 6-29, I
created a new dataset, Books, fill from the books.xml and bind to a DataGrid
control using its DataSource property. To make Listing 6-29 work, you need to
create a Windows application and drag a DataGrid control to the form. After
doing that, you need to write the Listing 6-29 code on the Form1 constructor or
Form load event.
public Form1( )
xmlDatadoc.DataSet.ReadXml("C:\\books.xml");
// of XmlDataDocument
DataSet ds = new DataSet("Books DataSet");
ds = xmlDatadoc.DataSet;
dataGrid1.DataSource = ds.DefaultViewManager;
The output of this program looks like figure 6-12. Only a few lines code, and
you're all set. Neat huh?
Figure-6.12.gif
You can save a DataSet data as an XML document using the Save method of
XmlDataDocument. Actually, XmlDataDocument comes from XmlDocument.,
and the XmlDocument class defines the Save method. I've already discussed
that you can use Save method to save your data in a string, stream, TextWriter,
and XmlWriter.
First, you create a DataSet object and fill it using a DataAdapter. The following
example reads the Customers table from the Northwind Access database and
fills data from the read to the DataSet:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C: \\
Northwind.mdb";
// create a new dataset object and fill using data adapter's fill method
da.Fill(ds);
doc.Save("C:\\XmlDataDoc.xml");
using System;
using System.Data;
using System.Data.OleDb;
using System.Xml;
namespace DataDocsampB2
class Class1
// Connection string
string ConnectionString =
// create a new dataset object and fill using data adapter's fill method
doc.Save("C:\\XmlDataDoc.xml");
}
}
After Looking at Listing 6-29, which illustrated the reading an XML document
in a DataGrid control, you must be wondering how it happened? It's all the
magic of the DataSet object. The DataSet object handles everthing for under the
hood:
doc.DataSet.ReadXml("C:\\outdata.xml");
As you see in this first line calling DataSet.ReadXml method to read an XML
document. The DataSet extracts the document and defines tables and columns
for you.
Generally, the root node of the XML document becomes a table; the document's
Name, Namespace, NamespaceURI, and prefix of the XML document become
the dataset's Name, Namespace, NamespaceURI, and Prefix respectively. If an
element's children have one or more children, they become another table inside
the main table in a nested format. Anything left from the tables becomes
columns of the table. The value of node is added as a row in a table. DataSet
takes care of all of this under the hood.
The DataSet
It is used to access data independently from any data resource. DataSet contains
a collection of one or more DataTable objects of data. The following diagram
shows the relationship between .NET Framework data provider and DataSet.
Fig: ADO.NET Architecture
My previous article explained XML, XSLT and CSS. To learn more XSL and
the syntax refer to here.
There are two main components in XSLT that helps transformations, XSLT
Processor and XSL Formatter. First, the XSLT processor takes two inputs, a
XML document and a XSLT stylesheet. The XSLT processor starts from the
root node and then it goes for the root node's children. The processor searches
the stylesheet element to see if any template element and other XSLT elements
are defined. As per the defined XSLT rules it fetches data from the XML
document and generates a results tree in XML format. The XML formatter takes
input as a result tree and generates the final end products as HTML, text other
XML format.
Please see Figure 1 for a better understanding.
Step 1
In this step we will add a XML file (XMLFile1.xml) and design it.
Go to your project, Add New Item and click on Data section. Then select XML
file.
Figure 2: Adding XML document in project
Code
1. <?xml version="1.0" encoding="iso-8859-1"?>
2. <!-- Edited by XMLSpy® -->
3. <breakfast_menu>
4. <food>
5. <name>Biriyani</name>
6. <price>$5.95</price>
7. <description>Rice with chicken</description>
8. <calories>650</calories>
9. </food>
10. <food>
11. <name>Juice</name>
12. <price>$1.95</price>
13. <description>Fruit juices like mango, banana, apple</
description>
14. <calories>200</calories>
15. </food>
16.</breakfast_menu>
Step 2
In this step we need to add a XSLT file (XSLTFile1.xslt) and design it.
Use the following preceding, Step 1, to add the XSLT file. After adding the
XSLT file we need to design it.
Code
1. <?xml version="1.0" encoding="iso-8859-1"?>
2. <!-- Edited by XMLSpy® -->
3. <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/
Transform" xmlns="http://www.w3.org/1999/xhtml">
4. <body style="font-family:Arial;font-size:12pt;background-
color:#EEEEEE">
5. <xsl:for-each select="breakfast_menu/food">
6. <div style="background-
color:teal;color:white;padding:4px">
7. <span style="font-weight:bold">
8. <xsl:value-of select="name"/>
9. </span>
10. - <xsl:value-of select="price"/>
11. </div>
12. <div style="margin-left:20px;margin-bottom:1em;font-
size:10pt">
13. <xsl:value-of select="description"/>
14. <span style="font-style:italic">
15. <xsl:value-of select="calories"/> (calories per serving)
16. </span>
17. </div>
18. </xsl:for-each>
19. </body>
20.</html>
In the preceding XSLT file, we are using a for-each element that will match
XML nodes (breakfast_menu/food). It will collect all the nodes in XML data
that match depending on the defined pattern(breakfast_menu/food) and loop
over it. The value-of element displays the XML data. Lastly a div and span are
added to make the display the ofdata in the design format with inline styles.
Step 3
Now we are ready with the XML and XSLT file. Next we need to write code for
loading the XML data then transform and display it.
Here we can implement a XSL transformation in the following two ways:
1. With XML Control
2. XslCompiledTransform class Without XML control
1. With XML Control
ASP.NET has a XML control present in the Toolbox and using that control we
can do the XSL transformation.
Here I added a Label control to display the generated HTML content that is
generated from XML data. The following code can be used to transform XML
data from an XML file (tutorial.xml) using the XSLT file(tutorial.xslt).
Browse the aspx file and you can see output as in Figure 3.
Figure 3: Output of XSL Transformation in ASP.NET
If you go to the aspx view source then you will see the HTML tags generated
and bind it to the label control.
Please see Figure 4 showing how the XSL transformation generates HTML
output depending on the defined XSLT rules.
Figure 4: HTML output after XSL Transformation
ADO.NET DataSet
It is a collection of data tables that contain the data. It is used to fetch data
without interacting with a Data Source that's why, it also known
as disconnected data access method. It is an in-memory data store that can hold
more than one table at the same time. We can use DataRelation object to relate
these tables. The DataSet can also be used to read and write data as XML
document.
ADO.NET provides a DataSet class that can be used to create DataSet object. It
contains constructors and methods to perform data related operations.
DataSet Properties
Properties Description
CaseSensitive It is used to check whether DataTable objects are case-
sensitive or not.
DataSet Methods
Method Description
Example:
Here, in this example, we are implementing DataSet and displaying data into a
gridview. Create a web form and drag a gridview from the toolbox to the form.
We can find it inside the data category.
// DataSetDemo.aspx
CodeBehind
// DataSetDemo.aspx.cs
1. using System;
2. using System.Data.SqlClient;
3. using System.Data;
4. namespace DataSetExample
5. {
6. public partial class DataSetDemo : System.Web.UI.Page
7. {
8. protected void Page_Load(object sender, EventArgs e)
9. {
10. using (SqlConnection con = new SqlConnection("data source=.; d
atabase=student; integrated security=SSPI"))
11. {
12. SqlDataAdapter sde = new SqlDataAdapter("Select * from stud
ent", con);
13. DataSet ds = new DataSet();
14. sde.Fill(ds);
15. GridView1.DataSource = ds;
16. GridView1.DataBind();
17. }
18. }
19. }
20.}
Output:
Execute this code by the combination of Ctrl+F5. It will produce the following
output.
ADO.NET DataAdapter
Example
// DataSetDemo.aspx
Output: