Programming Using Asp Dot Net Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 138

PROGRAMMING USING ASP DOT NET

UNIT-1
Asp.Net Overview:

ASP.NET is a Microsoft Web Development Framework. It is a part of the .NET


Platform. ASP.NET is used to build single page applications, dynamic
applications, enterprise applications, and online banking applications etc.

Let’s discuss the different models of ASP.NET Framework.

 NET Web Pages


 Net Web Forms
 NET MVC

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.

ASP.NET is a unified Web development model that includes the services


necessary for you to build enterprise-class Web applications with a minimum of
coding. ASP.NET is part of the .NET Framework, and when coding ASP.NET
applications you have access to classes in the .NET 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:

 A page and controls framework


 The ASP.NET compiler
 Security infrastructure
 State-management facilities
 Application configuration
 Health monitoring and performance features
 Debugging support
 An XML Web services framework
 Extensible hosting environment and application life cycle management
 An extensible designer environment

Don’t Confuse Framework, Modals, Libraries


Remember that

 .NET itself is a Platform which has many frameworks inside

o Net (Web Framework)

 Net Web Pages (Modal)


 Net Web Form (Modal)
 Net MVC (Modal)

o .Net Core (New Platform)

 Net Core (Web Framework)

 Net Web Pages (Framework)


 Net MVC (Modal)

.NET Core is actually using MVC 6.


Model Skills Development style Experience

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

w3school is the most known website to learn any web-based technology. It is


built on the top of web pages frameworks of ASP.NET. In Web Pages, client-
side code and server-side code are placed at the same page. It is similar to PHP,
and now it is called classic (old) ASP. If you want to build an application which
is something dynamic or partially dynamic, then you may prefer 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.

We can create multiple types of application using ASP.NET

1. Desktop Application : This type of application we need to


install it on windows operating system. For e.g. MS Office.
2. Web application : These types of application run in web
browser like Internet explorer or chrome.it need internet
connection.
We can create two types of web applications.

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

Millions of businesses use the Internet as a cost-effective communications


channel. It lets them exchange information with their target market and make
fast, secure transactions. However, effective engagement is only possible when
the business is able to capture and store all the necessary data, and have a means
of processing this information and presenting the results to the user.

Web applications use a combination of server-side scripts (PHP and ASP) to


handle the storage and retrieval of the information, and client-side scripts
(JavaScript and HTML) to present information to users. This allows users to
interact with the company using online forms, content management systems,
shopping carts and more. In addition, the applications allow employees to create
documents, share information, collaborate on projects, and work on common
documents regardless of location or device.

How a web application works

Web applications are usually coded in browser-supported language such as


JavaScript and HTML as these languages rely on the browser to render the
program executable. Some applications are dynamic, requiring server-side
processing. Others are completely static with no processing required at the
server.

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.

Here’s what a typical web application flow looks like:

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

Example of a web application

Web applications include online forms, shopping carts, word processors,


spreadsheets, video and photo editing, file conversion, file scanning, and email
programs such as Gmail, Yahoo and AOL. Popular applications include Google
Apps and Microsoft 365.

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.

Benefits of a web application

 Web applications run on multiple platforms regardless of OS or device as


long as the browser is compatible
 All users access the same version, eliminating any compatibility issues
 They are not installed on the hard drive, thus eliminating space
limitations
 They reduce software piracy in subscription-based web applications (i.e.
SaaS)
 They reduce costs for both the business and end user as there is less
support and

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

 Deliver static content.


 Content is delivered using the HTTP protocol only.

 Serves only web-based applications.


 No support for multi-threading.
 Facilitates web traffic that is not very resource intensive.

What is IIS?

IIS (Internet Information Services) is Microsoft’s web server offering, playing


second fiddle to market leader Apache. As is expected of a core Microsoft
product, it only runs and is bundled on Windows operating systems, but is
otherwise free for use. It is a closed software product and supported by solely
by Microsoft. Although development is not as open and quick as the open-
source user-supported nature of Apache, a behemoth like Microsoft can throw
formidable support and development resources at its products, and IIS has
fortunately benefitted from this. Actually it is one of the few Microsoft products
that even its detractors (grudgingly) agree can stand toe-to-toe with its open
source rival and even trounce it soundly in some areas. There is a lite version
called IIS Express that has been installable as a standalone freeware server from
Windows XP SP3 onwards. But this version only supports http and https.

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.

To install the Web Server (IIS) server role

To complete this procedure, you must be a member of


the Administrators group.

Note

To perform this procedure by using Windows PowerShell, open PowerShell,


type the following command, and then press ENTER. Install-WindowsFeature
Web-Server -IncludeManagementTools

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.

3. On the Installation Type page, click Next.


4. On the Server selection page, click Next.
5. On the Server roles page, select Web Server (IIS), and then click Next.
6. Click Next until you have accepted all of the default web server settings,
and then click Install.
7. Verify that all installations were successful, and then click Close.

Apache Web Server

 Apache, an open-source Web server created by


American software developer Robert McCool. Apache was released in 1995.
In the early 2020s, Apache servers deployed about 30 percent of
the Internet’s content, second only to Nginx.

 As a Web server, Apache is responsible for accepting directory (HTTP)


requests from Internet users and sending them their desired information in
the form of files and Web pages.

 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.

 The Apache server’s impact on the open-source software community is


partly explained by the unique license through which software from the
Apache Software Foundation is distributed.
 Apache was originally known as the NCSA HTTPd Web server and was
written by McCool when he was an undergraduate at the National Center for
Supercomputing Applications (NCSA) at the University of Illinois at
Urbana-Champaign.

 Apache is maintained and developed by a large community of volunteers and


developers from the Apache Software Foundation, as well as by
contributions from users worldwide.

Features of Apache Web Server

 Handling of static files


 Loadable dynamic modules
 Auto-indexing
 .htaccess
 Compatible with IPv6
 Supports HTTP/2
 FTP connections
 Gzip compression and decompression
 Bandwidth throttling
 Perl, PHP, Lua scripts
 Load balancing
 Session tracking
 URL rewriting
 Geolocation based on IP address

How does Apache Web Server Work?

Apache functions as a way to communicate over networks from client to server


using the TCP/IP protocol. Apache can be used for a wide variety of protocols,
but the most common is HTTP/S. HTTP/S or Hyper Text Transfer Protocol (S
stands for Secure) is one of the main protocols on the web, and the one protocol
Apache is most known for.

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.

Once a message reaches its destination or recipient, it sends a notice, or ACK


message, basically giving acknowledgment to the original sender that their data
has successfully arrived. If there’s an error in receiving data, or some packets
were lost in transit, the destination host or client sends a Not Acknowledged, or
NAK message, to inform the sender that the data needs to be retransmitted.

Who Uses Apache Web Server?

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.

Alternatives for Apache HTTP Server

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?

Definitions for 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.

 In simple terms a browser can be defined as “A software application used


to locate and display Web pages"

 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.

Most Commonly Used Languages

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 is not a programming language. But you should consider it as the


starting point of web development. HTML is where every budding web
developer starts.

What are the features of HTML?

HTML has all the features you want in a web development language.

 It is a platform-independent web programming language because you can


run it on any browser.
 You can embed any image, video, and audio to the web page.
 HTML markups all the texts inside the web design code. These markups
tell the browser to display texts and multimedia on a web page.
 HTML defines unique tags to maintain the semantic structure of the web
page.
What are the pros of HTML?

HTML, as a language for web development, has many advantages.

 HTML is used by 94.5% of the websites


 HTML-based websites run on every browser
 Simple to learn, use, and launch a website
 HTML makes a website fast as it is lightweight
 HTML doesn’t need any software.
 HTML comes by default in every system
 The loose syntax makes web programming easier to learn and use
 HTML is very easy to write
What are the cons of HTML?

 HTML is a static language


 You can’t create dynamic output with HTML alone
 Easy web pages may demand tons of coding
 HTML has weaker security features

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.

Like HTML, CSS is not a programming language. Since you’re only


determining the style of the webpage you’re developing, it makes sense not to
call it a programming language. But it’s a fundamental tech skill you should
know to design the website

JavaScript is a lightweight, interpreted programming language. It is designed


for creating network-centric applications. It is complimentary to and integrated
with Java. JavaScript is very easy to implement because it is integrated with
HTML. It is open and cross-platform.
Javascript

Javascript is a MUST for students and working professionals to become a great


Software Engineer specially when they are working in Web Development
Domain. I will list down some of the key advantages of learning Javascript:
 Javascript is the most popular programming language in the world
and that makes it a programmer’s great choice. Once you learnt
Javascript, it helps you developing great front-end as well as back-
end softwares using different Javascript based frameworks like
jQuery, Node.JS etc.
 Javascript is everywhere, it comes installed on every modern web
browser and so to learn Javascript you really do not need any
special environment setup. For example Chrome, Mozilla Firefox ,
Safari and every browser you know as of today, supports
Javascript.
 Javascript helps you create really beautiful and crazy fast websites.
You can develop your website with a console like look and feel and
give your users the best Graphical User Experience.
 JavaScript usage has now extended to mobile app development,
desktop app development, and game development. This opens
many opportunities for you as Javascript Programmer.
 Due to high demand, there is tons of job growth and high pay for
those who know JavaScript. You can navigate over to different job
sites to see what having JavaScript skills looks like in the job
market.
 Great thing about Javascript is that you will find tons of
frameworks and Libraries already developed which can be used
directly in your software development to reduce your time to
market.

What are the features of CSS?

CSS is one of the web languages which gives you massive control over web
design.

 CSS helps you control various styles


 You can customize text color and font size
 CSS lets you put spaces among paragraphs
 You have greater control over size and layout
 You can customize background images and colors more efficiently
 CSS also allows setting displays for multiple screens and devices
 CSS also controls HTML documents
 HTML and XHTML are easy to integrate with CSS
What are the pros of CSS?

CSS, as a web developer’s language, has plenty of benefits. Here’re some you’d
want to explore.

 CSS ensures faster speed for your website


 It needs less coding for a big effect on the webpage
 CSS is easy to manage
 CSS applies consistent styling elements on the web pages
 It saves a lot of time with short and efficient coding/maintenance
 CSS gives device compatibility to the website design
 You can change the position of HTML with CSS
What are the cons of CSS?

 Different CSS levels create confusion among beginner web developers


 CSS offers limited security features
 It demands compatibility testing across all the browsers.
 Compatibility testing may increase the workload for developers
Understanding HTTP Basics

HTTP stands for hypertext transfer protocol and is used to


transfer data across the Web.

It is a critical protocol for web developers to understand and because of it


widespread use it is also used in transferring data and commands in IOT
applications.

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 client makes a request and the server responds.

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:

 All requests originate at the client ( your browser)


 The server responds to a request.
 The requests(commands) and responses are in readable text.
 The requests are independent of each other and the server doesn’t need
to track the requests.
Request and Response Structure

Request and response message structures are the same and shown below:

A request consists of:

A command or request + optional headers + optional body content.

A response consists of:

A status code + optional headers + optional body content.

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.

The presence of a message body in a request is signalled by a Content-


Length or Transfer-Encoding header field. Request message framing is
independent of method semantics, even if the method does not define any use for
a message body. – RFC 7230 section 3.3.

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:

Method + Resource Path + protocol version

Example if we try to access the web page testpage.htm on www.testsite5.com

The the start line of the request would be

GET /test.htm HTTP/1.1

Where

 GET is the method


 /testpage.htm is the relative path to the resource.
 HTTP/1.1 is the protocol version we are using

Notes:

1. A relative path doesn’t include the domain name.


2. The web browser uses the URL that we enter to create the relative
URI of the resource.

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.

HTTP Responses and Response Codes

Each request has a response. The Response consists of a

 STATUS code And Description


 1 or more optional headers
 Optional Body message can be many lines including binary data

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.

You can find a complete list and their meaning here

Request Response Example

We are going to examine he requests and response when we access a simple


web page (testpage.htm)

Here is what I enter in the browser address bar:

and this is the response that the browser displays:

and here is a screen shot of the http request-response that happens behind the
scenes.
What is TCP/IP?

TCP/IP stands for Transmission Control Protocol / Internet Protocol. It defines


how electronic devices (like computers) should be connected over the Internet,
and how data should be transmitted between them.

TCP/IP stands for Transmission Control Protocol/Internet Protocol and is a suite


of communication protocols used to interconnect network devices on the
internet. TCP/IP is also used as a communications protocol in a private
computer network (an intranet or extranet).
The entire IP suite -- a set of rules and procedures -- is commonly referred to as
TCP/IP. TCP and IP are the two main protocols, though others are included in
the suite. The TCP/IP protocol suite functions as an abstraction layer between
internet applications and the routing and switching fabric.

TCP - Transmission Control Protocol

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

IP takes care of the communication between computers. It is responsible for


addressing, sending and receiving the data packets over the Internet.

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.

Common TCP/IP protocols include the following:

 Hypertext Transfer Protocol (HTTP) handles the communication


between a web server and a web browser.
 HTTP Secure handles secure communication between a web server
and a web browser.
 File Transfer Protocol handles transmission of files between
computers.
How does TCP/IP work?
TCP/IP uses the client-server model of communication in which a user or
machine (a client) is provided a service, like sending a webpage, by another
computer (a server) in the network.

Collectively, the TCP/IP suite of protocols is classified as stateless, which


means each client request is considered new because it is unrelated to previous
requests. Being stateless frees up network paths so they can be used
continuously.

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.

Why is TCP/IP important?


TCP/IP is nonproprietary and, as a result, is not controlled by any single
company. Therefore, the IP suite can be modified easily. It is compatible with
all operating systems (OSes), so it can communicate with any other system. The
IP suite is also compatible with all types of computer hardware and networks.

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.

The 4 layers of the TCP/IP model


TCP/IP functionality is divided into four layers, each of which includes specific
protocols:

1. The application layer provides applications with standardized data


exchange. Its protocols include HTTP, FTP, Post Office Protocol
3, Simple Mail Transfer Protocol and Simple Network Management
Protocol. At the application layer, the payload is the actual application
data.
2. The transport layer is responsible for maintaining end-to-end
communications across the network. TCP handles communications
between hosts and provides flow control, multiplexing and reliability.
The transport protocols include TCP and User Datagram Protocol,
which is sometimes used instead of TCP for special purposes.
3. The network layer, also called the internet layer, deals with packets
and connects independent networks to transport the packets across
network boundaries. The network layer protocols are IP and Internet
Control Message Protocol, which is used for error reporting.
4. The physical layer, also known as the network interface layer or data
link layer, consists of protocols that operate only on a link -- the
network component that interconnects nodes or hosts in the network.
The protocols in this lowest layer include Ethernet for local area
networks and Address Resolution Protocol.
5.
Uses of TCP/IP
TCP/IP can be used to provide remote login over the network for interactive file
transfer to deliver email, to deliver webpages over the network and to remotely
access a server host's file system. Most broadly, it is used to represent how
information changes form as it travels over a network from the concrete
physical layer to the abstract application layer. It details the basic protocols, or
methods of communication, at each layer as information passes through.

Pros and cons of TCP/IP


The advantages of using the TCP/IP model include the following:

 helps establish a connection between different types of computers;


 works independently of the OS;
 supports many routing protocols;
 uses client-server architecture that is highly scalable;
 can be operated independently;
 supports several routing protocols; and
 is lightweight and doesn't place unnecessary strain on a network or
computer.

The disadvantages of TCP/IP include the following:

 is complicated to set up and manage;


 transport layer does not guarantee delivery of packets;
 is not easy to replace protocols in TCP/IP;
 does not clearly separate the concepts of services, interfaces and
protocols, so it is not suitable for describing new technologies in new
networks; and
 is especially vulnerable to a synchronization attack, which is a type of
denial-of-service attack in which a bad actor uses TCP/IP.
TCP/IP Protocols For the Web

Web browsers and servers use TCP/IP protocols to connect to the Internet.
Common TCP/IP protocols are:

HTTP - Hyper Text Transfer Protocol

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 - Secure HTTP

HTTPS takes care of secure communication between a web server and a web
browser. HTTPS typically handles credit card transactions and other sensitive
data.

FTP - File Transfer Protocol

FTP takes care of transmission of files between computers.

IP is Connection-Less

IP is a "connection-less" communication protocol.

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

When an IP packet is sent from a computer, it arrives at an IP router.


The IP router is responsible for "routing" the packet to the correct destination,
directly or via another router.

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.

Analogy: Communicating via IP is like sending a long letter as a large number


of small postcards, each finding its own (often different) way to the receiver.

IP Addresses

IP uses 32 bits, or four numbers between 0 and 255, to address a computer.

IP addresses are normally written as four numbers separated by a period, like


this: 192.168.1.50.

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.

This is an IP address: 192.68.20.50. This might be the same address:


www.w3schools.com

This is your IP address: 108.161.252.158

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:

00000000, 00000001, 00000010, 00000011, 00000100, 00000101, 00000110,


00000111, 00001000 .......and all the way up to 11111111.

Domain Names

A name is much easier to remember than a 12 digit number.

Names used for TCP/IP addresses are called domain names.

w3schools.com is a domain name.


When you address a web site, like http://www.w3schools.com, the name is
translated to a number by a Domain Name Server (DNS).

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.

TCP/IP Protocols for Email

E-mail programs use TCP/IP for sending and receiving e-mails. The TCP/IP
protocols for email are:

SMTP - Simple Mail Transfer Protocol

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.

MIME - Multi-purpose Internet Mail Extensions

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.

POP - Post Office Protocol

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.

IMAP - Internet Message Access Protocol

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.

Other TCP/IP Protocols

ARP - Address Resolution Protocol

ARP is used by IP to find the hardware address of a computer network card


based on the IP address.

BOOTP - Boot Protocol

BOOTP is used for booting (starting) computers from the network.

DHCP - Dynamic Host Configuration Protocol

DHCP is used for allocation of dynamic IP addresses to computers in a network.

ICMP - Internet Control Message Protocol

ICMP takes care of error-handling in the network.

LDAP - Lightweight Directory Access Protocol

LDAP is used for collecting information about users and e-mail addresses from
the internet.

NTP - Network Time Protocol

NTP is used to synchronize the time (the clock) between computers.

PPTP - Point to Point Tunneling Protocol

PPTP is used for setting up a connection (tunnel) between private networks.

RARP - Reverse Address Resolution Protocol

RARP is used by IP to find the IP address based on the hardware address of a


computer network card.

SNMP - Simple Network Management Protocol

SNMP is used for administration of computer networks.


SSL - Secure Sockets Layer

The SSL protocol is used to encrypt data for secure data transmission.

TLS - Transport Layer Security

The TLS protocol is a newer and more secure version of SSL.

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.

Websites and web applications

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.

Framework If you have Development style Expertise


experience in
Web Forms Win Forms, Rapid development using a rich library of Mid-Level,
WPF, .NET controls that encapsulate HTML markup Advanced
RAD
MVC Ruby on Full control over HTML markup, code Mid-Level,
Rails, .NET and markup separated, and easy to write Advanced
tests. The best choice for mobile and
single-page applications (SPA).
Web Pages Classic ASP, HTML markup and your code together in New, Mid-
PHP the same file Level
Web Forms

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 MVC gives you a powerful, patterns-based way to build dynamic


websites that enables a clean separation of concerns and that gives you full
control over markup for enjoyable, agile development. ASP.NET MVC includes
many features that enable fast, TDD-friendly development for creating
sophisticated applications that use the latest web standards.

ASP.NET Web Pages

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.

What is .Net Framework?


.Net Framework is a software development platform developed by Microsoft
for building and running Windows applications. The .Net framework consists of
developer tools, programming languages, and libraries to build desktop and web
applications. It is also used to build websites, web services, and games.
The .Net framework was meant to create applications, which would run on the
Windows Platform. The first version of the .Net framework was released in the
year 2002. The version was called .Net framework 1.0. The Microsoft .Net
framework has come a long way since then, and the current version is .Net
Framework 4.7.2.
The Microsoft .Net framework can be used to create both – Form-
based and Web-based applications. Web services can also be developed using
the .Net framework.
The framework also supports various programming languages such as Visual
Basic and C#. So developers can choose and select the language to develop the
required application. In this chapter, you will learn some basics of the .Net
framework.
In this .Net Architecture tutorial, you will learn .NET Framework basics-

 .Net Framework Architecture


 .NET Components
 .Net Framework Design Principle

.Net Framework Architecture


.Net Framework Architecture is a programming model for the .Net platform
that provides an execution environment and integration with various
programming languages for simple development and deployment of various
Windows and desktop applications. It consists of class libraries and reusable
components.

The basic architecture of the .Net framework is as shown below.

.Net Framework Architecture Diagram

.NET Components
The architecture of .Net framework is based on the following key components;

1. Common Language Runtime


The “Common Language Infrastructure” or CLI is a platform in .Net
architecture on which the .Net programs are executed.

The CLI has the following key features:

Exception Handling – Exceptions are errors which occur when the application
is executed.

Examples of exceptions are:

 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.

Garbage Collection – Garbage collection is the process of removing unwanted


resources when they are no longer required.

Examples of garbage collection are

 A File handle which is no longer required. If the application has finished


all operations on a file, then the file handle may no longer be required.
 The database connection is no longer required. If the application has
finished all operations on a database, then the database connection may
no longer be required.

Working with Various programming languages –

As noted in an earlier section, a developer can develop an application in a


variety of .Net programming languages.

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)

A namespace is a logical separation of methods. We will learn these


namespaces more in detail in the subsequent chapters.

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.

 The Web application would be processed on a server, which would have


Internet Information Services Installed.
 Internet Information Services or IIS is a Microsoft component which is
used to execute an Asp.Net application.
 The result of the execution is then sent to the client machines, and the
output is shown in the browser.

ADO.Net – This technology is used to develop applications to interact with


Databases such as Oracle or Microsoft SQL Server.

Microsoft always ensures that .Net frameworks are in compliance with all the
supported Windows operating systems.

.Net Framework Design Principle


Now in this .Net Architecture tutorial, we will learn the design priciples of .Net
framework. The following design principles of the .Net framework is what
makes it very relevant to create .Net based applications.

1) Interoperability – The .Net framework provides a lot of backward support.


Suppose if you had an application built on an older version of the .Net
framework, say 2.0. And if you tried to run the same application on a machine
which had the higher version of the .Net framework, say 3.5. The application
would still work. This is because with every release, Microsoft ensures that
older framework versions gel well with the latest version.

2) Portability – Applications built on the .Net framework can be made to work


on any Windows platform. And now in recent times, Microsoft is also
envisioning to make Microsoft products work on other platforms, such as iOS
and Linux.

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.

The compiler adds a default namespace. This unnamed namespace, sometimes


referred to as the global namespace, is present in every file. It contains
declarations not included in a declared namespace. Any identifier in the global
namespace is available for use in a named namespace.

Namespaces implicitly have public access. For a discussion of the access


modifiers you can assign to elements in a namespace

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

1) The System.Web namespace

System.web namespace holds some basic ingredients which includes classes


and built-in Objects like
a. Server
b. Application
c. Request
d. Response

And Classes used for managing

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.

2) The System.Web.services namespace

The System.Web.services namespace is a initial point for creating the web


services. It contains web service classes , which allow to create XML web
services using Asp.Net . XML web services provides feature to exchange
messages in loosely coupled environment. using protocol like SOAP , HTTP ,
XML .
Some classes are as follows
a. WebMethodAttribute
b. Webservice
c. WebServiceAttribute
d. WebServiceBindingAttribute

3) The System.web.UI.WebControls namespace

The System.web.UI.WebControls namespace contains classes that provides to


create web server controls on web pages. These controls run on the server so we
can programmaticaly control elements . It also include form controls like text
boxes and buttons. special purpose controls such as calender , and Data Grid .
Web controls are more abstract than HTML controls . They also provide a
shophisticated formatting properties and events . The
System.web.UI.WebControls namespace contains web control class which is
the base class for all web controls

Some classes are as follows


a. Calendar
b. Check Box
c. Button
d. Base Data Bound Control
e. Data Control Field etc

4) The System.web.UI namespace

The System.web.UI namespace includes classes that allows to create server


controls with data- binding functionality , which has ability to save view state of
given control and pages (.aspx pages) . Many of these types allows to support
for controls System.web.UI .Html controls. It is a base class for all
HTML ,Web, and User Controls. Every aspx pages comes under it. Control
classes provides common set of functionslity

There are following controls available


 HTML server controls
 Web server controls
 User controls

Some classes are as follows

a. Attribute Collection
b. BaseParser
c. BaseTemplateParser
d. AsyncPostBackTrigger etc

5) The System.web.sessionstate namespace

Session state management comes under The System.web.sessionstate


namespace . That enable storage of data specific to a single client with in a web
application on the server. Session state is ideal for sensitive data such as mailing
address , credit card number , password , important numbers etc. Sesssion state
can be used with clients that do not support cookies.

Some classes are as follows


a. HttpSessionState
b. HttpSessionStateContainer
c. SessionIDManager
d. SessionStateModule etc
What is an IDE?

An IDE, or Integrated Development Environment, enables programmers to


consolidate the different aspects of writing a computer program.

IDEs increase programmer productivity by combining common activities of


writing software into a single application: editing source code, building
executables, and debugging.

Editing Source Code


Writing code is an important part of programming. We start with a blank file,
write a few lines of code, and a program is born! IDEs facilitate this process
with features like syntax highlighting and autocomplete.

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.

Compare these two code samples:

// without syntax highlighting

public class NiceDay {


public static void main(String[] args) {
System.out.println("It's a nice day out!");
}
}
// with syntax highlighting

public class NiceDay {


public static void main(String[] args) {
System.out.println("It's a nice day out!");
}
}
Syntax highlighting makes code easier to read by visually clarifying different
elements of language syntax.
Autocomplete
When the IDE knows your programming language, it can anticipate what you’re
going to type next!

We’ve seen statements with System.out.println() quite a bit so far. In an IDE,


we might see System as an autocomplete option after only typing Sy. This saves
keystrokes so the programmer can focus on logic in their code.

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.

Coding On Your Computer

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

ASP.NET Web Forms

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.

We can use Visual Studio to create ASP.NET Web Forms. It is an IDE


(Integrated Development Environment) that allows us to drag and drop server
controls to the web forms. It also allows us to set properties, events and methods
for the controls. To write business logic, we can choose any .NET language
like: Visual Basic or Visual C#.

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.

Fig: This diagram shows the components of the ASP.NET

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.

ASP.NET Web Forms Features

ASP.NET is full of features and provides an awesome platform to create and


develop web application. Here, we are discussing these features of Web Forms.

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.

Working with Data

In an ASP.NET Web Forms application, we use data-bound controls to


automate the presentation or input of data in web page UI elements such as
tables and text boxes and drop-down lists.

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.

Client Script and Client Frameworks

We can enhance the server-based features of ASP.NET by including client-


script functionality in ASP.NET Web Form pages. We can use client script to
provide a richer, more responsive user interface to the users. We can also use
client script to make asynchronous calls to the Web server while a page is
running in the browser.
Routing

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

Developing a secure application is most important aspect of software


development process. ASP.NET Web Forms allow us to add extensibility points
and configuration options that enable us to customize various security behaviors
in the application.

Performance

Web Forms provides good performance and allows us to modify performance


related to page and server control processing, state management, data access,
application configuration and loading, and efficient coding practices.

Debugging and Error Handling

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.

the basic controls available in ASP.NET.

Button Controls

ASP.NET provides three types of button control:


 Button : It displays text within a rectangular area.
 Link Button : It displays text that looks like a hyperlink.
 Image Button : It displays an image.
When a user clicks a button, two events are raised: Click and Command.
Basic syntax of button control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Click" / >
Common properties of the button control:

Property Description

Text The text displayed on the button. This is for button and
link button controls only.

ImageUrl For image button control only. The image to be displayed


for the button.

AlternateText For image button control only. The text to be displayed if


the browser cannot display the image.

CausesValidation Determines whether page validation occurs when a user


clicks the button. The default is true.

CommandName A string value that is passed to the command event when


a user clicks the button.

CommandArgument A string value that is passed to the command event when


a user clicks the button.

PostBackUrl The URL of the page that is requested when the user
clicks the button.

Text Boxes and Labels

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

TextMode Specifies the type of text box. SingleLine creates a


standard text box, MultiLIne creates a text box that
accepts more than one line of text and the Password
causes the characters that are entered to be masked. The
default is SingleLine.

Text The text content of the text box.

MaxLength The maximum number of characters that can be entered


into the text box.

Wrap It determines whether or not text wraps automatically for


multi-line text box; default is true.

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.

Rows The height of a multi-line text box in lines. The default


value is 0, means a single line text box.

The mostly used attribute for a label control is 'Text', which implies the text
displayed on the label.

Check Boxes and Radio Buttons

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.

Checked Specifies whether it is selected or not, default is false.

GroupName Name of the group the control belongs to.

List Controls

ASP.NET provides the following controls


 Drop-down list,
 List box,
 Radio button list,
 Check box list,
 Bulleted list.
These control let a user choose from one or more items from the list. List boxes
and drop-down lists contain one or more list items. These lists can be loaded
either by code or by the ListItemCollection editor.
Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax of drop-down list control:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common properties of list box and drop-down Lists:
Property Description

Items The collection of ListItem objects that represents the


items in the control. This property returns an object of
type ListItemCollection.

Rows Specifies the number of items displayed in the box. If


actual list contains more rows than displayed then a scroll
bar is added.

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 ("").

SelectionMode Indicates whether a list box allows single selections or


multiple selections.

Common properties of each list item objects:

Property Description

Text The text displayed for the item.

Selected Indicates whether the item is selected.

Value A string value associated with the item.

It is important to notes that:


 To work with the items in a drop-down list or list box, you use the
Items property of the control. This property returns a
ListItemCollection object which contains all the items of the list.
 The SelectedIndexChanged event is raised when the user selects a
different item from a drop-down list or list box.

The ListItemCollection

The ListItemCollection object is a collection of ListItem objects. Each ListItem


object represents one item in the list. Items in a ListItemCollection are
numbered from 0.
When the items into a list box are loaded using strings like:
lstcolor.Items.Add("Blue"), then both the Text and Value properties of the list
item are set to the string value you specify. To set it differently you must create
a list item object and then add that item to the collection.
The ListItemCollection Editor is used to add item to a drop-down list or list
box. This is used to create a static list of items. To display the collection editor,
select edit item from the smart tag menu, or select the control and then click the
ellipsis button from the Item property in the properties window.
Common properties of ListItemCollection:

Property Description

Item(integer) A ListItem object that represents the item at the specified


index.

Count The number of items in the collection.

Common methods of ListItemCollection:

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.

Add(ListItem) Adds a new item at the end of the collection.

Insert(integer, string) Inserts an item at the specified index location in the


collection, and assigns 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.

Remove(ListItem) Removes the specified item.

RemoveAt(integer) Removes the item at the specified index as the integer.

Clear Removes all the items of the collection.

FindByValue(string) Returns the item whose value is same as the string.

FindByValue(Text) Returns the item whose text is same as the string.


Radio Button list and Check Box list

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

RepeatLayout This attribute specifies whether the table tags or the


normal html flow to use while formatting the list when it
is rendered. The default is Table.

RepeatDirection It specifies the direction in which the controls to be


repeated. The values available are Horizontal and
Vertical. Default is Vertical.

RepeatColumns It specifies the number of columns to use when repeating


the controls; default is 0.

Bulleted lists and Numbered lists

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.

RepeatDirection It specifies the direction in which the controls to be


repeated. The values available are Horizontal and
Vertical. Default is Vertical.

RepeatColumns It specifies the number of columns to use when repeating


the controls; default is 0.

HyperLink Control

The HyperLink control is like the HTML <a> element.


Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
It has the following important properties:

Property Description

ImageUrl Path of the image to be displayed by the control.

NavigateUrl Target link URL.

Text The text to be displayed as the link.

Target The window or frame which loads the linked page.

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

AlternateText Alternate text to be displayed in absence of the image.

ImageAlign Alignment options for the control.

ImageUrl Path of the image to be displayed by the control.

Server Controls

The following table contains the server-side controls for the Web Forms.

Control Name Applicable Events Description

Label None It is used to display text


on the HTML page.

TextBox TextChanged It is used to create a text


input in the form.

Button Click, Command It is used to create a


button.

LinkButton Click, Command It is used to create a


button that looks similar
to the hyperlink.

ImageButton Click It is used to create an


imagesButton. Here, an
image works as a Button.

Hyperlink None It is used to create a


hyperlink control that
responds to a click event.

DropDownList SelectedIndexChanged It is used to create a


dropdown list control.

ListBox SelectedIndexCnhaged It is used to create a


ListBox control like the
HTML control.

DataGrid CancelCommand, EditCommand, It used to create a frid


DeleteCommand, ItemCommand, that is used to show data.
SelectedIndexChanged, We can also perform
PageIndexChanged, paging, sorting, and
SortCommand, UpdateCommand, formatting very easily
ItemCreated, ItemDataBound with this control.

DataList CancelCommand, EditCommand, It is used to create


DeleteCommand, ItemCommand, datalist that is non-
SelectedIndexChanged, tabular and used to show
UpdateCommand, ItemCreated, data.
ItemDataBound

Repeater ItemCommand, ItemCreated, It allows us to create a


ItemDataBound non-tabular type of
format for data. You can
bind the data to template
items, which are like bits
of HTML put together in
a specific repeating
format.

CheckBox CheckChanged It is used to create


checkbox.

CheckBoxList SelectedIndexChanged It is used to create a


group of check boxes
that all work together.
RadioButton CheckChanged It is used to create radio
button.

RadioButtonLis SelectedIndexChanged It is used to create a


t group of radio button
controls that all work
together.

Image None It is used to show image


within the page.

Panel None It is used to create a


panel that works as a
container.

PlaceHolder None It is used to set


placeholder for the
control.

Calendar SelectionChanged, It is used to create a


VisibleMonthChanged, calendar. We can set the
DayRender default date, move
forward and backward
etc.

AdRotator AdCreated It allows us to specify a


list of ads to display.
Each time the user re-
displays the page.

Table None It is used to create table.

XML None It is used to display XML


documents within the
HTML.

Literal None It is like a label in that it


displays a literal, but
allows us to create new
literals at runtime and
place them into this
control.

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

Button It is used to create HTML button.

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

Text Field Gives the user an input area on an HTML form

Text Area Used for multi-line input on an HTML form

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

Password An input area on an HTML form, although any characters typed


Field into this field are displayed as asterisks

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

Table Allows you to present information in a tabular format

Image Displays an image on an HTML form

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.

Horizontal Displays a horizontal line across the HTML page


Rule

ASP.NET – Directives

ASP.NET directives are instructions to specify optional settings, such as


registering a custom control and page language. These settings describe how the
web forms (.aspx) or user controls (.ascx) pages are processed by the .Net
framework.
The syntax for declaring a directive is:

<%@ directive_name attribute=value [attribute=value] %>

In this section, we will just introduce the ASP.NET directives and we will use
most of these directives throughout the tutorials.

The Application Directive

The Application directive defines application-specific attributes. It is provided


at the top of the global.aspx file.
The basic syntax of Application directive is:
<%@ Application Language="C#" %>

The attributes of the Application directive are:

Attributes Description

Inherits The name of the class from which to inherit.

Description The text description of the application. Parsers and


compilers ignore this.

Language The language used in code blocks.

The Assembly Directive

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:

<%@ Assembly Name ="myassembly" %>

The attributes of the Assembly directive are:

Attributes Description

Name The name of the assembly to be linked.

Src The path to the source file to be linked and compiled


dynamically.

The Control Directive

The control directive is used with the user controls and appears in the user
control (.ascx) files.
The basic syntax of Control directive is:

<%@ Control Language="C#" EnableViewState="false" %>

The attributes of the Control directive are:


Attributes Description

AutoEventWireup The Boolean value that enables or disables automatic


association of events to handlers.

ClassName The file name for the control.

Debug The Boolean value that enables or disables compiling


with debug symbols.

Description The text description of the control page, ignored by


compiler.

EnableViewState The Boolean value that indicates whether view state is


maintained across page requests.

Explicit For VB language, tells the compiler to use option explicit


mode.

Inherits The class from which the control page inherits.

Language The language for code and script.

Src The filename for the code-behind class.

Strict For VB language, tells the compiler to use the option


strict mode.

The Implements Directive

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:

<%@ Implements Interface="interface_name" %>

The Import Directive

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

The Master directive specifies a page file as being the mater page.
The basic syntax of sample MasterPage directive is:

<%@ MasterPage Language="C#" AutoEventWireup="true"


CodeFile="SiteMater.master.cs" Inherits="SiteMaster" %>

The MasterType Directive

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:

<%@ MasterType attribute="value"[attribute="value" ...] %>

The OutputCache Directive

The OutputCache directive controls the output caching policies of a web page or
a user control.
The basic syntax of OutputCache directive is:

<%@ OutputCache Duration="15" VaryByParam="None" %>

The Page Directive

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:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" Trace="true" %>

The attributes of the Page directive are:


Attributes Description

AutoEventWireup The Boolean value that enables or disables page events


that are being automatically bound to methods; for
example, Page_Load.

Buffer The Boolean value that enables or disables HTTP


response buffering.

ClassName The class name for the page.

ClientTarget The browser for which the server controls should render
content.

CodeFile The name of the code behind file.

Debug The Boolean value that enables or disables compilation


with debug symbols.

Description The text description of the page, ignored by the parser.

EnableSessionState It enables, disables, or makes session state read-only.

EnableViewState The Boolean value that enables or disables view state


across page requests.

ErrorPage URL for redirection if an unhandled page exception


occurs.

Inherits The name of the code behind or other class.

Language The programming language for code.

Src The file name of the code behind class.

Trace It enables or disables tracing.

TraceMode It indicates how trace messages are displayed, and sorted


by time or category.

Transaction It indicates if transactions are supported.

ValidateRequest The Boolean value that indicates whether all input data is
validated against a hardcoded list of values.

The PreviousPageType Directive


The PreviousPageType directive assigns a class to a page, so that the page is
strongly typed.
The basic syntax for a sample PreviousPagetype directive is:

<%@ PreviousPageType attribute="value"[attribute="value" ...] %>

The Reference Directive

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:

<%@ Reference Page ="somepage.aspx" %>

The Register Directive

The Register derivative is used for registering the custom server controls and
user controls.
The basic syntax of Register directive is:

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter"


%>

ASP.NET - Server Controls


Controls are small building blocks of the graphical user interface, which include
text boxes, buttons, check boxes, list boxes, labels, and numerous other tools.
Using these tools, the users can enter data, make selections and indicate their
preferences.
Controls are also used for structural jobs, like validation, data access, security,
creating master pages, and data manipulation.
ASP.NET uses five types of web controls, which are:
 HTML controls
 HTML Server controls
 ASP.NET Server controls
 ASP.NET Ajax Server controls
 User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These
controls can be grouped into the following categories:
 Validation controls - These are used to validate user input and
they work by running client-side script.
 Data source controls - These controls provides data binding to
different data sources.
 Data view controls - These are various lists and tables, which can
bind to data from data sources for displaying.
 Personalization controls - These are used for personalization of a
page according to the user preferences, based on user information.
 Login and security controls - These controls provide user
authentication.
 Master pages - These controls provide consistent layout and
interface throughout the application.
 Navigation controls - These controls help in navigation. For
example, menus, tree view etc.
 Rich controls - These controls implement special features. For
example, AdRotator, FileUpload, and Calendar control.
The syntax for using server controls is:

<asp:controlType ID ="ControlID" runat="server" Property1=value1


[Property2=value2] />

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

Properties of the Server Controls

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.

Attributes It is the collection of arbitrary attributes (for


rendering only) that do not correspond to properties
on the control.

BackColor Background color.

BindingContainer The control that contains this control's data binding.

BorderColor Border color.

BorderStyle Border style.

BorderWidth Border width.

CausesValidation Indicates if it causes validation.

ChildControlCreated It indicates whether the server control's child controls


have been created.

ClientID Control ID for HTML markup.

Context The HttpContext object associated with the server


control.

Controls Collection of all controls contained within the


control.

ControlStyle The style of the Web server control.

CssClass CSS class

DataItemContainer Gets a reference to the naming container if the


naming container implements IDataItemContainer.

DataKeysContainer Gets a reference to the naming container if the


naming container implements IDataKeysControl.

DesignMode It indicates whether the control is being used on a


design surface.

DisabledCssClass Gets or sets the CSS class to apply to the rendered


HTML element when the control is disabled.

Enabled Indicates whether the control is grayed out.

EnableTheming Indicates whether theming applies to the control.

EnableViewState Indicates whether the view state of the control is


maintained.

Events Gets a list of event handler delegates for the control.

Font Font.

Forecolor Foreground color.

HasAttributes Indicates whether the control has attributes set.

HasChildViewState Indicates whether the current server control's child


controls have any saved view-state settings.

Height Height in pixels or %.

ID Identifier for the control.

IsChildControlStateCleare Indicates whether controls contained within this


d control have control state.

IsEnabled Gets a value indicating whether the control is


enabled.

IsTrackingViewState It indicates whether the server control is saving


changes to its view state.

IsViewStateEnabled It indicates whether view state is enabled for this


control.

LoadViewStateById It indicates whether the control participates in


loading its view state by ID instead of index.

Page Page containing the control.

Parent Parent control.

RenderingCompatibility It specifies the ASP.NET version that the rendered


HTML will be compatible with.
Site The container that hosts the current control when
rendered on a design surface.

SkinID Gets or sets the skin to apply to the control.

Style Gets a collection of text attributes that will be


rendered as a style attribute on the outer tag of the
Web server control.

TabIndex Gets or sets the tab index of the Web server control.

TagKey Gets the HtmlTextWriterTag value that corresponds


to this Web server control.

TagName Gets the name of the control tag.

TemplateControl The template that contains this control.

TemplateSourceDirectory Gets the virtual directory of the page or control


containing this control.

ToolTip Gets or sets the text displayed when the mouse


pointer hovers over the web server control.

UniqueID Unique identifier.

ViewState Gets a dictionary of state information that saves and


restores the view state of a server control across
multiple requests for the same page.

ViewStateIgnoreCase It indicates whether the StateBag object is case-


insensitive.

ViewStateMode Gets or sets the view-state mode of this control.

Visible It indicates whether a server control is visible.

Width Gets or sets the width of the Web server control.

Methods of the Server Controls

The following table provides the methods of the server controls:

Method Description
AddAttributesToRender Adds HTML attributes and styles that need to
be rendered to the specified
HtmlTextWriterTag.

AddedControl Called after a child control is added to the


Controls collection of the control object.

AddParsedSubObject Notifies the server control that an element,


either XML or HTML, was parsed, and adds the
element to the server control's control
collection.

ApplyStyleSheetSkin Applies the style properties defined in the page


style sheet to the control.

ClearCachedClientID Infrastructure. Sets the cached ClientID value to


null.

ClearChildControlState Deletes the control-state information for the


server control's child controls.

ClearChildState Deletes the view-state and control-state


information for all the server control's child
controls.

ClearChildViewState Deletes the view-state information for all the


server control's child controls.

CreateChildControls Used in creating child controls.

CreateControlCollection Creates a new ControlCollection object to hold


the child controls.

CreateControlStyle Creates the style object that is used to


implement all style related properties.

DataBind Binds a data source to the server control and all


its child controls.

DataBind(Boolean) Binds a data source to the server control and all


its child controls with an option to raise the
DataBinding event.

DataBindChildren Binds a data source to the server control's child


controls.
Dispose Enables a server control to perform final clean
up before it is released from memory.

EnsureChildControls Determines whether the server control contains


child controls. If it does not, it creates child
controls.

EnsureID Creates an identifier for controls that do not


have an identifier.

Equals(Object) Determines whether the specified object is equal


to the current object.

Finalize Allows an object to attempt to free resources


and perform other cleanup operations before the
object is reclaimed by garbage collection.

FindControl(String) Searches the current naming container for a


server control with the specified id parameter.

FindControl(String, Int32) Searches the current naming container for a


server control with the specified id and an
integer.

Focus Sets input focus to a control.

GetDesignModeState Gets design-time data for a control.

GetType Gets the type of the current instance.

GetUniqueIDRelativeTo Returns the prefixed portion of the UniqueID


property of the specified control.

HasControls Determines if the server control contains any


child controls.

HasEvents Indicates whether events are registered for the


control or any child controls.

IsLiteralContent Determines if the server control holds only


literal content.

LoadControlState Restores control-state information.

LoadViewState Restores view-state information.


MapPathSecure Retrieves the physical path that a virtual path,
either absolute or relative, maps to.

MemberwiseClone Creates a shallow copy of the current object.

MergeStyle Copies any nonblank elements of the specified


style to the web control, but does not overwrite
any existing style elements of the control.

OnBubbleEvent Determines whether the event for the server


control is passed up the page's UI server control
hierarchy.

OnDataBinding Raises the data binding event.

OnInit Raises the Init event.

OnLoad Raises the Load event.

OnPreRender Raises the PreRender event.

OnUnload Raises the Unload event.

OpenFile Gets a Stream used to read a file.

RemovedControl Called after a child control is removed from the


controls collection of the control object.

Render Renders the control to the specified HTML


writer.

RenderBeginTag Renders the HTML opening tag of the control to


the specified writer.

RenderChildren Outputs the contents of a server control's


children to a provided HtmlTextWriter object,
which writes the contents to be rendered on the
client.

RenderContents Renders the contents of the control to the


specified writer.

RenderControl(HtmlTextWriter Outputs server control content to a provided


) HtmlTextWriter object and stores tracing
information about the control if tracing is
enabled.

RenderEndTag Renders the HTML closing tag of the control


into the specified writer.

ResolveAdapter Gets the control adapter responsible for


rendering the specified control.

SaveControlState Saves any server control state changes that have


occurred since the time the page was posted
back to the server.

SaveViewState Saves any state that was modified after the


TrackViewState method was invoked.

SetDesignModeState Sets design-time data for a control.

ToString Returns a string that represents the current


object.

TrackViewState Causes the control to track changes to its view


state so that they can be stored in the object's
view state property.

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 {

protected void Page_Load(object sender, EventArgs e) {


txtmessage.Text = " ";
}

protected void TreeView1_SelectedNodeChanged(object sender, EventArgs


e) {

txtmessage.Text = " ";


lblmessage.Text = "Selected node changed to: " +
TreeView1.SelectedNode.Text;
TreeNodeCollection childnodes = TreeView1.SelectedNode.ChildNodes;

if(childnodes != null) {
txtmessage.Text = " ";

foreach (TreeNode t in childnodes) {


txtmessage.Text += t.Value;
}
}
}
}
}

Execute the page to see the effects. You will be able to expand and collapse the
nodes.
ASP.NET Themes

ASP.NET themes are a collection of properties that define the appearance of


pages and controls in your Web site. A theme can include skin files, which
define property settings for ASP.NET Web server controls, and can also include
cascading style sheet files (.css files) and graphics. By applying a theme, you
can give the pages in your Web site a consistent appearance.
A theme is a collection of property settings that allow you to define the look of
pages and controls, and then apply the look consistently across pages in a Web
application, across an entire Web application, or across all Web applications on
a server.

Themes and Control Skins

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 default skin automatically applies to all controls of the same type


when a theme is applied to a page. A control skin is a default skin if
it does not have a SkinID attribute. For example, if you create a
default skin for a Calendar control, the control skin applies to
all Calendar controls on pages that use the theme. (Default skins are
matched exactly by control type, so that a Button control skin
applies to all Button controls, but not to LinkButton controls or to
controls that derive from the Button object.)

 A named skin is a control skin with a SkinID property set. Named


skins do not automatically apply to controls by type. Instead, you
explicitly apply a named skin to a control by setting the
control's SkinID property. Creating named skins allows you to set
different skins for different instances of the same control in an
application.

Cascading Style Sheets

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.

Theme Graphics and Other Resources

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.

Theme Settings Precedence

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.

Global theme elements cannot be partially replaced by elements of application-


level themes. If you create an application-level theme with the same name as a
global theme, theme elements in the application-level theme will not override
the global theme elements.

Properties You Can Define Using Themes

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 vs. Cascading Style Sheets

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 can define many properties of a control or page, not just


style properties. For example, using themes, you can specify the
graphics for a TreeView control, the template layout of
a GridView control, and so on.

 Themes can include graphics.

 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 a control's behavior so that it does not behave as expected.

 Inject client-side script, therefore posing a cross-site scripting risk.

 Alter validation.

 Expose sensitive information.


 The mitigations for these common threats are:

 Protect the global and application theme directories with proper


access control settings. Only trusted users should be allowed to write
files to the theme directories.

 Do not use themes from an untrusted source. Always examine any


themes from outside your organization for malicious code before
using them on you Web site.

 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.

How to: Apply ASP.NET Themes


 Article
 10/22/2014
 2 minutes to read

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.

To apply a theme to a Web site

1. In the application's Web.config file, set the <pages> element to the


name of the theme, either a global theme or a page theme, as shown
in the following example:

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.

2. To set a theme as a style sheet theme and be subordinated to local


control settings), set the styleSheetTheme attribute instead:

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.

To apply a theme to an individual page

 Set the Theme or StyleSheetTheme attribute of the @ Page directive


to the name of the theme to use, as shown in the following example:

Copy
<%@ Page Theme="ThemeName" %>
<%@ Page StyleSheetTheme="ThemeName" %>

The theme and its corresponding styles and skins now applies only
to the page declaring it.

Applying Skins to Controls

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

 Set the control's SkinID property, as shown in the following


example:

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

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

EnableClientScript Indicates whether client side validation will take.

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.


IsValid Indicates whether the value of the control is valid.

SetFocusOnError It indicates whether in case of an invalid control, the


focus should switch to the related input control.

ValidationGroup The logical group of multiple validators, where this


control belongs.

Validate() This method revalidates the control and updates the


IsValid property.

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.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server"
ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control

The CompareValidator control compares a value in one control with a fixed


value or a value in another control.
It has the following specific properties:

Properties Description

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare


with.

ValueToCompare It specifies the constant value to compare with.

Operator It specifies the comparison operator, the available values


are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching


against a pattern of a regular expression. The regular expression is set in the
ValidationExpression property.
The following table summarizes the commonly used syntax constructs for
regular expressions:

Character Escapes Description

\b Matches a backspace.

\t Matches a tab.
\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could be specified that
can be matched, called the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

[2-7a-mA-M] Matches any character specified in the range.

\w Matches any alphanumeric character and underscore.

\W Matches any non-word character.

\s Matches whitespace characters like, space, tab, new line


etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.


{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server"
ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator

The CustomValidator control allows writing application specific custom


validation routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting
language, such as JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="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

Complex pages have different groups of information provided in different


panels. In such situation, a need might arise for performing validation separately
for separate group. This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting
their ValidationGroup property.

Example

The following example describes a form to be filled up by all the students of a


school, divided into four houses, for electing the school president. Here, we use
the validation controls to validate the user input.
This is the form in design view:

The content file code is as given:


<form id="form1" runat="server">

<table style="width: 66%;">

<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";
}
}

Why we use validation controls?

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

Validation Controls in ASP.NET


An important aspect of creating ASP.NET Web pages for user input is to be
able to check that the information users enter is valid. ASP.NET provides a set
of validation controls that provide an easy-to-use but powerful way to check for
errors and, if necessary, display messages to the user.

There are six types of validation controls in ASP.NET


1. RequiredFieldValidation Control
2. CompareValidator Control
3. RangeValidator Control
4. RegularExpressionValidator Control
5. CustomValidator Control
6. ValidationSummary
The below table describes the controls and their work,

Validation Control Description


RequiredFieldValidation Makes an input control a required field
Compares the value of one input control to the
CompareValidator
value of another input control or to a fixed value
Checks that the user enters a value that falls
RangeValidator
between two values
Ensures that the value of an input control matches a
RegularExpressionValidator
specified pattern
Allows you to write a method to handle the
CustomValidator
validation of the value entered
Displays a report of all validation errors occurred
ValidationSummary
in a Web page

All validation controls are rendered in form as <span> (label are referred as
<span> on client by server)

Important points for validation controls


 ControlToValidate property is mandatory to all validate controls.
 One validation control will validate only one input control but
multiple validate control can be assigned to a input control.
Validation Properties

Usually, Validation is invoked in response to user actions like clicking submit


button or entering data. Suppose, you wish to perform validation on page when
user clicks submit button.

Server validation will only performed when CauseValidation is set to true.


When the value of the CausesValidation property is set to true, you can also use
the ValidationGroup property to specify the name of the validation group for
which the Button control causes validation.

Page has a Validate() method. If it is true this methods is executed. Validate()


executes each validation control.

To make this happen, simply set the CauseValidation property to true for submit
button as shown below:

<asp:Button ID="Button2" runat="server" Text="Submit"


CausesValidation=true />

Lets understand validation controls one by one with practical demonstration:

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks


to see if the data is entered for the input control. You can have a
RequiredFieldValidator control for each form element on which you wish to
enforce Mandatory Field rule.
1. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="
server"
2. Style="top: 98px; left: 367px; position: absolute; height: 26px; width
: 162px"
3. ErrorMessage="password required" ControlToValidate="TextBox2"
>
4. </asp:RequiredFieldValidator>
CompareValidator Control

The CompareValidator control allows you to make comparison to compare data


entered in an input control with a constant value or a value in a different 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

The RangeValidator Server Control is another validator control, which checks


to see if a control value is within a valid range. The attributes that are necessary
to this control are: MaximumValue, MinimumValue, and Type.
1. <asp:RangeValidator ID="RangeValidator1" runat="server"
2. Style="top: 194px; left: 365px; position: absolute; height: 22px; widt
h: 105px"
3. ErrorMessage="RangeValidator" ControlToValidate="TextBox4" M
aximumValue="100" MinimumValue="18" Type="Integer"></
asp:RangeValidator>
RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can be used


to identify simple and complex characters sequence that would otherwise
require writing code to perform.

Using RegularExpressionValidator server control, you can check a user's input


based on a pattern that you define using a regular expression.

It is used to validate complex expressions. These expressions can be phone


number, email address, zip code and many more. Using Regular Expression
Validator is very simple. Simply set the ValidationExpression property to any
type of expression you want and it will validate it.

If you don't find your desired regular expression, you can create your custom
one.

In the example I have checked the email id format:


1. <asp:RegularExpressionValidator ID="RegularExpressionValidator1
" runat="server" Style="top: 234px;
2. left: 366px; position: absolute; height: 22px; width: 177px"
3. ErrorMessage="RegularExpressionValidator" ControlToValidat
e="TextBox5"
4. ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+
([-.]\w+)*"></asp:RegularExpressionValidator>
The complete code for the above 4 controls is as,

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.

The ValidationSummary control is reporting control, which is used by the other


validation controls on a page.

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"

2. style="top: 390px; left: 44px; position: absolute; height: 38px;


width: 625px" />
Both ErrorMessage and Text properties are used to display error messages. Text
error message have precedence.

If you are using ValidationSummary than only ErrorMessage and Text property
is used.

The complete code for the above ValidationSummary is as:

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

It is a module of .Net Framework which is used to establish connection between


application and data sources. Data sources can be such as SQL Server and
XML. ADO.NET consists of classes that can be used to connect, retrieve, insert
and delete data.

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.

.NET Framework Data Providers

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.

Reading XML using Data Set

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.

