Professional Documents
Culture Documents
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
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>
2. Unpaired tags: These tags contain only single tag. No starting / ending
tag.
<tag>
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.
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.
<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>
<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>
<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>
<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>
<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>
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>
<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.
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.
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.
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ǁ.
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.
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
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
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
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:
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”.
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ǁ.
1) Request:
3) Session:
4) Application:
Ex:
Event Description
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.
v. Login Controls:
It includes with some controls, which implement login / logout related concepts,
without writing any code.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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>";
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
✵ 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.
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:
✵ 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.
Click on ―Saveǁ button to save the table. Then it asks for the table name. Enter
the desired table name.
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;
select * from Products where price not between 2000 and 8000
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)
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.
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
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.
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
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.
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.
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.
✵ 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:
✵ 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
//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();
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.
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.
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:
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.
✵ 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:
✵ 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
//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:
✵ 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.
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.
Demo:
✵ 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
💧 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.
✵ 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.
✵ 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, 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
✵ 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.
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
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.
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
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
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.
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)
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.
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)
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)
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.
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.
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.
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.
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:
Demo:
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:
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ǁ]
Demo:
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.
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 ―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).
1) Inline Styles:
Ex:
<asp:TextBox ID="TextBox4" runat="server" Style="font-family:Broadway;
border-color:Red; text-align:right;" Text="hello"></asp:TextBox>
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 ―Addǁ.
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ǁ.
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>
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ǁ.
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 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ǁ.
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.
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:
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.
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" %>
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.
To do this, type the following tag in the ―Sourceǁ view, after ―<%@ Page>ǁ tag.
<%@ Register Src="UserControlFileName" TagPrefix="xxxx" TagName="xxxx" %>
To invoke the control in the page, use the following tag, whereever required.
<Tagprefix:TagName />
Demo:
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).
Enter the name of the master page and click on ―Addǁ. Ex: MasterPage.master
The ―ContentPlaceHolderǁ tag represents the content in the other web pages.
In the master page, it should be empty.
Select ―Web Formǁ. Enter the name of the new web 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:
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:
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
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.
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.
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:
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:
Demo:
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:
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:
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.
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
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
linqtoobjectsdemo.aspx.cs
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>");
goes to
Demo on LINQ with Lambda Expressions:
linqwithlambda.cs
Response.Write("<font face=Tahoma>");
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);
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);
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);
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:
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.
✰ 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:
✰ 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:
✰ 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:
✰ 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.
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.
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ǁ.
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
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.
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.
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:
Implementation Code:
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.
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.
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
This control should be placed, at the top of all the AJAX extensions / toolkit controls,
after <form> tag.
When you drag the control, you can see the following tag in the ―Sourceǁ view.
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.
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.
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 is useful, when you have large amount of code in the UpdatePanel.
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:
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:
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: