You are on page 1of 511

Microsoft® .NET Framework 4.

And

ASP.NET
Web Programming Basics
In the modern world, internet is being used by everyone.
On the internet, we can find so many (around crores) or web sites.
Those web sites are stored in the web servers and can be accessible from any system
(web client) that is connected with Internet.
To access the web site, the user requires a software called ―Browserǁ.
We have several browsers available in the market.
✰ Microsoft Internet Explorer
✰ Mozilla Firefox
✰ Google Chrome
✰ Safari
✰ Netscape Navigator
etc.
The user can use any browser, based on his-own choice.
The first graphical-based browser is Mosaic, which is released in 1993.
While the web site is being transferred from web server to the web client, it should be
converted in binary format, using a protocol called ―HTTPǁ (Hypertext Transfer
Protocol).
In other words, all the web sites will be maintained using HTTP protocol.
Let us discuss how we are opening a web site.
Suppose you want to open Google web site.
First we open the browser (Microsoft Internet Explorer or any other browser).
Then we type the URL of the web site in the address bar. Ex: www.google.co.in
Then press Enter.
Then a ―Requestǁ will be sent to the web site.
The request will be travelled through the web and will be received by the web server.
Based on the given URL, the web server serves the home page of the web site to the
web client, as ―Responseǁ.
Let me show this interaction visually.
Basic Terminology in Web

Web Site:
✰ It‘s a collection of web pages.
✰ In other words, it‘s named memory location on the web.
✰ Every company purchases some amount of memory space on the web server. In that
space, some web pages will be uploaded. Then that memory space is called as
―web siteǁ.
✰ Every web site is a folder in the web server memory, in which all the web pages can
be stored.

URL:
✰ Every web site is associated with an address.
✰ That address of the web site is called as ―URLǁ (Uniform Resource Locator).
✰ The client can open the web site using the URL only.
✰ In simple, when you are browsing any web site on internet, the address displayed in
the address bar of the browser, is called as ―URLǁ.
▪ Ex: http://www.google.co.in

Web Server:
✰ A system, which serves one or more web sites on internet.

Web Client:
✰ Every system, which has internet connection, can be called as ―Web Clientǁ.
✰ Suppose you have internet connection in your system, then your system can be called
as ―Web Clientǁ.
✰ In the web client, browser should be there.

Browser:
✰ In the client system, to open the web sites, a software should be there.
✰ That software is called as ―Browserǁ.
✰ As you know, there are so many browsers are available in the market.
✰ Every browser should able to execute the following code:
▪ HTML code
▪ JavaScript code
▪ XML code
▪ CSS code
✰ Then only it can be called as a browser.

HTTP:
✰ It is the protocol, in which all the web sites are maintained.
✰ The applications that run under HTTP protocol can be called ―web applicationsǁ.

Web Page:
✰ It‘s a part of the web site.
✰ It contains some information.
✰ That information can be called as ―Contentǁ.
✰ The content may be in different formats (headings, text matter, images, links, tables,
controls like textboxes, buttons etc.)
✰ Every page is a file. Ex:
▪ page1.html
▪ page2.asp
▪ page3.aspx
▪ page4.php
▪ page5.jsp
etc.
Development Process of a Web Site

In order to develop your own web site, you have to follow 3 stages:
I. Page Designing Stage
II. Client Side Programming Stage
III. Server Side Programming Stage

I. Page Designing Stage:


✰ In this stage, you have to design all the web pages that are required in your web site.
✰ To design the web pages, we take the support of one language called HTML.

II. Client Side Programming Stage:


✰ This includes with writing some programs for client system.
✰ These programs will be executed in the client system.
✰ In other words, as a part of the interaction between the client system and server system,
some programs are needed for the client and some other for server.
✰ The client level programs are called as ―Client side programsǁ and server level
programs are called as ―Server side programsǁ.
✰ Especially, the browser itself executes the client side programs.
✰ These client side programs perform the client level operations like client level
calculations, validating the user-input values whether those values are valid or invalid
and sending a request to the web server etc.
✰ To write the client side programs, we take the support of client side programming
languages:
A. JavaScript
B. VBScript (outdated)
III. Server Side Programming Stage:
✰ As you know, the server side code will be executed at web server system, and then
the output will be given as response to the client.
✰ This server side programming includes with receiving the request from the client,
getting some input values from the client, making some operations on the input
values and giving the response to the client.
✰ To write the server side programs, we take the support of server side programming
languages.
A. ASP (Active Server Pages)
B. ASP.NET (Active Server Pages.NET)
C. JSP (Java Server Pages)
D. PHP (Pre-Hypertext Processive)
✰ Currently, in our course, we are concentrating on Microsoft technologies like ASP and
ASP.NET.
HTML
(Hyper Text Markup Language)

It‘s a designing language; it‘s not a programming language. That means it doesn‘t
contains any programming concepts such as data types, variables, operators, control
statements, arrays etc. It contains some design concepts only.
Its syntax is written in the form of tags. The tag name is to be written within the < and
> symbols.
Def of Tag: A keyword, which is written inside of < and > symbols is called as ―Tagǁ.
The tags are two types in html.
1. Paired tags: These tags contain starting tag and ending tag.

<tag>
some content
</tag>

Ex: <b>the bolded text</b>


This above example displays the given text in ―Boldǁ format.

2. Unpaired tags: These tags contain only single tag. No starting / ending
tag.
<tag>

Ex: <img src=ǁc:\sample.jpgǁ>


This above example the specified image on the screen.

It is used to design the static web pages.


Types of web pages:
1. Static Web Pages: These web pages contain some content, which will
not be changed at run time.
Ex: login page.
2. Dynamic Web Pages: These web pages content can be changed at
run time.
Ex: Inbox page.
It is the case insensitive language. That means you can write the code in upper case and
lower case also.
Every language uses any one of the translators (Compiler or interpreter). HTML uses
―Interpreterǁ. In other words, no compilation is needed for html code. At run time, it will
be interpreted by the interpreter. The browser acts as interpreter for html program.
It was released by W3C (World Wide Web Consortium). Consortium means, ―group of
expertsǁ. W3C is the non-commercial organization, which organizes all the web related
languages and technologies.
No specific editor for html. You can use several editors for typing the html programs.
✰ Notepad
✰ Edit Plus
✰ Microsoft Front Page
✰ Microsoft Visual InterDev
✰ Macromedia Dream Weaver
✰ Microsoft Visual Studio
✰ Microsoft Visual Web Developer
etc.
Browser doesn‘t highlight the errors in the html code.
The file name should be ―.htmlǁ or ―.htmǁ. There is no much difference between these
two extensions. You can give any one of these extensions.
A Simple Web Page Development using HTML

Open any editor (Notepad or Edit Plus).


Type the html code as follows:

Save the file as ―sample.htmlǁ in any folder. (Ex: Save in desktop).


Open the folder, in which you have saved the file. (Ex: Open Desktop).
Double click on ―sample.htmlǁ.
Then the html page will be displayed on the browser.
You can observe the title bar text as you mentioned in the <title> tag.
You can observe the web page content, as you written in <body> tag.

Understanding the HTML Syntax

The html program syntax contains few tags as follows.

The <html> tag specifies the starting and ending point of the html program.
The <head> tag contains some non-content information of the web page. Non-content
information means, which will not be displayed in the document area of the browser.
The <body> tag specifies actual content of the web page.

Understanding the concept of Attributes

An attribute is nothing but a small setting related to the tag.


If you are using a paired tag, it should be written in the starting tag only.
Syn:
<tag attribute=ǁvalueǁ>

The <body> tag attributes

1) bgcolor: Specifies background color of the web page.


2) background: Specifies background image path of the web page.
3) link: Specifies default color of the hyperlinks of the web page.
4) alink: Specifies active link color, while you place your mouse pointer on the hyperlink and
hold it.
5) vlink: Specifies visited link color, after you click the hyperlink once.

Important HTML Tags


1) Basic tags:
<HTML>
<HEAD>
<BODY>
<TITLE>
<META>
<SCRIPT>
<STYLE>
2) Text Formatting tags:
<H1>
<H2>
<H3>
<H4>
<H5>
<H6>
<FONT>
<BR>
<DIV>
<CENTER>
<B>
<I>
<U>
<TT>
<STRIKE>
<PRE>
<SUP>
<SUB>
<P>

3) Link tags:
<A>

4) List Tags:
<OL>
<UL>
<LI>

5) Multi-media tags:
<IMG>
<HR>
<BGSOUND>
<MARQUEE>
6) Table tags:
<TABLE>
<CAPTION>
<TR>
<TH>
<TD>

7) Form tags:
<FORM>
<INPUT>
<TEXTAREA>
<SELECT>
<OPTION>

Note: All of these tags are described in the ―HTML beginners guideǁ file, which is attached to
this material. If you don‘t have an idea about all of these tags, a try to learn those from that
―HTML beginners guideǁ text book.

We understand HTML tags with an example.


<hr>

<p align="justify">
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. </p>
<hr>

<h1>This is heading level 1</h1>


<h2>This is heading level 2</h2>
<h3>This is heading level 3</h3>
<h4>This is heading level 4</h4>
<h5>This is heading level 5</h5>
<h6>This is heading level 6</h6>
<hr>

<p align="justify">
<font size="4" face="Century Gothic">
<font color="green">
.NET Framework latest version 4.0. .NET Framework latest version
4.1. .NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. </font> <font
color="red">.NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. .NET Framework latest
version 4.0. .NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. .NET Framework latest
version 4.0.</font>
</font>
</p>

<hr>

<font face="Comic Sans MS" size="5">

<div align="right"> This


is normal text.<br>
<b>This is bold text.</b><br>
<i>This is italic text.</i><br>
<u>This is underline text.</u><br>
<tt>This is teletype text.</tt><br>
<strike>This is strike-out text.</strike>
</div>

<hr>

<center>

<img src="c:\earth.gif">
<img src="c:\earth.gif" width="50px" height="40px" alt="The globe is
moving around the sun!">

</center>

<hr>

<marquee>
C#.NET is the No. 1 language today!
</marquee>

<marquee direction="right">
C#.NET is the No. 1 language today!
</marquee>

<marquee direction="right" behavior="alternate">


C#.NET is the No. 1 language today!
</marquee>

<hr>

<center>
<marquee behavior="alternate" width="270px">
<img src="c:\globe2.jpg">
</marquee>
</center>

<hr>
<bgsound src="c:\josh.mp3">

<a href="sample.html">
Click here for first example...</a><br>
<br>
<a href="c:\globe2.jpg">
<img src="c:\globe2.jpg" width="100px" height="100px">
</a>
<br><br>
<a href="c:\josh.mp3">
Click here to listen the music</a><br><br>
<a href="c:\SilverJubilee.wmv">
Click here to watch the video</a><br>

<br>
<a href="#top">
Top..</a><br>

</font>

<font face="Tahoma">
<hr>

<table border="3px" cellpadding="15px" align="center">


<caption>Students Table</caption>

<tr bgcolor="bisque">
<th>Student ID</th>
<th>Student Name</th>
<th>Marks</th>
</tr>

<tr> <td>101</td>
<td>Ashok Kumar</td>
<td>78</td>

</tr>

<tr> <td>102</td>
<td bgcolor="pink">Kiran</td>
<td>53</td>

</tr>

<tr> <td>103</td>
<td>Kiranmayi</td>
<td>47</td>

</tr>

<tr> <td>104</td>
<td>Joji</td>
<td>96</td>

</tr>

</table>
</font>
</body>
</html>
Output:

(Continued…)
registration.html

<html>
<head>
<title>Forms demo</title>
</head>
<body>
<form>
<center>

<h1>ABC Technical Training Institute</h1>


<h2>Hyderabad</h2>
<h2>Student Registration Form</h2>
<hr>

Student Name:
<input type="text"><br>

Age:
<input type="text" size="3"><br>

Password:
<input type="password"><br>

Confirm Password:
<input type="password"><br>
<input type="checkbox">Documents submitted?<br>
Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>

Marital Status:
<input type="radio" name="mar">
Single
<input type="radio" name="mar">
Married
<input type="radio" name="mar">
Divorced<br>

Resume Attachment:
<input type="file">
Output:
Java Script
JavaScript is known as Client Side Programming Language.
The JavaScript code will be executed at client system, by the browser.
In other words, the JS code will be interpreted by the browser.
It is mainly used to
1. Implement programming manipulations on the web pages such as
performing some calculations, changing the control‘s values at run time
etc.
2. Implementation of client side validations.
Validation: The process of checking the user-input values, whether the given values are
valid or invalid.
If the entered values are valid, then we allow the page to be submitted. Otherwise we
have to display proper error message to user.
JavaScript was released by Netscape Corporation. Later, it is moderated under the
administration of W3C.
At first, it was supported only in ―Netscape Navigatorǁ browser. But now-a-days
it is supported by all famous browsers.
JavaScript differs from Java, whereas Java is a large programming language with so
many programming features.
JavaScript derives some programming features from Java. That‘s why, it was named like
that.
The JS code can be embedded within the HTML page.
It can access the values of HTML controls, and can implement some operation on those
values, and finally can generate some output.
The Syntax of JavaScript Code

The <script> tag specifies starting and ending point of the JS code.
You can‘t write the html tags directly in the <script> tag. You can write only JS code.
Confirm Password:
<input type="password"><br>
<input type="checkbox">Documents submitted?<br>
Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>

Marital Status:
<input type="radio" name="mar">
Single
<input type="radio" name="mar">
Married
<input type="radio" name="mar">
Divorced<br>

Resume Attachment:
<input type="file">
<input type="button" value="Add">
<br>

Select Coursetype:
<select>
<option>Normal Track</option>
<option>Fast Track</option>
<option>Super Fast Track</option>
</select><br><br>

Select your Course(s):


<select multiple>
<option>.NET 4.0</option>
<option>Java</option>
<option>Oracle DBA</option>
<option>Sql Server DBA</option>
<option>MS BI</option>
<option>Share Point</option>
</select>

<hr>

<input type="submit">
<input type="reset">

<hr>

</center>
</form>
</body>
</html>
Output:

Note: At run time, in the browser, java script code will be blocked, because of some protection
features of browser. At that time, the following message will be appeared.

To activate java script code, you click on the above message, and choose ―Allow
Blocked Contentǁ. Click ―Yesǁ for confirmation. Then java script code will be activated.

Observation:
In the above example, when you click on ―Submitǁ button, the ―validate()ǁ function will
be called automatically.
The ―validate()ǁ function is a user-defined function, which contains some code
for validating the age value, whether it is in the range of 18 and 60.
If the age is valid, the form will be submitted to the web server (you can observe a small
process in the browser‘s status bar).
If the age is not valid, it displays ―Invalid ageǁ message.

Note: To understand more better about JavaScript, refer to ―HTML beginners guideǁ book,
which is attached to this material.
ASP 3.0
(Active Server Pages)
Remember that ASP is different and ASP.NET is different. ASP.NET is the improved
version of ASP 3.0. The ASP 3.0 version was released in the year of 1998.
ASP 3.0 is known as Server Side Programming Language.
It is one of the famous web scripting language in 1990‘s (before .NET Framework).
It can also be called as ―web technologyǁ.
It is used to implement server side code that will be executed by the web server, and the
output will be sent to the client (browser) and displayed on the screen.
The server side program will be executed, whenever the user clicks on ―Submitǁ button
on the html page. The server side program will be written in the ―server pageǁ.
When we click on ―Submitǁ button in the html page, it will be submitted to the
web server.
The server code in the server page, will receive the input values from the client page
(.html page), and implements some server logic on those values.
So that the server code does the following:
1. Receive the input values from the client page
2. Implement some server side logic
3. Send response to the client.
The client page extension is ―.htmlǁ; and server page extension is ―.aspǁ.
loginclient.html (save this file in any folder)
<head>
<html>
<title>Login</title>
</head>
<body bgcolor="beige">
<center>
<form name="f1"
action="http://localhost/loginserver.asp"
method="post"> <
h
1
>
L
o
g
i
n
<
/
h
1
>
<
h
r
>
U
s
e
r
n
a
m
e
:
<input type="text" name="txt1"><br>

Password:
<input type="password" name="txt2"><br>
<hr>

<input type="submit">
<input type="reset">

</form>
</center>
</body>
</html>
To run this application, double click on ―loginclient.htmlǁ. Enter the user name
and password.
If you enter the correct user name and password (system and manager), it opens the
server page and shows ―You are successfully Logged in…ǁ message, otherwise it shows
―Invalid Username / Passwordǁ message.
After clicking on Submit button…

In the client page, you have to design a html form compulsory. In that <form> tag, you
have to give the address of the server page, to which it is to be submitted.
Syn: http:/servername/pagename.asp
When you click on ―Submitǁ button, the server page will be opened, based on the given
URL.
At the time of submission, the parameter values (username and password) will be sent to
the server page.
In the server page (loginserver.asp) code, the ―Dimǁ statement (Dim stands for
Dimension) declares two variables for storing user name and password.
After that we retrieve the values from the client page using the control‘s names (txt1 and
txt2).
Then we check the values whether those are correct or not, using If statement.
Then we give the response message to the client using ―Response.Write()ǁ statement.
Note: To run this example in fact, you require a software named IIS compulsory. We
discuss more about IIS in further sessions.

Note: This much knowledge on ASP 3.0 is enough, before entering into ASP.NET.
Web Servers
Suppose, you are trying store a web site in the web server system, and accessing it from
another client system on the network.
Then you require a software in the server computer, which serves the web site to the
clients.
If that software is not loaded in the server computer, your web site can‘t be served to
the clients. If the client sends a request, no one will be there to receive the request and
give the response.
So that you require a software called ―Web Server Softwareǁ.
Remember that, it should be loaded in the server system only; not required in the client
systems.
Responsibilities of web server software‘s:
1. Store the web sites in a special folder, which are ready to be served to
the clients.
2. Serve the web site files (web pages) to the clients, based on the given
URL.
3. Handle the ―Requestǁ and ―Responseǁ operations.
4. Execute the server side scripts, which code is written in <% and %>
tags.
5. Handle the security related features, if we require any.
For our Microsoft Technologies like ASP and ASP.NET, we have a web server software
named ―IISǁ (Internet Information Services) / (Internet Information Server).
In the previous ASP 3.0 example, already we have used IIS; (by storing the
loginserver.asp page in the ―wwwrootǁ folder).
Every web server uses a port, to have a communication with the clients.

Web Server Root Directory:


Every web server uses its own root directory, in which all the web sites can be
stored. Then only those web sites can be served to the clients. Especially for IIS, we
have a root directory called:
C:\Inetpub\wwwroot
The above folder is called as ―Root directory of IIS Web Serverǁ.
Each web technology is having its own supporting web server(s):

Web Technology Web Server


ASP IIS (Internet Information Services)
IIS (Internet Information Services)
ASP.NET (or)
ASP.NET Development Server
Apache Tomcat Web Server
JSP (or)
BEA Web Logic Server
PHP Apache Tomcat Web Server

Finally, ASP is supported in IIS only; and ASP.NET is supported in IIS and ASP.NET Development
Server also.
IIS (vs) ASP.NET Development Server
Sl.
IIS ASP.NET Development Server
No
1 Developed by Microsoft. Developed by Microsoft.
Supports ASP 3.0 web sites and ASP.NET
2 Supports ASP.NET web sites only.
web sites also.
It should be installed manually, by using
3 Windows bootable CD. It is in-built in Visual Studio.
Introduced in the year of 2000, with MS Introduced in the year 2005, along with
4
Windows 2000 Server. Visual Studio 2005.
It contains a root
5 directory (C:\Inetpub\wwwroot). No specific root directory
The web sites should be stored in the root The web site can be stored in any folder in
6
directory only. your hard disk.
The web site can be accessed from remote The web site can‘t be accessed from the
7 clients (other computers on the remote clients. It can be run within the
network). same system only.
8 It is a professional web server. It is a personal web server.
It can be installed without Visual Studio
9 also. It can‘t be installed without Visual Studio.
It uses different port no‘s for different web
sites. The port no will be generated
It uses a fixed and default port no called
10 uniquely, at run time.
―80ǁ.
Ex: http://localhost:1020/mywebsite
Here, 1020 is the port no.
Doesn‘t support much user-defined security
11 Supports some useful security features.
features.
Not recommended for professional usage;
as it is meant for developer‘s personal usage
12 Recommended for professional usage.
only. It is useful, when you have no
IIS software in your system.

Confirming the IIS whether it is installed in your system or not:


Try to find the following folder:
C:\Inetpub\wwwroot
If the above specifies folder is there, and then you can understand that, you have IIS
software on your system; so that your system can act as a web server.
Installing IIS:
Insert bootable Windows CD / DVD.
Click ―Startǁ – ―Control Panelǁ.
Open ―Add / Remove Programsǁ.
Click on ―Add / Remove Windows Componentsǁ.

Check the checkbox for ―Internet Information Servicesǁ option.

Click ―Nextǁ button.


Then necessary files will be copied and IIS will be loaded on your system.
Checking the Functionality of IIS, whether it is working properly or not:
Open the browser.
Type the following URL:
http://localhost/
Press Enter.
Then it shows home of the IIS as follows:

If you find the above type of screen, then you can understand as IIS is working on your
system.
If you find the following error page, then you can understand as IIS is not working
properly on your system (or) IIS is not installed on your system.
Note that, generally when you switch-on your system, then the IIS services also be
started automatically.
Because of some reasons, sometimes it may not be started by default. Then you need to
start the IIS services manually.

Starting / Stopping the Services of IIS:


Click on ―Startǁ – ―Runǁ.
Type ―inetmgrǁ and press Enter.
Then ―Internet Information Servicesǁ window will be displayed.
There, expand the local computer.
Then expand ―Web Sitesǁ.
Then observe ―Default Web Siteǁ.
If it is already started, no message will be shown there.
If it is stopped, it will be displayed as ―Default Web Site (Stopped)ǁ.
Then you try to start the services, by right clicking on the ―Default Web Siteǁ option,
and by clicking on ―Startǁ.

If you want to stop the services, you can do so, by right clicking on the ―Default Web
Siteǁ option, and by clicking on ―Stopǁ.

Clash between IIS and Oracle HTTP Server:


IMP Note: If you have Oracle software also installed in your system, the IIS
services can‘t be started, even though you try to start the IIS services as above; because by
default Oracle HTTP server‘s services will be started automatically; and both of these servers use
the same port no ―80ǁ. Then IIS will not work, even though you have installed it properly. Then
to solve this problem, first stop the Oracle HTTP Server by click on ―Startǁ – ―Programsǁ –
―Oracle
– OraHomeǁ – ―Oracle HTTP Serverǁ – ―Stop Oracle HTTP Server power by Apacheǁ.
After that, you try to start the IIS services, as explained above. Then IIS services will be started
for sure. If not yet, contact any network administrator.
Understanding the URL in IIS:
When you store a web page in the web server‘s root directory, then only you can access
it from the same system or any other client on the network also.
Suppose you have stored ―loginclient.htmlǁ page in the ―c:\Inetpub\wwwrootǁ
folder. Then the file full path can be mentioned as:
c:\inetpub\wwwroot\loginclient.html
But you can‘t access the web page with the above specified path from other computers;
because it is representing physical hard disk addressing.
So that you have to access the page with logical address as follows:
Syn: http://<servername>/pagename.extension
Ex: http://myserver/loginclient.html
Here, you have to mention the name of the server system, in which you have stored the
web page. You can also use the word ―localhostǁ, to represent the same system.
Syn: http://localhost/pagename.extension
Ex: http://localhost/loginclient.html

So now you can understand that the part of the URL, http://myserver represents
―wwwrootǁ folder in the ―myserverǁ computer.
To have accessibility for client pages and server pages from the client computers, we
have to store both these types of pages in the ―wwwrootǁ folder only.

The general problem, in the “wwwroot” folder maintenance:


If you try to store different applications on the same system, there may be clumsiness
with so many files in the ―wwwrootǁ folder.

Solution for the above problem / Understanding “Virtual Directory”:


You try to create your own folder in the ―wwwrootǁ folder; then you store the required
files, for your project in that your own folder.
For example, create a folder called ―testǁ in the ―wwwrootǁ folder.
Drag and drop the ―loginclient.htmlǁ page and ―loginserver.aspǁ pages into ―testǁ folder.
Then the physical path will be like this:
C:\Inetpub\wwwroot\test\loginclient.html
C:\Inetpub\wwwroot\test\loginserver.asp
And then the logical address will be
like this:
http://localhost/test/loginclient.html
http://localhost/test/loginserver.asp
Now, the ―testǁ directory is called as ―Virtual Directoryǁ.
Virtual Directory: A sub folder, which is created in ―wwwrootǁ folder, is called as
―Virtual Directoryǁ.
ASP.NET
(The Modern Generation Web Technology)

ASP.NET stands for Active Server Pages.NET.


It is a web technology, which is used for development of web sites.
It is also known as Server Side Programming Language.
It was released by Microsoft Corporation.
It is the advanced version of ―ASPǁ.
When you compare with ASP 3.0, it contains so many new concepts like Post backing,
Master pages, Themes, Skins, Login controls etc.
The server page file extension is ―.aspxǁ (Active Server Page Extended).

Requirements of ASP.NET:
Web Page Designing Language: HTML
Client Side Scripting Language: JavaScript
Programming Language: C#.NET / VB.NET
Web Server: IIS / ASP.NET Development Server

Types of Web Sites


1) Traditional Web Sites:
❖ This type of web sites are in usage, before ASP.NET (before 2002).
❖ According to this, for every interaction, two web pages will be maintained:
▪ Client Page (.html)
▪ Server Page (.aspx)
❖ The user first opens the client page. Whenever the user clicks on the ―Submitǁ
button, automatically the server page will be opened. In other words, a Request
will be sent to the server page.
❖ The server page is responsible to receive the data values from the client page,
and perform some server side logics.
❖ Finally, it gives Response to the client.
❖ So that ―Traditional web sitesǁ can also be called as “Request – Response
Web Sites”.

2) Post-backing Web Sites:


❖ This is introduced in ASP.NET (in 2002).
❖ In this kind of web sites also, “Submit – Request – Response” operations are
performed; but instead of maintaining two pages, only single page will be
maintained; and that page should be a server page.
❖ Ex: An ASP.NET server page will be submitted to the same page.
❖ PostBack: A page will be submitted to itself.
❖ For example, when we click on a button in ASP.NET, the page will be submitted
to itself. That means ―PostBackǁ is happened there.
❖ This facilitates us to reduce the no. of pages in the pages; so that maintenance is
easy; and clumsiness will be reduced.
❖ When compared with ―Traditional web sitesǁ, these web sites are the
next generation web sites.
❖ In fact, post-backing is the in-built feature of ASP.NET, you need no write any
code for that.
❖ In ASP.NET, almost 99.9%, we won‘t implement ―Traditional web sitesǁ.
We implement these ―Post-backing web sitesǁ only.

3) AJAX Web Sites:


❖ This is introduced in ASP.NET 3.5 (in 2008).
❖ This is the new style of web site development.
❖ The main advantage of AJAX (Asynchronous Java Script and XML) is to submit
the partial information to the web server.
❖ So that un-necessary content on the web page will not be refreshed / reloaded.
❖ As an advantage of this, your web site will be executed faster.
❖ We discuss about AJAX functionality at the end of ASP.NET.
Advantages of ASP.NET

Automatic Generation of Designer Code: While you are designing the web pages in
ASP.NET, it generates the necessary tags automatically. So don‘t require to type tags
manually.
Post-backing: This feature reduces no. of web pages in your web site. Because of this
feature, you can write the application logic just like the windows applications. That
means you can implement the necessary events at server side.
Master Pages: To avoid the repetition of designing the common content among
multiple pages.
Data Controls: To display the database data better with / without the writing the code
manually.
Validation Controls: Avoids the usage of ―JavaScriptǁ for implementing the validations.
Login Controls: To implement the common login / logout features, without writing any
code.
Crystal Reports: There is no other server side programming language, which supports
―Crystal reportsǁ in the web sites.
Themes and Skins: To have uniformity in the controls, designed in all the web pages;
and finally to make the web page as a good looking page.
Support of Multiple Cultures: You can display the contents of the web pages, in
different regional languages like English / French / Arabic / Telugu / Tamil etc.
Security: It supports several security models like Windows based security, Forms based
security, Passport based security, Role based security etc.
Caching: To store the output of the page temporarily in the cache memory, and make
the web site to be executed faster.
Multiple Languages: You can write the functionality related code in any of the .NET
languages (Visual C#.NET or Visual Basic.NET), that you want.
WebParts: To personalize the web site, for every user. The user can modify the page
contents right from the browser.
AJAX: To make the web site executed faster, and to attract the user with better
functionality.
Web Services: To implement some interaction between one web site to another web
site.
Getting Started with ASP.NET

Creating a new ASP.NET Web Site:


Open Visual Studio 2010.
Click on ―Fileǁ – ―Newǁ – ―Web Siteǁ.

Select the language as ―Visual C#ǁ.


Select ―ASP.NET Empty Web Siteǁ.
Select Web Location: File System / HTTP / FTP
1. File System: If you select this option, you can give any path for saving
the web site. Ex: D:\MyWebSites\WebSite1. Then your web site will be
configured in ASP.NET Development Server automatically.
2. HTTP: If you select this option, you can give the HTTP URL only. Ex:
http://localhost/WebSite1. Then your web site will be configured in IIS
automatically.
3. FTP: If you select this option, you can give the FTP URL only. Ex:
ftp://myserver/WebSite1. In this case also, your web site can run under
IIS only. The only thing is, instead of storing the web site in your local
hard disk, it will be stored in the FTP Server.
After entering all the details, click on OK.
Then the new web site will be created.
Then the screen looks like this:

The next thing is you have to add the web pages to your web site.
Adding Web Pages to the Web Site:
Open the solution explorer.
Right click on the web site name and choose ―Add New Itemǁ.
Then select ―Web Formǁ.
Enter the name of the new page. Ex: Default.aspx
Then click on ―Addǁ.
Adding HTML Pages to the Web Site:
Open the solution explorer.
Right click on the web site name and choose ―Add New Itemǁ.
Then select ―HTML Pageǁ.
Enter the name of the new page. Ex: sample.html / sample.htm.
The default extension is ―.htmǁ.
Then click on ―Addǁ.
After adding two web pages, you screen appears like this:

Note: In ASP.NET Web Sites, we use ―Server Pagesǁ (Web Forms) only; Very rarely only
we use HTML pages; because in the server page, we can implement html code, JavaScript
and also some server side concepts.
Development of Web Pages
The next thing you need to continue is how to develop the web pages.
Your page development contains two stages:
✵ Designing
✵ Coding

i) Development of Web Pages


At first, try to design the web page with html tags.
As you know about html tags already try to type some html code in ―Default.aspxǁ file,
in the <form> tag as follows:

Press F5 to run the web site.


Then the page will be executed on the browser automatically and it looks like as follows:
Close the browser and come back to the Visual Studio.
This is nothing but designing the web page with html tags.
You can view the web page in 3 views:
1. Source view: By default, you are in ―Sourceǁ view. It shows the design code in
the form of tags.
2. Design View: To open this, Click on ―Designǁ option at the bottom side in your
Visual Studio. It displays a preview of the web page. It is comfortable and easy
to modify the content also. If you make any changes in the design view, it will be
affected in source view automatically. The necessary tags will be generated
automatically.

3. Split View: It shows the design view and source view at-a-time; so that you can
observe modify the content easier.
Without the writing the tags manually, you can design the web page by dragging and
dropping the controls from Toolbox into the page also.
To practice this, try to do as follows.
Right click on ―Solution Explorerǁ – ―Add New Itemǁ – ―Web Formǁ – ―mypage.aspxǁ -
―Addǁ.
Open Toolbox.
Drag and drop 3 labels, 3 textboxes and a button into the page as follows:

Set the following properties:


Label1:
Text: Enter First Number:
Label2:
Text: Enter Second Number:
Button1:
Text: Add
Label3:
Text: Result:
The screen looks like this:

Double click on ―Addǁ button and write the code as follows:


To run the page, right click on ―mypage.aspxǁ in the Solution Explorer; and choose
―View in Browserǁ.
While you have designed the page by dragging the dropping the controls, in the
―mypage.aspxǁ file, some tags were generated automatically.
To view that, open the page in ―Sourceǁ view.
So finally, the conclusion is, for every ASP.NET Web Form, there will be two files.
1. pagename.aspx
▪ Contains the designer code in the form of tags
2. pagename.aspx.cs
▪ Contains the programmer code in ―C#.NETǁ syntaxes.

So, we are maintaining two inter-linked for every page, as above (one is for
designing purpose and other one is for programming purpose). This type of maintenance is called
as “Code behind Technique”. This model is the comfortable and recommend model to avoid
clumsiness of the code; because if you write the design code and programming code within a
single file, it may not be understandable clearly and the code will be lengthy. In the earlier
versions of ASP.NET, they have introduced another technique called “In-page technique”.

According that ―In-page techniqueǁ, we maintain the designer code and


programmer code within a single file (.aspx file). This is not recommend. Anyway, we can
implement that technique also now, just for having an idea.
Implementation of In-page Technique:
Open solution explorer.
Right click on the web site name and choose ―Add New Itemǁ.
Select ―Web Formǁ.
Un-check the check box called ―Place code in separate fileǁ. (By default it will
be checked).
Enter the name of the new page as ―inpagetest.aspxǁ.

Click on ―Addǁ.
Click on ―Designǁ view.
Drag and drop a button control.
Double click on that and see where the Button1_Click event will be generated.
It will be generated in the ―.aspxǁ file only, instead of ―.aspx.csǁ file.
This is the implementation of ―In-page techniqueǁ.

Every page is a class:


In behind of every page, there will be a class; So that when you run the page on the browser, an
object will be created for that class automatically. That means if 5 users open the same page, it
means there are 5 objects for the page class.
Implicit Objects in ASP.NET Serer Pages
For ASP.NET web page, the following objects are commonly available. That means, you
don‘t require creating these objects.

Object Class Description

Represents the request that is sent by


the client. Using this object, you can
Request System.Web.HttpRequest
access the parameter values that are
sent from the client page.

Used to give the response to the


Response System.Web.HttpResponse
client (browser).

Represents the current session state


of the web client. (We discuss more
Session System.Web.SessionState.HttpSessionState
about Session state in the further
sessions)

Represents the application state of


the web server. (We discuss more
Application System.Web.HttpApplicationState
about Session state in the further
sessions)

Understanding the above objects:

1) Request:

Gets the value of the control, submitted from


Request.Form[―control nameǁ]
the client page.

Gets the value of the parameter, submitted


Request.Params[―parameter nameǁ]
from the previous client or server page.
2) Response:

Writes the text or html tags to the web page


Response.Write(―xxxxǁ);
output.

Response.Redirect(―urlǁ); Opens the web page, based on the given URL.

3) Session:

Gets the value of the given session state


Session[―variable nameǁ]
variable
Session.Count Gets the total no. of session state variables.

4) Application:

Gets the value of the given application state


Application[―variable nameǁ]
variable
Gets the total no. of application state
Application.Count
variables.
The Page Life Cycle
Whenever the client sends a request (opens the web page), the following life cycle will
be executed at server side.
The Page Events
Based on the above page life cycle, the following events will be executed on the page. In
order to implement the code for the following events, follow the below syntax:

protected void Page_eventname(object sender, EventArgs e)


{
//some code
}

Ex:

protected void Page_Load(object sender, EventArgs e)


{
//some code
}

Event Description

PreInit Executes before initializing the implicit objects of the page.


Init Executes after initializing the implicit objects of the page.
PreLoad Executes before loading the web page contents in the memory.
Load Executes after loading the web page contents in the memory.
PreRender Executes before rendering (displaying) the output on the browser.
Unload Executes at the time of closing the web page.
Output:
ASP.NET Controls
Let us recollect how we were using the Toolbox.
In the toolbox, it contains a list of controls.
From those list of controls, you can drag and drop any control (Button, TextBox,
CheckBox etc.), into the page. Then the control will be created in the page.
In the toolbox, the controls are displayed in various categories:
1. Standard Controls
2. Data Controls
3. Validation Controls
4. Navigation Controls
5. Login Controls
6. WebParts Controls
7. AJAX Extensions Controls
8. Reporting Controls
9. HTML Controls
In the above categories, except ―HTML Controlsǁ, all other type of controls are
the ASP.NET controls. Obviously the controls under ―HTMLǁ category are the HTML
controls.
Already we know that ASP.NET is a server side programming language. All the ASP.NET
concepts are nothing but server side concepts. So that, all the ASP.NET controls are
known as ―Server Controlsǁ. These controls will be executed at server side only. For
example, you write the code for ―Button_Clickǁ event. That code will be
executed at server side only. So that ―Buttonǁ is the server control.
All HTML controls are the ―Client Controlsǁ. These controls will be executed at client
side. For example, you drag and drop ―Buttonǁ control from ―HTMLǁ category into the
page. If you write code for ―button1_Clickǁ event, the code will be executed at client
side only. One more thing that you have to observe is, you can write the code for
―HTML buttonǁ in JavaScript language only. So in that if you are using a HTML button,
you can‘t implement any ASP.NET server side concepts in that.
So, in 99.9% of cases, we prefer server side controls only, instead of client controls.
One more thing is, when you drag and drop any server control, an ASP.NET tag will be
generated in the ―Sourceǁ view.
<asp:ControlName>
For example, you drag a button control from ―Standardǁ category. It generates
the following tag.
<asp:Button ID="Button1" runat="server" Text="Button" />

The above is not offered by HTML; it‘s offered by ASP.NET; so that it can be called as
―ASP.NET Server side tagǁ.
Next, you drag a button control from ―HTMLǁ category. It generates the following tag.
<input id="Button1" type="button" value="button" />

The above is offered by HTML; so that it can be called as ―HTML Client side tagǁ.
The next thing is, you just double click the server button. It generates the
―button1_clickǁ event in the C# syntax. There, you can write the server side code.
protected void Button1_Click(object sender, EventArgs e)
{

After that, you just double click the client button. It generates the
―button2_onclickǁ event in the JavaScript syntax. There, you can write the client side
code only using JavaScript.
<script language="javascript" type="text/javascript">
function Button2_onclick()
{

}
</script>
Note: Drag the ―Server buttonǁ from ―Standardǁ category; and ―Client buttonǁ from
―HTMLǁ category.
Then run the web site, and click the server button and client button.
Then the output will be as follows:

When you click the server button, it shows the output on the page as shown in the above
screen.
When you click the client button, it shows the output message in the dialog box.
One more difference you need to observe in this case. When you click the server button,
the page will be ―posted-backǁ. Then you can observe a progress bar displayed in the
status bar in the browser. But when you click the client button, the page will not be posted-
back; simply the JavaScript code will be executed at the client side.
PostBack: The page will be submitted to itself. As a part of this, the page will be closed
and re-opened.

IMP Note: You can‘t access the client controls in server code.
HTML Server Controls:

For example, you try to do like this. Take a new web site and a web page; Drag and drop
―Textǁ control from ―HTMLǁ category. Its name will be ―Text1ǁ.
Then drag a server side Button control from ―Standardǁ category.
Next, you try to write the following code in ―Button1_Clickǁ event.
Text1.Value = DateTime.Now.ToString();

That above statement can‘t be accepted, because basically ―Text1ǁ is the HTML control.
But there is a provision to access the HTML controls in the server code also.
To do this, open the page in ―Sourceǁ view, and add runat=”server” attribute in
the
<input> tag. Then the code looks like this:
<input id="Text1" type="text" runat="server" />

Then above code will work. In fact, when you write the runat=ǁserverǁ attribute for the
<input> tag, even though the textbox is a HTML control, it is identified and accessible in
the server code. This type of special HTML controls are called as “HTML Server
Controls”.
Finally, the application looks like this:
Note: Drag the ―Text1ǁ control from ―HTMLǁ category; and ―Buttonǁ from ―Standardǁ category.
ASP.NET Server Controls
i. Standard Controls:
It includes with few most commonly used controls like Button, TextBox,
CheckBox, Image etc.

ii. Data Controls:


It includes with few database-related controls, which are used to display the database
data.

iii. Validation Controls:


It includes with some controls, which are meant for implementing ―validationsǁ,
without using JavaScript code.

iv. Navigation Controls:


It includes with some controls, which displays the links of the web site in
categorized format.

v. Login Controls:
It includes with some controls, which implement login / logout related concepts,
without writing any code.

vi. WebParts Controls:


It includes with some controls, which are meant for allowing the web page content,
to be changed by the user, straightaway from the browser.

vii. AJAX Extensions Controls:


To implement AJAX technology.

viii. Reporting Controls:


To display reports (Microsoft reports / Crystal reports) in the page.
i) Standard Controls
1. Button: Performs an operation, whenever it is clicked.

Properties of Button

Property Description
ID Specifies the name of the control.
Text Specifies the visible text of the control.
BackColor Specifies the background color.
ForeColor Specifies the foreground color.
Font Specifies the font settings like font name, bold, italic, size etc.
BorderWidth Specifies the border size in the form of pixels.
Specifies the style of the border. (None / Dotted / Dashed / Solid /
BorderStyle
Double / Groove / Ridge / Inset / Outset)
BorderColor Specifies the color of the border.
Width Specifies the width (in pixels).
Height Specifies the height (in pixels).
Specifies the tooltip message, which can be displayed whenever you
Tooltip
move the mouse pointer on the control.
TabIndex Specifies the index in the tab order.
Enables / disables the control. ―Trueǁ means the control is enabled.
Enabled It responds for the user. ―Falseǁ means the control is disabled. The
control will not respond for the user.
Displays / Hides the control. ―Trueǁ means the control is
Visible visible
(displayed on the screen). ―Falseǁ means the control is hidden. The
control will not be displayed on the screen.

Events of Button
Event Description
Click Executes on clicking on the control.

2. Label: Displays a static message.

Properties of Label

Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible

Events of Label
No Events.
3. TextBox: Used to take input values from the user.

Properties of TextBox
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Enables / Disables automatic post backing, whenever the user
AutoPostBack
performs an action that causes an event.
Specifies the maximum characters length, which can be entered in
MaxLength
the textbox.
ReadOnly Enables / Disables the read-only for the textbox.
TextMode SingleLine / MultiLine / Password
Wrap Enables / Disables automatic wrapping nature in the textbox.

Events of TextBox
Event Description
TextChanged Executes on changing the textbox text.

4. Image: Displays a static image.

Properties of Image
Property Description
ID, BackColor, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip, TabIndex, Visible
ImageUrl Specifies the url of the image to be displayed.

Events of Image
No Events.

5. Hyperlink: Opens another web page, whenever it is clicked.

Properties of Hyperlink
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Specifies the url, which is to be opened, whenever the hyperlink is
NavigateUrl
clicked.
ImageUrl Specifies the url of the image to be displayed.
Events of Hyperlink
No Events.

6. LinkButton: Looks like a hyperlink, and offers button functionality. That means
whenever it is clicked, ―Click()ǁ event will be executed.

Properties of LinkButton

Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Specifies the url, which is to be opened, whenever the hyperlink is
NavigateUrl
clicked.

Events of LinkButton

Event Description
Click Executes on clicking on the control.

7. ImageButton: Looks like an image control, but offers button functionality. It executes
―Click()ǁ event, whenever it is clicked.

Properties of ImageButton

Property Description
ID, BackColor, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip, TabIndex, Visible
ImageUrl Specifies the url of the image to be displayed.

Events of ImageButton

Event Description
Click Executes on clicking on the control.

8. CheckBox: Offers to display two options on the page (true / false).

Properties of CheckBox

Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible, AutoPostBack
Represents the current status of the checkbox, whether is checked or un-
Checked checked. (true / false)
TextAlign Left / Right

Events of CheckBox
Event Description
CheckedChanged Executes on checking / un-checking the checkbox.

9. RadioButton: This is to display few options on the page. At least 2 or more radio
buttons are to be placed. The user can select any one of the radio buttons.

Properties of RadioButton

Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible, AutoPostBack
Represents the current status of the radio button, whether it is checked or
Checked un-checked. (true / false)
TextAlign Left / Right
Used to group-up the radio buttons. You have to give same group name for
GroupName all the radio buttons in the group.

Events of RadioButton

Event Description
CheckedChanged Executes on checking / un-checking the radio button.

10. CheckBoxList: Contains multiple check boxes as items.

Properties of CheckBoxList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
TextAlign Left / Right
RepeatDirection Vertical / Horizontal

Events of CheckBoxList

Event Description
SelectedIndexChanged Executes on clicking on any check box in the list.
Run Time Properties of CheckBoxList

Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently checked or
Items[index].Selected
not (true / false).

11. RadioButtonList: Contains multiple radio buttons as items. It offers automatic grouping
nature of all the radio buttons, without specifying the ―GroupNameǁ property.

Properties of RadioButtonList

Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
TextAlign Left / Right
RepeatDirection Vertical / Horizontal

Events of RadioButtonList

Event Description
SelectedIndexChanged Executes on clicking on any radio button in the list.

Run Time Properties of RadioButtonList

Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently checked or
Items[index].Selected
not (true / false).

12. ListBox: Displays multiple items as options, so that the user can select any one (or
more) items.

Properties of ListBox
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
SelectionMode Single / Multiple

Events of ListBox

Event Description
SelectedIndexChanged Executes on clicking on any item in the list.

Run Time Properties of ListBox

Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently selected or
Items[index].Selected
not (true / false).

13. DropDownList: Displays multiple items as options, so that the user can select any one
of the items. It is same as ―Combo boxǁ in windows applications.

Properties of DropDownList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.

Events of DropDownList

Event Description
SelectedIndexChanged Executes on clicking on any item in the drop down.

Run Time Properties of DropDownList

Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently selected or
Items[index].Selected
not (true / false).
14. Table: It is an imitation to html tables. It offers to create tables with few rows and
columns, without typing the table tags.

Properties of Table
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Specifies the collection or rows, which are to be displayed in the table. It
contains the inner property called ―Cellsǁ, which specifies the cells
collection. First, click on ―Rowsǁ property. There, add the required no. of
Rows
rows. Then select the required to row and click on ―Cellsǁ option to add
the
cells to the selected row. There, add the required no. of cells. Specify the
actual cell text, in the ―Textǁ property.
BackImageUrl Specifies the background image path.
Caption Specifies a title for the table.
Specifies the position of the caption in the table. (Top / Bottom / Left /
CaptionAlign Bottom)
GridLines None / Horizontal / Vertical / Both
HorizontalAlign Left / Center / Right / Justify

Events of Table
No Events

15. Literal: Displays the output of given html code. It supports all the html tags.

Properties of Literal

Property Description
ID, Text, Visible

Events of Literal
No Events

16. Calendar: Displays a calendar. The user can switch to previous / next month.

Properties of Calendar
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
SelectedDate Specifies the currently selected date in the calendar control.
Caption Specifies a title for the calendar.
Specifies the position of the caption in the control. (Left / Right / Top /
CaptionAlign Bottom)
ShowGridLines Enables / disables the grid lines.
Events of Calendar

Event Description
SelectionChanged Executes on selecting any date in the calendar.

Run Time Properties of Calendar


Property Description
SelectedDate Represents currently selected date value in the calendar.

Note: ―AutoFormatǁ option is available for this control. To change the auto format style,
right click on the calendar control and choose ―Auto Formatǁ option.

17. Panel: Acts as container for other controls. You can drag any other controls into the
panel.

Properties of Panel
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, HorizontalAlign
Scrollbars None, Horizontal, Vertical, Both, Auto

Events of Panel
No Events

18. BulletedList: Used to display few items with bullets or numbering. It is similar to <OL>
and <UL> tags in HTML.

Properties of BulletedList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Numbered, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman, Disc,
BulletStyle Circle, Square, CustomImage
To specify the path of the CustomImage, to be displayed as bullet for
BulletImageUrl every item.

Events of BulletedList
Event Description
Click Executes on clicking the control.
19. FileUpload: Used to implement ―Uploadǁ option to the user. It displays a textbox with
―Browseǁ button. The user can click on ―Browseǁ button and choose any file. After that
the selected file path will be displayed in the textbox automatically. Later, in the submit
button code, you have to write necessary code for uploading the file from client system
to server system.

Properties of FileUpload

Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible

Methods of FileUpload
Method Description
The file will be uploaded (copied) from the original location, into
SaveAs(―destinatio the specified destination location, based on the given destination
n file pathǁ) path. Generally you need to give the destination file path as server
root directory. (c:\Inetpub\wwwroot\filename.ext)

Events of FileUpload
No Events
Default.aspx

(Continued…)
Label1:
Text: ABCD
Technologies
BorderCol #CC00CC
o
r:
BorderStyl Dotted
e
:
Font: Arial Black,
X-Large
BackColor: #CC0000
ForeColor: Yellow
Label2:

Label3:
Text: Student
Name:
Font: Arial

TextBox1
:
Font: Arial

Label4:
Text: Age:
Font: Arial

TextBox2
Label5:
Text: Password:
Font: Arial

TextBox3:
TextMode: Password
Font: Arial

Label6:
Text: Confirm Password:
Font: Arial
TextBox4:
TextMode: Password
Font: Arial
Label7:
Text: Address:
Font: Arial
TextBox5:
TextMode: Multiline
Width: 218px
Height: 85px
Font: Arial
Label8:
Text: DateOfJoining
Font: Arial
Calendar1
:
AutoFormat: Colorful2
CheckBox
1:
Text: Documents
Submitted?
Font: Arial
CheckBox
2:
Text: Is Already
Registered?
AutoPostBac True
k
:
Font: Arial
Label9:
Text: Existing
Registration
Number:
Visible: False

Label10:
Text: Gender:
Font: Arial

RadioButton1:
Text: Male
GroupName: g1
Font: Arial

RadioButton2:
Text: Female
GroupName: g1
Font: Arial
Label11:
Text: Marital Status:
Font: Arial
RadioButtonLis
t 1:
Items: Single,
Married,
Divorced
RepeatDirection: Horizontal
Font: Arial
Label12:
Text: Preferable
Timings:
Font: Arial
CheckBoxList1:
Items: Morning,
Afternoon,
Evening
RepeatDirection: Horizontal
Font: Arial
Label13:
Text: Resume
Attachment:
Font: Arial
CheckBox1:
Text: Documen
ts
Submitte
d?
Font: Arial
FileUpload1:
Font: Arial
Label14:
Text: Course Type:
Hyperlink5:
Text: Contact Us
Font: Arial
NavigateUrl: mailto:customerc
are @abcd.com

LinkButton2:
Text: Hide the globe
Font: Arial

Hyperlink6:
ImageUrl: globe2.jpg
(Copy the image
into the web site
folder)
NavigateUrl: globe.jpg
(Copy the image
into the web site
folder)
Panel1:
BackColor: #33CCFF
Label16:
Text: Search:
Font: Arial
TextBox7:
Font: Arial
ImageButton1:
ImageUrl: search_button.gif
(Copy the image
into the web site
folder)
Label17:
Text: (null)
Font: Arial
ForeColor: #400040
Literal1:
Text: <h3><marquee
bgcolor="lightpink
">A
Default.aspx.cs

protected void LinkButton2_Click(object sender, EventArgs e)


{
Image1.Visible = false;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Table1.Visible = true;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Label17.Text = "Your search string is: " + TextBox7.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
string studentname;
int age;
string password, confirmpassword, address;
DateTime doj;
bool doc_submitted, already_registered;
string existing_regno, gender, maritalstatus, preferrable_timings, resume_file,
coursetype, course;
studentname = TextBox1.Text;
age = Convert.ToInt32(TextBox2.Text);
password = TextBox3.Text;
confirmpassword = TextBox4.Text;
address = TextBox5.Text;
doj = Calendar1.SelectedDate;
doc_submitted = CheckBox1.Checked;
already_registered = CheckBox2.Checked;
existing_regno = TextBox6.Text;
if (RadioButton1.Checked == true)
gender = "Male";
else
gender = "Female";
maritalstatus = RadioButtonList1.SelectedItem.Text;

preferrable_timings = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
preferrable_timings = preferrable_timings + CheckBoxList1.Items[i].Text + ", ";
}
resume_file = FileUpload1.FileName;
coursetype = DropDownList1.SelectedItem.Text;
course = ListBox1.SelectedItem.Text;

string outputmsg = "<h1>Your data has been submitted successfully! The submitted
data is:</h1><h2>";
outputmsg += "Student Name: " + studentname + "<br>";
outputmsg += "Age: " + age + "<br>";
outputmsg += "Password: " + password + "<br>";
outputmsg += "Confirm Passowrd: " + confirmpassword + "<br>";
outputmsg += "Address: " + address + "<br>";
outputmsg += "Date of Joining: " + doj.ToShortDateString() + "<br>";
outputmsg += "Documents Submitted? " + doc_submitted + "<br>";
outputmsg += "Is Already Registered? " + already_registered + "<br>";
outputmsg += "Existing Registration Number: " + existing_regno + "<br>";
outputmsg += "Gender: " + gender + "<br>";
outputmsg += "Marital Status: " + maritalstatus + "<br>";
outputmsg += "Preferrable Timings: " + preferrable_timings + "<br>";
outputmsg += "Resume file: " + resume_file + "<br>";
outputmsg += "Course type: " + coursetype + "<br>";
outputmsg += "Course: " + course + "<br>";

string uploadingfilename = Request.PhysicalApplicationPath + FileUpload1.FileName;


FileUpload1.SaveAs(uploadingfilename);

outputmsg += "File uploaded successfully!";


outputmsg += "</h2>";

Response.Write(outputmsg);
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
Label9.Visible = true;
TextBox6.Visible = true;
TextBox6.Focus();
}
else
{
Label9.Visible = false;
TextBox6.Visible = false;
}
}
aboutus.aspx
Alignment of Controls

✵ In the previous example, you may feel like, the ―the alignment of controlsǁ was not good.
✵ Yes, we have not concentrated on making the controls alignment good there.
✵ Now, concentrate on that.
✵ You can maintain the controls positions better, in two ways:
1. With HTML Tables
2. With Absolution Positioning

1) With HTML Tables:

❖ First, click on ―Tableǁ menu – ―Insert Tableǁ.


❖ Then it generates a html table and the screen looks like this:
❖ Then drag and drop the required controls directly into the table cells. For
example you design a login page as follows:
❖ Select two cells on the top row, right click and choose ―Modifyǁ - ―Merge Cellsǁ.
❖ Select the top row, and select the alignment as ―Centerǁ; ―bgcolorǁ property as
any color.
❖ For all the left side cells select the alignment as ―Rightǁ and ―Widthǁ as ―50%ǁ.
❖ For all the right side cells, select the alignment as ―Leftǁ and ―Widthǁ as ―50%ǁ.
❖ Select the ―bgcolorǁ for both the cells in the bottom row.
❖ Then the screen looks like this:
❖ Now, the alignment is good. This is how to maintain the controls alignment
better, with HTML tables.
Output:

2) With Absolute Positioning:


❖ You can specify the exact fixed position for every control.
❖ For this, you have to type the following attribute for every control in the
―Sourceǁ view manually.
Style=ǁposition:absolute; left: n pixels; top: n pixelsǁ

Syntax for Absolute Positioning:

<tag Style="position:absolute; top: xxx; left: xxx;" />

Ex for Absolute Positioning:


<asp:Image ID="Image1" runat="server" ImageUrl="c:\globe2.jpg"
Style="position:absolute; top: 155px; left: 593px;" />
Output:
The “Wizard” Control

✵ This is one of the most useful controls.


✵ This is to display a wizard, with few steps. The user can navigate the wizard, by clicking on
―Previousǁ and ―Nextǁ buttons.

✵ You don‘t require to write the code for ―Step1ǁ, ―Step 2ǁ link buttons and
―Previousǁ,
―Finishǁ buttons.
✵ The only thing is, you need to design the contents, directly in the required step.
✵ This is control features ―Auto Formatǁ option also.

Steps:
✵ First, drag and drop the ―Wizardǁ control into the page.
✵ Then click on ―>ǁ symbol, and click ―Add/Remove Wizard Stepsǁ.
✵ In the dialog box, click on ―Addǁ button and add two more steps. Totally where will be 2
steps.
✵ Specify the ―Titleǁ property for each step.
1. First Step
2. Second Step
3. Third Step
4. Final Step

✵ Click on ―OKǁ.
✵ Then the screen looks like this:
✵ Then design the controls into the panel, given in each step. You can switch-into another
step, by clicking on the step name.
✵ First Step:

✵ Second Step:

✵ Third Step:
✵ Final Step:

✵ Then double click on ―Addǁ button and ―Multiplyǁ button, and write the following code.

✵ Finally, click on ―First Stepǁ at design time and run it.


The “AdRotator” Control

✵ This is to display ads in your web site.


✵ For example, you open any commercial web site. In most of the web sites, at top side, bottom
side or right side you can see some ads are getting displayed.
✵ You can observe one more thing here. When you open the same page in different times,
different ads will be displayed.
✵ In fact, an ad is nothing an image. Generally it will be a gif file or jpg file.
✵ So to display an ad in your web site, if you are using an ―Imageǁ control, you have to
write some code for displaying different images (ads) at different situations.
✵ To avoid this problem, we have a specialized control in ASP.NET, which is more useful
while you develop the commercial web sites.
✵ That control is ―AdRotatorǁ control. This control dramatically displays different images
(ads) in different situations.
✵ In other words, for every execution of the page, it displays any one of the ads that are
already configured in that control.
✵ Now, you can observe one more point. To use the ―AdRotatorǁ control, we have to
configure / describe the list of ads to be displayed.
✵ To describe the list of ad images used in your web site, you have to write the code in the
descriptive language called ―XMLǁ.
✵ In general, XML is known as ―Descriptive languageǁ, which is used to describe
some data.
✵ So here, in this ―AdRotatorǁ control, you require to use XML, for describing the list of ads.
✵ Let us understand the steps involved in this control development.

Steps:
✵ First, you need to collect the ad images. Just for practice purpose, you can download the
ads from internet (from various web sites).
✵ Then take a new web site.
✵ Open Solution Explorer. Right click on the web site and choose ―New Folderǁ.
✵ Enter the new folder name as ―adsǁ.
✵ Right click on ―adsǁ folder and choose ―Open Folder in Windows Explorerǁ.
✵ Then copy the all the ad images from your downloaded location, into the ―adsǁ folder.
✵ Come back to the Solution Explorer, right click on the web site and choose ―Add New Itemǁ.
✵ Select ―XML Fileǁ.
✵ Enter the file name as ―ads.xmlǁ.
✵ Click on ―Addǁ.
✵ Now, we need to write the xml code for describing the list of ad images.
✵ First, place the cursor in ―ads.xmlǁ file and open the ―Propertiesǁ window. There select
―Schemasǁ – click on ―…ǁ button – select
http://schemas.microsoft.com/AspNet/AdRotator-Advertisement-File-1.2 - right click on
that and click ―Use selected schemasǁ – Then click on OK.
✵ The syntax of advertisement file is like this:

✵ In the above syntax, <?xml version="1.0"?> tag is called as XML prologue, which specifies
that, the current document is a XML document and it also specifies about the XML
version, that we are using currently. The current XML version is 1.0.
✵ The <Advertisements> tag is called as root element, which specifies starting point and
closing point the advertisement descriptions. The ―xmlnsǁ specifies the XML schema file
reference. A XML schema decides or describes what tags can be written in an ―.xmlǁ file.
✵ Next, each ad is to be described in individual <Ad> tags. So that, you can write multiple
<Ad> tags. Each <Ad> tag may contain the following inner elements.
1. <ImageUrl>: Specifies the path and file name of the image file, which is to be
displayed at run time.
2. <AlternateText>: Contains the text that is to be displayed on the screen, in
place of the image, whenever the image file is not found at run time.
3. <NavigateUrl>: Contains the URL (just like in hyperlink control), which should
be opened when the user clicks an ad at run time.
✵ With this knowledge, you can write an advertisement descriptive file XML.
✵ For this application, write the code as follows:

<?xml version="1.0" encoding="utf-8" ?>


<Advertisements xmlns="http://schemas.microsoft.com/AspNet/AdRotator-Advertisement-
File-1.2">
<Ad xmlns="">
<ImageUrl>~/ads/ad1.gif</ImageUrl>
<AlternateText>about.com</AlternateText>
<NavigateUrl>http://www.about.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad2.gif</ImageUrl>
<AlternateText>usedvehicles.com</AlternateText>
<NavigateUrl>http://www.usedvehicles.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad3.gif</ImageUrl>
<AlternateText>wca.com</AlternateText>
<NavigateUrl>http://www.wca.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad4.gif</ImageUrl>
<AlternateText>accentcareers.com</AlternateText>
<NavigateUrl>http://www.accentcareers.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad5.gif</ImageUrl>
<AlternateText>doomed.com</AlternateText>
<NavigateUrl>http://www.doomed.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad6.gif</ImageUrl>
<AlternateText>quantum.com</AlternateText>
<NavigateUrl>http://www.quantum.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad7.gif</ImageUrl>
<AlternateText>rockboard.com</AlternateText>
<NavigateUrl>http://www.rockboard.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad8.gif</ImageUrl>
<AlternateText>mitsubishi.com</AlternateText>
<NavigateUrl>http://www.mitsubishi.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad9.gif</ImageUrl>
<AlternateText>abyss.com</AlternateText>
<NavigateUrl>http://www.abyss.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad10.gif</ImageUrl>
<AlternateText>google.com</AlternateText>
<NavigateUrl>http://www.google.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad11.gif</ImageUrl>
<AlternateText>reliance.com</AlternateText>
<NavigateUrl>http://www.reliance.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad12.gif</ImageUrl>
<AlternateText>amazon.com</AlternateText>
<NavigateUrl>http://www.amazon.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad13.gif</ImageUrl>
<AlternateText>uefa.com</AlternateText>
<NavigateUrl>http://www.uefa.com</NavigateUrl>
</Ad>
</Advertisements>

✵ Note: In the above code, the tilde character ―~ǁ represents the current working web
site path. For example, your web site is stored in the ―c:\Inetpub\wwwrootǁ folder. Your
web site name is ―WebSite1ǁ. Then the current directory
(c:\Inetpub\wwwroot\WebSite1) can be represented as ―~ǁ character.

✵ The next thing is, you take a new web page and drag and drop the ―AdRotatorǁ control.
✵ Select the following property for the ―AdRotator1ǁ control.
AdvertisementFile: ~/ads.xml
✵ The design some other controls that you need as follows:
✵ That‘s it. Everything is over and you can run the web site.
✵ At run time, every time you refresh the page or click on the button, it displays various ads.
Click on Refersh..
Click on Refersh..
In this way, you can have different-different ads using ―AdRotatorǁ control.
SQL Server 2005 Basics
1. Open SQL Server:
Click on ―Startǁ – ―Programsǁ – ―Microsoft SQL Server 2005ǁ – ―SQL
Server Management Studioǁ.
It displays ―Connect to Serverǁ dialog box.

Enter the following values:


1. Server type: Database Engine
2. Server name: Name of the system (You can see the computer name in
the ―My Computerǁ properties)
3. Authentication: SQL Server Authentication
▪ Login: sa
▪ Password: xxxx (The password can be given at the time of SQL
Server software installation) Ex: 123
(or)
Authentication: Windows Authentication
After successful login to the server, it displays ―SQL Server Management Studioǁ
window.
2. Object Explorer:
In SQL Server Management Studio, the
―Object Explorerǁ displays
the information about the databases,
tables, stored procedures and functions.
First of all, expand the option
―Databasesǁ; then it displays list
of databases that currently exist on this
system.
If you expand any database (For ex:
sample), it displays some folders like
―Tablesǁ, ―Viewsǁ,
―Programmabilityǁ etc.
When you expand the ―Tablesǁ folder,
it displays the list of tables that exist the
selected database.
If you want to see the table structure,
right click on that table and choose
―Modifyǁ option. There you can
make any changes in the table design
(structure).
If you want to open the table data, right
click on that table and choose ―Open Tableǁ. Then the table rows will be
opened. Here also you can make changes in the table data, and also you can add
new rows here.
3. Creating a new Database:
A database is a collection of tables.
To create a new database, right click on ―Databasesǁ and choose ―New
Databaseǁ.
Then enter the new database name. Ex: mydata
Click on OK.
4. Creating a new Table:
Right click on ―Tablesǁ option in the ―Object Explorerǁ and choose ―New Tableǁ.
Enter the table structure of the new table.

Click on ―Saveǁ button to save the table. Then it asks for the table name. Enter
the desired table name.

Close the window finally.


5. Important Data Types in SQL Server:
varchar(width)
datetime
numeric(width)
int
float
decimal(width,dec)
bit
image

6. Working with “Query window”:


―Query windowǁ is a window, where you can enter the SQL queries and execute
them.
Open the ―Query windowǁ, by clicking on ―New Queryǁ window option
in the toolbar.
Select the database from the database list, in which your query is to be
executed.
Enter the required SQL query in the window.
To execute, press ―F5ǁ (or) click on ―Executeǁ button in the toolbar.
Then the SQL statement will be executed.

7. IMP SQL Statements:


DDL:
1. CREATE
▪ create table tablename(column1 datatype(width), column2
datatype(width), …);

2. DROP
▪ drop table tablename;

3. ALTER
▪ alter table tablename add columnname datatype(width);
▪ alter table tablename drop column columnname;
▪ alter table tablename alter column
columnname datatype(width);

DML:
1. SELECT
▪ select * from tablename;
▪ select column1, column2, .. from tablename;
▪ select * from tablename where condition;
▪ select column1, column2, … from tablename where condition;

2. INSERT
▪ insert into tablename values(value1, value2,…);

3. DELETE
▪ delete from tablename;
▪ delete from tablename where condition;

4. UPDATE
▪ update tablename set column1=value1, column2=value2;
▪ update tablename set column1=value1, column2=value2 where
condition;

Some exercise on SQL:


insert into products values(101,'Monitors',7890)
insert into products values(102,'Keyboards',450)
insert into products values(103,'Mouses',590)
insert into products values(104,'Processors',6202)
insert into products values(105,'RAM',2829)

select * from products

select ProductID,ProductName from Products

select Price*10/100 Tax from Products

select * from Products where Productid=104

select * from Products order by price desc

select * from Products where price between 2000 and 8000

select * from Products where price not between 2000 and 8000

select * from Products where price like '%0.00'

select * from Products where price like ' .00'

update products set price=price+1000

select * from products

delete from products where price<1500

select * from products


8. T-SQL (Transaction SQL):
Procedures:
create procedure procedurename(@variable datatype(width),…)
as begin
declare @variable datatype(width)
…….
…….
end

Functions:
create function functionname(@variable datatype(width),…)
returns returndatatype
as begin
declare @variable datatype(width)
…….
…….
return returnvalue
end

Note: The procedure can’t return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix “@” symbol without fail.
Some exercise on T-SQL:
ADO.NET
(ActiveX Data Objects.NET)

ADO.NET is known as ―Database Technologyǁ, which is used to connect with


the databases. That means some objects will work for interacting with the databases.
Basically, why we require database connection is: the frontend application itself, can‘t
store any data permanently. So that we require a storage mechanism. That storage
mechanism is nothing but our databases.
It can be used for database connections and offers to perform database manipulations
like inserting data to the tables, deleting un-necessary data, retrieving the required data
from the tables etc.
It can be used in any type of applications like console applications, windows forms
applications, web sites, web services, WCF services etc.
It can be used in any .NET language like C#.NET, VB.NET, VC++.NET etc.
It was developed based on its previous version called ―ADOǁ.
It offers much efficient features to easily handle with the database tables, especially
when you are dealing with multiple tables.

What type of databases we can connect using ADO.NET:


File Databases:
dBASE, FoxPro, MS Access, MS Excel etc.
Server Databases:
SQL Server, Oracle, My SQL etc.
What we can do using ADO.NET:

Insert some data into the database table.


Delete some data from the database table.
Update the data of a table.
Retrieve some data from the table.
Execute a stored procedure / function, i.e. already created at backend using PL/SQL.

ADO.NET Database Connection Architecture

Note: Here, the driver acts as mediator between the frontend application and backend
databases. The driver can also be called as ―Providerǁ. This provider may be released by
Backend Company or Frontend Company.

For various databases, we have respective providers.


Database Provider Released by
SQL Server sqloledb.1 Microsoft Corp.
oraoledb.oracle.1 Oracle Corp.
Oracle
msdaora.1 Microsoft Corp.
MS Access / MS Excel / FoxPro /
microsoft.jet.oledb.4.0 Microsoft Corp.
dBASE
MS Access 2007 / 2010 microsoft.ace.oledb.12.0 Microsoft Corp.
Understanding the Connection String:
The connection string provides the details about the connection string. That means, if
you want to connect with the database, you have to specify some details about the
connection like:
1. Server
2. User ID
3. Password
4. Provider
Server: Specify the name of the server system, which you want to connect. If you want
to connect with other server system on the network, you specify the name of that
system. Ex: myserver. If you want to connect with the same system, mention the server
name as ―localhostǁ. The server name can also be called as ―data sourceǁ.
User ID: Specify the user name for logging-in with the database.
Password: Specify the password for logging-in with the database.
Provider: Specify the name of the driver / provider, which you want to use with the
connection. You can see the available provider names, in the above table.

Syntax of Connection String:


―provider=xxxxx; user id=xxxxx; password=xxxx; data source=xxxxxǁ

Note: Just for separation of the individual values, we are using ―;ǁ.

ADO.NET Library
To perform above mentioned database operations, ADO.NET technology offers some pre-
defined classes, organized in the form of namespaces.
Library: System.Data
OleDbConnection

OleDbCommand

OleDbDataReader

OleDbDataAdapter

OleDbParameter

ADO.NET NameSpaces:

1) System.Data
Contains necessary classes and namespaces to manipulate the databases.
2) System.Data.SqlClient
Contains necessary classes, used to interact with the SQL Server database.
3) System.Data.OleDb
Contains necessary classes, used to interact with any other databases. Of course,
the OleDb namespace also supports to connect with SQL server database, but we
won‘t use it for SQL Server, because ―SqlClientǁ namespace is especially
available for that.
ADO.NET Classes:

1) Connection:
Maintains the connection with the database.
2) Command:
Executes a query statement (select statement), non-query statement (insert
statement / delete statement / update statement) or a stored procedure /
function at backend.
3) DataReader:
It acts as a buffer, which holds the data, after execution of a query statement at
backend.
4) DataAdapter:
Executes a query statement at backend.
5) Parameter:
Sends a parameter (argument) value to a backend stored procedure / function.
6) DataSet:
Acts as a buffer, which holds multiple tables at-a-time.
7) DataTable:
Acts as a buffer, which holds a single table (collection of rows and columns).
8) DataRow:
Acts as a buffer, which holds a single row.
9) DataColumn:
Acts as a buffer, which holds a single column.

Note: All of above are the classes; you need to create object(s) for those classes.
Connecting the Database

Library: SqlConnection / OleDbConnection

ConnectionString: This property contains the connection string, used for the
connection.
Open(): This method opens the database connection.
Close(): This method disconnects the database connection.

Connecting with SQL Server:


Import the Library (at the top):
using System.Data.SqlClient;
Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>ǁ;
Note: The ―initial catalogǁ specifies the name of the SQL Server database, in which
your table exists.
Open the connection:
cn.Open();
Close the connection:
cn.Close();
Connecting with Oracle / MS Access / Fox Pro:
Import the Library (at the top):
using System.Data.OleDb;
Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
Prepare the Connection string:
cn.ConnectionString = ―provider=oraoledb.oracle.1;

Oracle data source=<name of the


server>; user id=<user name>;
password=<password>ǁ;
MS
cn.ConnectionString =
Access /
dBASE / ―provider=microsoft.jet.oledb.4.0;data source=<path of the
FoxPro
database file>ǁ;

Open the connection:


cn.Open();
Close the connection:
cn.Close();

Create a new Web Site.


Add ―Default.aspxǁ page to the web site.
Open Solution Explorer. Right click on ―Default.aspxǁ and select ―Set as Start Pageǁ.
Design ―Default.aspxǁ as follows:
Set the properties of HyperLink1:
1. Text: Database Connection Demo
2. NavigateUrl: ~/DatabaseConnectionDemo.aspx
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ.
Enter the page name as ―DatabaseConnectionDemo.aspxǁ.
Click on ―Addǁ.
Design the ―DatabaseConnectionDemo.aspxǁ page as shown:
Write the code:
using System.Data.SqlClient;
using System.Data.OleDb;

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123";
cn.Open();
Label2.Text = "Successfully Connected with SQL Server";
cn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=oraoledb.oracle.1;user id=scott;password=tiger";
cn.Open();
Label2.Text = "Successfully Connected with Oracle";
cn.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data
source=c:\\database1.mdb";
cn.Open();
Label2.Text = "Successfully Connected with MS Access";
cn.Close();
}
Sending Commands to the Database
After connecting the database, you can send the commands to the database.
ADO.NET supports to send the following types of commands.
1. Insertion Command
2. Deletion Command
3. Updation Command
4. Select Command / Query Command
5. Stored Procedure / Function Command

1) Insertion Command:
To insert a new row into the table.
SQL statement: insert into tablename values(value1, value2,…)

2) Deletion Command:
To delete one or more rows from the table.
SQL statement: delete from tablename where condition

3) Updation Command:
To update (modify) the table data.
SQL statement: update tablename set column1=value1, column2=value2
where condition

4) Select Command:
To retrieve the data from the database table, into the frontend application.
SQL statement: select * from tablename

5) Stored Procedure / Function Command:


To call a stored procedure / function from the frontend application, that is already
created at backend.
SQL statement: No SQL statement is needed
Understanding the “Command” class:
In order to send the commands, you need to use ―Commandǁ class.
Library: SqlCommand / OleDbCommand

a) CommandText: This property contains the SQL statement (insertion statement


/ deletion statement / updation statement / select statement)

b) Connection: This property contains the reference of the connection object,


based on which, the above given SQL statement is to be executed.

c) CommandType: This property specifies the type of the command that you want
to execute. It is of two types:
✵ Text: (default) This is used for any SQL statement (insertion statement /
deletion statement / updation statement / select statement)
✵ StoredProcedure: This is used for Stored Procedure / Function only.

d) Parameters: This property contains the list of parameters (argument values),


that are to be sent to backend, while you are calling a stored procedure /
function. It is of ―collectionǁ type, so that you can add any no. of parameters.

e) ExecuteNonQuery(): This method is used to execute any SQL statement


(insertion statement / deletion statement / updation statement / select
statement) or a stored procedure / function also. In other words, this method
moves the execution flow to backend database, execute the command there and
then come back with some result. This method returns ―no. of rows affectedǁ,
which represents the count of the rows, which are affected by executing this
command. Suppose, after executing a delete statement, 2 rows are deleted. So it
returns the integer value ―2ǁ.

f) ExecuteReader(): This method is used to execute ―selectǁ statement only. In


other words, it is used to retrieve some data from the database, based on the
given select statement. In other words, this method moves the execution flow to
backend database, execute the command there and then come back with some
result data. This method returns the table data, based on the given select
statement.

Implementation Code for SQL Server:


Import the Library (at the top):
using System.Data.SqlClient;
Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>ǁ;
Open the connection:
cn.Open();
Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statementǁ;
Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
Close the connection:
cn.Close();
Implementation Code for Oracle (or any other database):
Import the Library (at the top):
using System.Data.OleDb;
Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>ǁ;
Open the connection:
cn.Open();
Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statementǁ;
Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
Close the connection:
cn.Close();
Demo:
✵ Open SQL Server 2005.
✵ Create a new database, with name as ―demoǁ.
✵ In that database, create a table named ―Customersǁ, as shown below.

✵ Open the previous demo web site.


✵ Open ―Default.aspxǁ page and add the hyperlinks called ―Insertionǁ,
―Deletionǁ,
―Updationǁ as shown below:
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as ―Insertion.aspxǁ.
Click on ―Addǁ.
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as ―Deletion.aspxǁ.
Click on ―Addǁ.
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as ―Updation.aspxǁ.
Click on ―Addǁ.
✵ Come back to ―Default.aspxǁ and set the following properties:
✵ Properties of ―HyperLink2ǁ:
Text: Insertion
NavigateUrl: ~/Insertion.aspx
✵ Properties of ―HyperLink3ǁ:
Text: Deletion
NavigateUrl: ~/Deletion.aspx
✵ Properties of ―HyperLink4ǁ:
Text: Updation
NavigateUrl: ~/Updation.aspx
✵ Design the ―Insertion.aspxǁ page as follows:

✵ Write the code:


Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:

" + textBox1.Text + "


✵ Design the ―Deletion.aspxǁ page as follows:
✵ Write the code:
✵ Design the ―Updation.aspxǁ page as follows:

✵ Write the code:


Retrieving Data from the Database
For retrieving the table data from the database, you write a select statement (query
statement) in the frontend code.
Next, you need to pass it to backend using ―Commandǁ class object.
Then your select statement will be executed at backend. Then the DBMS (Oracle / SQL
Server / My SQL etc.), returns the result data, based on the executed query. For
example, if your statement is ―select * from departmentsǁ, then the entire departments
table data will be returned as it is.
Then frontend, you have to receive the data into a temporary memory location (buffer).
To create a buffer in your code, you can use ―DataReaderǁ class.
After that, you can present the data on the screen for the user.
This is the flow of data. You can observe this flow in the following diagram.
Library:
Connection: Maintains the connection with database.
Command: Sends a SQL statement and executes it at backend.
DataReader: Acts as a buffer. It holds the data, which is received from database.

Note: Here, to execute the select statement, you have to use ―ExecuteReader()ǁ
method of command class. After execution of the statement, it returns the entire data, i.e.
retrieved from the database, in the form of ―DataReaderǁ class object. So that we have to
receive it into an instance of ―DataReaderǁ class.

Classes, to be used in this concept:

Understanding the “DataReader” class:


It‘s known as buffer. It‘s not visible; it stores the data in the memory.
It contains the data in the form of a table itself.
Ex:

Library: SqlDataReader / OleDbDataReader

a) Read(): This method moves the record pointer, to the next record. For the first
time call of this method, the record pointer point-outs the first record. After that,
for every call it jumps to next record. If the next record is found, then it returns
―trueǁ; if the next record is not found, that means whenever it is reached end of
the data, then it returns ―Falseǁ.
Ex:

dr.Read();

(true)
dr.Read();

(true)

dr.Read();

(true)

dr.Read();

(true)

dr.Read();
b) [“column name”]: This indexer gets the value, at the specified column name,
in the current row, which is currently pointed-out by the record pointer.

c) [index]: This indexer gets the value, at the specified column index, in the
current row, which is currently pointed-out by the record pointer. The column
index always starts from ―0ǁ.

d) Close(): This method closes the buffer. At the end of your code, you can close
it.

Implementation Code for SQL Server:


✵ Import the Library (at the top):
using System.Data.SqlClient;
✵ Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
✵ Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>ǁ;
✵ Open the connection:
cn.Open();
✵ Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
✵ Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statementǁ;
✵ Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
✵ Construct the “DataReader” class object:
SqlDataReader dr;
✵ Open the connection:
cn.Open();
✵ Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();
✵ Read the next row.
dr.Read();
✵ Get the value at specific column:
dr[column index];
(or)
dr[―column_nameǁ];
✵ Close the buffer:
dr.Close();
✵ Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


✵ Import the Library (at the top):
using System.Data.OleDb;
✵ Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
✵ Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>ǁ;
✵ Open the connection:
cn.Open();
✵ Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
✵ Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statementǁ;
✵ Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
✵ Construct the “DataReader” class object:
OleDbDataReader dr;
✵ Open the connection:
cn.Open();
✵ Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();
✵ Read the next row.
dr.Read();
✵ Get the value at specific column:
dr[column index];
(or)
dr[―column_nameǁ];
✵ Close the buffer:
dr.Close();
✵ Close the connection:
cn.Close();
Demo:

✵ Open the previous demo web site.


✵ Add the hyperlink called ―View Data using Data Readerǁ as shown below:

✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as
―DataReaderDemo.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink5ǁ:
Text: View Data using Data Reader
NavigateUrl: ~/DataReaderDemo.aspx
✵ Design the ―DataReaderDemo.aspxǁ page as follows:

✵ Write the Code:


❑ Sometimes, you may need to display the records based on the user-entered value. For
example, when the user enters the customer id, then you need to display the respective
customer details. We take a demonstration like that:

✵ Add the hyperlink called ―View Data using Data Reader – Conditional Dataǁ as
shown below:
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as
―DataReaderDemo_ConditionalData.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink7ǁ:
Text: View Data using Data Reader – Conditional Data
NavigateUrl: ~/DataReaderDemo_ConditionalData.aspx

✵ Design the ―DataReaderDemo_ConditionalDataǁ page as follows:

✵ Write the Code:


cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select customername,gender,amount from customers where
customerid=" + TextBox1.Text + " ";
cmd.Connection = cn;

//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();

//presentation / buffer logic


if (dr.Read() == true)
{
TextBox2.Text = Convert.ToString(dr[0]);
if (Convert.ToString(dr[1]) == "Male")
RadioButton1.Checked = true;
else
RadioButton2.Checked = true;
TextBox3.Text = Convert.ToString(dr[2]);
}
else
Label6.Text = "No Data Found...";

dr.Close();
cn.Close();
}
ADO.NET Disconnected Model
ADO.NET database connection is of two types:
1. Connected Model:
▪ Implemented with ―DataReaderǁ buffer.
2. Disconnected Model:
▪ Implemented with ―DataSetǁ, ―DataTableǁ, ―DataRowǁ buffers.

To overcome the limitations of ―Connected Modelǁ, ADO.NET introduces ―Disconnected


Modelǁ.
The main advantage of ―Disconnected Modelǁ is, even though the connected is
not opened, it works. That means, when you execute any statement, the connected will
be opened, then the statement will be executed and then finally the connected will be
closed.
But the connected model is not like that. If you take the buffer called ―data
readerǁ which is used in the connected model, it works when the connection is opened
only. But the ―disconnected modelǁ buffers work even though the connection is opened
or not.
In the connected model, we were using only one buffer.
1. DataReader
In the disconnected model, three buffers are used.
1. DataSet
2. DataTable
3. DataRow

Library:
Connection: Maintains the connection with database.

DataAdapter: Sends a sql statement and executes it at backend. It‘s just like Command
class, in the connection oriented model. The difference between Command class and
DataAdapter class is, the ―Commandǁ class is used to execute any type of
statement (insert statement, delete statement, update statement and select statement).
But adapter executes select statement only.
DataSet: Holds the data that is received from database, after execution of DataAdapter.
It can hold multiple tables data at-a-time. In other words, it contains an array of tables.

DataTable: Holds a single table, from the DataSet.

DataRow: Holds a single row, from the DataTable.

Limitations of Connection Oriented Model


(or)

Advantages of Disconnected Model

The ―DataReaderǁ works only when the connection is closed. But the ―DataTableǁ
works even though the database is disconnected.
The ―DataReaderǁ buffer supports record travelling only once in its lifetime. But the
―DataTableǁ buffer supports record travelling any no. of times in its life time.
The ―DataReaderǁ buffer supports only forward record travelling. It doesn‘t
supports backward or random record travels. But ―DataTableǁ supports forward,
backward and random record travels.
―DataReaderǁ supports sequential records travels only. It doesn‘t supports to pick-up a
record directly with its index. But ―DataTableǁ supports to pick-up a record directly with
its index.
―DataReaderǁ supports only column indexing. ―DataTableǁ supports both column and
row indexing.
―DataReaderǁ data can‘t be assigned to ―DataGridViewǁ control. But the ―DataTableǁ
data can be assigned to the ―DataGridViewǁ control.
Diagrammatical View of Disconnected Model:
Classes, to be used in this concept:

Understanding the “DataAdapter” class:


Tables[table_index]: Gets the entire table, from the ―Tablesǁ array, based on
the given index. So, ―Tablesǁ is an array here.

Clear(): Clears all the tables, and makes the dataset empty.
Understanding the “DataTable” class:
Rows.Count: Gets the no. of rows that exist in the current table.
Rows[row_index]: Gets the single row at the specified index.
Columns.Count: Gets the no. of columns that exist in the current table.
Columns[column_index]: Gets the single column at the specified index.

Understanding the “DataRow” class:


[column_index]: This indexer gets the value at the given column, based on the given
index.
[“column_name”]: This indexer gets the value at the given column, based on the
given column.

Implementation Code for SQL Server:


Import the Library (at the top):
using System.Data.SqlClient;
Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>ǁ;
Open the connection:
cn.Open();
Construct the “DataAdapter” class object:
SqlDataAdapter adp = new SqlDataAdapter(―select statementǁ,cn);
Construct the “DataSet” class object:
DataSet ds = new DataSet();
Construct the “DataTable” class object:
DataTable dt;
Construct the “DataRow” class object:
DataRow drow;
Execute the adapter and receive the data into DataSet:
adp.Fill(ds);
Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];
Get the total no. of rows in the table:
dt.Rows.Count;
Get the total no. of columns in the table:
dt.Columns.Count;
Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
Get the particular value in the “DataRow”:
drow[column index];
(or)
drow[―column
nameǁ];
Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


Import the Library (at the top):
using System.Data.OleDb;
Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>ǁ;
Open the connection:
cn.Open();
Construct the “DataAdapter” class object:
OleDbDataAdapter adp = new OleDbDataAdapter(―select statementǁ,cn);
Construct the “DataSet” class object:
DataSet ds = new DataSet();
Construct the “DataTable” class object:
DataTable dt;
Construct the “DataRow” class object:
DataRow drow;
Execute the adapter and receive the data into DataSet:
adp.Fill(ds);
Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];
Get the total no. of rows in the table:
dt.Rows.Count;
Get the total no. of columns in the table:
dt.Columns.Count;
Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
Get the particular value in the “DataRow”:
drow[column index];
(or)
drow[―column
nameǁ];
Close the connection:
cn.Close();
Demo:

✵ Open the previous demo application.


✵ Add the hyperlink called ―View Data using Data Setǁ as shown below:

✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the page name as
―DataSetDemo.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink7ǁ:
Text: View Data using Data Set
NavigateUrl: ~/DataSetDemo.aspx
✵ Design the ―DataSetDemo.aspxǁ page as follows:

✵ Write the Code:


❑ Sometimes, you may need to display the records one-by-one in flexible manner,
depending on the clicked buttons like ―Firstǁ, ―Previousǁ, ―Nextǁ, ―Lastǁ. We take a
demonstration like that:

✵ Add the hyperlink called ―View Data using Data Set – Flexible Records Presentationǁ as
shown below:
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the page name as
―DataSetDemo_FlexibleRecords.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink8ǁ:
Text: View Data using Data Set – Flexible Records Presentation
NavigateUrl: ~/DataSetDemo_FlexibleRecords.aspx

✵ Design the ―DataSetDemo_FlexibleRecords.aspxǁ page as follows:

✵ Write the Code:


static int RowIndex;
DataRow drow;

private void Display()


{
drow = dt.Rows[RowIndex];
TextBox1.Text = Convert.ToString(drow[0]);
TextBox2.Text = Convert.ToString(drow[1]);
if (Convert.ToString(drow[2]) == "Male")
RadioButton1.Checked = true;
else
RadioButton2.Checked = true;
TextBox3.Text = Convert.ToString(drow[3]);
}

protected void Page_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

//DataTable impl
dt = ds.Tables[0];

if (Page.IsPostBack == false)
{
//display first record
RowIndex = 0;
Display();
}
Label6.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
//display first record
RowIndex = 0;
Display();
}
protected void Button2_Click(object sender, EventArgs e)
{
//display previous record
RowIndex--;
❑ Using with the DataTable buffer, it is possible to display the data in the ―GridViewǁ
control (or in any other ―Data Controlsǁ). In other words, the dataset data can be assigned into
―GridViewǁ control programmatically. The ―GridViewǁ control is one of the major famous
controls, which displays the data in a table format. It is easy to use it. To assign the data into
this ―GridViewǁ control, write the following statement:

GridView1.DataSource = datatable_obj;
GridView1.DataBind();

Here, the ―DataBind()ǁ method displays the data on the screen. By default, when you assign the
―DataSourceǁ property, that source of the data only be applied. But the data will not be
displayed on the screen. When you call the DataBind() method, then only the data will be
rendered on the output.
Sample Output:

We take a demonstration like that:

✵ Add the hyperlink called ―View Data using Data Set - GridViewǁ as shown below:

✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the form name as
―DataSetDemo_GridView.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink9ǁ:
Text: View Data using Data Reader
NavigateUrl: ~/DataSetDemo_GridView.aspx
✵ Design the ―DataSetDemo_GridView.aspxǁ page as follows:

[Drag and drop the ―GridViewǁ control from the ―Dataǁ category at the toolbox].
✵ Write the Code:
Working with Stored Procedures / Functions
This is to call a procedure / function from the frontend application.
This includes with:
1. First, create the procedure / function at backend using PL SQL.
2. Call it with its name, from the frontend code.
Note: PL SQL is supported by SQL Server, Oracle and My SQL.

Purpose / Advantages of Stored Procedures / Functions:


To perform multiple database transactions (insert / delete / update / select) at-a-time,
with a single database call.
To retrieve multiple tables data at-a-time, with a single database call.
To implement complex database logics, which is a collection of multiple if conditions,
loops etc.
To hide query / non-query statements in the code.
To have a faster execution, because the stored procedure is basically a pre-compiled
object.

For example, in your project you want to perform 2 insertions, 3 deletions at various
tables. If you implement the code with previous concepts, you require large code and moreover
at run time 5 database calls will be sent. That means the execution flow goes to the backend,
executes one statement and comes back. For all of these, it takes much time. So the application
will be executed slower. If the application is running multiple client systems simultaneously, it will
be slower. It that time, this ―Stored Procedure Callingǁ concept is recommended. As an
advantage of this, those 5 transactions would be performed with a single database call.
Library:
Connection: Maintains the connection with database.
Command: Calls a database procedure / function.
Parameter: Represents the argument value for the procedure / function.

Implementation Code for SQL Server:


Import the Library (at the top):
using System.Data.SqlClient;
Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>ǁ;
Open the connection:
cn.Open();
Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
Assign the reference of “Connection” class object to “Command” class object:
cmd.Connection = cn;
Assign the procedure / function name that is to be executed:
cmd.CommandText = ―xxxxxǁ;
Assign the command type to “Command” class object:
cmd.CommandType = CommandType.StoredProcedure;
Assign the parameters (if any) to the “Command” class object:
cmd.Parameters.AddWithValue(―parameter_nameǁ, value);
………………….;
………………….;
Execute the procedure / function:
cmd.ExecuteNonQuery();
Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


Import the Library (at the top):
using System.Data.OleDb;
Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>ǁ;
Open the connection:
cn.Open();
Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
Assign the reference of “Connection” class object to “Command” class object:
cmd.Connection = cn;
Assign the procedure / function name that is to be executed:
cmd.CommandText = ―xxxxxǁ;
Assign the command type to “Command” class object:
cmd.CommandType = CommandType.StoredProcedure;
Assign the parameters (if any) to the “Command” class object:
cmd.Parameters.AddWithValue(―parameter_nameǁ, value);
………………….;
………………….;
Execute the procedure / function:
cmd.ExecuteNonQuery();
Close the connection:
cn.Close();

Demo:

✵ Open SQL Server 2005.


✵ Already you have created ―demoǁ database. Confirm, whether it is exist or not.
✵ In that database, create a table named ―Studentsǁ, as shown below.

✵ Click on ―New Queryǁ option in the toolbar.


✵ Then type the following code:

✵ Then Press ―F5ǁ.


✵ It displays the following message:
Command(s) completed successfully.
✵ Enter some sample data as follows:
✵ Open the previous demo web site in Visual Studio.
✵ Add the hyperlink called ―Stored Procedure Demoǁ as shown below:
✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the page name as
―DataSetDemo_GridView.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink10ǁ:
Text: Stored Procedure Demo
NavigateUrl: ~/StoredProcedureDemo.aspx
✵ Design the ―StoredProcedureDemo.aspxǁ page as follows:
✵ Write the Code:
Demo on Retrieving Multiple Tables Data using
Stored Procedure:

✵ Open SQL Server 2005.


✵ Click on ―New Queryǁ option in the toolbar.
✵ In the ―demoǁ database, create the stored procedure as follows.

✵ Then Press ―F5ǁ.


✵ It displays the following message:
Command(s) completed successfully.

✵ Open the previous demo web site in Visual Studio.


✵ Add the hyperlink called ―Stored Procedure Demo – Multiple Tablesǁ as shown below:

✵ Click on ―WebSiteǁ menu – ―Add New Itemǁ. Enter the page name as
―StoredProcedureDemo_MultipleTables.aspxǁ. Click on ―Addǁ.
✵ Properties of ―HyperLink11ǁ:
Text: Stored Procedure Demo – Multiple Tables
NavigateUrl: ~/StoredProcedureDemo_MultipleTables.aspx

✵ Design the ―StoredProcedureDemo_MultipleTables.aspxǁ page as follows:


[Drag and drop two ―GridViewǁ controls into the page from the ―Dataǁ category at the toolbox]

✵ Write the Code:


Data Controls

💧 These controls are used to display the database data in various formats.
💧 Instead of using the regular standard controls like labels, textboxes etc., it is better
to use these ―Data controlsǁ. For example, we have already used a data control
called
―GridViewǁ, which presents the data in a table format.
💧 In this way, we have to discuss about other data controls also.
💧 The following are all the important data controls in ASP.NET 4.0:
✵ AccessDataSource
✵ SqlDataSource
✵ GridView
✵ DetailsView
✵ FormView
✵ ListView
✵ Chart

💧 One more thing that you need to remember that, these controls supports the
database connections in two models:
1. Programming Model:
▪ We have to write all the code for database connections, for retrieving the
data from the database and for performing insertions, deletions,
updations etc., just like we have implemented the code in the previous
ADO.NET examples.
▪ It takes much time.
▪ But it is better to perform any type of database manipulations.
2. Non-Programming Model
▪ We don‘t need to write any code for database connections, retrievals,
insertions etc.; simply we have drag and drop the ―data sourceǁ
controls such as AccessDataSource, SqlDataSource etc., and we have to
configure those controls properly. These data source controls can
interact with the database and can serve the data to the other data
controls like GridView, DetailsView etc.
▪ It‘s like an express-style. Within minutes, we can finish our work. It‘s
very much easy to use, when compared with programming model.
▪ But it‘s much difficult to implement any additional new style of database
manipulations, which are not defined in the existing data controls.

💧 Being a programmer, we have the full choice a programming model / non-programming


model. Anyway, it‘s much easy to use ―non-programming modelǁ.
💧 Already in the previous ADO.NET applications, we have implemented programming-
model, to interact with the database.
💧 Now, we are going to take a demo application, in a non-programming model.

✵ Open Visual Studio 2010.


✵ Create a new web site.
✵ Take a new web page.
✵ Design the page like this:
✵ At first, we are using ―AccessDataSourceǁ control, which gets the data from an Access
database.
✵ Just for demo purpose, let‘s create an Access Database.
✵ Open Microsoft Office Access 2007.
✵ Select ―Blank Databaseǁ option.
✵ Enter the database name as ―Database1.accdbǁ. (Where as accdb stands for Access
Database).
✵ Select the folder as ―My Documentsǁ.
✵ Click on ―Createǁ.
✵ It shows ―Table1ǁ like this:
✵ Right click on ―Table1ǁ and choose ―Design Viewǁ.
✵ Enter the table name as ―Regionsǁ.

✵ Click on OK.
✵ Then type the table structure as follows:
✵ Save the table.
✵ Right click on ―Regionsǁ table at left side, and choose ―Openǁ option.
✵ Type some sample data as follows:
✵ Now, the table is ready. Save the table and close MS Access completely.
✵ Come back to Visual Studio.
✵ Copy the ―Database1.accdbǁ file from the My Documents folder and right click on the
web site name in the Solution Explorer and ―Pasteǁ it.
✵ Drag the drop the ―AccessDataSourceǁ control from the ―Dataǁ category in the toolbar.
✵ Select the ―AccessDataSource1ǁ control in the page and click on ―>ǁ button.
✵ Then select ―Configure Data Sourceǁ option.
✵ Then click on ―Browseǁ.
✵ Then select the ―Database1.accdbǁ file, which is already copied into the web site folder.
✵ Click on OK.
✵ Click on Next.
✵ Select the required table name. Ex: ―Regionsǁ.
✵ If you want to get all the columns, select ―*ǁ in the ―Columnsǁ option; or if you want
to display few columns, then select the required columns only, by selecting the check
boxes. Then it generates the select statement automatically. You can see that select
statement also.
✵ If you want to give any condition for retrieving the data, click on ―Whereǁ condition and
select the required options there.
✵ If you want to sort the data, then click on ―Order Byǁ option and select the appropriate
option there.
✵ Click on Next.
✵ To test the query whether it is working properly or not now, click on ―Test Queryǁ
button. Then it shows the data at the database.
✵ Finally, click on ―Finishǁ button.
✵ Now the ―AccessDataSource1ǁ control is configured properly. This control can serve the
data to other controls like GridView etc.
✵ Now, drag and drop the ―GridViewǁ control, again from the toolbox.
✵ Select the ―GridView1ǁ control and click on ―>ǁ button.
✵ Then click on ―Choose Data Sourceǁ option. Select the ―AccessDataSource1ǁ from
the dropdown list.
✵ Now, all the columns in the GridView will be configured itself. Then it seems like this:
✵ At design time, it shows a preview of data.
✵ At run time, it shows the actual data.
✵ Now, run the web site. The present output will be like this:
✵ In the similar way, you can configure ―SqlDataSourceǁ control for retrieving the
data from other databases. Of course, you can use it for Access database also. That
means, for MS Access database, instead of ―AccessDataSourceǁ, you can
also use
―SqlDataSourceǁ. Anyway, ―SqlDataSourceǁ control is especially meant for
other databases like SQL Server, Oracle etc.
✵ Let‘s continue with usage of ―SqlDataSourceǁ control.
✵ Now, drag and drop the ―SqlDataSourceǁ control from the toolbox.
✵ Click on ―>ǁ button and choose ―Configure Data Sourceǁ option.
✵ It shows a dialog box as follows:
✵ Then in the dialog box, click on ―New Connectionǁ option.
✵ Click on ―Changeǁ.
✵ Then select the appropriate type of database, which you want to connect. Mainly you can
choose
Microsoft Access Database File
Microsoft SQL Server
Oracle Database
✵ For example, choose ―Microsoft SQL Serverǁ and click on OK.
✵ Enter the following Details:
✰ Server name: localhost
✰ Use SQL Server Authentication
▪ Username: sa
▪ Password: 123 (my be vary in your system)
✰ Save my password
✰ Database name: demo
✵ Click on ―Test Connectionǁ, whether above connection details are accepted or not. If it
is successfully connected, then it shows the following message.

✵ If the connection is not succeeded, it shows the following type of message:


✵ Then make sure whether all the above connection details are properly entered or not.
✵ Anyway, after successful connection, click on OK button.
✵ Then it comes back to the ―Configure Data Sourceǁ dialog box, and
automatically generates the connection string, based on the above given connection
details. To see the automatic generated connection string, click on ―+ǁ symbol.
Then it shows the connection string as follows:
✵ Click on ―Nextǁ to continue.
✵ Click on ―Nextǁ.
✵ Then just like in the AccessDataSource, select the required table name and required columns.
✵ If required you click on ―Whereǁ option to given any conditions; you can also select the
sorting column by click on ―Order Byǁ option.
✵ Click on ―Advancedǁ button now, and select the option called ―Generate INSERT,
UPDATE and DELETE statementsǁ.
✵ Then click on OK. This particular option is useful, to perform insertion, updation and
deletion operations straight-away from the data controls. To fully understand this option
purpose, we have to proceed with other options, in the GridView. We discuss about
additional options in the GridView control in the rest of this demo application
development process.
✵ Anyway, click on the ―Nextǁ button.
✵ Click on ―Test Queryǁ button, to test the query.
✵ Click on Finish.
✵ Now, the ―SqlDataSource1ǁ control is configured properly and its ready.
✵ Then drag and drop one more ―GridViewǁ control and click on ―>ǁ button.
✵ Then click on ―Choose Data Sourceǁ option. Select the ―SqlDataSource1ǁ from the
dropdown list.
✵ Then the screen looks like this:
✵ Run the web site, to see the output.
✵ Then output will be like this:
✵ Now, this is the time for discussing about the advanced options, available in the
―GridViewǁ control.
✵ Select the ―GridView2ǁ control and click on ―>ǁ button.
✵ Then click on ―Auto Formatǁ option. Then select any one of the given auto format styles.
✵ After selecting the auto format styles, the grid looks like this:
✵ Enable Paging: Again, click on ―>ǁ button and click on ―Enable Pagingǁ option. This
option displays the page numbers at bottom side of the grid control, which displays the
data, based on the selected page numbers. This is useful, when large no. of records is
there in the database. By default, it shows 10 records per every page. Of course, you can
change the no. or records per page, using ―PageSizeǁ property.
✵ Enable Sorting: Again, click on ―>ǁ button in the GridView, and select ―Enable
Sortingǁ option. Then at run time, it allows the user click on the column name, to sort the
data in ascending or descending order. When the user clicks on the required column
name first, the data will be sorted in ascending order. When the user clicks the same
column again, then the data will be sorted in descending order. For this sorting, we don‘t
require to write any code.
✵ Enable Editing: Again, click on ―>ǁ button in the GridView, and select ―Enable
Editingǁ option. Then it shows a link button called ―Editǁ for every row in the grid. The
user can click on ―Editǁ option at any row, to directly update the data. Then it
automatically shows textboxes in place of the values. There, the user can change the
values. To confirm the modifications, the user has to click on ―Updateǁ link button. Then
automatically the data will be modified in the database. For this updation also we don‘t
require to write any code.
✵ Enable Deleting: Again, click on ―>ǁ button in the GridView, and select
―Enable Deletingǁ option. Then it shows a link button called ―Deleteǁ for every row in
the grid. The user can click on ―Deleteǁ option at any row, to directly delete the data.
Whenever it is clicked at run time, automatically the data will be deleted permanently in
the database. For this deletion also we don‘t require to write any code.
✵ Enable Selection: Again, click on ―>ǁ button in the GridView, and select
―Enable Selectionǁ option. Then it shows a link button called ―Selectǁ for every row in
the grid. The user can click on ―Selectǁ option at any row, to select the particular row.
Whenever it is clicked at run time, it automatically the selected row will be highlighted.

✵ Of course, you can do something, whenever the ―Selectǁ button is clicked. You have to
write some code for that.
✵ To do so, double click on the GridView control. Then it generates
―SelectedIndexChangedǁ event. That event will be executed automatically, whenever the
user selects any row, by clicking on ―Selectǁ link button at run time.
✵ For a demonstration, drag one Label control (below the grid control) and write the following
code:
✵ The output will be like this:

✵ In this way, you are able to implement ―Pagingǁ, ―Sortingǁ, ―Editingǁ, ―Deletingǁ
and
―Selectionǁ features in the GridView control. But ―Insertionǁ feature is not supported in
this control. But insertion feature is also available in other controls like
―DetailsViewǁ,
―FormViewǁ etc.

Note: Remember that all the above practiced concepts are supported in any other databases
also, like Access, Oracle etc.; not only for SQL Server.

✵ Now, let us continue with ―DetailsViewǁ control.


✵ Drag and drop the ―DetailsViewǁ control from the toolbox into the page.
✵ Just like in the grid control, choose the data source as ―SqlDataSource1ǁ.
✵ This control displays the data in a single-record view.
✵ Then user can navigate among the records, by clicking on the page numbers.
✵ In this control also, you have the common options like:
Auto Format
Enable Paging
Enable Inserting
Enable Editing
Enable Deleting
✵ When the ―Insertingǁ feature is enabled, by clicking on ―Newǁ option, the user can
insert a new row at run time. For this also we don‘t require to write any code.
✵ The output of DetailsView control is as follows:

✵ Next, you drag and drop the ―FormViewǁ control.


✵ The ―FormViewǁ control is similar to the ―DetailsViewǁ control.
✵ The main difference between these two controls is, in the DetailsView control we can‘t
customize the visibility of the data. The data will be displayed in a table format (as shown
above) only. But in the FormView, we can customize anything.
✵ Now for the ―FormView1ǁ control, select the DataSource as ―SqlDataSource1ǁ.
✵ Select ―Enable Pagingǁ and ―Auto Formatǁ options also.
✵ Then for FormView control looks like this:

✵ Now, the DetailsView and FormView controls are looking almost all same.
✵ But you can change the design of FormView control. To do so, click on ―>ǁ button and
choose ―Edit Templatesǁ option.
✵ Then the control looks like this:
✵ Now, you can make some changes.
✵ For example, suppose you want to display the gender in a RadioButtonList control, instead of
the label control.
✵ Then delete the ―GenderLabelǁ control in the above design and drag the
―RadioButtonListǁ control from the toolbox into the ―ItemTemplateǁ directly.
✵ Then select the following properties of RadioButtonList1 control:
Items: Male
Female
RepeatDirection: Horizontal
RepeatLayout: Flow

✵ Then select that radiobuttonlist control and click on ―>ǁ button.


✵ Click on ―Edit Data Bindingsǁ option.
✵ Select the property as ―SelectedValueǁ.
✵ Select ―Bound toǁ as ―Genderǁ.
✵ Click on OK.
✵ Then to close the template editing, click on ―>ǁ button and choose ―End
Template Editingǁ option.
✵ Then the output will be like this:

✵ Now, let us continue with ―ListViewǁ control.


✵ Drag and drop the ―ListViewǁ control into the page. This control displays the data in a
variety format.
✵ Select the ―ListView1ǁ control and click on ―>ǁ button.
✵ Select the Data Source as ―SqlDataSource1ǁ.
✵ Again click on ―>ǁ button and choose ―Configure ListViewǁ option.
✵ Select the required Layout. Ex: Tiled.
✵ Select any auto format style. Ex: Professional.
✵ Select any additional options like ―Enable Editingǁ, ―Enable Insertingǁ etc.

✵ Finally click on OK.


✵ The output will be like this:

✵ Now, let us use the ―Chartǁ control. This ―Chartǁ control is introduced in ASP.NET 2010
version. It‘s not available in the older versions.
✵ Drag and drop the Chart control from the toolbox into the page.
✵ Select the ―Chart1ǁ control and choose the following options:
Choose Data Source: SqlDataSource1
Chart Type: (any chart type from the list)
X Value Member: CustomerName
Y Value Member: Amount
✵ Now, the chart control is ready. The output will be like this:

✵ In this way, we can display the same data in various models, using different data controls.
Crystal Reports
―Crystal Reportsǁ is known as a reporting tool.
This is used for development of database reports in the projects.
A database report displays the database data, in a summary manner.
A database report is ready to print. The report file extension is ―.rptǁ.
That can be exported to ―Excelǁ / ―HTMLǁ etc., formats.
Generally, in every live project, the data entered by the data entry operators, should be
displayed to the administrator in a ―Reportǁ format. That can be called as a ―Database
Reportǁ.
―Crystal Reportsǁ are developed by ―Seagate Corporationǁ, and has a strong integration
with Visual Studio.
Note: In Visual Studio 2010, the crystal reports are not available by default; we need to
install it separately. In the older versions (Visual Studio 2005 and 2008), Crystal reports
are in-built.

Implementation of Crystal Reports

1. Create a Crystal Report.

Create a new web site.


Click on ―WebSiteǁ menu – ―Add New Itemǁ.
Select ―Reportingǁ – ―Crystal Reportǁ.
Enter the name of the new report. Ex: StudentsReport.rpt.
Click on ―Addǁ.
A wizard will be displayed.
Select the report type as
―Standardǁ and click on OK.
The ―Standard Report
Creation Wizardǁ dialog box will be
appeared.
There, expand the option
―Create New Connectionǁ and
expand ―OLE DB (ADO)ǁ
Then ―OLE DB (ADO)ǁ dialog
box will be appeared.
There, select the appropriate driver
/ provider name, based on the
database which you want to
connect.
❖ Sql Server Microsoft OLE DB Provider for SQL Server
❖ Oracle Microsoft OLE DB Provider for Oracle
❖ MS Access Microsoft Jet OLE DB 4.0 Provider
After selecting
the provider (Ex:
Microsoft OLE DB
Provider for Sql
Server), click on
―Nextǁ button.
Enter the server
name (name of
the system), user
id, password and
select database
name.

Ex:
Server name: classroom
User ID:sa
Password: 123
Database: sample

Click on ―Finishǁ.
Then the ―OLE DB (ADO)ǁ dialog box will be closed and the focus will be come back to
―Standard Report Creation Wizardǁ dialog box. And now, the ―OLE DB (ADO)ǁ option
will be expanded.Expand the database name and select the table name, which you
want. (Ex: students).
Click on ―>ǁ button to add the selected table into the right side list.
Click on ―Nextǁ.
Expand the table name. Then the list of columns will be displayed.
Now you have to add the require column(s), into the right side list, which you want to
display in the crystal report.
To add all the columns, click on ―>>ǁ button. To add the columns one-by-one, select
the column first and click on ―>ǁ button.
Click on ―Nextǁ.
Select the grouping column, based on which you want to group-up the data
(optional). If you don‘t want to group the data, simply leave it blank.
Click on ―Finishǁ.
Then the report wizard will be completed and the report will be generated
automatically.
The report will be displayed in the design view. This can be called as ―Report Design
Viewǁ.
Then the report file will be added into the ―Solution Explorerǁ. Ex: studentsreport.rpt

2. Design the Crystal Report.


The ―Report Design Viewǁ offers to change the design of the report.
The report design view contains 5 sections like:
Report Header: This section contains the objects that are to be displayed
only at the top of the report.

Page Header: This section contains the objects that are to be displayed at
the top of each page.

Details: This section contains the objects that are to be repeated for each
row of the database table. Generally, it displays the actual data values.

Report Footer: This section contains the objects that are to be displayed
at the bottom of the report.

Page Footer: This section contains the objects that are to be displayed at
the bottom of each page.

To change any font / border / alignment / colors / paragraph of the objects, right click
on the require object and choose the ―Format Objectǁ option.

To add new objects, right click on the empty area and choose ―Insertǁ, where you
can select ―Special Fieldǁ / ―Text Objectǁ / ―Summaryǁ / ―Lineǁ / ―Boxǁ /
―Chartǁ /
―Pictureǁ. After selecting any one of these options, click anywhere, where you want
to insert that object.

3. Invoke it in the Web Page.


The crystal report file can‘t be executed individually, it requires a web page.
In other words, the crystal report can be executed on a web page.
To contain the crystal report in the page, a control is required, that is called as
―CrystalReportViewerǁ.
This contains is able to display a crystal report on the page.
To implement this, come back to the form and drag ―CrystalReportViewerǁ
control under ―Reportingǁ category from the toolbox into the form.
Select the ―CrystalReportViewer1ǁ control - Click on ―>ǁ button – Then select ―New
report sourceǁ option.

There, select the ―studentsreport.rptǁ file from the drop down list.
Then click on OK.
Then the page looks like this:
Run the web site. At run time, it asks for run-time authentication for security purpose.
Then you have to enter the password (Ex: 123) and click on ―Finishǁ.
The ―CrystalReportViewerǁ control offers the following features at

run time. Exporting the report to other formats like excel,

pdf, doc etc. Printing the report through a printer.

Refresh the report data.

Show/Hide the Group Tree.

Navigating the First / Previous / Next / Last Pages in the report.

Find the required text.


Change the Zoom of the data.
Output:

Enter the password as ―123ǁ (or the password according to your system) and click on ―Log onǁ.
Validation Controls

✰ The validation controls are meant for performing client side validations.
✰ Def of Validation: The ―Validationǁ is a process, that checks the user input
values, whether those are correct or not. According to this, whenever the user clicks on
―submitǁ button on the client system, the user-input values will be validated first. If all
of those values are valid, then the page will be submitted to the web server. Otherwise,
an error message will be displayed to the user and the page will not be submitted to the
web server.
✰ Advantage of Validation: As an advantage of validation, invalid values containing pages
would not be submitted to the web server. So that we can avoid the stress on web
server.
✰ In older days, the client side validations are performed by using the code written in
―java scriptǁ language. But in newer age of web development like ASP.NET, validation
controls are introduced to replace the role of ―java script validationsǁ.
✰ Advantage of Validation Controls: Validation controls are very much easy to use. You
don‘t require to write even single line of code also to use them. So that we can avoid
―java scriptǁ usage. In order to perform different kinds of validations, ASP.NET
offers different types of validation controls.
✰ Functionality of Validation Controls: A validation control performs a particular type
of validation on input / selection based controls like textbox, checkbox, checkboxlist,
radiobuttonlist, listbox, dropdownlist etc. At run time, whenever the user clicks on
―Submitǁ button it validates the particular control. If the given value is valid, it allows
the page to be submitted. Otherwise, it stops the submition of the page and displays an
error message on the page. By default, its forecolor is set to ―redǁ.
Validation Controls in ASP.NET
A. Client Side Validation Controls
1) RequiredFieldValidator
2) RangeValidator
3) RegularExpressionValidator
4) CompareValidator
5) ValidationSummary
B. Server Side Validation Controls
6) CustomValidator

Implementation of Validation Controls

1. RequiredFieldValidator: Checks for the value entry in a particular control, and makes
it as mandatory control. That means the user should enter the value in the specified field.
Otherwise, it stops the submition of the page to the server.

Properties of RequiredFieldValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.

2. RangeValidator: Checks the entered value whether it is in a given numerical range or


not. If it is within the range, the value is valid. Otherwise, it is invalid.

Properties of RangeValidator
Property Description
Contains the reference of the control (textbox,
ControlToValidate
checkbox, radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
MinimumValue Contains the minimum value in the range.
MaximumValue Contains the maximum value in the range.
Specifies the data type of value. (Integer / Double / Currency /
Type
String / Date)

3. RegularExpressionValidator: Checks the entered value whether it matches with a


specified format or not. If it is matched with the specified format, the value is valid.
Otherwise, it is invalid. Ex: Phone numbers, e-mail addresses, web site addresses, zip
codes, postal codes etc.

Properties of RegularExpressionValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
ValidationExpression Specifies the format, to be checked.

4. CompareValidator: This can be used in 3 models.

A. Comparison with a fixed value.


The control‘s value will be compared with a fixed value.

Properties of CompareValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically,
ErrorMessage
on entering the invalid value.
true / false. Whenever it is true, the focus will be moved to
SetFocusOnError
that control, whenever the invalid value is found.
ValueToCompare Specifies the fixed value that is to be compared.
Specifies the relation operator, used for comparison. (Equal,
Operator NotEqual, LessThan, LessThanEqual,
GreaterThan,
GreaterThanEqual)
Specifies the data type of value. (Integer / Double / Currency
Type
/ String / Date)
B. Comparison with another control’s value.
The control‘s value will be compared with another control‘s value.

Properties of CompareValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be
ErrorMessage
appeared automatically, on entering the invalid value.
true / false. Whenever it is true, the focus will be moved to
SetFocusOnError
that control, whenever the invalid value is found.
Specifies the name of the control, with which you want to
ControlToCompare
compare the value.
Specifies the relation operator, used for comparison. (Equal,
Operator NotEqual, LessThan, LessThanEqual, GreaterThan,
GreaterThanEqual)
Specifies the data type of value. (Integer / Double / Currency
Type
/ String / Date)

C. Data Type Comparison.


Checks the value for a specified data type. It doesn‘t compares with any other value.

Properties of CompareValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be
ErrorMessage
appeared automatically, on entering the invalid value.
true / false. Whenever it is true, the focus will be moved to
SetFocusOnError
that control, whenever the invalid value is found.
Operator ―DataTypeCheckǁ
Specifies the expected data type of value. (Integer / Double
Type
/ Currency / String / Date)

5. ValidationSummary: This doesn‘t perform any individual validation. It is designed for


the pages, having more no. of validation controls within the same page. At the time of
submition, this controls takes the error messages from other validation controls and re-
displays them in a bulleted format. You don‘t require to set any properties for this
control.

6. CustomValidator: Used to perform some other external type of validations, which


includes with some code to be executed. For example, in a form, there is a textbox, to
enter a filename. The validation is to not to enter non-existing file named. So that, there
is a necessity of validating the file name, whether it is actually exist on the disk or not. At
that time, you have to use ―CustomValidatorǁ. But unlike other validation controls, this
requires to write some code for validation. The validation code can be implemented in
―ServerValidateǁ event.

Properties of CustomValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
Default.aspx
success.aspx
Navigation Controls
✰ These controls are used to display the links in the web site, in a categorized format (with
parent and child format).
✰ The following are the navigation controls.
1. Menu
2. TreeView
✰ To understand these two controls better, let‘s start with a demo application.
Create a new web site.
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Default.aspxǁ – Click on Add.
Design the ―Default.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Aboutus.aspxǁ – Click on Add.
Design the ―Aboutus.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Contactus.aspxǁ – Click on Add.
Design the ―Contactus.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―registration.aspxǁ – Click on Add.
Design the ―registration.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―login.aspxǁ – Click on Add.
Design the ―login.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―ConsumerProducts.aspxǁ – Click on Add.
Design the ―ConsumerProducts.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―HomeAppliances.aspxǁ – Click on Add.
Design the ―HomeAppliances.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―PrepaidServices.aspxǁ – Click on Add.
Design the ―PrepaidServices.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―PrepaidVouchers.aspxǁ – Click on Add.
Design the ―PrepaidVouchers.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―PostpaidServices.aspxǁ – Click on Add.
Design the ―PostpaidServices.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―PostpaidPlans.aspxǁ – Click on Add.
Design the ―PostpaidPlans.aspxǁ as follows:
Come back to the ―Default.aspxǁ.
Drag and drop the ―Menuǁ control from the toolbox into the page.

Then click on ―>ǁ button and select ―Edit Menu Itemsǁ option.
Then it displays Menu Item Editor dialog box.
Then click on the first ―+ǁ button to ―Add the root itemǁ. Root items means, main
menu items (top level items in the menu).
Then it shows the properties in the right side panel. Then specify the following
properties:
1. Text: Home
2. NavigateUrl: Default.aspx
That means, when the user clicks on the menu item, the specified page in the
NavigateUrl property will be opened automatically. For example, when the user clicks on
―Homeǁ link, then ―Default.aspxǁ will be opened.
In the similar way, add one more root item and specify the following properties:
1. Text: About Us
2. NavigateUrl: Aboutus.aspx
Add one more root item and specify the following properties:
1. Text: Contact Us
2. NavigateUrl: Contactus.aspx
Add one more root item and specify the following properties:
1. Text: Products
Add one more root item and specify the following properties:
1. Text: Services
Add one more root item and specify the following properties:
1. Text: Register
2. NavigateUrl: registration.aspx
Add one more root item and specify the following properties:
1. Text: Login
2. NavigateUrl: login.aspx
Then the screen looks like this:

To add the child items, you have to use second ―+ǁ symbol, which is called ―Add a
child itemǁ.
For example, click on ―Productsǁ and click on ―Add a child itemǁ option. Then it creates
a child item inside of ―Productsǁ item. Specify the following properties:
1. Text: Consumer Products
2. NavigateUrl: ConsumerProducts.aspx
Again, select ―Productsǁ item and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Home Appliances
2. NavigateUrl: HomeAppliances.aspx
Then select ―Servicesǁ item and click on ―Add a child itemǁ option. Specify the following
properties:
1. Text: Prepaid
Again, select ―Servicesǁ item and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Postpaid
Then click on ―Prepaidǁ and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Prepaid Services
2. NavigateUrl: PrepaidServices.aspx
Again, select ―Prepaidǁ and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Prepaid Vouchers
2. NavigateUrl: PrepaidVouchers.aspx
Then click on ―Postpaidǁ and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Postpaid Services
2. NavigateUrl: PostpaidServices.aspx
Again, select ―Postpaidǁ and click on ―Add a child itemǁ option. Specify the
following properties:
1. Text: Postpaid Plans
2. NavigateUrl: PostpaidPlans.aspx
Finally, the screen looks like this:
In this way, you can create any no. of items, up to any level.
Click on OK.
Select the Menu1 control and click on ―>ǁ button. Choose ―Auto Formatǁ option. Select
any one of the auto format styles.
Click on OK.
Select the ―Menu1ǁ control and set the following
property: Orientation: Horizontal
Now, let us try to implement ―TreeViewǁ control. The same links, which you
have maintained in the Menu control as above, can be designed in TreeView control also.
Drag and drop the ―TreeViewǁ control into the page.
Select the ―TreeView1ǁ control and click on ―>ǁ button.
Click on ―Edit Nodesǁ option.
Then it shows a dialog box like this:
Just like you have designed the menu items above, you design the same items here.
After adding all the nodes, the dialog box looks like this:
Again select the ―TreeView1ǁ control and click on ―>ǁ button. Click on ―Auto
Formatǁ option. Select any one of the auto format styles:
Click on OK.
Again select the ―TreeView1ǁ control and click on ―>ǁ button. Check the checkbox, called
―Show Linesǁ.
Run the web site and click on the links. Then the respective web pages will be opened.
Output:
Note: Generally in the live projects, you don‘t require to have both of these controls at-
a-time. You try to use any one of these, because the basic purpose is same for both of
these controls.
Login Controls
✰ These controls are meant for the implementation of the following features.
1. Registration
2. Login
3. Change Password
4. Logout
5. Forgot Password
✰ These controls offer a great support to implement the above mentioned features in your
web site, even without writing any code (at least one line of code also not required).
✰ So that you can develop the web sites on fast track.
✰ In fact, if you observe most of the web sites today, the above mentioned features are the
most common in majority of the web sites. That‘s why Microsoft gives the login controls
to the ASP.NET programmers.
✰ The following are the available login controls:
1. CreateUserWizard
2. Login
3. LoginName
4. ChangePassword
5. LoginStatus
6. PasswordRecovery
✰ To understand these controls practically, lets us start with a demo application.

Create a new web site.


Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Default.aspxǁ – Click on Add.
Design the ―Default.aspxǁ page as follows:
Now, drag and drop the ―CreateUserWizardǁ control from the toolbox, into the page.
This control helps the user to be registered in the web site.
Then the screen looks like this:
That‘s it. The control is ready to use. No need of writing any code.
This control contains two steps (like a Wizard control).
Currently you are viewing the first step. To switch to the second step, click on ―>ǁ
button and choose the ―Completeǁ step.
At run time, after successful registration of the user, the ―Completeǁ step will
be displayed.
Anyhow, when the user clicks on the ―Continueǁ button at run time, generally other
page can be opened. Suppose, you want to display ―loginǁ page, when the user
clicks the
―Continueǁ button. Then click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ
– Type the name as ―login.aspxǁ – Click on Add.
In the ―login.aspxǁ, drag and drop the ―Loginǁ control from the toolbox.
Then it looks like this:
For this control also we don‘t require to write any code. It‘s ready to use. But after
successful login, generally other page will be opened. So that we have to add a separate
page.
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―mainpage.aspxǁ – Click on Add.
Design the mainpage.aspx as follows:
But we have to maintain the link between the Login control and the ―mainpage.aspxǁ;
because, at run time, after successful login, the ―mainpage.aspxǁ is to be opened.
Then come back to the ―login.aspxǁ page.
Select the ―Login1ǁ control and set the following property:
1. DestinationPageUrl: mainpage.aspx
That‘s it. Now, the login control is fully configured.
Come back to the ―Default.aspxǁ page.
Select the ―CreateUserWizard1ǁ control and set the following property:
1. ContinueDestinationPageUrl: login.aspx
Click on ―>ǁ button, and come back to the first step called ―Sign up for Your Newǁ.
Now, you can run the web site and test the registration and login features.
Open the Solution Explorer; right click on ―Default.aspxǁ and choose ―Set as Start Pageǁ.
Run the web site.
Enter some sample details and click on ―Create Userǁ button.
Ex:

After clicking on ―Create Userǁ button, it shows the following message.


Note: While you are entering the password, you need to enter at least one non-alpha
numeric character (special character), such as #, $, @, *, & etc.
Ex: satya123#
Click on ―Continueǁ.
Then it shows the ―login.aspxǁ page.
Close the web site and run it again.
Just for demonstration purpose, register one more user as follows:
Password: syam123$
Now, there are two users in your web site, named ―satyaǁ and ―syamǁ.
Then you may have some doubt: Where all the user‘s information is being stored?
Answer: In the SQL Server database.
But, we have not created the database!! Don‘t worry; the database has been created
automatically! You don‘t require doing anything particularly for that.
To see the database name, open the Solution explorer. Select the web site name and
click on ―Refreshǁ button. Then it shows a database file called ―ASPNETDB.mdfǁ under
the ―App_Dataǁ folder.
Note: In fact, the ―App_Dataǁ is a
system- recommended folder, in which we can store
all the necessary database files or other data source
files such as XML files.
To make the controls looking better, set the auto
format styles for the Login1 and CreateUserWizard1
controls.
Suppose, you want to display the currently logged-in username in the ―mainpage.aspxǁ
page. Then drag and drop the ―LoginNameǁ control into the page, just beside
the
―Welcomeǁ message.
Then the screen, looks like this:

At run time, the ―LoginNameǁ control displays the currently logged-in user name
automatically.
Run the web site and test it.
Next, If you want to offer ―Change Passwordǁ option in your site, add a hyperlink into the
―mainpage.aspxǁ and set the following properties:
1. Text: Change Password
2. NavigateUrl: changepassword.aspx
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―changepassword.aspxǁ – Click on Add.
Drag and drop the ―ChangePasswordǁ control from the toolbox.
Set the following properties for the ―ChangePassword1ǁ control:
1. ContinueDestinationPageUrl: mainpage.aspx
To use it, you have to run the web site, enter the current user name, new password,
confirm password and click on ―Change Passwordǁ button. It itself, updates the
new password in the database.
Next, suppose you want to implement ―Log outǁ option in your web site. Then drag and
drop the ―LoginStatusǁ control into the ―mainpage.aspxǁ.
Now, the mainpage.aspx looks like this:
At run time, the LoginStatus control displays ―Loginǁ option or ―Logoutǁ option.
That means, if any user currently logged-in, then it displays ―Logoutǁ option. If no user,
currently logged-in, then it displays ―Loginǁ option.
Set the following properties of ―LoginStatus1ǁ.
1. LogoutAction: RedirectToLoginPage
With the help of above property, when the user clicks on ―Logoutǁ option at run time, it
comes back to the ―login.aspxǁ page.
To test it, you have to run the web site.
Next, we are trying to implement ―Forgot Passwordǁ feature.
Design the ―Default.aspxǁ page as follows:
Properties of
―HyperLink1ǁ:
1. Text: Login
2. NavigateUrl: login.aspx
Properties of ―HyperLink2ǁ:
1. Text: Click here
2. NavigateUrl: forgotpassword.aspx
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―forgotpassword.aspxǁ – Click on Add.
Then in this page, drag and drop the ―PasswordRecoveryǁ control from toolbox.
Set the auto format style.
Then the page looks like this:
Let us test this control whether it is working or not.
Run the web site.
Click on ―Forgot Password – Click hereǁ option.
Enter the username. Ex: satya
Click on ―Submitǁ.
Then it shows the security question, which is given at the time of user registration.
Enter the proper answer. Ex: green
Click on ―Submitǁ button.
In fact, an E-mail is automatically would be sent to the user, with the password
information.
But now, it would not be sent properly. You will get this type of error message:
To solve this problem, you have to configure the ―SMTP settingsǁ in your web site. After
you configure, this control works properly.
So, let us continue with configuring ASP.NET
the SMTP Settings. Configuration
Close the browser and come back (Click here)
to the Visual Studio.
Open Solution Explorer and select
the web site name.
Click on ―ASP.NET Configurationǁ
option.
Then it displays
―ASP.NET Web Site
Administrative Toolǁ.
It‘s an inbuilt feature of
ASP.NET, which is used to
customize the settings of
the web site.
Click on ―Applicationǁ tab.
Click on ―Configure SMTP e-mail settingsǁ option.
Then it displays the following options:
Then type the following details:
1. Server name: name of the SMTP server / localhost
2. Server Port: 25 (a fixed port no of SMTP protocol)
3. From: The e-mail address, from which the password recovery e-mail is to
be sent. For ex type customercare@peerstech.com.
Click on ―Saveǁ button.
Then the above specified SMTP settings will be saved.
Click on OK.
Close the browser and come back to Visual Studio.
Then the necessary changes will be made in the ―web.configǁ file.
To see those changes, double click on ―web.configǁ file in the Solution Explorer.
But still, it won‘t work, because the mail domain (peerstech.com), which you are using
in the above mentioned mail address doesn‘t exist actually.
So that we have to create a alias domain (dummy domain), with the name of
―peerstech.comǁ.
To create it, click on ―Startǁ – ―Runǁ.
Then type ―inetmgrǁ and click on OK.

Then it opens the ―Internet Information Servicesǁ (IIS) window.


There, expand the local computer name.
Expand ―Default SMTP Virtual Serverǁ.
Select the option ―Domainsǁ.
Then it shows existing list of domains, which are configured currently in the IIS server.
Right click on ―Domainsǁ – choose ―Newǁ – ―Domainǁ.

Then select ―Aliasǁ.


Click on Next.
Specify the name as ―peerstech.comǁ.

Click on Finish.
Then it will be added to the existing domains list.
That‘s it. It‘s ready.
Close the IIS window and come back to Visual Studio.
Run the web site and test the ForgotPassword option. Now it works.
After entering the correct username and correct answer for the question, it displays the
following message at run time.
To find out the E-mail, open the following folder.
c:\Inetpub\mailroot\Drop
There, you can find a file that contains the E-mail.
Double click on that file.
Then you can read the e-mail.
If you configure the ―Outlook Expressǁ properly, the e-mail will be sent automatically to
the Inbox of the user.
Anyway, you can find the password, which is given as an encrypted value in
the e-mail. Ex: dgJfi^cdx=>d]h
The user has to use this above password, to login. Of course, after next login, the user
can change the password.
To test it, run the web site, and try to login with above given encrypted password (you
can copy the password and paste it directly in the password textbox, at the login page).
After that try to change the password using ―Change Passwordǁ option.
WebParts Controls

The WebParts controls allow the user to change the web page content dynamically at run
time, though the browser.

This is a concept of personalization, which remembers your settings automatically, based


your login information (username and password). If you run the web site later (after few
days or months also), the same settings will be loaded.

Important WebParts Controls:


1. WebPartManager
2. WebPartZone

Create a new web site.


Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Default.aspxǁ – Click on Add.
Drag and drop the ―WebPartManagerǁ control from the toolbox into the page
(at the top).
Drag and drop the two or the ―WebPartZoneǁ controls.
Re-size the WebPartZone controls and set the auto-format styles, as per your desire.
Rename the ―WebPartZone1ǁ as ―FirstZoneǁ using ID property.
Rename the ―WebPartZone2ǁ as ―SecondZoneǁ using ID property.
Rename the ―WebPartZone3ǁ as ―ThirdZoneǁ using ID property.
Drag the drop any controls (like labels, buttons, textboxes, checkbox, calendars etc.) into
the web part zones.
(Continued…)
Run the web site.
You can observe ―Minimizeǁ and ―Closeǁ options for each control, at right side corner.
Note: If you minimize any control, you can restore it later. If you close it, you can‘t
restore it again.
Close the browser and come back to Visual Studio.
Drag and drop a ―DropDownListǁ control.
Select it and click on ―>ǁ symbol. Click on ―Enable AutoPostBackǁ option.
Set the Dropdownlist items as follows:
Click on OK.
Double click on the DropDownList1 control and write the code:

Run the web site.


By default, you will be in ―Browseǁ mode.
Select ―Designǁ mode from the Dropdownlist.
Now, you can move any control from one WebPartZone to any other WebPartZone.

This is the advantage of ―Designǁ mode.


State Management in ASP.NET
This is to send some data values from one web page to another web page.
For example, if you take any mailing web site, when you enter the user name and
password in the login page, that same user name is carried into the inbox page and
compose page etc.
For another example, if you enter your question in the Google home page, that value can
be carried into the next page, which displays the search results.
In this way, you require to transfer / share some data values among two or more pages
also.
This is possible using ―State Managementǁ concept.
The state management concept can be implemented in many ways.
1. Using Query String
2. Using Cookies
3. Using Session State
4. Using Application State
5. Using View State

Transferring Information between Pages


With Query String

The query string is the string attached to URL, which is displayed in the browser‘s
address bar. The query string starts with ―?ǁ symbol.
When you want to pass one or more values from one page to another page as
arguments, you can send them with the ―Query Stringǁ, in the following format.
Syn: http://localhost:portno/WebSiteName/WebPage.aspx?parameter=value
Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n=100

When you want to pass multiple values with the query string, use the following
format: Syn:
http://localhost:portno/WebSiteName/WebPage.aspx?parameter1=value1&
parameter2=value2
Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n1=140&n2=98

To get the parameter value in the next page, use this syntax:
Syn: Request.Params[―parameter nameǁ]
Ex: Request.Params[―nǁ]
The above syntax gets the value of the given parameter, in string format.

Create a new web site.


Add the ―Default.aspxǁ page.
Design the ―Default.aspxǁ page as shown:

Write the code:


Add the ―display1.aspxǁ page.
Design the ―display1.aspxǁ page as shown:

Write the code:


Set the ―Default.aspxǁ as Start Page.
Run the web site.

Limitations of Passing Information with Query String:

No security is available, because the argument names and values will be displayed in the
browser‘s title bar. You can‘t pass the values in hidden mode.
The values can be sent from one page to another page only. But, the values can‘t be
retrieved from other pages, forwarded from the second page.
You can share only string values or numerical values among multiple pages. Of course,
even though you pass the numerical values, it treats the value as a string value only.
Anyhow, you can‘t pass ―objects”.

Note: To overcome the above first two limitations, ―Cookiesǁ concept is introduced.

Cookies
A cookie can be used to share values among two or multiple web pages.
Cookies are stored at client system only.
A cookie will be created as a text file in the ―c:\Documents And
Settings\Username\Cookiesǁ folder on the client system. These files will be created
dynamically at run time.
When compared with ―Query Stringǁ, the advantage of cookies is, it doesn‘t display the
values in the address bar. The value can be passed in hidden mode.
Another advantage of ―Cookiesǁ is, cookies alive among multiple web pages, not
only between one page to another page. That means you can access the values stored in
the cookies from any other pages, navigated from the current page.
According to the OOP standards in ASP.NET, every cookie is an object for a pre-defined
class called ―HttpCookieǁ.
Implementation:
A. Assign value to the Cookie:

Create cookie object:


HttpCookie obj = new HttpCookie(―variable_nameǁ, ―valueǁ);

Assign the cookie object to Response:


Response.Cookies.Add(obj);
B. Get value from the Cookie:
Request.Cookies[―variable_nameǁ].Value

Demo:

Open the previous demo web site.


Add the ―Submit using Cookiesǁ button in the Default.aspx as shown:

Write the code:


Add the ―display2.aspxǁ page.
Design the ―display2.aspxǁ page as shown:

Write the code:


Limitations of “Cookies”
Cookies will be stored in the form of text files during run time in the client system. Those
files can be easily visible by other users. It is easy to modify or delete the cookie files. It
is easy to hack the cookie files from remote systems also. So, cookies are not much
secured.
Cookie files will not be deleted automatically. So that, it leads to waste of hard disk
memory.
It doesn‘t supports to share ―objectsǁ among multiple pages. It supports to share
strings or numerical values only.

Finally, now-a-days, cookies are out-dated. To overcome the limitations of cookies, we use
―Sessionsǁ.
Session State
Whenever a client (browser) is connected, the ―Sessionǁ state will be
created automatically; and the session will be closed automatically whenever the client
(browser) is disconnected.
Here, ―stateǁ means some memory, at web server.
For every client (browser), a separate session will be created. For example, your web site
is being opened by 100 users (from 100 browsers). That means there will be 100
sessions.
Similar to Cookies, the ―Session stateǁ is used to share values among multiple pages.
For example, between login and logout, the current user name, user id number and
password will be stored in the session state.
Now-a-days, ―Cookiesǁ are outdated. Instead of cookies, sessions are used.
The main difference between cookies and session state is: a cookie will be saved on the
client system; and the session will be saved at web server.
Sessions are more secured, when compared with ―Cookiesǁ, as sessions will be saved at
web server.
Sessions will not be saved in the form of any files. Those are stored as logical objects in
the web server memory.
Sessions are able to share values and objects also.
Implementation of ―Session stateǁ is easier, when compared with ―Cookiesǁ.
To access the session state, you can use the implicit object called ―Sessionǁ. That
means you don‘t require to create the ―Sessionǁ it is commonly available for all the web
pages by default.
The ―Sessionǁ object always represents current session, in which the web page is being
executed.

Implementation:
A. Assign value to the Session:
Session[―nameǁ] = value;
B. Get value from the Session (gets the session variable value in “Object”
type):
Session[―nameǁ]
C. Clear all the values in the current session:
Session.Clear();

Demo:

Open the previous demo web site.


Add the ―Submit using Session Stateǁ button in the Default.aspx as shown:
Write the code:

Add the ―display3.aspxǁ page.


Design the ―display3.aspxǁ page as shown:
Write the code:

Application State
Another state available in ASP.NET is ―Applicationǁ state. Similar to ―Session stateǁ, the
―Application stateǁ holds the data values or objects among multiple web pages in
the web site.
Similar to ―Session stateǁ, the ―Application stateǁ also will be stored at web server. It
offers much security.
The only difference between ―Sessionǁ and ―Applicationǁ states is: ―The
Session state data will be lost automatically whenever the browser is closed. But the
Application state data will not be lost even after the browser is closed. It will remain until
you stop the web serverǁ.
In other words, the session is limited to single client. Individual sessions are created for
every client. But for all the clients, ―Applicationǁ state is accessible.
Conclusion: When you want to store any data value, that is related one user, you prefer
to use ―Sessionǁ state. Whenever your data value is to be accessible from other users
also, then you prefer ―Applicationǁ state.

Implementation:
A. Assign value to the Application:
Application[―nameǁ] = value;
B. Get value from the Application (gets the application state variable value in
“Object” type):
Application[―nameǁ]

C. Clear all the values in the Application state:


Application.Clear();

Demo:

Open the previous demo web site.


Add the ―Submit using Application Stateǁ button in the Default.aspx as shown:
Write the code:

Add the ―display4.aspxǁ page.


Design the ―display4.aspxǁ page as shown:
Write the code:
View State
―View Stateǁ is a state that keeps the current state of the web page, during post back.
Post Backing: The web page gets re-loaded automatically, whenever the user performs
an event at run time. Here, the page will be submitted to the same page itself. This
process is called as ―Post Backingǁ. For example, if the user clicks on a button, the
page will be posted back.
At the time of post backing, the web page will be closed and the same web page will be
re-loaded. In fact, the textbox values / list box selections etc., would not be re-loaded, if
―View Stateǁ concept is not implemented.
Because of ―View Stateǁ, ASP.NET is able to get the web page to the previous state, as
it is submitted at the time of post back.
As a part of this ―View Stateǁ, at the time of Post Backing, ASP.NET automatically saves
the current values of the controls in a separate string temporarily. After re-loading the
page, the controls values will be re-stored to its previous state, based on the values in
view state string.
In fact, the ―View Stateǁ is maintained automatically by ASP.NET, you don‘t
require implementing it manually.

Demo
Open the previous demo web site.
Add ―viewstatedemo.aspxǁ page and design it as shown.
Open Solution Explorer; right click on ―viewstatedemo.aspxǁ and click ―View in Browserǁ.
Enter some values.
Click on the button. Then the ―post backingǁ will be done. But the no values will be lost.
Global.asax
This file contains the events, related to entire web site.
Here is the list of events, written in global.asax file:
1. Application_Start: This event executes automatically, whenever the
―Application Stateǁ is created. The Application State will be created automatically,
whenever the web server is started.

2. Application_End: This event executes automatically, whenever the


―Application Stateǁ is closed (erased). The Application State will be closed
automatically, whenever the web server is stopped.

3. Application_Error: This event executes automatically, whenever any type of


exception occurs, during the execution of any web page of the current web site.

4. Session_Start: This event executes automatically, whenever the ―Session


Stateǁ is created. The Session State will be created automatically, whenever the
user opens the web site on the browser. In other words, it executes when a new
client is connected.

5. Session_End: This event executes automatically, whenever the ―Session Stateǁ


is closed. The Session State will be closed automatically, whenever the user
closes the web site on the browser. In other words, it executes when browser is
closed (disconnected).

Demo
Open the previous demo web site.
Open Solution Explorer. Right click on the web site name and click on ―Add New Itemǁ –
select ―Global Application Classǁ – Click on ―Addǁ.
It generates the following events automatically.
Type the code as follows:
Add ―usercountpage.aspxǁ and design it as shown:
Write the code:

Open Solution Explorer; right click on ―usercountpage.aspxǁ and click on ―View


in Browserǁ.
Copy the URL from the address bar; open another browser; and paste the URL.
Note: Every time you run the page, the user count will be incremented automatically.

Come back to Visual Studio.


Add ―errorpage.aspxǁ and design it as shown:
Add ―errortestpage.aspxǁ and design it as shown:
Write the code:

Open Solution Explorer; Right click on ―errortestpage.aspxǁ and select ―View in Browserǁ.
Click on the button.
Then it shows the ―errorpage.aspxǁ automatically, because of the code that you
have written in ―Application_Errorǁ event at global.asax file.
Uniformity of the Content
This concept target is to maintain uniformity (looks similar) for the content or controls.
Suppose you have 10 main headings your web page. Which would the better one? Either
displaying all those 10 headings with different styles (fonts, colors, borders etc.); or
displaying all those with common and uniform style..?
The correct answer is second option. That means it‘s a good and professional way, if you
plan to give the common styles for all the headings. Of course, not only for headings; for
textboxes, labels, list boxes, menu items etc., it is better to apply common styles only.
At the this situation, this uniformity maintenance is possible in many ways:
1. CSS
2. Themes
3. Skins

CSS
(Cascading Style Sheets)

This is to overcome the limitations of HTML and also to apply common style among
several controls on the same or different web pages.
This can also be called as ―DHTMLǁ (Dynamic Hypertext Markup Language).
DHTML offers better designing features, which are not supported by classic HTML.
This also used to implement common design styles among different types of controls.
It contains no new tags. It contains several attributes for better designing.
In fact, CSS is not only related to ASP.NET. It is the generalized web page designing
concept, which is available in PHP and J2EE etc., also.
In ASP.NET, these styles can be applied for both HTML tags and ASP.NET controls also.
Implementation Models of CSS
1) Inline Styles: The styles are limited to the currently element (tag) only.
2) Internal Styles: The styles are limited to the tags, used in the same page.
3) External Styles: The styles can be applied to the tags, within the same web site
(multiple web pages).

Important CSS Attributes:

Attribute Possible Values


font-family any font name
font-size 1 to unlimited
font-weight normal / bold
text-align left / center / right / justify
vertical-align top / middle / bottom
text-decoration none / underline
text-transform none / lowercase / uppercase / capitalize
letter-spacing n (space between each character)
word-spacing n (space between each word)
line-height n (space between each line)
top pixels (Gap between the top margin to the current element)
left pixels (Gap between the left margin to the current element)
position relative / absolute
background-color any color
background any image path
background-repeat repeat / no-repeat
border-style none / solid / double / groove / inset / outset / dashed / dotted
border-color any color
border-width pixels
border-left-style none / solid / double / groove / inset / outset / dashed / dotted
border-left-color any color
border-left-width pixels
border-right-style none / solid / double / groove / inset / outset / dashed / dotted
border-right-color any color
border-right-width pixels
border-top-style none / solid / double / groove / inset / outset / dashed / dotted
border-top-color any color
border-top-width pixels
border-bottom-style none / solid / double / groove / inset / outset / dashed / dotted
border-bottom-color any color
border-bottom-width Pixels
default / pointer / wait / text / hand / crosshair / help / move, e-resize /
cursor n-resize / ne-resize / nw-resize / s-resize, se-resize, sw-resize, w-resize
width pixels
height pixels
n (specifies the order of the element in rendering the content on the
z-index page)
Implementation of CSS Styles

1) Inline Styles:

Syn: <tag Style=ǁattribute1:value1; attribute2:value2;….ǁ>


Description: The CSS styles can be applied for the current tag only.

Ex:
<asp:TextBox ID="TextBox4" runat="server" Style="font-family:Broadway;
border-color:Red; text-align:right;" Text="hello"></asp:TextBox>

<h1 Style="font-family:Lucida Handwriting; font-size: 35px; font-weight:bold;


text-align:center; text-decoration:underline; text-transform:capitalize; letter-
spacing:5px; word-spacing:10px; line-height:2; background-color:lightgreen;
color:red; border-style: dotted; border-color:Red; border-width:10px; border-
bottom-style:dashed; border-top-style: groove; cursor: hand; width:
700px;">hello</h1>

2) Internal Styles:
Syn:
<head>
<style type=ǁtext/cssǁ>
tag
{
attribute1:value1; attribute2:value2;….
}
</style>
</head>

Description: The CSS styles can be applied for every instance of the specified
tag in the current page.
Ex:
<style type="text/css">
h2
{
color:Blue;
font-family: Tahoma;
font-size: 30px;
}
</style>

Invoke it:
<h2>hello</h2>

3) External Styles:
Syn: (“xxxxxx.css” file)
tag
{
attribute1:value1; attribute2:value2;….
}

Description: The CSS styles can be applied for every instance of the specified
tag in every page, that is linked with the ―.cssǁ file.

To link the ―.cssǁ file, write the following tag in the page.
<head>
<link href=ǁcss file pathǁ rel=ǁStylesheetǁ type=ǁtext/cssǁ />
</head>

Instead, you also drag and drop the ―.cssǁ file from Solution Explorer into the
web page. Then Visual Studio automatically generates the above ―<link>ǁ tag in
the ―<head>ǁ tag automatically.
Adding “.css” files to the Web Site

Click on ―Web Siteǁ menu – ―Add New

Itemǁ. Select ―StyleSheetǁ option.

Enter the name of the css file. Ex: StyleSheet.css

Click on ―Addǁ.

Then the css file will be added to the web site.

CSS Classes

In the ―Internal Stylesǁ and ―External Stylesǁ, common styles will be applied for every
instance of particular tag. Instead, you can have a choice for applying the CSS styles for
the required instances only, with the concept called ―CSS classesǁ.

Finally, the ―CSS Classesǁ concept can be used in two situations:


1) To apply common CSS styles for selective instances of a tag.
2) To apply common CSS styles for selective instances of multiple

tags. To create a CSS class, follow the syntax:


.classname
{
attribute1:value1; attribute2:value2;….
}

To apply the CSS style for the required html tag, follow the syntax:
<tag class=ǁclassnameǁ>

To apply the css style for the required server tag, follow the syntax:
<asp:tag CssClass=ǁclassnameǁ>

Ex:
<head runat="server">
<style type="text/css">
.mytextbox
{
color:Red;
font-family: Tahoma;
font-size: 30px;
border-style: double;
}
</style>
</head>

Invoke the class:


<asp:TextBox ID="TextBox2" runat="server" CssClass="mytextbox"></asp:TextBox>

Create a new web site.


Add the ―cssdemo.aspxǁ page.
Design the ―cssdemo.aspxǁ page as shown:
Open Solution Explorer – right click on the web site name and click on ―Add New Itemǁ.
Select ―Style Sheetǁ.
Enter the any file name. Ex: StyleSheet.css
Click ―Addǁ.
Then the screen looks like this:

Remove that body tag and make file empty, because we don‘t require it now.
On the screen, you can observe ―Style Sheetǁ toolbar.

If you don‘t find it, click on ―Viewǁ menu – ―Toolbarsǁ – ―Style Sheetǁ option. Then
the toolbar will be there.
Then click on the first button called ―Add Style Ruleǁ.

Then it displays the following dialog box.


Click on ―Class nameǁ option and enter the any class name. Ex: MyTextBox.
It automatically generates the Style rule preview as ―.MyTextBoxǁ (as you know already
that, every CSS class name should start with . (dot)).

Click on OK.
Then it generates CSS class syntax in the code.
Then click on the class name (MyTextBox) and click on ―Build Styleǁ option in the toolbar.
Then it shows ―Modify Styleǁ dialog box.
Select any formatting effects that you want.

Click on OK.
Then it automatically generates the style sheet code as below:
Come back to the ―cssdemo.aspxǁ page.
Drag the ―StyleSheet.cssǁ file from the Solution Explorer, into the page and drop it in
the page.
Then it links the CSS file to the web page. That means, it generates the <link> tag
automatically in the code.
Next, specify the following property for all the
textboxes. CssClass: MyTextBox
Run the web site.
Finally your page looks like this:
This is how to apply CSS styles in ASP.NET.
Themes
As you know in the previous concept, the CSS styles are used to apply common design
styles. But the limitation of CSS is, CSS styles are always executed at client level.
The CSS styles can‘t be applied at sever level. So that, using CSS, you can set the
general properties like font styles, colors, cursors, borders etc., but you can‘t set the
special properties related to the server controls.
For example, you can‘t set the ―ReadOnlyǁ property of a textbox using CSS. In the same
way, you can‘t set the ―NavigateUrlǁ property of a hyperlink using CSS.
In this case, to replace the usage of ―CSS stylesǁ, the ―Themesǁ are introduced.
The advantage of themes is: those can set the any property of the server controls. For
example, you can do the above two examples using ―Themesǁ.
One more advantage is: you don‘t require setting any property like ―CssClassǁ, if you
are using ―Themesǁ. The style will be applied commonly for all the controls, that you
have mentioned in the skin file.
The themes can be implemented in a ―skin fileǁ (with .skin extension), and placed in the
―App_Themesǁ folder.
When you create a theme, its skin file is placed in the ―App_Themesǁ folder.
Note: The themes are completely dynamic. Its effect would not be displayed in the
―Designǁ view.

Implementation of Themes:
First, add a skin file by clicking on ―Web Siteǁ menu – ―Add New Itemǁ – ―Skin Fileǁ.
Enter the name of the theme. Ex: MyTheme.skin
Click on ―Addǁ.
It asks a confirmation, to create ―App_Themesǁ folder. Click on ―Yesǁ.
Then the skin file will be created as follows:

In the skin file, you can write the tags for server controls like <asp:Label> etc., along
with few properties. The tag should contain runat=server attribute.
Ex: <asp:Label runat=ǁserverǁ BackColor=ǁPinkǁ />
To impose the theme in the required .aspx page, simply write the Theme=”theme
name” attribute the <%@ Page> directive.

Note: If the property values are clashed between the control and the theme, the theme properties
only be applied at run time.

Note: To disable the themes for a specific tag instance, simply use EnableTheming=”false”
attribute for the required tag.

Demo:

Open the previous demo web site.


Add the ―themesdemo.aspxǁ page and design it as shown:

Open Solution Explorer; right click on the web site name and click on ―Add New Itemǁ.
Select ―Skin Fileǁ.
Enter the file name as ―MyTheme.skinǁ.
Click on ―Addǁ.
It asks a confirmation, whether you want to place the skin file in the
―App_Themesǁ folder or not. You click on ―Yesǁ.

Then the screen looks like this:

Delete all the commented code and type the code manually as follows:
IMP Note: While you are typing the above code, no help
can be given by Visual Studio. You have to take care about
casing and all other things. If you don‘t type it in proper
casing, it won‘t work. It causes some errors.
Come back to the ―themesdemo.aspxǁ page.
Open the properties window and choose
―DOCUMENTǁ option from the list, which is displayed at
the top of the properties window.
Select the ―Themeǁ property as ―MyThemeǁ from the list.
Select the ―Label3ǁ and set the following
property: EnableTheming: False
Then run the web site.
At run time, the theme will be applied, and the page looks
like this on the browser:
Limitations of Themes:
As per the default nature of themes, for all the controls, common styles will be applied
automatically.
Suppose if you want to apply one type of style for few controls on the page, and another
type of style for few other controls on the page, it not possible.
Solution: Use ―Skinsǁ.
Skins
Skins are similar to CSS classes.

Similar to CSS class, the skin has a name.


It can be written in the ―.skinǁ file.
One skin file may contain any no. of skins.

Implementation:
Create the tag designs with “SkinID” attribute (in the skin file):
<tag runat=ǁserverǁ property=ǁvalueǁ SkinID=ǁskin nameǁ />
Access the Skin with “SkinID” attribute (in the aspx page):
<tag runat=ǁserverǁ SkinID=ǁskin nameǁ />

Demo:

Open the previous demo web site.


Add the ―skinsdemo.aspxǁ page and design it as shown:
Open Solution Explorer; right click on the web site name and click on ―Add New Itemǁ.
Select ―Skin Fileǁ.
Enter the file name as ―MyTheme2.skinǁ.
Click on ―Addǁ.
It asks a confirmation, whether you want to place the skin file in the
―App_Themesǁ folder or not. You click on ―Yesǁ.
Then the screen looks like this:
Delete all the commented code and type the code manually as follows:
Come back to the ―skinsdemo.aspxǁ page.
Open the properties window and choose ―DOCUMENTǁ option from the list,
which is displayed at the top of the properties window.
Select the ―Themeǁ property as ―MyTheme2ǁ from the list.
For the first five textboxes, set the following
property: SkinID: PinkAndRed
For the remaining five textboxes, set the following
property: SkinID: BisqueAndBlue
Then run the web site.
At run time, the theme will be applied, and the page looks like this on the browser:

Note: If you don‘t apply the SkinID property, no style will be applied.
So finally, we have few textboxes with one style, and few other textboxes with another
style.
This is possible using Skins.
Web User Controls
Similar to ―User Controlsǁ in windows applications, you can develop user controls in the
web sites also.
As you know already, the advantage of user controls is, those can be used in any web
page, and avoids designing repetitive content in multiple pages.
That means you need to design the content once and you can use it any no. of times in
any page.

Implementation of Web User Controls

1. Add the User Control to the Web Site:


Click on ―Web Siteǁ menu – ―Add New

Itemǁ. Select ―Web User Controlǁ.

Enter the name of the user control and click on ―Addǁ.

Note: The file extension for web control file is ―.ascxǁ. (Active Server
Control Extended).

Then the user control will be created with the following statement in the
―Sourceǁ view.
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>

2. Design and Develop the User Control

Design the user control, as per on your requirement. Drag the required controls
from the toolbox, (just like web page) and write the code in the ―.ascx.csǁ file if
needed.

3. Link the User Control with the Web Page

To do this, type the following tag in the ―Sourceǁ view, after ―<%@ Page>ǁ tag.
<%@ Register Src="UserControlFileName" TagPrefix="xxxx" TagName="xxxx" %>

4. Invoke the User Control

To invoke the control in the page, use the following tag, whereever required.
<Tagprefix:TagName />
Demo:

Create a new web site.


Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Default.aspxǁ – Click on Add.
Design the ―Default.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Aboutus.aspxǁ – Click on Add.
Design the ―Aboutus.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―Contactus.aspxǁ – Click on Add.
Design the ―Contactus.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―registration.aspxǁ – Click on Add.
Design the ―registration.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ – Type the name as
―login.aspxǁ – Click on Add.
Design the ―login.aspxǁ as follows:

Open solution explorer; right click on the web site name and choose ―Add New Itemǁ.
Select ―Web User Controlǁ.
Enter any name. Ex: WebUserControl.ascx
Note: ascx stands for Active Server Control Extended.
Click on ―Addǁ.
Design it as shown:
Come back to the ―Default.aspxǁ.
Drag the ―WebUserControl.ascxǁ and drop it into the page.
Then the control will be added to the page.
In the same way, drag and drop the ―WebUserControl.ascxǁ into all other pages also.
After designing the user control, the pages looks like this:
Run the web site.

Note: To avoid the repetition of design like above example, you can use another concept called
as ―Master Pagesǁ.
Master Pages
Similar to ―User Controlsǁ, the common design can be shared among multiple web
pages using ―Master Pagesǁ concept.
A master page is similar to web page, but it‘s not a web page.
The master page file extension is ―.masterǁ.
It also contains some design and code in the ―.csǁ file.
It can be executed on the browser directly.
This is meant for re-usability only.
That means the master page content can be re-usable by other web pages (.aspx
pages).

Implementation of Master Pages

1. Add the Master Page to the Web Site:

Click on ―Web Siteǁ menu – ―Add New

Itemǁ. Select ―Master Pageǁ.

Enter the name of the master page and click on ―Addǁ. Ex: MasterPage.master

2. Design and Develop the Master Page:

Design the required content in the master page before ―ContentPlaceHolderǁ


tag, and write the necessary code in the ―.master.csǁ file.

The ―ContentPlaceHolderǁ tag represents the content in the other web pages.
In the master page, it should be empty.

3. Create a Web Page with the Reference of Master Page:

Click on ―Web Siteǁ menu – ―Add New Itemǁ.

Select ―Web Formǁ. Enter the name of the new web page.

Select the option ―Select Master Pageǁ.

Click on ―Addǁ.

Then it displays the list of all available master pages in the project. Select the master
page name and click on ―OKǁ.
In this content page, you design any content in the ―ContentPlaceHolderǁ tag.
Demo:

Create a new web site.


Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Master Pageǁ – Type the name
as
―MasterPage.masterǁ – Click on Add.
Design the ―MasterPage.aspxǁ as follows:
Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ.
Type the name as ―Default.aspxǁ.
Select the option ―Select Master Pageǁ.
Click on Add.
Select ―MasterPage.masterǁ.
Click on OK.
Design it shows the screen like this:

Design the new content in content place holder as follows:


Click on ―WebSiteǁ menu – ―Add New Itemǁ – ―Web Formǁ.
Type the name as ―Aboutus.aspxǁ.
Select the option ―Select Master Pageǁ.
Click on Add.
Select ―MasterPage.masterǁ.
Click on OK.
Design it shows the screen like this:
Design the new content in content place holder as follows:
Run the web site.
The common content, which you have designed in the master page, will be repeated in
―Aboutusǁ page and ―Defaultǁ page.
Run the web site.
Caching
Caching (pronounced as ―Cashingǁ), is one of the most powerful concept of ASP.NET.
This is introduced to reduce the stress on web server.
If your application is being executed simultaneously from two or more browser windows
on the same system, or it is being executed simultaneously from two or more client
systems on the network, or it is being executed simultaneous from two or more web
clients on internet, on each post back of the page, a new request to the web server
would be passed. So that, the entire page is to be refreshed. That means the contents of
the web page would be re-loaded and the code will be executed every time. This causes
heavy stress on the web server.
For example, there is a submit button on your web page. If the submit button is clicked
on one client, it is not a much stress on the web server. You suppose that the button is
clicked from 20 client systems at-a-time. So that 20 requests will be passed to the web
server. The web server should respond to the 20 clients. So this leads to slow-up the
execution, because of heavy stress on the web server.
To avoid this kind of problems, ―Cachingǁ concept is introduced.
According to this, you can store the page and its output in the cache memory up to a
certain time.
If any request is sent to the web server, within the time limitation, the page will not be
re-loaded / re-executed. No code will be executed. Simply the previously cached web
page will be sent to the client as response.
After completion of the specified time limit, the cached page will be removed
automatically.
If any request is sent to the web server after the time limit, the page will be re-loaded as
usual.
Generally, it is recommended to store most frequently used web pages in the cache
memory, using ―Cachingǁ concept.
At this same time, it is not recommended to store the web pages in the cache memory,
which pages content can be frequently changed dynamically at run time. Ex: Inbox page,
cricket scores page, examination results page.
Types of Caching:
1. Output Caching:

The output of the web page will be stored in the cache memory, for a while (based
on the time limit that you have given).

Syntax: Write the following tag in the ―Sourceǁ view, after Page directive:
<%@ OutputCache Duration="seconds" VaryByParam="none" %>

2. Fragment Caching:

This is also one kind of output caching.

But instead of storing the full page output in the cache memory, partial page (part
of the page) output only be stored.

To implement this, you have to implement the ―OutputCacheǁ in the Web User
Control.

After that, drag and drop the ―WebUserControlǁ into the web

page. That‘s all. Then finally it will be fragment caching.

3. Data Caching:

This is used to store the frequently used database data, in the cache memory.

For the first time, when the user opens the web page, you connect with the
database and get the data from the database; and store it in the cache memory.

Later, you can get the cached data on the same page or another page also, without
contacting the database.

Create a new web site.


Add ―Default.aspxǁ page and design it as shown:
Write the code:

Open the ―Sourceǁ view.


Type the <%@ OutputCache %> tag at the top, after <Page> directive as follows:
Run the web site.
When you click the button for the web site, current system time will be displayed.
But when you click the button every time, the time will not be displayed, because it
executes no code for the second time onwards.
If you click on the button after 20 seconds, the time will be refreshed. Again, that output
will remain up to another 20 seconds.
This is the effect of output caching.

Note: The attribute ―VaryByParamǁ can be used for the pages, having the parameters in the
query string. When you want to use this, you write it as VaryByParam=”*”. Whenever you
write like this, separate copies will be created in the cache for the page, having different query
strings. If there are no changes in the query string, then cached output will be given as response
to the user.

Fragment caching demo:

To continue the demo application with ―Fragment cachingǁ, open the solution explorer,
right click on the web site name and choose ―Add New Itemǁ.
Select ―Web User Controlǁ.
Enter the name as ―WebUserControl.ascxǁ.
Click on ―Addǁ.
Design the ―WebUserControl.ascxǁ as shown:
Write the code:

Open the ―Sourceǁ view.


Type the <%@ OutputCache %> tag at the top, after <Control> directive as follows:
Add the ―fragmentcachingdemo.aspxǁ and design it as shown:

Write the code:

Drag and drop the ―WebUserControl.ascxǁ from solution explorer, into the page.
Then the screen looks like this:
Run the web site.
Click on the Submit button. In fact, (if you are not implementing the caching feature),
when you click on the button, the complete page will be posted-back (re-loaded). That
means Page_Load() event also will be executed. At the same time, Page_Load() of Web
User Control also will be executed.
But in the label, which you have designed in the web page, displays the latest system
time.
But the user control will not be re-loaded. So that, in the label, which you have designed
in the WebUserControl, latest system time will not be displayed.
This is the effect of ―fragment cachingǁ.
Data Caching Demo:

To continue the demo application with ―Data cachingǁ, add the


―datacachingdemo.aspxǁ and design it as shown:

Write the code:


Run the web site.
When run the web page, it loads the data from database and it will be stored into the
cache memory.
When you click on ―Show Dataǁ button, instead of loading the data from database, the
data will be loaded from cache memory, and will be displayed in the GridView1 control.
This is the effect of data caching.
Common Tasks in JavaScript

i. Displaying pop-up windows:


Generally while you are browsing the web sites, sometimes, some ads will be
displayed in a separate window.
That window can be called as popup window.

To generate this type of popup windows, use the following syntax:


window.open("pagename.ext", "any_name",
"location=no,toolbar=no,menubar=no,width=xx,height=xx ");

Demo:

Create a new web site.


Add the ―popupdemo.aspxǁ and design it as follows:
Add the ―myad.aspxǁ page and design it as follows with an image control:
Select the ―DOCUMENTǁ properties in the ―properties windowǁ and set the
following property:
Title: Ad
Type the <body> tag as follows:
<body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>

Come back to the ―popupdemo.aspxǁ.


Select the ―Show Popup Windowǁ button and set the following
property: OnClientClick: javascript:window.open("myad.aspx",
"popup1",
"location=no,toolbar=no,menubar=no,width=728px,height=
75px");

Run the web site and click on the button. It shows the popup ad automatically.
ii. Displaying dialog boxes:
JavaScript supports two types of dialog boxes:
1) Alert Boxes (Message Boxes):
Syntax: window.alert("message");

2) Confirmation Boxes:
Syntax: window.confirm("message");

Demo:

Open the previous demo web site.


Add the ―dialogboxes.aspxǁ and design it as follows:
Set the button1 properties:
OnClientClick: javascript:window.alert("Hello, World!");
Set the button2 properties:
OnClientClick: return window.confirm("Are you sure?");

Add ―confirmationmessage.aspxǁ page and design it as follows:


Come back to the ―dialogboxes.aspxǁ.
Double click on button2 and write the code:

Note: When the user clicks on ―OKǁ button at run time, the ―confirmationmessage.aspxǁ page
will be displayed, because the confirm() method returns ―trueǁ value. Otherwise, no action will
be done, because the confirm() method returns ―falseǁ value.
iii. Displaying Status Bar Messages on the Browser:
Syntax:
window.status=ǁmessageǁ;

Demo:

Open the previous demo web site.


Add the ―statusbardemo.aspxǁ page and design it as follows:

Open the page in ―Sourceǁ view.


Change the <body> tag as follows:

<body onload="javascript:window.status='Move the mouse pointer on to the image...';">

Change the <asp:Image> tag as follows:


<asp:Image ID="Image1" runat="server" ImageUrl="laptop.jpg"
onMouseOver="javascript:window.status='Click the Image';"
OnMouseOut="javascript:window.status='Move the mouse pointer on to the image...';"
onClick="javascript:window.alert('You have clicked in the image');" />

Come back to the Design view.


Run the web site and observe the status bar on the browser.
LINQ
▪ LINQ (pronounced link) stands for ―Language Integrated Queryǁ.
▪ This concept is introduced in .NET Framework 3.5.
▪ This is a ―query writing technologyǁ.
▪ This is most useful while working large amount of data in the live projects.

Introduction:

▪ In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
▪ In the modern world, the data sources are not only the databases. The application can
access the data from various other data sources like XML files, SAP, CSV (Comma
Separated Values) files etc.
▪ But you can‘t write a query on the non-database data, which in the form of objects, XML
etc. There, you can write the queries using the new concept called ―LINQǁ.
▪ You can write queries on arrays, objects, tables, xml using LINQ.
▪ Note: Before writing the LINQ queries, you should import the ―System.Linqǁ namespace.

The following example shows a small demo on LINQ:

Create a new web site.


Add the ―linqtoarraysdemo.aspxǁ page.
Write the code:
Run the web site.
You get the output as follows:

In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can write the queries
on various data sources.

LINQ Syntax:
▪ The above syntax consists of 7 clauses.
from clause
in clause
let clause
where clause
orderby clause
select clause
group by clause

▪ Mandatory clauses:
from clause
in clause
select clause

Clause: A part of the query.

Understanding Clauses:

1. from clause: This is used to specify the range variable name. At run time, the one-by-
one element (in a loop) will be assigned to this range variable and based on this range
variable other clauses like where, let, order by etc., will be executed..
2. in clause: This is used to specify the data source for the query, from where data comes
to execute the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required. It
supports to have both ascending and descending order.
6. select clause: This is used to specify the object, which is required in the query results.
In general, we give
7. group by (optional): This is similar to ―group byǁ clause in SQL. This retrieves
grouped data, based on a column.
Note: The LINQ query returns the result in the form of IEnumerable<data type> type.
IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable

Demo on LINQ to Objects:

Open the previous demo web site.


Open the solution explorer; right click on the web site name and choose ―Add
New Itemǁ.
Select ―Classǁ.
Enter the name as ―Student.csǁ.
Click on ―Addǁ.
It asks for confirmation, whether you want to place the file in the ―App_Codeǁ folder or
not. Click on ―Yesǁ.
Write the code:
Add the ―linqtoobjectsdemo.aspxǁ page.
Write the code:

linqtoobjectsdemo.aspx.cs

public partial class linqtoobjectsdemo : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)
};

Response.Write("<font face=Tahoma>");
//linq query with where clause
var result1 = from s in stu where s.Course == "MCA" select s;
Response.Write("MCA Students:" + "<br>");
foreach (Student r in result1)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with compound where clause


var result2 = from s in stu where s.Name.EndsWith("a") && s.Marks >= 400 &&
s.Marks <= 600 select s;
Response.Write("<br>Students whose name ends with 'a', and marks is >=400 and
<=600:" + "<br>");
foreach (Student r in result2)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with let and where clauses


var result3 = from s in stu let avg = s.Marks / 10 where avg < 35 select s;
Response.Write("<br>Failed Students:" + "<br>");
foreach (Student r in result3)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause


var result4 = from s in stu orderby s.Marks select s;
Response.Write("<br>Students (sort on marks):" + "<br>");
foreach (Student r in result4)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");
Run the web site and the output will be like this:
LINQ with Lambda Expressions
▪ LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
▪ The previously written linq queries are written with ―General Query Syntaxǁ.
▪ Syntax for Lambda Expression:
DataSource.Clause(range_variable_name => Expression)
▪ Ex:
stu.Where(s => s.Marks < 300)

goes to
Demo on LINQ with Lambda Expressions:

Open the previous demo web site.


Add the ―linqwithlambda.aspxǁ page.
Write the code:

linqwithlambda.cs

public partial class linqwithlambda : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)
};

Response.Write("<font face=Tahoma>");

//linq query with where clause


var result1 = stu.Where(s => s.Course == "MCA");
Response.Write("MCA Students:<br>");
foreach (Student r in result1)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with compound where clause


var result2 = stu.Where(s => s.Name.EndsWith("a") && s.Marks >= 400 && s.Marks
<= 600);
Response.Write("<br>Students whose name ends with 'a', and marks is >=400 and
<=600: <br>");
foreach (Student r in result2)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause


var result4 = stu.OrderBy(s => s.Marks);
Response.Write("<br>Students (sort on marks): <br>");
foreach (Student r in result4)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause (descending)


var result5 = stu.OrderByDescending(s => s.Marks);
LINQ to SQL
▪ This is to get the database data and perform LINQ queries on database data.

Demo on LINQ to SQL:

Open SQL Server 2005.


Create the ―Customersǁ table as follows:

Enter some sample data:


Create the ―Ordersǁ table as follows:
Enter some sample data:
Right click on ―Database Diagramsǁ and click on ―New Database Diagramǁ.
It displays ―Add Tableǁ dialog box.

Select ―Customersǁ table and click on ―Addǁ.


Select ―Ordersǁ table and click on ―Addǁ.
Click on ―Closeǁ.
Drag the ―CustomerIDǁ column from ―Customersǁ table and drop it on
―CustomerIDǁ column in ―Ordersǁ table.
Click on OK.
Click on OK.
Save the diagram.

Open Visual Studio 2010.


Open the previous demo web site.
Open the solution explorer; right click on the web site name and choose ―Add
New Itemǁ.
Select ―LINQ to SQL Classesǁ.
Enter the file name as ―MyDB.dbmlǁ. (DBML stands for Database Markup Language).
It asks for confirmation, whether you want to place the file in the ―App_Codeǁ folder or
not. Click on ―Yesǁ.
Open the ―Server Explorerǁ by clicking on ―Viewǁ menu – ―Server Explorerǁ.
Right click on ―Data Connectionsǁ and click on ―Add Connectionǁ.
Click on ―Changeǁ.
Select the required database. Ex: ―Microsoft SQL Serverǁ.
Enter the following details:
1. Server name: localhost
2. Use SQL Server Authentication:
▪ User name: sa
▪ Password: 123
3. Database name: demo
Click on ―Test Connectionǁ. It displays connection succeeded message.
Click on OK.
Then a connection component will be created in the ―Server Explorerǁ.
Expand the ―demoǁ database in the server explorer.
Expand ―Tablesǁ.
Drag and drop the ―Customersǁ table into the DBML designer.
In the same way, drag and drop the ―Ordersǁ table into the DBML designer.
Click on the plain area and observe the properties window.
It shows the DataContext name, associated with this
DBML file. Ex: MyDBDataContext
This is the class name, using which you can create the object while you write the code.
Using with that object, you can access the ―Customersǁ and ―Ordersǁ tables data.
But you don‘t require writing any code for database connection and retrieving the data
from the database.
Open the solution explorer; right click on the web site name and choose ―Add
New Itemǁ.
Select ―Web Formǁ.
Enter the name as ―linqtosqldemo.aspxǁ.
Click on ―Addǁ.
Design the ―linqtosqldemo.aspxǁ as follows:
Write the code:
protected void LinkButton3_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Where(c => c.Gender == "Female");

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderBy(c => c.Amount);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton5_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderByDescending(c => c.Amount);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Take(2);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Skip(2);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton8_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Amount >= 4000 && c.Amount <=
5000);
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);

var customerslist = customerslist1.Union(customerslist2);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton9_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);

var customerslist = customerslist1.Intersect(customerslist2);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton10_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);

var customerslist = customerslist1.Except(customerslist2);

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton11_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from cust in db.Customers
join ord in db.Orders
on cust.CustomerID equals ord.CustomerID
select new { cust.CustomerID, cust.CustomerName, cust.Gender,
cust.Amount, ord.OrderID, ord.ProductID, ord.Price, ord.OrderDate };

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
Run the web site and click on the link buttons.
XML
XML stands for ―Extensible Markup Languageǁ.
It is also a markup language, just like HTML, which contains tags.
But unlike HTML, the XML contains no pre-defined tags. It contains only user-defined
tags.
This xml code can be written in a file with ―.xmlǁ file.
This is used to describe the data in a structured format.
The xml files can be used as ―secondary databasesǁ.
Generally, xml documents are portable, in order to share the data among two projects
developed in different languages.

Ex: employees.xml
Create a new web site.
Add the ―Default.aspxǁ page.
Open the solution explorer; right click on the web site name and choose ―Add
New Itemǁ.
Select ―XML Fileǁ.
Enter the file name as ―employees.xmlǁ.
Type the code:

Design the ―Default.aspxǁ page as follows:


Write the code:

Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
Run the web site.
Output:
Web Site Configuration
For every application, some settings will be there.
For example, for MS Word, there is an option called ―Word Optionsǁ, where you can set
some settings related to MS Word software. For another example, for winamp also some
settings will be there like last opened play list, last played media file, last used theme,
status of ―Repeatǁ and ―Shuffleǁ options etc.
For the ASP.NET web sites also, some settings are there.
Those settings are written in a file called ―web.configǁ.
In fact, there are two files:
1. web.config
2. machine.config
The above two are called as web configuration files in ASP.NET.

Sl. No web.config machine.config


1 Contains the configuration settings, related Contains the configuration settings,
to a single web site. related to entire server machine.
2 Located in the web site folder. Located in the following folder.
C:\WINDOWS\Microsoft.NET\Framework\
v4.0.30319\Config\machine.config

Note: Both of those files can be written in XML language.


To open the machine.config file, open the following folder.
C:\WINDOWS\Microsoft.NET\Framework\ v4.0.30319\Config
Double click on ―machine.configǁ file.
Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.

Understanding the web.config file:


✰ Create a new web site.
✰ When you create the web site, automatically this file will be created.
✰ To open this, open Solution Explorer and double click on ―web.configǁ file.
✰ The xml document starts with XML prologue, which specifies the xml version.

✰ All other code can be written a root element called <configuration>.

✰ The next important section is <appSettings>. This is used to store or configure the
application settings, which are related to entire web site. For example, you want to
display the company‘s phone number in several web pages. So that, if you write the
phone number in each page it will be much difficult to change it later, because you
require to change it in all the required pages.
✰ Instead, you try to store it (write it) in the web.config file, at the <appSettings> section.
Then later if you want to change it, you can change it easily, without changing any code
in all the pages.
✰ To take a demonstration, change the <appSettings/> tag as follows:

✰ Open the ―Default.aspxǁ page and design it as follows:

✰ Write the code:


✰ Run the web site. The output will be like this:

✰ That means, at run the opens the web.config file automatically, then the company location
and phone number will be taken from <appSettings> tag and will be displayed in the
labels.
✰ Suppose, you want to the change the company location and phone number now. Where
we need to change? You have to change in the <appSettings> tag; and no changes in
your code of the page.
✰ Just for a demo, change the company location and phone number in the web.config file
as follows:
✰ Run the web site. These values will be affected in the output directly.

✰ In the similar way, you are strongly recommended to store the connection strings in the
web.config file, at <connectionStrings> tag; because there may be some changes in the
connection string in future.

✰ Come back to Default.aspx and add a button called ―Connect to SQL Serverǁ as shown.
✰ Write the code:

✰ The next thing you have to observe is <compilation> tag.


✰ This tag specifies the mode of debug (true / false).
✰ When it is set to ―trueǁ, it shows the code, when the exceptions occur; break points also
work.
✰ When it is set to ―falseǁ, it shows a default error message page, when the exceptions occur;
break points won‘t work.
✰ By default, when you create the web site, it will be ―falseǁ. After you run the web site
for the first time, it will be automatically changed as ―trueǁ.
✰ It is recommended to set it as ―trueǁ, when the development process in under progress.
✰ It is recommended to set it as ―falseǁ, before you publish it on the internet; because you
won‘t show the code to the user, when an exception occurs.
✰ The next thing you have to observe is <authentication> tag.
✰ This tag specifies the mode of ASP.NET security. The modes are:
A. None
B. Windows
C. Forms
D. Passport
✰ The default mode is ―Windowsǁ.

✰ We discuss more about this ASP.NET Security concepts and authentication modes later.
✰ The next thing you have to observe is <customErrors> tag.
✰ CustomError means customized errors.

✰ Note: By default, the above code will be under commented mode. You have to un- comment it,
by moving the --> tag to up.
✰ These custom errors are used to display required web pages, when some special type of
error occurs at run time.
✰ For example, whenever the user tries to open a non-existing filename, there will be one
type of error at server. That error code is ―404ǁ.
✰ Observe the following tag:
✰ According to the above tag, whenever 404-error occurs, ASP.NET automatically redirects
the execution flow to the above specified html page called ―FileNotFound.htmǁ.
✰ To test this functionality, do like this:
✰ Run the web site as follows:

✰ In the above screen, the user has tried to open the ―abc.aspxǁ page, which is not there
in our web site. So that ASP.NET is showing the default error message as above.
✰ In the above screen, you can observe the error code as ―HTTP 404ǁ.

✰ Anyway, using <customErrors> tag, you can display another page, at this case.
✰ To do so, close the browser and come back to Visual Studio.
✰ Open the Solution Explorer; right click on the web site name and choose ―Add
New Itemǁ.
✰ Select ―HTML Pageǁ.
✰ Enter the file name as ―FileNotFound.htmǁ.
✰ Click on ―Addǁ.
✰ Design the ―FileNotFound.htmǁ page as follows:

✰ Change the <customErrors> mode as ―Onǁ.

✰ Run the web site and enter the non-existing file name as follows:
✰ When you try to open the ―abc.aspxǁ (or any non-existing file name), it shows the
―FileNotFound.htmǁ page as above.
✰ In the similar way, when the user is not having proper permission to open the web site, it
raises ―403ǁ error. At this error, it shows ―NoAccess.htmǁ page.
✰ Custom Error Modes:
A. On: Custom errors always work.
B. Off: Custom errors won‘t work.
C. RemoteOnly: Custom errors won‘t work in the server system, in which the web
site is stored. Those work from other client systems only.
✰ For all other types of errors, a common page is maintained; i.e. ―GenericErrorPage.htmǁ.
✰ To test it, add the ―GenericErrorPage.htmǁ page and design it as shown:
✰ Open the web.config file and change the connection string wrongly (Ex: change the password
as 456).
✰ Right click on ―Default.aspxǁ and click on ―View in Browserǁ.
✰ Click on ―Connect to SQL Serverǁ button.
✰ Then it shows ―GenericErrorPage.htmǁ page as follows:
✰ Next, observe the <pages> tag. Here, you can specify ―themeǁ attribute as follows:

✰ If you specify any theme as above, that theme will be applied for all the web pages commonly.

Note: In the other sections of the web.config file like <httpHandlers>, <httpModules>,
<compilers>, <system.webServer>, <runtime> etc., we don‘t require to change anything
particularly.
Session State Modes in web.config file
Let us continue with the discussion of web.config file.
In that file, you can configure the session state modes using <sessionState> tag.

The session state modes are:


1. Off
2. InProc (default)
3. StateServer
4. SQLServer

1) Off: Session state is not activated. That means, in your web site session state will not
work.
2) InProc: Session state will be maintained in the memory, which is allocated for original
ASP.NET process that is called as ―aspnet_wp.exeǁ file.
3) StateServer: The session state will be maintained as a separate process, by a separate
server called ―ASP.NET State Serverǁ.
4) SQLServer: The session state will be maintained in the SQL Server database.

Demo on Session States:

Open the previous demo application.


Add the ―sessiontest.aspxǁ page and design it as shown:
Write the code:

Add the ―display.aspxǁ page and design it as shown:


Write the code:

Run the ―sessiontest.aspxǁ page and test it. It works properly.


Open the web.config file and change the <sessionState> tag as follows:

Now, run the ―sessiontest.aspxǁ page. When you enter any name in the textbox and
click on Submit button, it won‘t work; because currently session state is disabled in this
web site.
Open the web.config file and change the <sessionState> tag as follows:

Now, run the ―sessiontest.aspxǁ page. It won‘t work properly; because you have
specified that session state is to be maintained as a separate process, by ASP.NET State
Server. But by default, that server is not started. You have to start it manually.
To do so, open Control Panel – Administrative Tools – Services.
Right click on ―ASP.NET State Servicesǁ and click on ―Startǁ.

Then the service will be started.


Come back to Visual Studio and run the ―sessionstate.aspxǁ page now. It works properly
now. So that currently session state is being maintained in ASP.NET State Server only.
Open the web.config file and change the <sessionState> tag as follows:
Now, run the ―sessiontest.aspxǁ page. It won‘t work properly; because you have
specified that session state is to be maintained in SQL Server database. But by default,
that SQL Server is not configured to store the sessions. You have to configure it
manually.
To do so, open the following folder:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

Double click on ―InstallSqlState.sqlǁ file.


It opens the SQL script in SQL Server 2005.
Press F5 to execute the script.
Then it configures the SQL Server database(s), which are required to store the session
and application states data in SQL Server.
Now come back to Visual Studio, and run the ―sessiontest.aspxǁ page. Now, it
works perfectly. If not, change the <sessionState> tag in web.config as follows:
Then sesssiontest.aspx page works properly.

Working with ASP.NET Configuration Tool:

This is the in-built features of Visual Studio.


This is the easier way to customize or change some portions of the web.config file, in an
easier way.
To start with this, open the solution explorer first.
Select the web site. Click on ―ASP.NET Configurationǁ option in the solution explorer.

Then ASP.NET Web Site Administration Tool will be opened.


There, we have three major options.
1. Security
2. Application Configuration
3. Provider Configuration
Click on ―Securityǁ.
There, you have three options.
1. Users: To create or modify the users-information, who are registered with
―Login Controlsǁ.
2. Roles: To create or manage the user roles like ―adminǁ role, ―customerǁ role and
―guestǁ role etc.
3. Access Roles: To apply the privileges of the users that specifies ―which users
can access which pagesǁ.
Note: We will discuss about this ―Securityǁ concepts in the next chapters more in-depth.
Come back to ―Homeǁ and click on ―Application Configurationǁ. Then it opens the
―Applicationǁ tab.
Here, we have four options:
1. Application Settings
2. SMTP Settings
3. Application Status
4. Debugging and Tracing
Application Settings: Using this option, you can create or modify the application
settings (just like <appSettings> tag in web.config file).
Click on ―Manage application settingsǁ. Then it shows application settings, which
are already configured in web.config file.
To add a new application setting, click on ―Create new application settingǁ option.
Enter the name and value of the application setting.
Click on ―Saveǁ.
Click on OK.
It adds the value to the list; immediately, ―web.configǁ file also will be updated.
Come ―Backǁ to ―Applicationǁ tab.
Configure SMTP E-mail settings: This is to be configured, when you want to send
automatic e-mails from your web site.
Note: Already we know how to configure the SMTP E-mail settings, in the previous
sessions.
Application Status: It should be always ―onlineǁ only. It should not be offline. If it is
offline, it won‘t work on the browser.
To test it, click on ―Take application offlineǁ and try to run any page. It won‘t run. Again
come back to this web site administrative tool and click on ―Take application
onlineǁ. Then it works normally.
Debugging and Tracing – Configure debugging and tracing: This is to enable or
disable the debugging and tracing.
If you uncheck the ―Enable debuggingǁ option, then the <compilation> tag will
be modified as:
<compilation debug="false">
</compilation>

If you check the ―Enable debuggingǁ option, then the <compilation> tag will be
modified as:
<compilation debug="true">
</compilation>
The other options in this screen are related to ―tracingǁ concept. We will discuss more
about this ―tracingǁ, in the further sessions later.
Click on ―Backǁ.
Debugging and Tracing – Define default error page: This is used to change the
generic error page (default error page which is to be displayed on occurrence of any type
of error in the web site). For more information, recollect the knowledge of
<customErrors> tag from previous sessions.
Here, you can select any other page, which acts as default error page.
Click on ―Saveǁ.
Provider: Always, it should be ―AspNetSqlProviderǁ only.
This is all about working with the ―ASP.NET Web Site Administrative Toolǁ.
Close the browser and come back to Visual Studio.
Note: When you change any setting in the ―ASP.NET Web Site Administrative Toolǁ, the
necessary changes would be made in the web.config file automatically.
Tracing
Using this tracing, the developer can get more technical information about the page
execution at run time.
To enable this feature, first option required page and set the following property of the
DOCUMENT object:
Trace: true

Create a new web site.


Add ―Default.aspxǁ page and design it as shown:

Open the ―DOCUMENTǁ properties and set the following


property: Trace: true
Run the web site.
It displays the output as follows:

Along with the content of the web page, it displays:


1. Details about the request.
2. Trace information (execution flow of all the page level events).
3. Information about the controls, used in the page.
4. Session state variables details.
5. Application state variables details.
6. Cookies details, which are added to the ―Requestǁ object.
7. Cookies details, which are added to the ―Responseǁ object.
8. Headers collection.
9. Form collection (the values come from the previous client page, if any)
10. Other server side details.
Just for information, you see all those details. Note that, all this information is read-only.
Close the browser.
To enable the tracing feature for all the web pages in your web site, open the
―web.configǁ file and write the following tag:
Now, if you run any page in the web site, tracing will be by default activated.
To disable the tracing feature, simply delete the <trace> tag (or) set it as
enabled=”false”.
ASP.NET Web Site Security
This is to make the web site secured, which would not be accessible by un-authorized
users.
Currently your web site is accessible by everyone. Now, our target is to make the web
site to be secured, which is accessible by authorized users, and not accessible by
unauthorized users.
For this task, ASP.NET provides some security models:
1. Windows based authentication
2. Forms based authentication
3. Role based authentication
Windows based authentication: For maintenance of user names and passwords, we
depend on Windows O/S. That means, for some of the windows users, the web site
accessible; and for other windows users, the web site is inaccessible.
Forms based authentication: For maintenance of user names and password, we
depend on ―ASPNETDBǁ database, which will be created by ASP.NET automatically,
when we use Login controls. Anyway, identifying the genuine user can be done using the
above maintained users database. In other words, for users who logged-in properly only,
the web site accessible; if the user is not logged-in properly, any of the web pages are
not accessible.
Role based authentication: According to this, we need to maintain the different user
roles like administrator, manager, customer, normal user, guest etc. At run time, if any
user logs-in, ASP.NET checks the type of the user, and allows to access the related web
pages only; other pages are inaccessible. For example, if manager logs-in, the
―managerǁ related pages only are accessible. He can‘t access administrator pages or
customer related pages.
To demonstrate these authentication modes practically, we start with an example.
Create a new web site.
Add the ―Default.aspxǁ and design it as shown:

Windows based Security:


First, let us start with understanding the windows based security.
To do so, first open the ―Control Panelǁ – ―User Accountsǁ and create some users.
For this demo, create 3 users named ―ramǁ, ―sitaǁ and ―laxmanǁ.
Come back to our web site in Visual Studio.
Now, you have to specify the list of windows users, who are eligible or permitted to
access this web site.
Syn: systemname\username
Ex: development01\admin
Here, ―development01ǁ is the system name; ―adminǁ is the user name.
Note: To know your system name, right click on ―My Computerǁ and click on
―Propertiesǁ. Select ―Computer nameǁ and then observe the ―Full computer nameǁ.
Open the web.config file and type the <authentication> tag as follows:
Now, if you login as ―ramǁ or ―sitaǁ, the web site can be accessed normally.
If other users logged-in, the web site is inaccessible. If you try to open the web site,
while you are in other user name (other than ram and sita), then it shows the following
type of message on the browser:

This is nothing but ―Windows based securityǁ.


Forms based Security:

Open the previous demo web site.


For understanding the ―Forms based securityǁ, you need to implement Login
controls first.
To do so, first design the ―Default.aspxǁ page as follows:

Set the properties of ―CreateUserWizard1ǁ:


❖ ContinueDestinationPageUrl: mainpage.aspx
Set the properties of ―Login1ǁ:
❖ DestinationPageUrl: mainpage.aspx
Add the ―mainpage.aspxǁ and design it as shown:
Add the ―AboutUs.aspxǁ and design it as shown:
Add ―ContactUs.aspxǁ page and design it as shown:

Open web.config file and write the <authentication> as follows:

Now, try to run the mainpage.aspx, contactus.aspx or aboutus.aspx pages directly


without login. Those can‘t be executed. It automatically reverts to ―Default.aspxǁ page.
After you login properly, you can open any page.
Role based Security:

To understand this, do the following steps:


Open the solution explorer.
Right click on the web site name and click on ―New Folderǁ. Enter its name as ―adminǁ.
Right click on the web site name again, and click on ―New Folderǁ. Enter its name as
―guestǁ.
Right click on ―adminǁ folder and click on ―Add New Itemǁ. Select ―Web Formǁ. Enter
the file name as ―adminwelcome.aspxǁ. Click on ―Addǁ. Then the page will be
added in
―adminǁ folder.
Design the ―adminwelcome.aspxǁ page as follows:

Right click on ―guestǁ folder and click on ―Add New Itemǁ. Select ―Web Formǁ. Enter
the file name as ―guestwelcome.aspxǁ. Click on ―Addǁ. Then the page will be
added in
―guestǁ folder.
Design the ―guestwelcome.aspxǁ page as follows:
Make sure that few users are registered or not. If not, run the web site and register few
users. Ex: satya, syam, sridhar.
Open the solution explorer. Select the web site name. Click on ―ASP.NET Configurationǁ
option.
Click on ―Securityǁ.
It shows the no. of ―Existing Usersǁ as ―3ǁ.
You can click on ―Create Userǁ option to register a new user. To modify the details of
existing users, you can click on ―Manage Usersǁ.
Now, click on ―Select authentication typeǁ.
Select ―From the internetǁ option.
Click on ―Doneǁ.
Click on ―Enable Rolesǁ. Then user roles will be enabled.
Now, you have to create two roles. (admin and guest).
To do so, click on ―Create or Manage Rolesǁ.
Enter the role name as ―adminǁ and click on ―Add Roleǁ.
Enter one more role name as ―guestǁ and click on ―Add Roleǁ.
Click on ―Manageǁ option, which is at right side of ―adminǁ role.
Now, you have to select the users, under the ―adminǁ role. For example, let us imagine
as ―satyaǁ is the administrator.
So click on ―Allǁ.
It shows all the available user names.
Then check the checkbox for ―satyaǁ user only. It will be saved immediately.
Click on ―Backǁ.
Click on ―Manageǁ option, which is at right side of ―guestǁ role.
Now, you have to select the users, under the ―guestǁ role. For example, let us imagine as
―syamǁ and ―sridharǁ are the guests.
So click on ―Allǁ.
It shows all the available user names.
Then check the checkbox for ―syamǁ and ―sridharǁ users only. It will be saved
immediately.
Click on ―Backǁ. All the roles are created and the necessary users are mapped with the
user roles.
Now, you have to continue with mapping our web site folder structure, with the user
roles. That means you have to specify which folders are accessible for which user roles.
To do so, come back to ―Securityǁ option.
Click on ―Create Access Rulesǁ option. Click on ―SecurityDemoǁ (web site name). Select
―All Usersǁ – Select ―Allowǁ. Click on OK.
Click on ―Create Access Rulesǁ option again. Click on ―adminǁ folder in the tree
structure. Select ―adminǁ role – Select ―Allowǁ. Click on OK.
Click on ―Create Access Rulesǁ option again. Click on ―adminǁ folder in the tree
structure. Select ―guestǁ role – Select ―Denyǁ. Click on OK.
Click on ―Create Access Rulesǁ option again. Click on ―guestǁ folder in the tree
structure. Select ―adminǁ role – Select ―Denyǁ. Click on OK.
Click on ―Create Access Rulesǁ option again. Click on ―guestǁ folder in the tree
structure. Select ―guestǁ role – Select ―Allowǁ. Click on OK.

Now, all the access rules are created.


Finally admin role users can access admin pages only and guest role users can access
guest pages only.
Close the browser and come back to Visual Studio.
Right click on ―adminwelcome.aspxǁ and click on ―View in Browserǁ. It shows
the Default.aspx page. Login as ―satyaǁ. After login, adminwelcome.aspx page will
be displayed. Here ―adminwelcome.aspxǁ page is allowed, because ―satyaǁ is in
―adminǁ role.
Close the browser.
Right click on ―adminwelcome.aspxǁ and click on ―View in Browserǁ. It shows
the Default.aspx page. Login as ―syamǁ or ―sridharǁ. After login, adminwelcome.aspx
page will not be displayed. Here ―adminwelcome.aspxǁ page is not allowed, because
―syamǁ and ―sridharǁ are in ―guestǁ role.
In the same way, test the ―guestwelcome.aspxǁ also.
This is the implementation of Role based security.
Localization and Globalization
Localization: Displaying a page contents in the selected regional language.
Globalization: Displaying all pages in the selected regional language.
To specify the required language culture, you require the culture code. The culture code
contains 4 alphabets, separated with hyphen (-).
Ex: hi-IN (Hindi – India)
te-IN (Telugu – India)
en-US (English – US)
etc.
Changing the culture will be automatically effected in number formats, default date and
time formats, week names, calendar control, currency styles etc.

Create a new web site.


Add ―Default.aspxǁ page and design it as shown:
Write the code:

Run the web site. Output:


In the above output screen, you can observe the date & time formats, currency styles,
number forms in English-US Format.
Suppose, you want to display those in Chinese format.
To do so, you close the browser and come back to Visual Studio.
Open the Properties window; select the ―DOCUMENTǁ option.
Specify the following property:
Culture: zh-SG Chinese (Simplified, Singapore)
Run the web site. Output:
Now, you can observe the date and time formats, currency style, calendar etc., in
Chinese language.
In this way, you can select any culture. All major cultures from all the countries are
displayed in the ―Cultureǁ property of DOCUMENT object.
For example, again change the
culture as: Culture: te-IN Telugu
(India)
Run the web site. Output:
Now, you can observe the output in telugu language, by following the Indian date & time
formats and currency formats.
This concept is called as ―Localizationǁ.

Allowing the user to change the culture at run time:

The user also can change the culture straightaway from the browser, using ―Toolsǁ –
―Internet Optionsǁ – ―Languagesǁ option at run time.
But being a programmer, you have to allow it. Then only the contents will be displayed in
user-selected language.
To do so, first, take one more web page called ―UserSelectedCulture.aspxǁ and design it
just like ―Default.aspxǁ.
Write the code, same as ―Default.aspxǁ page.

Set the following property of


DOCUMENT object: Culture: auto:hi-IN
Hi = Hindi
IN = India
Note: The word ―autoǁ allows ASP.NET, to display the contents in user-selected culture.
Run the web site. By default it displays the contents in Hindi language as usual.
Click on ―Toolsǁ menu – ―Internet Optionsǁ – ―Languagesǁ – ―Addǁ.
Select the required language. Ex: ta-IN
ta = Tamil
IN = India
Click on OK.
Move the culture to up; because top culture only be considered in the list.
Click on OK.
Click on OK.
Click on ―Refreshǁ.
Then the contents will be displayed in Tamil language.
This also comes under ―Localizationǁ.

Globalization:
Globalization means, displaying all the pages in a common culture.
So that instead of specifying the culture in each web page individually, you specify the
culture in web.config file, so that it will be applied for all the pages commonly.
To do so, open the web.config file and type the following tag:

fr = French and CA = Canada


Note: Don‘t specify any culture in the web page.
Run the web site. Then the output will be displayed in specified culture.
This is nothing but globalization.
Sending E-Mails using SMTP Protocol
SMTP stands for Simple Mail Transfer Protocol.
Using SMTP protocol, you can send E-Mails to any mail domain like yahoo, gmail, hotmal
etc.
In the modern world, being a developer, usually you may require to send automatic E-
Mails through your application. There, you require to use this SMTP protocol.
SMTP depends on a web server called IIS. In other words SMTP is used to send the E-
mails, by taking the support of IIS server.
Library: System.Net.Mail.SmtpClient
This class object act as a client for SMTP protocol, which can send a request to SMTP
server, to send an E-mail.

Implementation Code:

Import the namespace:


using System.Net.Mail;
Create an object for “SmtpClient” class:
SmtpClient sc = new SmtpClient(―server nameǁ);
Bond the SmtpClient class object and IIS:
sc.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
Send the E-mail directly:
sc.Send(―from_addressǁ, ―to_addressǁ, ―subjectǁ, ―message bodyǁ);

Create a new web site.


Add ―Default.aspxǁ page and design it as shown:
Write the code:

Run the web site and test it:


Check the mail: Open the following directory:
C:\Inetpub\mailroot\Drop
Double click on the E-mail file.
Important Note: Here, we are using the local domain called peerstech.com for
demonstration. (peerstech.com domain has been created in the previous chapters. For
more information, read the chapter called ―Configuring E-Mail Serverǁ). Remember that,
the same code works for real internet e-mail addresses also. Suppose, if you send the e-
mail to your friend‘s gmail id, your friend has to open the gmail web site and has to
check it in the inbox. So, the same example code works for all the mail addresses on
Internet. No issues in that. But, if you are giving an E-mail ID, which really exist on
Internet, you require the Internet connection with your system, for sure.
The previous example is a simple demo, to send the e-mails. Sometimes, you require
sending the e-mails with attachments also. At that time, you require knowledge on
―MailMessageǁ class.

Understanding MailMessage Class:


MailMessage(―fromǁ, ―toǁ, ―subjectǁ, ―message bodyǁ)
It‘s a constructor, that initializes the ―fromǁ, ―toǁ, ―subjectǁ and ―message bodyǁ
values.
Attachments
It‘s a collection of attachment files.
Attachments.Add(attachment_object)
It adds the given attachment to the collection of Attachments.

Demo on E-Mails with Attachments:

Open the previous demo web site.


Add the ―EMailsWithAttachmentsDemo.aspxǁ page and design it as shown:

Write the code:


Run the web site:
Test the e-mail:
ASP.NET Web Services
The ―Web Servicesǁ is one of the most attractive and famous feature of ASP.NET.
At a glance, you can share some code among multiple web applications using the web
services.
In fact, you can develop two types of web applications using ASP.NET
1) ASP.NET Web Sites
2) ASP.NET Web Services
If you have a comparison between web sites and web services, features wise /
implementation wise both of these are differ from each other.
To understand better, let us imagine a situation on real-time development.

Example:
Let us imagine there is a software company called ―Aǁ.
It is developing a web site called ―Online shoppingǁ.
In this online shopping web site, the list of available products will be presented to the
customer.
After that, if the customer clicks on a product, then it displays the additional details
about that product like product manufacturing date, expiry date, price etc.
Finally, if the customer wants to buy the product, he/she has to enter the credit card
number for payment.
Then the credit card number is to be validated.
At the time of this validation, being a programmer, you have to check whether the
entered credit card number is correct or not and it is actually issued by the bank or not
and also you have to check for the available balance in the related bank account.
But here is the problem. The entire information about the bank customers and credit
cards related information is only available at bank database only. The bank can‘t give its
database to outsiders for security reasons.
But you are working in a software company, so that you can‘t connect to the bank
database directly, because the bank‘s database server is not available in your software
company.
In this case, web services are used to solve the problem; and indirectly the web service
allows you to get connected with the bank database and also to perform necessary
validations.

Purpose of Web Services:


To share some code among multiple web projects.
To get connect with external database servers.
To get external information, this is not available in our software company. (For example,
―way2sms.comǁ is accessing the information of yahoo and gmail users their and mails).
To publish the business logic in a server, and share it from multiple web applications. In
other words, ―Web Servicesǁ are the Distributed Technology for web applications. (For
more information about Distributed Technologies, refer ―Application Logicǁ concept
in C#.NET).

Important Tips related to Web Services:


A web service doesn‘t contain any user interface. In other words, it doesn‘t contain any
web pages.
It contains only the re-usable code (similar to ClassLibrary Project).
Web Services run based on SOAP (Simple Object Access Protocol).
After compiling your web service, visual studio gives an URL for your web service. With
that URL, any other programmer can link the web service from his/her web site through
online.
The methods written in the web service are called as ―Web Methodsǁ.
Those web methods directly can be called from any other web sites.
While executing the web methods online, necessary arguments can be passed from the
web site. After executing the web method, the return value will be passed to the web
site.
As above, the arguments and return values can be transferred through web in XML
format.
Web Method:
A web method is a method, which can be called from any other web site.
It can be executed directly on the web.
It can receive arguments.
It should return any value.
It should be defined as ―publicǁ method only.
Development of ASP.NET Web Services
Creating a new ASP.NET Web Service:
Click on ―Fileǁ – ―Newǁ – ―Web Siteǁ.
Select the template as ―ASP.NET Web Serviceǁ.
Select the
Location as
―File Systemǁ.
Select the
Language as
―Visual C#ǁ.
Enter the
path and
name of the
web service,
where it is to
be saved.
Ex: SimpleWebServiceDemo
Click on OK.
Then the specified web service will be created.

Understanding the Web Service Directory Structure:


It creates a class called ―Serviceǁ in ―App_Codeǁ folder.
The ―Serviceǁ class contains the actual web methods on the web service.
It contains ―HelloWorldǁ method for sample. Of course, you can remove that method.
To run the web methods for testing purpose, the ―Service.asmxǁ page
provides a dummy web page. Note: ASMX = Active Server Methods Extended.

Syntax of Web Method:


[WebMethod]
public returntype methodname(arguments)
{
//some code
return(value);
}
Note: The line [WebMethod] provides the information to the compiler, that the next coming
method is a web method, that should be invoked through SOAP protocol.
Just for a trail, write the following method in the ―Serviceǁ class.

Testing the Web Methods:


For a test execution, simply run the web service by pressing ―F5ǁ.
On the browser, you can see a page which looks like this:

Click on the web method name, which you want to execute. Ex:
GetRandomNumber.
Then enter the values for the arguments (for min and max).
Then click on ―Invokeǁ button.
Then a request to
the web service will
be passed and the
web method will be
executed.
Finally, you can get
the returned value in
xml format.

Having the URL of Web Services:


When you run the web service, you can see the URL on the browser‘s address
bar. Ex:
http://localhost:1360/SimpleWebServiceDemo/Service.asmx

Invoking the ASP.NET Web Services from a Web Site


Already you know that ASP.NET web services are mainly meant for re-usability.
Those can be accessed / invoked from a web site.
You can observe the steps for invoking a web service as follows:

Create a new ASP.NET Web Site:


Click on ―Fileǁ – ―Newǁ – ―Web Siteǁ.
Select ―ASP.NET Web Siteǁ.
Enter the name and location of the new web site.
Ex: SimpleWebServiceInvokeDemo
Click on OK.

Link the Web Service, with your Web Site:


Click on ―Web Siteǁ menu – ―Add Web Referenceǁ.
Then enter the URL of your web service.
Ex: http://localhost:1360/SimpleWebServiceDemo/Service.asmx
Click on ―GOǁ.
Then it displays
the
―service.asmxǁ
page.
After that, you
have to enter the
web reference
name. Ex: MyRef
A web reference
acts as
representation for
web service.
Finally click on ―Add Referenceǁ.
Then the web service will be linked with your web site; and the necessary files will be
copied into the web site folder.

Call the Web Methods:


Design the ―Default.aspxǁ page as shown:
Write the code:

Run the web site and test it.


AJAX
(Asynchronous JavaScript and XML)

AJAX is one of the new features introduced in ASP.NET 3.0.


AJAX is the new Web Development Technology offered by ASP.NET.
It is the most powerful feature of ASP.NET, which dramatically reduces stress on web
servers.
In the year of 2007, Microsoft Corporation introduces ATLAS, which is renamed as AJAX in
late 2007.
AJAX is a client technique, which internally uses two languages like JavaScript and XML.
Already you know that JavaScript is the client side language, which can be executed by
browser. XML is a data descriptive language, which describes the data values in a
structured manner.
In the same way, already you know that web sites development models are 3 types totally.
1. Traditional Web Sites
2. Post-Backing Web Sites
3. AJAX Web Sites
The limitations of Traditional web sites are overcome with Post-backing web sites.
The main limitation of post-backing web sites is: the web page will be post-backed for
every user action like clicking the buttons, selecting a date in the calendar, clicking on a
node in the TreeView, selecting an item in the list box etc.
In post-backing, the entire page will be refreshed / re-loaded.
So that, web server has to give response for every post-back. This leads to heavy stress on
the web server. Dramatically, this makes the web site executing very slowly.
This problem can be solved with the introduction of AJAX. With the support of AJAX
technology,
Web Page Execution in AJAX Technology:
On clicking on the ―Submitǁ button, a request will be sent to the server. But that request
is not the traditional request. With the traditional request, you were submitting the
complete page. So now, instead of submitting the complete page to the web server, part of
the page will be submitted.
Then execution flow will be reached to the web server. There, the server side code will be
executed. (For ex: button1_Click code).
As usual, it comes back with some response. The response will be updated on the UI.
So, the main differences between post-backing web sites and AJAX web sites is:
▪ In post-backing web sites, entire page will be closed and re-loaded. But in AJAX
web sites, the will not be closed or re-loaded. The page will be as it is only. But
some part of the web page will be submitted to the server and it gets re-loaded.
This is called as ―Asynchronous Server Callǁ.
▪ If the full page is getting submitted and re-loaded it can be called as ―Post-backǁ.
If partial page is getting submitted and re-loaded, then it can be called as ―Call
backǁ. So in AJAX web sites, callback will be there, instead of post-back.

Previously, in post-backing web sites, the ―HttpRequestǁ will be sent and ―HttpResponseǁ
will be received. Here in AJAX, ―XmlHttpRequestǁ will be sent and ―XmlHttpResponseǁ will
be received. In other words, the client side values would be passed to the web server in
XML format, in AJAX technology. In this way, you require ―XMLǁ usage in AJAX.
To send and receive the ―XmlHttpRequestǁ and ―XmlHttpResponseǁ, you require to write
some code in a language. That language is ―JavaScriptǁ. In this way, you require
―JavaScriptǁ usage in AJAX.
The ASP.NET AJAX

To develop ASP.NET web sites with AJAX technology, you are supposed to work with two
types of controls.
A. AJAX Extension Controls
B. AJAX Toolkit Controls

A. AJAX Extension Controls:


These are in-built controls in ASP.NET. These controls are available in the toolbox under
―AJAX Extensionsǁ tab.
1. ScriptManager
2. UpdatePanel
3. UpdateProgress
4. Timer

B. AJAX Toolkit Controls:


These can be added into the toolbox explicitly by downloading ―AjaxControlToolkit.dllǁ
file from the Microsoft ASP.NET‘s official web site, and adding the reference of that DLL
file to your web site.
URL: http://www.asp.net/ajax
Implementation of AJAX Extensions
I. ScriptManager:

This control should be placed, at the top of all the AJAX extensions / toolkit controls,
after <form> tag.

This enables the AJAX technology in your web page.

When you drag the control, you can see the following tag in the ―Sourceǁ view.

<asp:ScriptManager ID="ScriptManager1" runat="server">


</asp:ScriptManager>

II. UpdatePanel:

This control contains the content, which is to be updated in AJAX model, on the post
back.

When you drag the control, you can see the following tag in the ―Sourceǁ view.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

The <ContentTemplate> tag contains the actual content. In this tag, you drag and
drop the controls, that you want.

If any control in the UpdatePanel requires post back, the entire page would not be
re-loaded. Just the required content would be updated with the support of call-back.

So, this feature improves the execution speed of the page.

Create a new web site.


Add ―ajaxdemo1.aspxǁ page and design it as follows:
Write the code:

Run the web site and test it. It works perfectly. The problem here is, when you click
on ―Addǁ button especially, you can observe a small blink in you page
contents. That‘s because of post-back. The entire page will be re-loaded. In fact, it is
enough to submit the ―aǁ and ―bǁ values here and get the result in the third
textbox. So that, you can implement AJAX here.

To do so, open toolbox; drag and drop the ―ScriptManagerǁ control into the page
at the top (as shown on the screen).
Drag and drop the UpdatePanel control. It‘s like a normal panel control. You drag
and drop the necessary labels and textboxes, into the UpdatePanel (as shown the
screen).

That‘s it. Run the web site and test it directly on the browser. Now also, the output
will be displayed correctly, when you click on ―Addǁ button. But the thing is, the
page will not be posted-back; instead, ―call-backǁ will be performed.

Let‘s take one demo on AJAX.


Add the ―ajaxdemo2.aspxǁ page and design it as shown:
Write the code:

Run the web site and test it. Now, when you click on the first button the time will be
refreshed, without a post-back; because the button is inside of
―UpdatePanelǁ control. When you click on the second button, post-back will be
performed as usual, because it is not inside of ―UpdatePanelǁ control.
III. UpdateProgress:

This control is helpful, if it is taking much time to execute large amount of code,
while a call-back is being performed in an UpdatePanel.

This control contains the content, which is to be displayed while the page is getting
call back.

This improves the user-friendly nature.

This is useful, when you have large amount of code in the UpdatePanel.

By default, it contains some link with the UpdatePanel control.

When you drag the control, you can see the following tag in the ―Sourceǁ view.
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>

</ProgressTemplate>
</asp:UpdateProgress>

Demo on UpdateProgress:

Open the previous demo web site.


Add ―ajaxdemo3.aspxǁ page and design it as shown:
Write the code:

Run the web site and test it. Now, it takes 3 seconds, to refresh the time.

In these 3 seconds of duration, no indication is given to the user. So, at this time,
the user may be in dynamo, whether the site is working properly or not.

To solve this problem, drag and drop the ―UpdateProgressǁ control into the
same page and design it as shown:
Now, run the web site and test it. When you click on ―Refreshǁ button now,
the
―loading…ǁ message and the hour glass image will be displayed for that 3 seconds of
duration.

IV. Timer:

This control is same as ―Timerǁ control in Windows Applications.

It executes certain process repetitively at every completion of certain interval time.

When you drag the control, you can see the following tag in the ―Sourceǁ view.
<asp:Timer ID="Timer1" runat="server">
</asp:Timer>
Demo on Timer:

Open the previous demo web site.


Add ―ajaxdemo4.aspxǁ page and design it as shown:

Set the Timer1


Properties: Enabled:
true Interval: 1000

Write the code:

Run the web site.

You might also like