The Read xml Method

ReadXml is an overloaded method; you can use it to read a data stream,


TextReader, XmlReader, or an XML file and to store into a DataSet object,
which can later be used to display the data in a tabular format. The ReadXml
method has eight overloaded forms. It can read a text, string, stream,
TextReader, XmlReader, and their combination formats. In the following
example, create a new DataSet object.

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:

//Create a DataSet object

DataSet ds = new DataSet();

// Fill with the data

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.

The ReadXmlSchema method

The ReadXMLSchema method reads an XML schema in a DataSet object. It


has four overloaded forms. You can use a Text Reader, string, stream, and
XmlReader. The following example shows how to use a file as direct input and
call the ReadXmlSchema method to read the file:

DataSet ds = new DataSet();

ds.ReadSchema(@"c:\books.xml");

The following example reads the file XmlReader and uses XmlTextReader as
the input of ReadXmlSchema:

//Create a dataset object

DataSet ds = new DataSet("New DataSet");

// Read xsl in an XmlTextReader

XmlTextReader myXmlReader = new XmlTextReader(@"c:\books.Xml");

// Call Read xml schema

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

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.

Listing 6-26. Write xml Method

using System;

using System.IO;

using System.Xml;

using System.Data;

namespace XmlAndDataSetsampB2

class XmlAndDataSetSampCls

public static void Main()


{

try

// Create a DataSet, namespace and Student table

// with Name and Address columns

DataSet ds = new DataSet("DS");

ds.Namespace = "StdNamespace";

DataTable stdTable = new DataTable("Student");

DataColumn col1 = new DataColumn("Name");

DataColumn col2 = new DataColumn("Address");

stdTable.Columns.Add(col1);

stdTable.Columns.Add(col2);

ds.Tables.Add(stdTable);

//Add student Data to the table

DataRow newRow; newRow = stdTable.NewRow();

newRow["Name"] = "Mahesh Chand";

newRow["Address"] = "Meadowlake Dr, Dtown";

stdTable.Rows.Add(newRow);

newRow = stdTable.NewRow();

newRow["Name"] = "Mike Gold";

newRow["Address"] = "NewYork";

stdTable.Rows.Add(newRow);
newRow = stdTable.NewRow();

newRow["Name"] = "Mike Gold";

newRow["Address"] = "New York";

stdTable.Rows.Add(newRow);

ds.AcceptChanges();

// Create a new StreamWriter

// I'll save data in stdData.Xml file

System.IO.StreamWriter myStreamWriter = new

System.IO.StreamWriter(@"c:\stdData.xml");

// Writer data to DataSet which actually creates the file

ds.WriteXml(myStreamWriter);

myStreamWriter.Close();

catch (Exception e)

Console.WriteLine("Exception: {0}", e.ToString());

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.

Listing 6-27WriteXml method output

<?xml version="1.0" ?>

<DS xmlns="StdNamespace">

<Student>

<Name>Mahesh Chand</Name>

<Address>Meadowlake Dr, Dtown</Address>

</Student>

<Student>

<Name>Mike Gold</Name>

<Address>NewYork</Address>

</Student>

<Student>

<Name>Mike Gold</Name>

<Address>New York</Address>

</Student>

</DS>

The Write xml schema method


This method writes DataSet structure to an XML schema. WriteXmlSchema has
four overloaded methods. You can write the data to a stream, text, TextWriter,
or Xmlwriter. Listing 6-28 uses XmlWriter for the output.

Listing 6-28. write xml schema sample

using System;

using System.IO;

using System.Xml;

using System.Data;

namespace XmlAndDataSetsampB2

class XmlAndDataSetSampCls

public static void Main()

DataSet ds = new DataSet("DS");

ds.Namespace = "StdNamespace";

DataTable stdTable = new DataTable("Students");

DataColumn col1 = new DataColumn("Name");

DataColumn col2 = new DataColumn("Address");

stdTable.Columns.Add(col1);
stdTable.Columns.Add(col2);

ds.Tables.Add(stdTable);

// Add student Data to the table

DataRow newRow; newRow = stdTable.NewRow();

newRow["Name"] = "Mahesh chand";

newRow["Address"] = "Meadowlake Dr, Dtown";

stdTable.Rows.Add(newRow);

newRow = stdTable.NewRow();

newRow["Name"] = "Mike Gold";

newRow["Address"] = "NewYork";

stdTable.Rows.Add(newRow);

ds.AcceptChanges();

XmlTextWriter writer = new XmlTextWriter(Console.Out);

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 shows the XmlDataDocument hierarchy.

Figure-6.10.gif

Figure 6-10. Xml Data Document hierarchy

Besides overriding the methods of XmlNode and XmlDocument,


XmlDataDocument also implements its own methods. The XmlDataDocument
class lets you lead relational data using the DataSet object as well as XML
documents using the Load and LoadXml methods. As figure 6-11 indicates, you
can use a DataSet to load relational data to an XmlDataDocument object and
use the Load or LoadXml methods to read an XML document. Figure 6-11
shows a relationship between a Reader, Writer, DataSet, and
XmlDataDocument.

The XmlDataDocument class extends the functionality of XmlDocument and


synchronizes it with DataSet. As you know a DataSet is a powerful object in
ADO.NET. As figure 6-11 shows, you can take data from two different sources.
First, you can load data from an XML document with the help of XmlReader,
and second, you can load data from relational data sources with the help of
database provides and DataSet. The neat thing is the data synchronization
between these two objects. That means if you update data in a DataSet object,
you see results in the XmlDataDocument object and vice versa. For example, if
you add a record to a DataSet object, the action will add one node to the
XmlDataDocument object representing the newly added record.
Once the data is loaded, you're allowed to use any operations that you were able
to use on XmlDocument objects. You can also use XmlReader and XmlWriter
objects to read and write the data.

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.

Loading Data using Load and LoadXml from the XmlDataDocument

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:

XmlDataDocument doc = new XmlDataDocument();

doc.Load("c:\\Books.xml");

Or you can load an XML fragment, as in the following example:

XmlDataDocument doc = new XmlDataDocument();


doc.LoadsXml("<Record> write something </Record>");

Loading Data Using a DataSet

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:

XmlDataDocument doc = new XmlDataDocument();

doc.DataSet.ReadXmlSchema("test. Xsd");

Or

doc.DataSet.ReadXml("<Record> write something </Record>");

Displaying XML Data In a data Set Format

As mentioned previously, you can get DataSet object from an


XmlDataDocument object by using its DataSet property. OK, now it's time to
see how to do that. The next sample will show you how easy is to display an
XML document data in a DataSet format.
To read XML document in a dataset, first you read to document. You can read a
document using the ReadXml method of the DataSet object. The DataSet
property of XmlDataDocument represents the dataset of XmlDataDocument.
After reading a document in a dataset, you can create data views from the
dataset, or you can also use a DataSet'sDefaultViewManager property to bind to
data-bound controls, as you can see in the following code:

XmlDataDocument xmlDatadoc = new XmlDataDocument();

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.

Listing 6-29. XmlDataDocumentSample.cs

public Form1( )

// Initialize Component and other code here

// Create an XmlDataDocument object and read an XML

XmlDataDocument xmlDatadoc = new XmlDataDocument();

xmlDatadoc.DataSet.ReadXml("C:\\books.xml");

// Create a DataSet object and fill with the dataset

// of XmlDataDocument
DataSet ds = new DataSet("Books DataSet");

ds = xmlDatadoc.DataSet;

// Attach dataset view to the Data Grid control

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

Figure 6-12. XmlDataDocumentSample.cs output

Saving Data from a DataSet to XML

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:

string SQLStmt = "SELECT * FROM Customers";


string ConnectionString =

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C: \\
Northwind.mdb";

// Create data adapter

OleDbDataAdapter da = new OleDbDataAdapter(SQLStmt,


ConnectionString);

// create a new dataset object and fill using data adapter's fill method

DataSet ds = new DataSet();

da.Fill(ds);

Now, you create an instance of XmlDataDocument with the DataSet as an


argument and call the Save method to save the data as an XML document:

XmlDataDocument doc = new XmlDataDocument(ds);

doc.Save("C:\\XmlDataDoc.xml");

Listing 6-30 shows a complete program listing. You create an


XmlDataDocument object with dataset and call the save method to save the
dataset data in an XML file.

Listing 6-30. Saving the dataset data to an XML document

using System;
using System.Data;

using System.Data.OleDb;

using System.Xml;

namespace DataDocsampB2

class Class1

static void Main(string[] args)

{// create SQL Query

string SQLStmt = "SELECT * FROM Customers";

// Connection string

string ConnectionString =

"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = C:\\


Northwind.mdb";

// Create data adapter

OleDbDataAdapter da = new OleDbDataAdapter(SQLStmt,


ConnectionString);

// create a new dataset object and fill using data adapter's fill method

DataSet doc = new DataSet();

// Now use SxlDataDocument's Save method to save data as an


XML file XmlDataDocument doc = new XmlDataDocument(ds);

doc.Save("C:\\XmlDataDoc.xml");

}
}

XmlDataDocument: Under the Hood

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

Which one should we use DataReader or DataSet?

We should consider the following points to use DataSet.

o It caches data locally at our application, so we can manipulate it.


o It interacts with data dynamically such as binding to windows forms
control.
o It allows performing processing on data without an open connection. It
means it can work while connection is disconnected.
If we required some other functionality mentioned above, we can
use DataReader to improve performance of our application.

DataReader does not perform in disconnected mode. It requires DataReader


object to be connected.

Sometimes we get a requirement to display XML data in a style/design format.


If we browse a XML file directly then it displays the XML nodes with data. So
XSLT helps us to display XML data in a design/specific format.

My previous article explained XML, XSLT and CSS. To learn more XSL and
the syntax refer to here.

How XSLT works internally

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.

Figure 1: XSL Transformation internally

To implement a XSL transformation in ASP.NET we need to execute the


following procedure.

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.

First it loads the XML content in a variable using File.ReaAllText(). Then it


assigns XML content to the XML control using the DocumentContent property.
Lastly it assigns a XSLT file to the XML control using the TransformSource
property. Then the XML control loads XML content, transforms it into HTML
content and renders it in the browser.

Please refer to the following code:


1. protected void Button1_Click(object sender, EventArgs e)
2. {
3. // This is being read from the same folder as this page is in.(only f
or demo purpose)
4. // In real applications this xml might be coming from some externa
l source or database.
5. string xmlString = File.ReadAllText(Server.MapPath("XMLFile1.
xml"));
6.
7. // Define the contents of the XML control
8. Xml1.DocumentContent = xmlString;
9.
10. // Specify the XSL file to be used for transformation.
11. Xml1.TransformSource = Server.MapPath("XSLTFile1.xslt");
12.}
2. XslCompiledTransform class Without XML control

In the .NET Framework a class XslCompiledTransform is present in the


System.Xml.Xsl namespace that can be used to do the transformation. Then the
XslCompiledTransform object calls the Load() method to load the XSLT
file content into the object. Next it calls the Transform() method to create a
HTML string and write data into the TextReader object.

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).

Add the following namespaces:


1. using System.Xml;
2. using System.Xml.Xsl;
3. using System.IO;
4. using System.Text;
Code
1. protected void Button2_Click(object sender, EventArgs e)
2. {
3. Xml1.Visible = false;
4. ltlTutorial.Visible = true;
5.
6. // Getting file path
7. string strXSLTFile = Server.MapPath("XSLTFile1.xslt");
8. string strXMLFile = Server.MapPath("XMLFile1.xml");
9.
10. // Creating XSLCompiled object
11. XslCompiledTransform objXSLTransform = new XslCompiledTr
ansform();
12. objXSLTransform.Load(strXSLTFile);
13.
14. // Creating StringBuilder object to hold html data and creates Text
Writer object to hold data from XslCompiled.Transform method
15. StringBuilder htmlOutput = new StringBuilder();
16. TextWriter htmlWriter = new StringWriter(htmlOutput);
17.
18. // Creating XmlReader object to read XML content
19. XmlReader reader = XmlReader.Create(strXMLFile);
20.
21. // Call Transform() method to create html string and write in Text
Writer object.
22. objXSLTransform.Transform(reader, null, htmlWriter);
23. ltlTutorial.Text = htmlOutput.ToString();
24.
25. // Closing xmlreader object
26. reader.Close();
27.}
Now our code is ready to display XML data in design format. In Step 3 I used
two options to do XSL transformations, so you can use any one of them.

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 Class Signature

1. public class DataSet : System.ComponentModel.MarshalByValueCompo


nent, System.ComponentModel.IListSource,
2. System.ComponentModel.ISupportInitializeNotification, System.Runtim
e.Serialization.ISerializable,
3. System.Xml.Serialization.IXmlSerializable
DataSet Constructors
Constructor Description

DataSet() It is used to initialize a new instance of the


DataSet class.

DataSet(String) It is used to initialize a new instance of a


DataSet class with the given name.

DataSet(SerializationInfo, It is used to initialize a new instance of a


StreamingContext) DataSet class that has the given serialization
information and context.

DataSet(SerializationInfo, It is used to initialize a new instance of the


StreamingContext, Boolean) DataSet class.

DataSet Properties
Properties Description
CaseSensitive It is used to check whether DataTable objects are case-
sensitive or not.

DataSetName It is used to get or set name of the current DataSet.

DefaultViewManager It is used to get a custom view of the data contained in the


DataSet to allow filtering and searching.

HasErrors It is used to check whether there are errors in any of the


DataTable objects within this DataSet.

IsInitialized It is used to check whether the DataSet is initialized or not.

Locale It is used to get or set the locale information used to


compare strings within the table.

Namespace It is used to get or set the namespace of the DataSet.

Site It is used to get or set an ISite for the DataSet.

Tables It is used to get the collection of tables contained in the


DataSet.

DataSet Methods

The following table contains some commonly used methods of DataSet.

Method Description

BeginInit() It is used to begin the initialization of a


DataSet that is used on a form.

Clear() It is used to clear the DataSet of any data by


removing all rows in all tables.
Clone() It is used to copy the structure of the DataSet.

Copy() It is used to copy both the structure and data


for this DataSet.

CreateDataReader(DataTable[]) It returns a DataTableReader with one result


set per DataTable.

CreateDataReader() It returns a DataTableReader with one result


set per DataTable.

EndInit() It ends the initialization of a DataSet that is


used on a form.

GetXml() It returns the XML representation of the data


stored in the DataSet.

GetXmlSchema() It returns the XML Schema for the XML


representation of the data stored in the
DataSet.

Load(IDataReader, LoadOption, It is used to fill a DataSet with values from a


DataTable[]) data source using the supplied IDataReader.

Merge(DataSet) It is used to merge a specified DataSet and its


schema into the current DataSet.

Merge(DataTable) It is used to merge a specified DataTable and


its schema into the current DataSet.

ReadXml(XmlReader, It is used to read XML schema and data into


XmlReadMode) the DataSet using the specified XmlReader
and XmlReadMode.

Reset() It is used to clear all tables and removes all


relations, foreign constraints, and tables from
the DataSet.
WriteXml(XmlWriter, It is used to write the current data and
XmlWriteMode) optionally the schema for the DataSet using
the specified XmlWriter and XmlWriteMode.

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

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehin


d="DataSetDemo.aspx.cs"
2. Inherits="DataSetExample.DataSetDemo" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. </div>
12. <asp:GridView ID="GridView1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None">
13. <AlternatingRowStyle BackColor="White" />
14. <EditRowStyle BackColor="#2461BF" />
15. <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeCol
or="White" />
16. <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeCo
lor="White" />
17. <PagerStyle BackColor="#2461BF" ForeColor="White" Horizon
talAlign="Center" />
18. <RowStyle BackColor="#EFF3FB" />
19. <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333" />
20. <SortedAscendingCellStyle BackColor="#F5F7FB" />
21. <SortedAscendingHeaderStyle BackColor="#6D95E1" />
22. <SortedDescendingCellStyle BackColor="#E9EBEF" />
23. <SortedDescendingHeaderStyle BackColor="#4870BE" />
24. </asp:GridView>
25. </form>
26.</body>
27.</html>

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

The DataAdapter works as a bridge between a DataSet and a data source to


retrieve data. DataAdapter is a class that represents a set of SQL commands and
a database connection. It can be used to fill the DataSet and update the data
source.

DataAdapter Class Signature

1. public class DataAdapter : System.ComponentModel.Component, Syste


m.Data.IDataAdapter
DataAdapter Constructors
Constructors Description

DataAdapter() It is used to initialize a new instance of a DataAdapter class.

DataAdapter(DataAdapter It is used to initializes a new instance of a DataAdapter class f


) an existing object of the same type.
Methods
Method Description

CloneInternals() It is used to create a copy of this instanc


DataAdapter.

Dispose(Boolean) It is used to release the unmanaged resou


used by the DataAdapter.

Fill(DataSet) It is used to add rows in the DataSet to m


those in the data source.

FillSchema(DataSet, SchemaType, String, It is used to add a DataTable to the speci


IDataReader) DataSet.

GetFillParameters() It is used to get the parameters set by the


when executing an SQL SELECT statemen

ResetFillLoadOption() It is used to reset FillLoadOption to its def


state.

ShouldSerializeAcceptChangesDuringFill() It determines whether


AcceptChangesDuringFill property should
persisted or not.

ShouldSerializeFillLoadOption() It determines whether the FillLoadOp


property should be persisted or not.

ShouldSerializeTableMappings() It determines whether one or m


DataTableMapping objects exist or not.

Update(DataSet) It is used to call the respective INSE


UPDATE, or DELETE statements.

Example
// DataSetDemo.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehin


d="DataSetDemo.aspx.cs"
2. Inherits="DataSetExample.DataSetDemo" %>
3. <!DOCTYPE html>
4.
5. <html xmlns="http://www.w3.org/1999/xhtml">
6. <head runat="server">
7. <title></title>
8. </head>
9. <body>
10. <form id="form1" runat="server">
11. <div>
12.
13. </div>
14. <asp:GridView ID="GridView1" runat="server" CellPadding="3"
BackColor="#DEBA84"
15. BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px
" CellSpacing="2">
16. <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
17. <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeCo
lor="White" />
18. <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />

19. <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />


20. <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" F
oreColor="White" />
21. <SortedAscendingCellStyle BackColor="#FFF1D4" />
22. <SortedAscendingHeaderStyle BackColor="#B95C30" />
23. <SortedDescendingCellStyle BackColor="#F1E5CE" />
24. <SortedDescendingHeaderStyle BackColor="#93451F" />
25. </asp:GridView>
26. </form>
27.</body>
28.</html>
CodeBehind
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:

You might also like