Material
Material
HARSHA VARDHAN
And
ASP.NET
Hour 6 ASP.NET Introduction and Advantages, Getting started with ASP.NET Page 46
Hour 7 Inpage Technique and Code behind Technique, Page Definition Syntax Page 62
Hour 8 Implicit Objects , Page Execution Life Cycle, Page Events Page 64
Hour 9 Client controls (vs) Server Controls; HTML Server Controls, Post Backing Page 70
Hour 10 Standard Controls Page 76
Hour 11 Tables Designing, Absolute Positioning Page 93
Hour 12 Wizard and AdRotator Controls Page 100
A typical web
Web Server
Web Site
Web Client 1
Browser
Request
Response
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.
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
HTML
(Hyper Text Markup Language)
It‘s a designing language; it‘s not a programming language. That means it doesn‘t
contains any programming concepts such as data types, variables, operators, control
statements, arrays etc. It contains some design concepts only.
Its syntax is written in the form of tags. The tag name is to be written within the < and
> symbols.
Def of Tag: A keyword, which is written inside of < and > symbols is called as ―Tag‖.
The tags are two types in html.
1. Paired tags: These tags contain starting tag and ending tag.
<tag>
some content
</tag>
2. Unpaired tags: These tags contain only single tag. No starting / ending
tag.
<tag>
You can observe the title bar text as you mentioned in the <title> tag.
You can observe the web page content, as you written in <body> tag.
<html>
<head>
<title>any title</title>
</head>
<body>
some content
</body>
</html>
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.
Demo.html
<html>
<head>
<title>Demo on HTML tags</title>
</head>
<body bgcolor="lightyellow">
<a name="top">
<h1 align="center">
HTML Demo Page</h1>
<h2 align="center">
(Hypertext Markup Language)
</h2>
<hr>
<p align="justify">
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. </p>
<hr>
<p align="justify">
<font size="4" face="Century Gothic">
<font color="green">
.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
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>
<div align="right">
This is normal text.<br>
<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>
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">
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:
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.
<html>
<head>
<title>any title</title>
<script language=”javascript”>
//some js code
</script>
</head>
<body>
some content
</body>
</html>
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.
registration.html
<html>
<head>
<title>Forms demo</title>
</head>
<body>
<form>
<center>
<h1>ABC Technical Training Institute</h1>
<h2>Hyderabad</h2>
<h2>Student Registration Form</h2>
<hr>
Student Name:
<input type="text"><br>
Age:
<input type="text" size="3"><br>
Password:
<input type="password"><br>
Confirm Password:
<input type="password"><br>
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‖.
//implement some
server side operations
<html>
<head>
<title>Login</title>
</head>
<body bgcolor="beige">
<center>
<form name="f1" action="http://localhost/loginserver.asp"
method="post">
<h1>Login</h1><hr>
Username:
<input type="text" name="txt1"><br>
Password:
<input type="password" name="txt2"><br>
<hr>
<input type="submit">
<input type="reset">
</form>
</center>
</body>
</html>
C:\Inetpub\wwwroot\loginserver.asp
(save this file in the specified folder only, otherwise it won‘t run)
<html>
<head>
<title>Login Server</title>
</head>
<body>
<center>
<h1>
<%
'Get the values from the client page
Dim s1,s2
s1 = Request.Form("txt1")
s2 = Request.Form("txt2")
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.
In the client page, you have to design a html form compulsory. In that <form> tag, you
have to give the address of the server page, to which it is to be submitted.
Syn: http:/servername/pagename.asp
When you click on ―Submit‖ button, the server page will be opened, based on the given
URL.
At the time of submission, the parameter values (username and password) will be sent to
the server page.
In the server page (loginserver.asp) code, the ―Dim‖ statement (Dim stands for
Dimension) declares two variables for storing user name and password.
After that we retrieve the values from the client page using the control‘s names (txt1 and
txt2).
Then we check the values whether those are correct or not, using If statement.
Then we give the response message to the client using ―Response.Write()‖ statement.
Note: To run this example in fact, you require a software named IIS compulsory. We
discuss more about IIS in further sessions.
Note: This much knowledge on ASP 3.0 is enough, before entering into ASP.NET.
Web Servers
Suppose, you are trying store a web site in the web server system, and accessing it from
another client system on the network.
Then you require a software in the server computer, which serves the web site to the
clients.
If that software is not loaded in the server computer, your web site can‘t be served to
the clients. If the client sends a request, no one will be there to receive the request and
give the response.
So that you require a software called ―Web Server Software‖.
Remember that, it should be loaded in the server system only; not required in the client
systems.
Responsibilities of web server software‘s:
1. Store the web sites in a special folder, which are ready to be served to
the clients.
2. Serve the web site files (web pages) to the clients, based on the given
URL.
3. Handle the ―Request‖ and ―Response‖ operations.
4. Execute the server side scripts, which code is written in <% and %>
tags.
5. Handle the security related features, if we require any.
For our Microsoft Technologies like ASP and ASP.NET, we have a web server software
named ―IIS‖ (Internet Information Services) / (Internet Information Server).
In the previous ASP 3.0 example, already we have used IIS; (by storing the
loginserver.asp page in the ―wwwroot‖ folder).
Every web server uses a port, to have a communication with the clients.
Web Server
IIS
Web Site
port
Finally, ASP is supported in IIS only; and ASP.NET is supported in IIS and ASP.NET
Development Server also.
Installing IIS:
Insert bootable Windows CD / DVD.
Click ―Start‖ – ―Control Panel‖.
Open ―Add / Remove Programs‖.
Click on ―Add / Remove Windows Components‖.
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.
Then you try to start the services, by right clicking on the ―Default Web Site‖ option, and
by clicking on ―Start‖.
If you want to stop the services, you can do so, by right clicking on the ―Default Web
Site‖ option, and by clicking on ―Stop‖.
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.
Drag and drop the ―loginclient.html‖ page and ―loginserver.asp‖ pages into ―test‖ folder.
Then the physical path will be like this:
C:\Inetpub\wwwroot\test\loginclient.html
C:\Inetpub\wwwroot\test\loginserver.asp
And then the logical address will be like this:
http://localhost/test/loginclient.html
http://localhost/test/loginserver.asp
Now, the ―test‖ directory is called as ―Virtual Directory‖.
Virtual Directory: A sub folder, which is created in ―wwwroot‖ folder, is called as
―Virtual Directory‖.
ASP.NET
(The Modern Generation Web Technology)
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
The user first opens the client page. Whenever the user clicks on the ―Submit‖
button, automatically the server page will be opened. In other words, a Request
will be sent to the server page.
The server page is responsible to receive the data values from the client page,
and perform some server side logics.
Finally, it gives Response to the client.
So that ―Traditional web sites‖ can also be called as “Request – Response
Web Sites”.
//implement some
server side operations
In fact, post-backing is the in-built feature of ASP.NET, you need no write any
code for that.
In ASP.NET, almost 99.9%, we won‘t implement ―Traditional web sites‖. We
implement these ―Post-backing web sites‖ only.
Form
Submit
Postback
Advantages of ASP.NET
Automatic Generation of Designer Code: While you are designing the web pages in
ASP.NET, it generates the necessary tags automatically. So don‘t require to type tags
manually.
Post-backing: This feature reduces no. of web pages in your web site. Because of this
feature, you can write the application logic just like the windows applications. That
means you can implement the necessary events at server side.
Master Pages: To avoid the repetition of designing the common content among
multiple pages.
Data Controls: To display the database data better with / without the writing the code
manually.
Validation Controls: Avoids the usage of ―JavaScript‖ for implementing the validations.
Login Controls: To implement the common login / logout features, without writing any
code.
Crystal Reports: There is no other server side programming language, which supports
―Crystal reports‖ in the web sites.
Themes and Skins: To have uniformity in the controls, designed in all the web pages;
and finally to make the web page as a good looking page.
Support of Multiple Cultures: You can display the contents of the web pages, in
different regional languages like English / French / Arabic / Telugu / Tamil etc.
Security: It supports several security models like Windows based security, Forms based
security, Passport based security, Role based security etc.
Caching: To store the output of the page temporarily in the cache memory, and make
the web site to be executed faster.
Multiple Languages: You can write the functionality related code in any of the .NET
languages (Visual C#.NET or Visual Basic.NET), that you want.
WebParts: To personalize the web site, for every user. The user can modify the page
contents right from the browser.
AJAX: To make the web site executed faster, and to attract the user with better
functionality.
Web Services: To implement some interaction between one web site to another web
site.
3. FTP: If you select this option, you can give the FTP URL only. Ex:
ftp://myserver/WebSite1. In this case also, your web site can run under
IIS only. The only thing is, instead of storing the web site in your local
hard disk, it will be stored in the FTP Server.
After entering all the details, click on OK.
Then the new web site will be created.
Then the screen looks like this:
The next thing is you have to add the web pages to your web site.
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.
2. Design View: To open this, Click on ―Design‖ option at the bottom side in your
Visual Studio. It displays a preview of the web page. It is comfortable and easy
to modify the content also. If you make any changes in the design view, it will be
affected in source view automatically. The necessary tags will be generated
automatically.
3. Split View: It shows the design view and source view at-a-time; so that you can
observe modify the content easier.
Without the writing the tags manually, you can design the web page by dragging and
dropping the controls from Toolbox into the page also.
To practice this, try to do as follows.
Right click on ―Solution Explorer‖ – ―Add New Item‖ – ―Web Form‖ – ―mypage.aspx‖ -
―Add‖.
Open Toolbox.
Drag and drop 3 labels, 3 textboxes and a button into the page as follows:
To run the page, right click on ―mypage.aspx‖ in the Solution Explorer; and choose ―View
in Browser‖.
While you have designed the page by dragging the dropping the controls, in the
―mypage.aspx‖ file, some tags were generated automatically.
To view that, open the page in ―Source‖ view.
So finally, the conclusion is, for every ASP.NET Web Form, there will be two files.
1. pagename.aspx
Contains the designer code in the form of tags
2. pagename.aspx.cs
Contains the programmer code in ―C#.NET‖ syntaxes.
So, we are maintaining two inter-linked for every page, as above (one is for
designing purpose and other one is for programming purpose). This type of maintenance is called
as “Code behind Technique”. This model is the comfortable and recommend model to avoid
clumsiness of the code; because if you write the design code and programming code within a
single file, it may not be understandable clearly and the code will be lengthy. In the earlier
versions of ASP.NET, they have introduced another technique called “In-page technique”.
According that ―In-page technique‖, we maintain the designer code and programmer
code within a single file (.aspx file). This is not recommend. Anyway, we can implement that
technique also now, just for having an idea.
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.
For ASP.NET web page, the following objects are commonly available. That means, you
don‘t require creating these objects.
1) Request:
2) Response:
3) Session:
4) Application:
Whenever the client sends a request (opens the web page), the following life cycle will
be executed at server side.
Client Server
filename.aspx
(class)
Browser
Create an object
Initialize
Render
Unload
Ex:
Event Description
Default.aspx.cs
ASP.NET Controls
Let us recollect how we were using the Toolbox.
In the toolbox, it contains a list of controls.
From those list of controls, you can drag and drop any control (Button, TextBox,
CheckBox etc.), into the page. Then the control will be created in the page.
In the toolbox, the controls are displayed in various categories:
1. Standard Controls
2. Data Controls
3. Validation Controls
4. Navigation Controls
5. Login Controls
6. WebParts Controls
7. AJAX Extensions Controls
8. Reporting Controls
9. HTML Controls
In the above categories, except ―HTML Controls‖, all other type of controls are the
ASP.NET controls. Obviously the controls under ―HTML‖ category are the HTML controls.
Already we know that ASP.NET is a server side programming language. All the ASP.NET
concepts are nothing but server side concepts. So that, all the ASP.NET controls are
known as ―Server Controls‖. These controls will be executed at server side only. For
example, you write the code for ―Button_Click‖ event. That code will be executed at
server side only. So that ―Button‖ is the server control.
All HTML controls are the ―Client Controls‖. These controls will be executed at client
side. For example, you drag and drop ―Button‖ control from ―HTML‖ category into the
page. If you write code for ―button1_Click‖ event, the code will be executed at client side
only. One more thing that you have to observe is, you can write the code for ―HTML
button‖ in JavaScript language only. So in that if you are using a HTML button, you can‘t
implement any ASP.NET server side concepts in that.
So, in 99.9% of cases, we prefer server side controls only, instead of client controls.
One more thing is, when you drag and drop any server control, an ASP.NET tag will be
generated in the ―Source‖ view.
<asp:ControlName>
For example, you drag a button control from ―Standard‖ category. It generates the
following tag.
<asp:Button ID="Button1" runat="server" Text="Button" />
The above is not offered by HTML; it‘s offered by ASP.NET; so that it can be called as
―ASP.NET Server side tag‖.
Next, you drag a button control from ―HTML‖ category. It generates the following tag.
<input id="Button1" type="button" value="button" />
The above is offered by HTML; so that it can be called as ―HTML Client side tag‖.
The next thing is, you just double click the server button. It generates the
―button1_click‖ event in the C# syntax. There, you can write the server side code.
protected void Button1_Click(object sender, EventArgs e)
{
After that, you just double click the client button. It generates the ―button2_onclick‖
event in the JavaScript syntax. There, you can write the client side code only using
JavaScript.
<script language="javascript" type="text/javascript">
function Button2_onclick()
{
}
</script>
Note: Drag the ―Server button‖ from ―Standard‖ category; and ―Client button‖ from ―HTML‖
category.
Default.aspx.cs
Default.aspx
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.
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.
v. Login Controls:
It includes with some controls, which implement login / logout related concepts,
without writing any code.
i) Standard Controls
1. Button: Performs an operation, whenever it is clicked.
Properties of Button
Property Description
ID Specifies the name of the control.
Text Specifies the visible text of the control.
BackColor Specifies the background color.
ForeColor Specifies the foreground color.
Font Specifies the font settings like font name, bold, italic, size etc.
BorderWidth Specifies the border size in the form of pixels.
Specifies the style of the border. (None / Dotted / Dashed / Solid /
BorderStyle
Double / Groove / Ridge / Inset / Outset)
BorderColor Specifies the color of the border.
Width Specifies the width (in pixels).
Height Specifies the height (in pixels).
Specifies the tooltip message, which can be displayed whenever
Tooltip
you 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.
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
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
GroupName
for 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.
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
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.
Property Description
SelectedDate Represents currently selected date value in the calendar.
Note: ―AutoFormat‖ option is available for this control. To change the auto format style,
right click on the calendar control and choose ―Auto Format‖ option.
17. Panel: Acts as container for other controls. You can drag any other controls into the
panel.
Properties of Panel
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, HorizontalAlign
Scrollbars None, Horizontal, Vertical, Both, Auto
Events of Panel
No Events
18. BulletedList: Used to display few items with bullets or numbering. It is similar to <OL>
and <UL> tags in HTML.
Properties of BulletedList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Numbered, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman, Disc,
BulletStyle
Circle, Square, CustomImage
To specify the path of the CustomImage, to be displayed as bullet for
BulletImageUrl
every item.
Events of BulletedList
Event Description
Click Executes on clicking the control.
19. FileUpload: Used to implement ―Upload‖ option to the user. It displays a textbox with
―Browse‖ button. The user can click on ―Browse‖ button and choose any file. After that
the selected file path will be displayed in the textbox automatically. Later, in the submit
button code, you have to write necessary code for uploading the file from client system
to server system.
Properties of FileUpload
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Methods of FileUpload
Method Description
The file will be uploaded (copied) from the original location, into
SaveAs(―destination the specified destination location, based on the given destination
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…)
Design Label3:
Label1: Text: Student Name:
Text: ABCD Technologies Font: Arial
BorderColo #CC00CC
r: TextBox1:
BorderStyle Dotted Font: Arial
:
Font: Arial Black, X-Large Label4:
BackColor: #CC0000 Text: Age:
ForeColor: Yellow Font: Arial
Label2: TextBox2
Text: Registration Form :
Font: Century Gothic, Large Font: Arial
ForeColor: #FF3300
.NET 4.0 and Visual Studio 2010 Page 87 of 558
D. HARSHA VARDHAN
Label5: Label10:
Text: Password: Text: Gender:
Font: Arial Font: Arial
TextBox3: RadioButton1:
TextMode: Password Text: Male
Font: Arial GroupName: g1
Font: Arial
Label6:
Text: Confirm Password: RadioButton2:
Font: Arial Text: Female
GroupName: g1
TextBox4: Font: Arial
TextMode: Password
Font: Arial Label11:
Text: Marital Status:
Label7: Font: Arial
Text: Address:
Font: Arial RadioButtonList
1:
TextBox5: Items: Single, Married,
TextMode: Multiline Divorced
Width: 218px RepeatDirection: Horizontal
Height: 85px Font: Arial
Font: Arial
Label12:
Label8: Text: Preferable Timings:
Text: DateOfJoining Font: Arial
Font: Arial
CheckBoxList1:
Calendar1: Items: Morning, Afternoon,
AutoFormat: Colorful2 Evening
CheckBox1: RepeatDirection: Horizontal
Text: Documents Submitted? Font: Arial
Font: Arial Label13:
CheckBox2: Text: Resume Attachment:
Text: Is Already Registered? Font: Arial
AutoPostBack True CheckBox1:
: Text: Documents
Font: Arial Submitted?
Label9: Font: Arial
Text: Existing Registration FileUpload1:
Number: Font: Arial
Visible: False
Font: Arial Label14:
Text: Course Type:
TextBox6: Font: Arial
Visible: False
Font: Arial DropDownList1:
.NET 4.0 and Visual Studio 2010 Page 88 of 558
Items: Normal Track, Fast
Track, Super Fast
Track
D. HARSHA VARDHAN
LinkButton1: Hyperlink5:
Text: Show Duration Details Text: Contact Us
Font: Arial Font: Arial
NavigateUrl: mailto:customercare
Table1: @abcd.com
Rows: Add 4 rows and 2 cells in
each row. Type the text as LinkButton2:
shown. Text: Hide the globe
Font: Arial Font: Arial
Visible: False
Hyperlink6:
Label15: ImageUrl: globe2.jpg
Text: Course: (Copy the image into
Font: Arial the web site folder)
NavigateUrl: globe.jpg
ListBox1: (Copy the image into
Items: .NET 4.0, Java, Share the web site folder)
Point, Oracle, Sql Server,
Silver Light Panel1:
Font: Arial BackColor: #33CCFF
Button1: Label16:
Text: Submit Text: Search:
Font: Arial Font: Arial
Image1: TextBox7:
ImageUrl: earth.gif Font: Arial
(Copy the image into the
web site folder) ImageButton1:
ImageUrl: search_button.gif
Hyperlink1: (Copy the image into
Text: About Us the web site folder)
NavigateUrl: aboutus.aspx
Font: Arial Label17:
Text: (null)
Hyperlink2: Font: Arial
Text: Google Search ForeColor: #400040
NavigateUrl: http://www.google.co.in
Font: Arial Literal1:
Text: <h3><marquee
Hyperlink3: bgcolor="lightpink">A
Text: Click to listen audio ll Rights Reserved.
NavigateUrl: josh.mp3 Copy Right ©
(Copy the audio file into 2010</marquee></h
the web site folder) 3>
Font: Arial
Hyperlink4:
Text: Click to view video
NavigateUrl: SilverJubilee.wmv
(Copy the video file into
.NET 4.0 and Visual Studio
the web site folder)2010 Page 89 of 558
Font: Arial
D. HARSHA VARDHAN
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>";
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
Then it generates a html table and the screen looks like this:
Then drag and drop the required controls directly into the table cells. For
example you design a login page as follows:
Select two cells on the top row, right click and choose ―Modify‖ - ―Merge Cells‖.
Select the top row, and select the alignment as ―Center‖; ―bgcolor‖ property as
any color.
For all the left side cells select the alignment as ―Right‖ and ―Width‖ as ―50%‖.
For all the right side cells, select the alignment as ―Left‖ and ―Width‖ as ―50%‖.
Select the ―bgcolor‖ for both the cells in the bottom row.
Then the screen looks like this:
Now, the alignment is good. This is how to maintain the controls alignment
better, with HTML tables.
Output:
Output:
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.
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‖.
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.
<AlternateText>mitsubishi.com</AlternateText>
<NavigateUrl>http://www.mitsubishi.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad9.gif</ImageUrl>
<AlternateText>abyss.com</AlternateText>
<NavigateUrl>http://www.abyss.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad10.gif</ImageUrl>
<AlternateText>google.com</AlternateText>
<NavigateUrl>http://www.google.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad11.gif</ImageUrl>
<AlternateText>reliance.com</AlternateText>
<NavigateUrl>http://www.reliance.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad12.gif</ImageUrl>
<AlternateText>amazon.com</AlternateText>
<NavigateUrl>http://www.amazon.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad13.gif</ImageUrl>
<AlternateText>uefa.com</AlternateText>
<NavigateUrl>http://www.uefa.com</NavigateUrl>
</Ad>
</Advertisements>
Note: In the above code, the tilde character ―~‖ represents the current working web site
path. For example, your web site is stored in the ―c:\Inetpub\wwwroot‖ folder. Your web
site name is ―WebSite1‖. Then the current directory (c:\Inetpub\wwwroot\WebSite1) can
be represented as ―~‖ character.
The next thing is, you take a new web page and drag and drop the ―AdRotator‖ control.
Select the following property for the ―AdRotator1‖ control.
AdvertisementFile: ~/ads.xml
The design some other controls that you need as follows:
That‘s it. Everything is over and you can run the web site.
At run time, every time you refresh the page or click on the button, it displays various
ads.
Click on Refersh..
Click on Refersh..
In this way, you can have different-different ads using ―AdRotator‖ control.
2. Object Explorer:
In SQL Server Management Studio, the
―Object Explorer‖ displays the
information about the databases, tables,
stored procedures and functions.
First of all, expand the option
―Databases‖; then it displays list of
databases that currently exist on this
system.
If you expand any database (For ex:
sample), it displays some folders like
―Tables‖, ―Views‖, ―Programmability‖
etc.
When you expand the ―Tables‖ folder, it
displays the list of tables that exist the
selected database.
If you want to see the table structure,
right click on that table and choose
―Modify‖ option. There you can make
any changes in the table design
(structure).
If you want to open the table data, right
click on that table and choose ―Open Table‖. Then the table rows will be opened.
Here also you can make changes in the table data, and also you can add new
rows here.
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;
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;
use master
drop database test
GO
use test
GO
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.
Procedure:
GO
execute ShowSquare 5
Function:
GO
select dbo.GetCube(5)
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
Data
DataSet
DataTable
DataRow
DataColumn
SqlClient OleDb
SqlConnection OleDbConnection
SqlCommand OleDbCommand
SqlDataReader OleDbDataReader
SqlDataAdapter OleDbDataAdapter
SqlParameter 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.
Connection
ConnectionStrin
g
Open()
Close()
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.
using System.Data.SqlClient;
using System.Data.OleDb;
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
Connection Command
ConnectionStrin CommandText
g Connection
Open() CommandType
Close() Parameters
ExecuteNonQuery()
ExecuteReader()
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.
Demo:
Open SQL Server 2005.
Create a new database, with name as ―demo‖.
In that database, create a table named ―Customers‖, as shown below.
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as ―Insertion.aspx‖.
Click on ―Add‖.
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as ―Deletion.aspx‖.
Click on ―Add‖.
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as ―Updation.aspx‖.
Click on ―Add‖.
Come back to ―Default.aspx‖ and set the following properties:
Properties of ―HyperLink2‖:
Text: Insertion
NavigateUrl: ~/Insertion.aspx
Properties of ―HyperLink3‖:
Text: Deletion
NavigateUrl: ~/Deletion.aspx
Properties of ―HyperLink4‖:
Text: Updation
NavigateUrl: ~/Updation.aspx
Insertion.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(5,'Arun','Male',8000)";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
Label2.Text = n + " Row Inserted.";
else
Label2.Text = "Insertion failed.";
cn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();
string gen;
if (RadioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(" + TextBox1.Text + ", ' " +
TextBox2.Text + " ' , ' " + gen + " ' , " + TextBox3.Text + ")";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
//presentation logic
if (n > 0)
Label8.Text = n + " Row Inserted.";
else
Label8.Text = "Insertion failed.";
cn.Close();
}
Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:
Deletion.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from customers where customerid=" + TextBox1.Text
+ " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
//presentation logic
if (n > 0)
Label3.Text = n + " Row Deleted.";
else
Label3.Text = "Deletion failed.";
cn.Close();
}
Updation.aspx.cs
using System.Data.SqlClient;
string gen;
if (RadioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update customers set customername= ' " + TextBox2.Text + " '
, gender= ' " + gen + " ' , amount=" + TextBox3.Text + " where customerid=" +
TextBox1.Text + " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
//presentation logic
if (n > 0)
Label6.Text = n + " Row Updated.";
else
Label6.Text = "Updation failed.";
cn.Close();
}
Connection
.NET
Application
Library:
Connection: Maintains the connection with database.
Command: Sends a SQL statement and executes it at backend.
DataReader: Acts as a buffer. It holds the data, which is received from database.
Note: Here, to execute the select statement, you have to use ―ExecuteReader()‖ method of
command class. After execution of the statement, it returns the entire data, i.e. retrieved from
the database, in the form of ―DataReader‖ class object. So that we have to receive it into an
instance of ―DataReader‖ class.
Connection
ConnectionStrin
g
Open()
Close()
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
DataReader
Read()
[“column name”]
[index]
Close()
Ex:
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();
(false)
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.
Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();
Read the next row.
dr.Read();
Get the value at specific column:
dr[column index];
(or)
dr[―column_name‖];
Close the buffer:
dr.Close();
Close the connection:
cn.Close();
Demo:
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
DataReaderDemo.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
Sometimes, you may need to display the records based on the user-entered value. For
example, when the user enters the customer id, then you need to display the respective
customer details. We take a demonstration like that:
Add the hyperlink called ―View Data using Data Reader – Conditional Data‖ as shown
below:
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataReaderDemo_ConditionalData.aspx‖. Click on ―Add‖.
Properties of ―HyperLink7‖:
Text: View Data using Data Reader – Conditional Data
NavigateUrl: ~/DataReaderDemo_ConditionalData.aspx
DataReaderDemo_ConditionalData.aspx.cs
using System.Data.SqlClient;
//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();
}
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.
Connection
DataSet
DataTable
0
1
2
3
.NET DataRow
Application 0 1 2
Connection
ConnectionString
Open()
Close()
DataAdapter
DataAdapter(“select statement”,
connection_object)
Fill(dataset_object)
DataSet
Tables[table_index]
Clear()
DataTable
Rows.Count
Rows[row_index]
Columns.Count
Columns[column_index]
DataRow
[column_index]
[“column name”]
Clear(): Clears all the tables, and makes the dataset empty.
Demo:
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
DataSetDemo.aspx.cs
using System.Data;
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
Sometimes, you may need to display the records one-by-one in flexible manner, depending on
the clicked buttons like ―First‖, ―Previous‖, ―Next‖, ―Last‖. We take a demonstration like that:
Add the hyperlink called ―View Data using Data Set – Flexible Records Presentation‖ as
shown below:
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the page name as
―DataSetDemo_FlexibleRecords.aspx‖. Click on ―Add‖.
Properties of ―HyperLink8‖:
Text: View Data using Data Set – Flexible Records Presentation
NavigateUrl: ~/DataSetDemo_FlexibleRecords.aspx
DataSetDemo_FlexibleRecords.aspx.cs
using System.Data;
using System.Data.SqlClient;
//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--;
if (RowIndex < 0)
{
RowIndex++;
Label6.Text = "Already at first record.";
}
Display();
}
protected void Button3_Click(object sender, EventArgs e)
{
//display previous record
RowIndex++;
if (RowIndex == dt.Rows.Count)
{
RowIndex--;
Label6.Text = "Already at last record.";
}
Display();
}
protected void Button4_Click(object sender, EventArgs e)
{
//display last record
RowIndex = dt.Rows.Count - 1;
Display();
}
}
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
[Drag and drop the ―GridView‖ control from the ―Data‖ category at the toolbox].
DataSetDemo_DataGridView.aspx.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//DataTable impl
DataTable dt;
dt = ds.Tables[0];
//grid logic
GridView1.DataSource = dt;
GridView1.DataBind();
}
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.
Connection
Command
(provider, data (procedure / .NET
db Source, user id, function name,
parameters) Application
password)
Demo:
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the page name as
―DataSetDemo_GridView.aspx‖. Click on ―Add‖.
Properties of ―HyperLink10‖:
Text: Stored Procedure Demo
NavigateUrl: ~/StoredProcedureDemo.aspx
Design the ―StoredProcedureDemo.aspx‖ page as follows:
StoredProcedureDemo.aspx.cs
using System.Data;
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "calculategrades";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
//presentation logic
Label1.Text = "Procedure Executed..";
cn.Close();
}
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
[Drag and drop two ―GridView‖ controls into the page from the ―Data‖ category at the toolbox]
StoredProcedureDemo_MultipleTables.aspx.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//DataTable impl
DataTable dt1, dt2;
dt1 = ds.Tables[0];
dt2 = ds.Tables[1];
//grid logic
GridView1.DataSource = dt1;
GridView1.DataBind();
GridView2.DataSource = dt2;
GridView2.DataBind();
}
Data Controls
These controls are used to display the database data in various formats.
Instead of using the regular standard controls like labels, textboxes etc., it is better to
use these ―Data controls‖. For example, we have already used a data control called
―GridView‖, which presents the data in a table format.
In this way, we have to discuss about other data controls also.
The following are all the important data controls in ASP.NET 4.0:
AccessDataSource
SqlDataSource
GridView
DetailsView
FormView
ListView
Chart
One more thing that you need to remember that, these controls supports the database
connections in two models:
1. Programming Model:
We have to write all the code for database connections, for retrieving the
data from the database and for performing insertions, deletions,
updations etc., just like we have implemented the code in the previous
ADO.NET examples.
It takes much time.
But it is better to perform any type of database manipulations.
2. Non-Programming Model
We don‘t need to write any code for database connections, retrievals,
insertions etc.; simply we have drag and drop the ―data source‖ controls
such as AccessDataSource, SqlDataSource etc., and we have to
configure those controls properly. These data source controls can
interact with the database and can serve the data to the other data
controls like GridView, DetailsView etc.
It‘s like an express-style. Within minutes, we can finish our work. It‘s
very much easy to use, when compared with programming model.
But it‘s much difficult to implement any additional new style of database
manipulations, which are not defined in the existing data controls.
At first, we are using ―AccessDataSource‖ control, which gets the data from an Access
database.
Just for demo purpose, let‘s create an Access Database.
Open Microsoft Office Access 2007.
Select ―Blank Database‖ option.
Enter the database name as ―Database1.accdb‖. (Where as accdb stands for Access
Database).
Select the folder as ―My Documents‖.
Click on ―Create‖.
It shows ―Table1‖ like this:
Click on OK.
Then type the table structure 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 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.
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:
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.
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.
Then make sure whether all the above connection details are properly entered or not.
Anyway, after successful connection, click on OK button.
Then it comes back to the ―Configure Data Source‖ dialog box, and automatically
generates the connection string, based on the above given connection details. To see the
automatic generated connection string, click on ―+‖ symbol. Then it shows the
connection string as follows:
If required you click on ―Where‖ option to given any conditions; you can also select the
sorting column by click on ―Order By‖ option.
Click on ―Advanced‖ button now, and select the option called ―Generate INSERT, UPDATE
and DELETE statements‖.
Then click on OK. This particular option is useful, to perform insertion, updation and
deletion operations straight-away from the data controls. To fully understand this option
purpose, we have to proceed with other options, in the GridView. We discuss about
additional options in the GridView control in the rest of this demo application
development process.
Anyway, click on the ―Next‖ button.
Click on ―Test Query‖ button, to test the query.
Click on Finish.
Now, the ―SqlDataSource1‖ control is configured properly and its ready.
Then drag and drop one more ―GridView‖ control and click on ―>‖ button.
Then click on ―Choose Data Source‖ option. Select the ―SqlDataSource1‖ from the
dropdown list.
Then the screen looks like this:
Now, this is the time for discussing about the advanced options, available in the
―GridView‖ control.
Select the ―GridView2‖ control and click on ―>‖ button.
Then click on ―Auto Format‖ option. Then select any one of the given auto format styles.
After selecting the auto format styles, the grid looks like this:
Enable Paging: Again, click on ―>‖ button and click on ―Enable Paging‖ option. This
option displays the page numbers at bottom side of the grid control, which displays the
data, based on the selected page numbers. This is useful, when large no. of records is
there in the database. By default, it shows 10 records per every page. Of course, you can
change the no. or records per page, using ―PageSize‖ property.
Enable Sorting: Again, click on ―>‖ button in the GridView, and select ―Enable Sorting‖
option. Then at run time, it allows the user click on the column name, to sort the data in
ascending or descending order. When the user clicks on the required column name first,
the data will be sorted in ascending order. When the user clicks the same column again,
then the data will be sorted in descending order. For this sorting, we don‘t require to
write any code.
Enable Editing: Again, click on ―>‖ button in the GridView, and select ―Enable Editing‖
option. Then it shows a link button called ―Edit‖ for every row in the grid. The user can
click on ―Edit‖ option at any row, to directly update the data. Then it automatically shows
textboxes in place of the values. There, the user can change the values. To confirm the
modifications, the user has to click on ―Update‖ link button. Then automatically the data
will be modified in the database. For this updation also we don‘t require to write any
code.
Enable Deleting: Again, click on ―>‖ button in the GridView, and select ―Enable
Deleting‖ option. Then it shows a link button called ―Delete‖ for every row in the grid.
The user can click on ―Delete‖ option at any row, to directly delete the data. Whenever it
is clicked at run time, automatically the data will be deleted permanently in the database.
For this deletion also we don‘t require to write any code.
Enable Selection: Again, click on ―>‖ button in the GridView, and select ―Enable
Selection‖ option. Then it shows a link button called ―Select‖ for every row in the grid.
The user can click on ―Select‖ option at any row, to select the particular row. Whenever it
is clicked at run time, it automatically the selected row will be highlighted.
Of course, you can do something, whenever the ―Select‖ button is clicked. You have to
write some code for that.
To do so, double click on the GridView control. Then it generates
―SelectedIndexChanged‖ event. That event will be executed automatically, whenever the
user selects any row, by clicking on ―Select‖ link button at run time.
For a demonstration, drag one Label control (below the grid control) and write the
following code:
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, 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.
After selecting
the provider (Ex:
Microsoft OLE DB
Provider for Sql
Server), click on
―Next‖ button.
Enter the server
name (name of
the system), user
id, password and
select database
name.
Ex:
Server name: classroom
User ID:sa
Password: 123
Database: sample
Click on ―Finish‖.
Then the ―OLE DB (ADO)‖ dialog box will be closed and the focus will be come back to
―Standard Report Creation Wizard‖ dialog box. And now, the ―OLE DB (ADO)‖ option
will be expanded.Expand the database name and select the table name, which you
want. (Ex: students).
Click on ―>‖ button to add the selected table into the right side list.
Click on ―Next‖.
Expand the table name. Then the list of columns will be displayed.
Now you have to add the require column(s), into the right side list, which you want to
display in the crystal report.
To add all the columns, click on ―>>‖ button. To add the columns one-by-one, select
the column first and click on ―>‖ button.
Click on ―Next‖.
Select the grouping column, based on which you want to group-up the data
(optional). If you don‘t want to group the data, simply leave it blank.
Click on ―Finish‖.
Then the report wizard will be completed and the report will be generated
automatically.
The report will be displayed in the design view. This can be called as ―Report Design
View‖.
Then the report file will be added into the ―Solution Explorer‖. Ex: studentsreport.rpt
Report Header: This section contains the objects that are to be displayed
only at the top of the report.
Page Header: This section contains the objects that are to be displayed at
the top of each page.
Details: This section contains the objects that are to be repeated for each
row of the database table. Generally, it displays the actual data values.
Report Footer: This section contains the objects that are to be displayed at
the bottom of the report.
Page Footer: This section contains the objects that are to be displayed at
the bottom of each page.
To change any font / border / alignment / colors / paragraph of the objects, right click
on the require object and choose the ―Format Object‖ option.
To add new objects, right click on the empty area and choose ―Insert‖, where you can
select ―Special Field‖ / ―Text Object‖ / ―Summary‖ / ―Line‖ / ―Box‖ / ―Chart‖ /
―Picture‖. After selecting any one of these options, click anywhere, where you want to
insert that object.
There, select the ―studentsreport.rpt‖ file from the drop down list.
Run the web site. At run time, it asks for run-time authentication for security purpose.
Then you have to enter the password (Ex: 123) and click on ―Finish‖.
The ―CrystalReportViewer‖ control offers the following features at run time.
Exporting the report to other formats like excel, pdf, doc etc.
Printing the report through a printer.
Refresh the report data.
Show/Hide the Group Tree.
Navigating the First / Previous / Next / Last Pages in the report.
Find the required text.
Change the Zoom of the data.
Output:
Enter the password as ―123‖ (or the password according to your system) and click on ―Log on‖.
Validation Controls
The validation controls are meant for performing client side validations.
Def of Validation: The ―Validation‖ is a process, that checks the user input values,
whether those are correct or not. According to this, whenever the user clicks on ―submit‖
button on the client system, the user-input values will be validated first. If all of those
values are valid, then the page will be submitted to the web server. Otherwise, an error
message will be displayed to the user and the page will not be submitted to the web
server.
Advantage of Validation: As an advantage of validation, invalid values containing
pages would not be submitted to the web server. So that we can avoid the stress on web
server.
In older days, the client side validations are performed by using the code written in ―java
script‖ language. But in newer age of web development like ASP.NET, validation controls
are introduced to replace the role of ―java script validations‖.
Advantage of Validation Controls: Validation controls are very much easy to use. You
don‘t require to write even single line of code also to use them. So that we can avoid
―java script‖ usage. In order to perform different kinds of validations, ASP.NET offers
different types of validation controls.
Functionality of Validation Controls: A validation control performs a particular type
of validation on input / selection based controls like textbox, checkbox, checkboxlist,
radiobuttonlist, listbox, dropdownlist etc. At run time, whenever the user clicks on
―Submit‖ button it validates the particular control. If the given value is valid, it allows the
page to be submitted. Otherwise, it stops the submition of the page and displays an error
message on the page. By default, its forecolor is set to ―red‖.
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, 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 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.
enter a filename. The validation is to not to enter non-existing file named. So that, there
is a necessity of validating the file name, whether it is actually exist on the disk or not. At
that time, you have to use ―CustomValidator‖. But unlike other validation controls, this
requires to write some code for validation. The validation code can be implemented in
―ServerValidate‖ event.
Properties of CustomValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
Design regExpValidatoryEMail
ControlToValidate: txtEMail
lblValidationDemo ErrorMessage: Enter a Valid E-Mail address.
lblName ValidationExpression: Internet e-mail address.
txtName lblCourse
ReqValidatorName rbListCourse
ControlToValidate: txtName Items: C, C++, Java, .NET
ErrorMessage: Please enter any name. reqValidatorCourse
SetFocusOnError: true ControlToValidate: rbListCourse
lblAge ErrorMessage: Select any course.
txtAge lblCity
rngValidatoryAge txtCity
ControlToValidate: txtAge comValidatorCity
ErrorMessage: Age should be between 18 ControlToValidate: txtCity
and 60. ErrorMessage: “Vijayawada” is not allowed.
MinimumValue: 18 ValueToCompare: Vijayawada
MaximumValue: 60 Type: String
Type: Integer Operator: NotEqual
lblPhone lblPassword
txtPhone txtPassword
regExpValidatorPhone TextMode: Password
ControlToValidate: txtPhone
ErrorMessage: Enter a Valid Phone
Number.
ValidationExpression: U.S. Phone Number
lblEMail
txtEMail
reqValidatorPassword comValidatorDOJ
ControlToValidate: txtPassword ControlToValidate: txtDOJ
ErrorMessage: Password can’t be blank. ErrorMessage: Invalid Date.
lblConfirmPassword Type: Date
txtConfirmPassword Operator: DataTypeCheck
TextMode: Password lblNumber
comValidatorConfirmPassword txtNumber
ControlToValidate: txtConfirmPassword CustomerValidator1
ControlToCompare: txtPassword ControlToValidate: txtNumber
ErrorMessage: Password and Confirm Password ErrorMessage: Only the numbers, divisible by 3 are
should be same. allowed.
Type: String ValidationSummary1
Operator: Equal Button1
lblDOJ
txtDOJ
Default.aspx
Default.aspx.cs
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int n = Convert.ToInt32(args.Value);
if (n % 3 == 0)
args.IsValid = true;
else
args.IsValid = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid) //this condition is required only when, you are using "CustomValidator" in
the page.
Response.Redirect("success.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.
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:
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.
Now, drag and drop the ―CreateUserWizard‖ control from the toolbox, into the page. This
control helps the user to be registered in the web site.
Then the screen looks like this:
That‘s it. The control is ready to use. No need of writing any code.
This control contains two steps (like a Wizard control).
Currently you are viewing the first step. To switch to the second step, click on ―>‖ button
and choose the ―Complete‖ step.
At run time, after successful registration of the user, the ―Complete‖ step will be
displayed.
Anyhow, when the user clicks on the ―Continue‖ button at run time, generally other page
can be opened. Suppose, you want to display ―login‖ page, when the user clicks the
―Continue‖ button. Then click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ –
Type the name as ―login.aspx‖ – Click on Add.
In the ―login.aspx‖, drag and drop the ―Login‖ control from the toolbox.
Then it looks like this:
For this control also we don‘t require to write any code. It‘s ready to use. But after
successful login, generally other page will be opened. So that we have to add a separate
page.
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―mainpage.aspx‖ – Click on Add.
Design the mainpage.aspx as follows:
But we have to maintain the link between the Login control and the ―mainpage.aspx‖;
because, at run time, after successful login, the ―mainpage.aspx‖ is to be opened.
Then come back to the ―login.aspx‖ page.
Select the ―Login1‖ control and set the following property:
1. DestinationPageUrl: mainpage.aspx
That‘s it. Now, the login control is fully configured.
Come back to the ―Default.aspx‖ page.
Select the ―CreateUserWizard1‖ control and set the following property:
1. ContinueDestinationPageUrl: login.aspx
Click on ―>‖ button, and come back to the first step called ―Sign up for Your New‖.
Now, you can run the web site and test the registration and login features.
Open the Solution Explorer; right click on ―Default.aspx‖ and choose ―Set as Start Page‖.
Run the web site.
Ex:
Click on ―Continue‖.
Then it shows the ―login.aspx‖ page.
Password: syam123$
Now, there are two users in your web site, named ―satya‖ and ―syam‖.
Then you may have some doubt: Where all the user‘s information is being stored?
Answer: In the SQL Server database.
But, we have not created the database!! Don‘t worry; the database has been created
automatically! You don‘t require doing anything particularly for that.
To see the database name, open the Solution explorer. Select the web site name and
click on ―Refresh‖ button. Then it shows a database file called ―ASPNETDB.mdf‖ under
the ―App_Data‖ folder.
Note: In fact, the ―App_Data‖ is a system-
recommended folder, in which we can store all the
necessary database files or other data source files
such as XML files.
To make the controls looking better, set the auto
format styles for the Login1 and CreateUserWizard1
controls.
Suppose, you want to display the currently logged-in username in the ―mainpage.aspx‖
page. Then drag and drop the ―LoginName‖ control into the page, just beside the
―Welcome‖ message.
Then the screen, looks like this:
At run time, the ―LoginName‖ control displays the currently logged-in user name
automatically.
Run the web site and test it.
Next, If you want to offer ―Change Password‖ option in your site, add a hyperlink into the
―mainpage.aspx‖ and set the following properties:
1. Text: Change Password
2. NavigateUrl: changepassword.aspx
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―changepassword.aspx‖ – Click on Add.
Drag and drop the ―ChangePassword‖ control from the toolbox.
Set the following properties for the ―ChangePassword1‖ control:
1. ContinueDestinationPageUrl: mainpage.aspx
To use it, you have to run the web site, enter the current user name, new password,
confirm password and click on ―Change Password‖ button. It itself, updates the new
password in the database.
Next, suppose you want to implement ―Log out‖ option in your web site. Then drag and
drop the ―LoginStatus‖ control into the ―mainpage.aspx‖.
Now, the mainpage.aspx looks like this:
At run time, the LoginStatus control displays ―Login‖ option or ―Logout‖ option.
That means, if any user currently logged-in, then it displays ―Logout‖ option. If no user,
currently logged-in, then it displays ―Login‖ option.
Set the following properties of ―LoginStatus1‖.
1. LogoutAction: RedirectToLoginPage
With the help of above property, when the user clicks on ―Logout‖ option at run time, it
comes back to the ―login.aspx‖ page.
To test it, you have to run the web site.
Next, we are trying to implement ―Forgot Password‖ feature.
Design the ―Default.aspx‖ page as follows:
Properties of ―HyperLink1‖:
1. Text: Login
2. NavigateUrl: login.aspx
Properties of ―HyperLink2‖:
1. Text: Click here
2. NavigateUrl: forgotpassword.aspx
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―forgotpassword.aspx‖ – Click on Add.
Then in this page, drag and drop the ―PasswordRecovery‖ control from toolbox.
Set the auto format style.
Then the page looks like this:
Click on ―Submit‖.
Then it shows the security question, which is given at the time of user registration.
Enter the proper answer. Ex: green
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 the SMTP Settings.
ASP.NET
Close the browser and come back to the Visual Studio. Configuration
Open Solution Explorer and select the web site name. (Click here)
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 Next.
Specify the name as ―peerstech.com‖.
Click on Finish.
Then it will be added to the existing domains list.
If you configure the ―Outlook Express‖ properly, the e-mail will be sent automatically to
the Inbox of the user.
Anyway, you can find the password, which is given as an encrypted value in the e-mail.
Ex: dgJfi^cdx=>d]h
The user has to use this above password, to login. Of course, after next login, the user
can change the password.
To test it, run the web site, and try to login with above given encrypted password (you
can copy the password and paste it directly in the password textbox, at the login page).
After that try to change the password using ―Change Password‖ option.
WebParts Controls
The WebParts controls allow the user to change the web page content dynamically at run
time, though the browser.
This is a concept of personalization, which remembers your settings automatically, based
your login information (username and password). If you run the web site later (after few
days or months also), the same settings will be loaded.
Important WebParts Controls:
1. WebPartManager
2. WebPartZone
Re-size the WebPartZone controls and set the auto-format styles, as per your desire.
Rename the ―WebPartZone1‖ as ―FirstZone‖ using ID property.
Rename the ―WebPartZone2‖ as ―SecondZone‖ using ID property.
Rename the ―WebPartZone3‖ as ―ThirdZone‖ using ID property.
Drag the drop any controls (like labels, buttons, textboxes, checkbox, calendars etc.) into
the web part zones.
(Continued…)
Note: If you minimize any control, you can restore it later. If you close it, you can‘t
restore it again.
Close the browser and come back to Visual Studio.
Drag and drop a ―DropDownList‖ control.
Select it and click on ―>‖ symbol. Click on ―Enable AutoPostBack‖ option.
Click on OK.
Double click on the DropDownList1 control and write the code:
Default.aspx.css
using System.Web.UI.WebControls.WebParts;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
else
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
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.
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
Response.Redirect("display1.aspx?uname=" + s);
}
display1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Params["uname"];
Label1.Text = "Welcome, " + s;
}
No security is available, because the argument names and values will be displayed in the
browser‘s title bar. You can‘t pass the values in hidden mode.
The values can be sent from one page to another page only. But, the values can‘t be
retrieved from other pages, forwarded from the second page.
You can share only string values or numerical values among multiple pages. Of course,
even though you pass the numerical values, it treats the value as a string value only.
Anyhow, you can‘t pass ―objects”.
Note: To overcome the above first two limitations, ―Cookies‖ concept is introduced.
Cookies
A cookie can be used to share values among two or multiple web pages.
Cookies are stored at client system only.
A cookie will be created as a text file in the ―c:\Documents And
Settings\Username\Cookies‖ folder on the client system. These files will be created
dynamically at run time.
When compared with ―Query String‖, the advantage of cookies is, it doesn‘t display the
values in the address bar. The value can be passed in hidden mode.
Another advantage of ―Cookies‖ is, cookies alive among multiple web pages, not only
between one page to another page. That means you can access the values stored in the
cookies from any other pages, navigated from the current page.
According to the OOP standards in ASP.NET, every cookie is an object for a pre-defined
class called ―HttpCookie‖.
Implementation:
A. Assign value to the Cookie:
Create cookie object:
HttpCookie obj = new HttpCookie(―variable_name‖, ―value‖);
Assign the cookie object to Response:
Response.Cookies.Add(obj);
B. Get value from the Cookie:
Request.Cookies[―variable_name‖].Value
Demo:
Default.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
HttpCookie ck = new HttpCookie("uname", s);
Response.Cookies.Add(ck);
Response.Redirect("display2.aspx");
}
display2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Cookies["uname"].Value;
Label1.Text = "Welcome, " + s;
}
Limitations of “Cookies”
Cookies will be stored in the form of text files during run time in the client system. Those
files can be easily visible by other users. It is easy to modify or delete the cookie files. It
is easy to hack the cookie files from remote systems also. So, cookies are not much
secured.
Cookie files will not be deleted automatically. So that, it leads to waste of hard disk
memory.
It doesn‘t supports to share ―objects‖ among multiple pages. It supports to share strings
or numerical values only.
Finally, now-a-days, cookies are out-dated. To overcome the limitations of cookies, we use
―Sessions‖.
Session State
Whenever a client (browser) is connected, the ―Session‖ state will be created
automatically; and the session will be closed automatically whenever the client (browser)
is disconnected.
Here, ―state‖ means some memory, at web server.
For every client (browser), a separate session will be created. For example, your web site
is being opened by 100 users (from 100 browsers). That means there will be 100
sessions.
Similar to Cookies, the ―Session state‖ is used to share values among multiple pages. For
example, between login and logout, the current user name, user id number and
password will be stored in the session state.
Now-a-days, ―Cookies‖ are outdated. Instead of cookies, sessions are used.
The main difference between cookies and session state is: a cookie will be saved on the
client system; and the session will be saved at web server.
Sessions are more secured, when compared with ―Cookies‖, as sessions will be saved at
web server.
Sessions will not be saved in the form of any files. Those are stored as logical objects in
the web server memory.
Sessions are able to share values and objects also.
Implementation of ―Session state‖ is easier, when compared with ―Cookies‖.
To access the session state, you can use the implicit object called ―Session‖. That means
you don‘t require to create the ―Session‖ it is commonly available for all the web pages
by default.
The ―Session‖ object always represents current session, in which the web page is being
executed.
Implementation:
A. Assign value to the Session:
Session[―name‖] = value;
B. Get value from the Session (gets the session variable value in “Object”
type):
Session[―name‖]
C. Clear all the values in the current session:
Session.Clear();
Demo:
Default.aspx.cs
protected void Button3_Click(object sender, EventArgs e)
{
Session["uname"] = TextBox1.Text;
Response.Redirect("display3.aspx");
}
display3.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Session["uname"]);
Label1.Text = "Welcome, " + s;
}
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:
Default.aspx.cs
protected void Button4_Click(object sender, EventArgs e)
{
Application["uname"] = TextBox1.Text;
Response.Redirect("display4.aspx");
}
display4.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Application["uname"]);
Label1.Text = "Welcome, " + s;
}
View State
―View State‖ is a state that keeps the current state of the web page, during post back.
Post Backing: The web page gets re-loaded automatically, whenever the user performs
an event at run time. Here, the page will be submitted to the same page itself. This
process is called as ―Post Backing‖. For example, if the user clicks on a button, the page
will be posted back.
At the time of post backing, the web page will be closed and the same web page will be
re-loaded. In fact, the textbox values / list box selections etc., would not be re-loaded, if
―View State‖ concept is not implemented.
Because of ―View State‖, ASP.NET is able to get the web page to the previous state, as it
is submitted at the time of post back.
As a part of this ―View State‖, at the time of Post Backing, ASP.NET automatically saves
the current values of the controls in a separate string temporarily. After re-loading the
page, the controls values will be re-stored to its previous state, based on the values in
view state string.
In fact, the ―View State‖ is maintained automatically by ASP.NET, you don‘t require
implementing it manually.
Demo
Open the previous demo web site.
Add ―viewstatedemo.aspx‖ page and design it as shown.
Open Solution Explorer; right click on ―viewstatedemo.aspx‖ and click ―View in Browser‖.
Enter some values.
Click on the button. Then the ―post backing‖ will be done. But the no values will be lost.
Global.asax
This file contains the events, related to entire web site.
Here is the list of events, written in global.asax file:
1. Application_Start: This event executes automatically, whenever the
―Application State‖ is created. The Application State will be created automatically,
whenever the web server is started.
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.
Global.asax
<%@ Application Language="C#" %>
<script runat="server">
Response.Redirect("errorpage.aspx");
}
</script>
usercountpage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
int n = Convert.ToInt32(Application["usercount"]);
Label1.Text = "This web site is viewed by " + n + " users.";
}
Copy the URL from the address bar; open another browser; and paste the URL.
Note: Every time you run the page, the user count will be incremented automatically.
errortestpage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
int[] a = { 10, 20, 30, 40 };
int x = a[5];
Response.Write(x);
}
Open Solution Explorer; Right click on ―errortestpage.aspx‖ and select ―View in Browser‖.
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.
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.
CSS Classes
In the ―Internal Styles‖ and ―External Styles‖, common styles will be applied for every
instance of particular tag. Instead, you can have a choice for applying the CSS styles for
the required instances only, with the concept called ―CSS classes‖.
Finally, the ―CSS Classes‖ concept can be used in two situations:
1) To apply common CSS styles for selective instances of a tag.
2) To apply common CSS styles for selective instances of multiple tags.
To create a CSS class, follow the syntax:
.classname
{
attribute1:value1; attribute2:value2;….
}
To apply the CSS style for the required html tag, follow the syntax:
<tag class=‖classname‖>
To apply the css style for the required server tag, follow the syntax:
<asp:tag CssClass=‖classname‖>
Ex:
<head runat="server">
<style type="text/css">
.mytextbox
{
color:Red;
font-family: Tahoma;
font-size: 30px;
border-style: double;
}
</style>
</head>
Open Solution Explorer – right click on the web site name and click on ―Add New Item‖.
Select ―Style Sheet‖.
Enter the any file name. Ex: StyleSheet.css
Click ―Add‖.
Then the screen looks like this:
Remove that body tag and make file empty, because we don‘t require it now.
On the screen, you can observe ―Style Sheet‖ toolbar.
If you don‘t find it, click on ―View‖ menu – ―Toolbars‖ – ―Style Sheet‖ option. Then the
toolbar will be there.
Then click on the first button called ―Add Style Rule‖.
Click on ―Class name‖ option and enter the any class name. Ex: MyTextBox.
It automatically generates the Style rule preview as ―.MyTextBox‖ (as you know already
that, every CSS class name should start with . (dot)).
Click on OK.
Then it generates CSS class syntax in the code.
Then click on the class name (MyTextBox) and click on ―Build Style‖ option in the toolbar.
Click on OK.
Then it automatically generates the style sheet code as below:
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‖.
Delete all the commented code and type the code manually as follows:
MyTheme.skin
<asp:Label runat="server" Font-Bold="True" Font-Name="Tahoma" ForeColor="Green"
Font-Size="14px" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Lucida Handwriting"
BackColor="DarkGreen" ForeColor="Yellow" Font-Size="14px" />
<asp:Button runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="DarkRed" ForeColor="Yellow" Font-Size="14px"/>
IMP Note: While you are typing the above code, no help
can be given by Visual Studio. You have to take care about
casing and all other things. If you don‘t type it in proper
casing, it won‘t work. It causes some errors.
Come back to the ―themesdemo.aspx‖ page.
Open the properties window and choose ―DOCUMENT‖
option from the list, which is displayed at the top of the
properties window.
Select the ―Theme‖ property as ―MyTheme‖ from the list.
Select the ―Label3‖ and set the following property:
EnableTheming: False
Then run the web site.
At run time, the theme will be applied, and the page looks
like this on the browser:
Limitations of Themes:
As per the default nature of themes, for all the controls, common styles will be applied
automatically.
Suppose if you want to apply one type of style for few controls on the page, and another
type of style for few other controls on the page, it not possible.
Solution: Use ―Skins‖.
Skins
Skins are similar to CSS classes.
Similar to CSS class, the skin has a name.
It can be written in the ―.skin‖ file.
One skin file may contain any no. of skins.
Implementation:
Create the tag designs with “SkinID” attribute (in the skin file):
<tag runat=‖server‖ property=‖value‖ SkinID=‖skin name‖ />
Access the Skin with “SkinID” attribute (in the aspx page):
<tag runat=‖server‖ SkinID=‖skin name‖ />
Demo:
Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
Select ―Skin File‖.
Enter the file name as ―MyTheme2.skin‖.
Click on ―Add‖.
It asks a confirmation, whether you want to place the skin file in the ―App_Themes‖
folder or not. You click on ―Yes‖.
Then the screen looks like this:
Delete all the commented code and type the code manually as follows:
MyTheme2.skin
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Pink" ForeColor="Red" Font-Size="20px" SkinID="PinkAndRed" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Bisque" ForeColor="Blue" Font-Size="20px" SkinID="BisqueAndBlue" />
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.
Demo:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Aboutus.aspx‖ – Click on Add.
Design the ―Aboutus.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Contactus.aspx‖ – Click on Add.
Design the ―Contactus.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―registration.aspx‖ – Click on Add.
Design the ―registration.aspx‖ as follows:
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―login.aspx‖ – Click on Add.
Design the ―login.aspx‖ as follows:
Open solution explorer; right click on the web site name and choose ―Add New Item‖.
Select ―Web User Control‖.
Enter any name. Ex: WebUserControl.ascx
Note: ascx stands for Active Server Control Extended.
Click on ―Add‖.
Design it as shown:
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:
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).
Demo:
Caching
Caching (pronounced as ―Cashing‖), is one of the most powerful concept of ASP.NET.
This is introduced to reduce the stress on web server.
If your application is being executed simultaneously from two or more browser windows
on the same system, or it is being executed simultaneously from two or more client
systems on the network, or it is being executed simultaneous from two or more web
clients on internet, on each post back of the page, a new request to the web server
would be passed. So that, the entire page is to be refreshed. That means the contents of
the web page would be re-loaded and the code will be executed every time. This causes
heavy stress on the web server.
For example, there is a submit button on your web page. If the submit button is clicked
on one client, it is not a much stress on the web server. You suppose that the button is
clicked from 20 client systems at-a-time. So that 20 requests will be passed to the web
server. The web server should respond to the 20 clients. So this leads to slow-up the
execution, because of heavy stress on the web server.
To avoid this kind of problems, ―Caching‖ concept is introduced.
According to this, you can store the page and its output in the cache memory up to a
certain time.
If any request is sent to the web server, within the time limitation, the page will not be
re-loaded / re-executed. No code will be executed. Simply the previously cached web
page will be sent to the client as response.
After completion of the specified time limit, the cached page will be removed
automatically.
If any request is sent to the web server after the time limit, the page will be re-loaded as
usual.
Generally, it is recommended to store most frequently used web pages in the cache
memory, using ―Caching‖ concept.
At this same time, it is not recommended to store the web pages in the cache memory,
which pages content can be frequently changed dynamically at run time. Ex: Inbox page,
cricket scores page, examination results page.
Types of Caching:
1. Output Caching:
The output of the web page will be stored in the cache memory, for a while (based
on the time limit that you have given).
Syntax: Write the following tag in the ―Source‖ view, after Page directive:
<%@ OutputCache Duration="seconds" VaryByParam="none" %>
2. Fragment Caching:
This is also one kind of output caching.
But instead of storing the full page output in the cache memory, partial page (part of
the page) output only be stored.
To implement this, you have to implement the ―OutputCache‖ in the Web User
Control.
After that, drag and drop the ―WebUserControl‖ into the web page.
That‘s all. Then finally it will be fragment caching.
3. Data Caching:
This is used to store the frequently used database data, in the cache memory.
For the first time, when the user opens the web page, you connect with the database
and get the data from the database; and store it in the cache memory.
Later, you can get the cached data on the same page or another page also, without
contacting the database.
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
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:
WebUserControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
fragmentcachingdemo.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
Drag and drop the ―WebUserControl.ascx‖ from solution explorer, into the page.
Then the screen looks like this:
To continue the demo application with ―Data caching‖, add the ―datacachingdemo.aspx‖
and design it as shown:
datacachingdemo.aspx.cs
using System.Data.SqlClient;
using System.Data;
DataTable dt;
dt = ds.Tables[0];
Cache["mydata"] = dt;
Label1.Text = "Data Loaded from Database";
}
else
{
Label1.Text = "Data Loaded from Cache";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//some code for displaying the data...
DataTable dt = (DataTable)Cache["mydata"];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Demo:
Add the ―myad.aspx‖ page and design it as follows with an image control:
Select the ―DOCUMENT‖ properties in the ―properties window‖ and set the following
property:
Title: Ad
Type the <body> tag as follows:
<body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>
Run the web site and click on the button. It shows the popup ad automatically.
2) Confirmation Boxes:
Syntax: window.confirm("message");
Demo:
dialogboxes.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("confirmationmessage.aspx");
}
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.
Demo:
LINQ
LINQ (pronounced link) stands for ―Language Integrated Query‖.
This concept is introduced in .NET Framework 3.5.
This is a ―query writing technology‖.
This is most useful while working large amount of data in the live projects.
Introduction:
In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
In the modern world, the data sources are not only the databases. The application can
access the data from various other data sources like XML files, SAP, CSV (Comma
Separated Values) files etc.
But you can‘t write a query on the non-database data, which in the form of objects, XML
etc. There, you can write the queries using the new concept called ―LINQ‖.
You can write queries on arrays, objects, tables, xml using LINQ.
Note: Before writing the LINQ queries, you should import the ―System.Linq‖ namespace.
//ling query
var result = from n in numbers where n < 10 select n;
//output
foreach (var x in result)
Response.Write(x + ", ");
}
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:
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
Student.cs
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
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>");
Response.Write("</font>");
}
}
Run the web site and the output will be like this:
goes to
linqwithlambda.cs
Response.Write("<font face=Tahoma>");
Response.Write("</font>");
}
}
LINQ to SQL
This is to get the database data and perform LINQ queries on database data.
linqtosqldemo.aspx.cs:
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from c in db.Customers where c.Gender == "Female" select c;
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
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 = "";
}
GridView1.DataSource = null;
GridView1.DataBind();
}
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
employees.xml
Default.aspx.cs
using System.Data;
Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
Run the web site.
Output:
Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.
The xml document starts with XML prologue, which specifies the xml version.
<configuration>
………..
</configuration>
The next important section is <appSettings>. This is used to store or configure the
application settings, which are related to entire web site. For example, you want to
display the company‘s phone number in several web pages. So that, if you write the
phone number in each page it will be much difficult to change it later, because you
require to change it in all the required pages.
Instead, you try to store it (write it) in the web.config file, at the <appSettings> section.
Then later if you want to change it, you can change it easily, without changing any code
in all the pages.
To take a demonstration, change the <appSettings/> tag as follows:
<appSettings>
<add key="CompanyLocation" value="Hyderabad"/>
<add key="PhoneNo" value="040-23923020"/>
</appSettings>
using System.Configuration;
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:
<appSettings>
<add key="CompanyLocation" value="Banglore"/>
<add key="PhoneNo" value="9993999790"/>
</appSettings>
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.
<connectionStrings>
<add name="MyConn" connectionString="data source=localhost;user
id=sa;password=123;initial catalog=demo"/>
</connectionStrings>
Come back to Default.aspx and add a button called ―Connect to SQL Server‖ as shown.
using System.Data.SqlClient;
<compilation debug="true">
When it is set to ―true‖, it shows the code, when the exceptions occur; break points also
work.
When it is set to ―false‖, it shows a default error message page, when the exceptions
occur; break points won‘t work.
By default, when you create the web site, it will be ―false‖. After you run the web site for
the first time, it will be automatically changed as ―true‖.
It is recommended to set it as ―true‖, when the development process in under progress.
It is recommended to set it as ―false‖, before you publish it on the internet; because you
won‘t show the code to the user, when an exception occurs.
The next thing you have to observe is <authentication> tag.
This tag specifies the mode of ASP.NET security. The modes are:
A. None
B. Windows
C. Forms
D. Passport
The default mode is ―Windows‖.
<authentication mode="Windows"/>
We discuss more about this ASP.NET Security concepts and authentication modes later.
The next thing you have to observe is <customErrors> tag.
CustomError means customized errors.
Note: By default, the above code will be under commented mode. You have to un-
comment it, by moving the --> tag to up.
These custom errors are used to display required web pages, when some special type of
error occurs at run time.
For example, whenever the user tries to open a non-existing filename, there will be one
type of error at server. That error code is ―404‖.
Observe the following tag:
According to the above tag, whenever 404-error occurs, ASP.NET automatically redirects
the execution flow to the above specified html page called ―FileNotFound.htm‖.
To test this functionality, do like this:
Run the web site as follows:
In the above screen, the user has tried to open the ―abc.aspx‖ page, which is not there
in our web site. So that ASP.NET is showing the default error message as above.
In the above screen, you can observe the error code as ―HTTP 404‖.
Anyway, using <customErrors> tag, you can display another page, at this case.
To do so, close the browser and come back to Visual Studio.
Open the Solution Explorer; right click on the web site name and choose ―Add New
Item‖.
Select ―HTML Page‖.
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:
<pages theme="any_theme_name">
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.
<sessionState mode="InProc">
</sessionState>
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.
sessiontest.aspx.cs
display.aspx.cs
<sessionState mode="Off">
</sessionState>
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:
<sessionState mode="StateServer">
</sessionState>
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‖.
<sessionState mode="SQLServer">
</sessionState>
Now, run the ―sessiontest.aspx‖ page. It won‘t work properly; because you have
specified that session state is to be maintained in SQL Server database. But by default,
that SQL Server is not configured to store the sessions. You have to configure it
manually.
To do so, open the following folder:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
To add a new application setting, click on ―Create new application setting‖ option.
Enter the name and value of the application setting.
Click on ―Save‖.
Click on OK.
It adds the value to the list; immediately, ―web.config‖ file also will be updated.
Come ―Back‖ to ―Application‖ tab.
Configure SMTP E-mail settings: This is to be configured, when you want to send
automatic e-mails from your web site.
Note: Already we know how to configure the SMTP E-mail settings, in the previous
sessions.
Application Status: It should be always ―online‖ only. It should not be offline. If it is
offline, it won‘t work on the browser.
To test it, click on ―Take application offline‖ and try to run any page. It won‘t run. Again
come back to this web site administrative tool and click on ―Take application online‖.
Then it works normally.
Debugging and Tracing – Configure debugging and tracing: This is to enable or
disable the debugging and tracing.
If you uncheck the ―Enable debugging‖ option, then the <compilation> tag will be
modified as:
<compilation debug="false">
</compilation>
If you check the ―Enable debugging‖ option, then the <compilation> tag will be modified
as:
<compilation debug="true">
</compilation>
The other options in this screen are related to ―tracing‖ concept. We will discuss more
about this ―tracing‖, in the further sessions later.
Click on ―Back‖.
Debugging and Tracing – Define default error page: This is used to change the
generic error page (default error page which is to be displayed on occurrence of any type
of error in the web site). For more information, recollect the knowledge of
<customErrors> tag from previous sessions.
Here, you can select any other page, which acts as default error page.
Click on ―Save‖.
Provider: Always, it should be ―AspNetSqlProvider‖ only.
This is all about working with the ―ASP.NET Web Site Administrative Tool‖.
Close the browser and come back to Visual Studio.
Note: When you change any setting in the ―ASP.NET Web Site Administrative Tool‖, the
necessary changes would be made in the web.config file automatically.
Tracing
Using this tracing, the developer can get more technical information about the page
execution at run time.
To enable this feature, first option required page and set the following property of the
DOCUMENT object:
Trace: true
<system.web>
<trace enabled="true" pageOutput="true"/>
</system.web>
Now, if you run any page in the web site, tracing will be by default activated.
To disable the tracing feature, simply delete the <trace> tag (or) set it as
enabled=”false”.
For this demo, create 3 users named ―ram‖, ―sita‖ and ―laxman‖.
<authentication mode="Windows">
</authentication>
<authorization>
<allow users="localhost\ram"/>
<allow users="localhost\sita"/>
<deny users="*"/>
</authorization>
Now, if you login as ―ram‖ or ―sita‖, the web site can be accessed normally.
If other users logged-in, the web site is inaccessible. If you try to open the web site,
while you are in other user name (other than ram and sita), then it shows the following
type of message on the browser:
<authentication mode="Forms">
<forms loginUrl="Default.aspx"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
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‖.
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.
Default.aspx.cs
In the above output screen, you can observe the date & time formats, currency styles,
number forms in English-US Format.
Suppose, you want to display those in Chinese format.
To do so, you close the browser and come back to Visual Studio.
Open the Properties window; select the ―DOCUMENT‖ option.
Specify the following property:
Culture: zh-SG Chinese (Simplified, Singapore)
Now, you can observe the date and time formats, currency style, calendar etc., in
Chinese language.
In this way, you can select any culture. All major cultures from all the countries are
displayed in the ―Culture‖ property of DOCUMENT object.
For example, again change the culture as:
Culture: te-IN Telugu (India)
Run the web site. Output:
Now, you can observe the output in telugu language, by following the Indian date & time
formats and currency formats.
This concept is called as ―Localization‖.
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‖.
UserSelectedCulture.aspx.cs
Click on OK.
Move the culture to up; because top culture only be considered in the list.
Click on OK.
Click on OK.
Click on ―Refresh‖.
Then the contents will be displayed in Tamil language.
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:
<globalization culture="fr-CA"/>
(or)
<globalization culture="auto:fr-CA"/>
Implementation Code:
Default.aspx.cs
using System.Net.Mail;
Important Note: Here, we are using the local domain called peerstech.com for
demonstration. (peerstech.com domain has been created in the previous chapters. For
more information, read the chapter called ―Configuring E-Mail Server‖). Remember that,
the same code works for real internet e-mail addresses also. Suppose, if you send the e-
mail to your friend‘s gmail id, your friend has to open the gmail web site and has to
check it in the inbox. So, the same example code works for all the mail addresses on
Internet. No issues in that. But, if you are giving an E-mail ID, which really exist on
Internet, you require the Internet connection with your system, for sure.
The previous example is a simple demo, to send the e-mails. Sometimes, you require
sending the e-mails with attachments also. At that time, you require knowledge on
―MailMessage‖ class.
MailMessage
MailMessage(“from”, “to”, “subject”, “message
body”)
Attachments
EMailsWithAttachmentsDemo.aspx.cs
using System.Net.Mail;
mail.Attachments.Add(att1);
mail.Attachments.Add(att2);
sc.Send(mail);
Label8.Text = "E-Mail Sent Successfully!!";
}
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.
Web Method:
A web method is a method, which can be called from any other web site.
It can be executed directly on the web.
It can receive arguments.
It should return any value.
It should be defined as ―public‖ method only.
Just for a trail, write the following method in the ―Service‖ class.
[WebMethod]
public int GetRandomNumber(int min, int max)
{
Random r = new Random();
int n = r.Next(min, max);
return (n);
}
Click on the web method name, which you want to execute. Ex:
GetRandomNumber.
Then enter the values for the arguments (for min and max).
Click on ―GO‖.
Then it displays
the ―service.asmx‖
page.
After that, you
have to enter the
web reference
name. Ex: MyRef
A web reference
acts as
representation for
web service.
Finally click on ―Add Reference‖.
Then the web service will be linked with your web site; and the necessary files will be
copied into the web site folder.
Default.aspx.cs
using MyRef;
WCF
(Windows COMMUNICATION Foundation)
Since the introduction of the .NET Framework 3.0, Microsoft has made available
a new way to build Web services. Until the .NET Framework 3.0 came out, it was not a simple
task to build components that were required to communicate a message from one point to
another because Microsoft offered more than one technology that you could use for such an
action.
For instance, you could have used ASP.NET Web services (as just seen), MSMQ
(Microsoft Message Queue), .NET Remoting, and even the System.Messaging namespace. Each
technology has its own pros and cons. ASP.NET Web Services (also known as ASMX Web
Services) provided the capability to easily build interoperable Web services. The WSE enabled
you to easily build services that took advantage of some of the WS-* message protocols. MSMQ
enabled the queuing of messages, making it easy to work with solutions that were only
intermittently connected. .NET Remoting was a fast way to move messages from one .NET
application to another. Moreover, these are Microsoft options only. This does not include all the
options available in other environments, such as the Java world.
Using the WCF, you will be able to take advantage of all the items that make
distribution technologies powerful. WCF is the answer and the successor to all these other
message distribution technologies.
Looking back, you can see the gradual progression to the service-oriented
architecture model. In the 1980s, the revolution arrived with the concept of everything being an
object. When object-oriented programming came on the scene, it was enthusiastically accepted
as the proper means to represent entities within a programming model. The 1990s took that one
step further, and the component-oriented model was born. This enabled objects to be
encapsulated in a tightly coupled manner. It was only recently that the industry turned to a
service-oriented architecture because developers and architects needed to take components and
have them distributed to other points in an organization, to their partners, or to their customers.
This distribution system needed to have the means to transfer messages between machines that
were generally incompatible with one another. In addition, the messages had to include the
ability to express the metadata about how a system should handle a message.
If you ask 10 people what an SOA is, you‘ll probably get 11 different answers,
but there are some common principles that are considered to be foundations of a service-
oriented architecture:
❑ Boundaries are explicit: Any datastore, logic, or entity uses an interface to expose its data
or capabilities. The interface provides the means to hide the behaviors within the service, and the
interface front-end enables you to change this behavior as required without affecting
downstream consumers.
❑ Services are autonomous: All the services are updated or versioned independently of one
another. Thus, you do not upgrade a system in its entirety; instead, each component of these
systems is an individual entity within itself and can move forward without waiting for other
components to progress forward. Note that with this type of model, once you publish an
interface, that interface must remain unchanged. Interface changes require new interfaces
(versioned, of course).
❑ Services are based upon contracts, schemas, and policies: All services developed
require a contract regarding what is required to consume items from the interface (usually done
through a WSDL document). Along with a contract, schemas are required to define the items
passed in as parameters or delivered through the service (using XSD schemas). Finally, policies
define any capabilities or requirements of the service.
❑ Service compatibility that is based upon policy: The final principle enables services to
define policies (decided at runtime) that are required to consume the service. These policies are
usually expressed through WS-Policy.
If your own organization is considering establishing an SOA, the WCF is a framework that works
on these principles and makes it relatively simple to implement. The next section looks at what
the WCF offers. Then you can dive into building your first WCF service.
WCF Overview
As stated, the Windows Communication Foundation is a means to build
distributed applications in a Microsoft environment. Although the distributed application is built
upon that environment, this does not mean that consumers are required to be Microsoft clients
or to take any Microsoft component or technology to accomplish the task of consumption. On the
other hand, building WCF services means you are also building services that abide by the
principles set forth in the aforementioned SOA discussion and that these services are vendor
agnostic — thus, they are able to be consumed by almost anyone.
You can build WCF services using Visual Studio 2008. Note that because this is a
.NET Framework 3.0 component, you are actually limited to the operating systems in which you
can run a WCF service. Whereas the other Microsoft distribution technologies mentioned in this
chapter do not have too many limitations on running on Microsoft operating systems, an
application built with WCF can only run on Windows XP SP2, Windows Vista, or Windows Server
2008.
When you build a WCF project in this manner, the idea is that you build a
traditional class library that is compiled down to a DLL that can then be added to another project.
The separation of code and project is a powerful division on larger projects. That said, you can,
however, just as easily build a WCF service directly in your .NET project, whether that is a
console application or a Windows Forms application. The approach taken for the examples in this
chapter show you how to build a WCF service that is hosted in a console application. Keep in
mind that for the services you actually build and deploy, it is usually better to build them directly
as a WCF Service Library project and use the created DLL in your projects or in IIS itself.
Before we jump into building a WCF service, first consider what makes up a
service built upon the WCF framework.
Microsoft as the ABC of WCF. Each letter of WCF means something in particular in the WCF
model, including the following:
Basically, you can think of this as follows: ‗‗A‘‘ is the where, ‗‗B‘‘ is the how, and ‗‗C‘‘ is the what.
Finally, a hosting environment is where the service is contained. This constitutes an application
domain and process. All three of these elements (the service, the endpoints, and the hosting
environment) are put together to create a WCF service offering, as depicted.
The next step is to create a basic service using the WCF framework.
To build your service, prior to hosting it, you must perform two main steps. First,
you need to create a service contract. Second, you must create a data contract. The service
contract is really a class with the methods that you want to expose from the WCF service. The
data contract is a class that specifies the structure you want to expose from the interface.
Once you have a service class in place, you can host it almost anywhere. When
running this from Visual Studio 2010 / 2008, you will be able to use the same built-in hosting
mechanisms that are used by any standard ASP.NET application. To build your first WCF
application, select File – New - Web Site from the Visual Studio menu and call the project
WCFService1. The example this chapter will run through here demonstrates how to build the WCF
service by building the interface, followed by the service itself.
Click on OK.
Then it creates the WCF Service project.
Open the ―App_Code\IService.cs‖ file using Solution Explorer.
Write the code:
IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
int Add(int a, int b);
[OperationContract]
int Subtract(int a, int b);
[OperationContract]
int Multiply(int a, int b);
[OperationContract]
int Divide(int a, int b);
[OperationContract]
CompositeType GetSquareAndCube(int n);
// Use a data contract as illustrated in the sample below to add composite types to service
operations.
[DataContract]
public class CompositeType
{
int square_val;
int cube_val;
[DataMember]
public int Square
{
get { return square_val; }
set { square_val = value; }
}
[DataMember]
public int Cube
{
get { return cube_val; }
set { cube_val = value; }
}
}
Service.cs
return (a * b);
}
Default.aspx.cs
AJAX
(Asynchronous JavaScript and XML)
-------------------------- Request
-------------------------- (XmlHttpRequest)
--------------------------
Execute some Server Code
--------------------------
-------------------------- Response
-------------------------- (XmlHttpResponse)
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.
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
II. UpdatePanel:
This control contains the content, which is to be updated in AJAX model, on the post
back.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
The <ContentTemplate> tag contains the actual content. In this tag, you drag and
drop the controls, that you want.
If any control in the UpdatePanel requires post back, the entire page would not be
re-loaded. Just the required content would be updated with the support of call-back.
So, this feature improves the execution speed of the page.
ajaxdemo1.aspx.cs
Run the web site and test it. It works perfectly. The problem here is, when you click
on ―Add‖ button especially, you can observe a small blink in you page contents.
That‘s because of post-back. The entire page will be re-loaded. In fact, it is enough
to submit the ―a‖ and ―b‖ values here and get the result in the third textbox. So that,
you can implement AJAX here.
To do so, open toolbox; drag and drop the ―ScriptManager‖ control into the page at
the top (as shown on the screen).
Drag and drop the UpdatePanel control. It‘s like a normal panel control. You drag
and drop the necessary labels and textboxes, into the UpdatePanel (as shown the
screen).
That‘s it. Run the web site and test it directly on the browser. Now also, the output
will be displayed correctly, when you click on ―Add‖ button. But the thing is, the page
will not be posted-back; instead, ―call-back‖ will be performed.
Let‘s take one demo on AJAX.
Add the ―ajaxdemo2.aspx‖ page and design it as shown:
ajaxdemo2.aspx.cs
Run the web site and test it. Now, when you click on the first button the time will be
refreshed, without a post-back; because the button is inside of ―UpdatePanel‖
control. When you click on the second button, post-back will be performed as usual,
because it is not inside of ―UpdatePanel‖ control.
III. UpdateProgress:
This control is helpful, if it is taking much time to execute large amount of code,
while a call-back is being performed in an UpdatePanel.
This control contains the content, which is to be displayed while the page is getting
call back.
This improves the user-friendly nature.
This is useful, when you have large amount of code in the UpdatePanel.
By default, it contains some link with the UpdatePanel control.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
</ProgressTemplate>
</asp:UpdateProgress>
Demo on UpdateProgress:
ajaxdemo3.aspx.cs
Run the web site and test it. Now, it takes 3 seconds, to refresh the time.
In these 3 seconds of duration, no indication is given to the user. So, at this time,
the user may be in dynamo, whether the site is working properly or not.
To solve this problem, drag and drop the ―UpdateProgress‖ control into the same
page and design it as shown:
Now, run the web site and test it. When you click on ―Refresh‖ button now, the
―loading…‖ message and the hour glass image will be displayed for that 3 seconds of
duration.
IV. Timer:
This control is same as ―Timer‖ control in Windows Applications.
It executes certain process repetitively at every completion of certain interval time.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:Timer ID="Timer1" runat="server">
</asp:Timer>
Demo on Timer:
ajaxdemo3.aspx.cs
AJAXControlToolKit
Demo:
Open the previous demo web site.
Add the ―AjaxToolkitDemo.aspx‖ page.
Download the ―AjaxControlToolkit.dll‖ file from
Microsoft‘s web site.
URL: http://www.asp.net/ajax
Right click on the toolbox and select ―Add Tab‖.
A new tab will be created in the toolbox. Enter a
meaningful name of the new tab. Ex: ―AJAX
Toolkit‖.
Right click on ―AJAX Toolkit‖ tab and select
―Choose Items‖.
Click on Browser and select the
―AjaxControlToolkit.dll‖ file from the download
location.
Click on OK.
Then automatically all the controls will be added to
that tab.
In this session, we are covering most important
controls of this toolkit, which may be generally
used in the now-a-days live projects development.
Note: Most of the AJAX toolkit controls are
extenders. The extender controls works depending
on other controls.
Continued…
If you are using AjaxControlToolkit.dll v3.5 or higher, drag and drop the
―ToolKitScriptManager‖ control from the toolbox, on to the top of the page (as shown on
the screen). If you are using older version of AjaxControlToolkit.dll (v2.0, v3.0 etc.) then
use ―ScriptManager‖ control, because ―ToolKitScriptManager‖ control is not available.
Select the ―First Name‖ textbox and click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―DropShadowExtender‖ option.
Click on OK.
That‘s all. A shadow will be displayed at run time, under the ―first name‖ textbox.
Output:
Click on OK.
Run the web site. Click on ―Submit‖ button, without entering the first name.
Then the validation message will be displayed like this:
Click on OK.
Set the properties of TextBox3:
WatermarkText: mm/dd/yyyy
WatermarkCssClass: mywater
Add ―StyleSheet.css‖ file.
Type the code:
StyleSheet.css
.mywater
{
background-color: Gray;
color: Silver;
}
Run the web site and observe the date of birth textbox. The watermark text will be
displayed in specified CSS style. Output:
Click on OK.
Run the web site and observe the ―date of joining‖ textbox. It displays the calendar, and
then the cursor enters into the textbox. Click on any date. Then the selected date will be
displayed in the textbox.
Output:
Click on OK.
Run the web site and observe the ―password‖ textbox. While you type the password in the
textbox, it displays the strength of it (Low / Very Low / Average / Strong / Excellent /
Unbreakable etc.).
Output:
Click on OK.
Run the web site. It allows you to type few characters, to quickly select the medicine
names in the dropdown list.
Output:
Click on OK.
Run the web site. Even though you scroll the web page, the image always will be
displayed on the screen.
Output:
WPF
(Windows Presentation Foundation)
XAML
Extensible Application Markup Language (XAML) is an XML syntax used to define the
hierarchical structure of the user interface.
In the following line, you can see the declaration of a button named button1 with the
content ―Click Me!‖.
The <Button> element specifies the use of the Button class:
<Button Content=”Click Me!” Background=”LightGreen” />
There‘s always a .NET class behind an XAML element.
With attributes and child elements, you set the value of properties.
Click on OK.
Then the Visual Studio window will be appeared like this:
Note: Every WPF window contains two files.
1. Windowname.xaml
2. Windowname.xaml.cs
Properties
The XAML language supports the properties to be written in two ways.
1. Properties as Attributes:
The properties can be written as attributes.
Ex: <Button Content=‖Click Me!‖ Background=‖LightGreen‖ />
2. Properties as Elements:
Ex:
<Button>
<Button.Background>
LightGreen
</Button.Background>
Click Me!
</Button>
WPF Controls
Sl.
Control Description
No
1 Button Responds for Click event.
2 CheckBox Can be checked or un-checked.
3 RadioButton Can be checked or un-checked with grouping nature.
4 TextBox Used to take input values.
Used to develop the text editing applications with better features
5 RichTextBox
than TextBox.
6 PasswordBox Used to take passwords.
7 ScrollBar Can be scrolled by the user.
8 Slider Same as TrackBar in windows forms applications.
9 ProgressBar Displays the progress of a particular task.
10 Label Displays a static message.
11 Menu Displays a menu bar.
12 ContextMenu Displays a context menu, whenever you right click on a control.
13 TabControl Contains multiple tabs.
14 TreeView Contains several tree nodes.
15 Border Displays a border around the specified area.
16 Grid Contains the controls in the form of rows and columns.
17 Image Displays an image.
18 Rectangle Displays a rectangle.
19 Ellipse Displays an ellipse or circle.
20 Canvas Similar to Panel control in windows forms applicationn.
21 WrapPanel Similar to FlowLayoutPanel control windows forms applications.
Window1.xaml.cs
Shapes
Line
<Line X1="xxx" Y2=" xxx" X2=" xxx" Y2=" xxx" Stroke="xxx" StrokeThickness="xxx" />
Rectangle
<Rectangle Name="xxx" Top="xx" Left="xx" Width="xx" Height="xx" Stroke="xxx" />
Ellipse
<Ellipse Name="xxx" Top="xx" Left="xx" Width="xx" Height="xx" Stroke="xxx" />
Path (Curve)
<Path Stroke="xxx" StrokeThickness="xx" Data="xxx" />
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Canvas>
<Ellipse Canvas.Left="50" Canvas.Top="50" Width="100" Height="100"
Stroke="Blue" StrokeThickness="4" Fill="Yellow" />
<Ellipse Canvas.Left="60" Canvas.Top="65" Width="25" Height="25"
Stroke="Blue" StrokeThickness="3" Fill="White" />
<Ellipse Canvas.Left="70" Canvas.Top="75" Width="5" Height="5"
Fill="Black" />
<Path Stroke="Blue" StrokeThickness="4"
Data="M 62,125 Q 95,122 102,108" />
<Line X1="124" X2="132" Y1="144" Y2="166" Stroke="Blue"
StrokeThickness="4" />
<Line X1="114" X2="133" Y1="169" Y2="166" Stroke="Blue"
StrokeThickness="4" />
<Line X1="92" X2="82" Y1="146" Y2="168" Stroke="Blue"
StrokeThickness="4" />
<Line X1="68" X2="83" Y1="160" Y2="168" Stroke="Blue"
StrokeThickness="4" />
</Canvas>
</Grid>
</Window>
Transformation
1. RotateTransform
<ControlName.LayoutTransform>
<RotateTransform Angle=‖xx‖ />
</ControlName.LayoutTransform>
2. SkewTransform
<ControlName.LayoutTransform>
<SkewTransform AngleX=‖xx‖ AngleY=‖xx‖ />
</ControlName.LayoutTransform>
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Button Margin="-113,45,-139,0" Name="button1" Height="44"
VerticalAlignment="Top">
<Button.LayoutTransform>
<RotateTransform Angle="40" />
</Button.LayoutTransform>
Rotate Transformation Button
</Button>
<Button HorizontalAlignment="Left" Margin="35,100,0,58" Name="button2"
Width="170">
<Button.LayoutTransform>
<SkewTransform AngleX="3" AngleY="28" />
</Button.LayoutTransform>
Skew Transformation Button
</Button>
</Grid>
</Window>
Brushes in WPF
The brushes can be used for backgrounds / foregrounds for any control. Use the
following syntaxes within <ControlName.Background> or <ControlName.Foreground>
tags.
SolidColorBrush
<SolidColorBrush>xxxx</SolidColorBrush>
LinearGradientBrush
<LinearGradientBrush StartPoint=‖xx,xx‖ EndPoint=‖xx,xx‖>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
</LinearGradientBrush>
RadialGradientBrush
<RadialGradientBrush Center=‖xx,xx‖ GradientOrigin=‖xx,xx‖ RadiusX=‖xx‖
RadiusY=‖xx‖ SpreadMethod=‖xx‖>
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
</RadialGradientBrush>
DrawingBrush
<DrawingBrush>
<DrawingBrush.Drawing>
<GeometryDrawing Brush=‖xxx‖>
<GeometryDrawing.Geometry>
<GeometryGroup>
<EllipseGeometry RadiusX=‖xx‖ RadiusY=‖xx‖ Center=‖xx,xx‖ />
<EllipseGeometry RadiusX=‖xx‖ RadiusY=‖xx‖ Center=‖xx,xx‖ />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen>
<Pen.Brush>xxx</Pen.Brush>
</Pen>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
ImageBrush
<ImageBrush ImageSource=‖xxxxx‖ />
VisualBrush
<VisualBrush>
<VisualBrush.Visual>
<StackPanel Background=‖xxx‖>
<Rectangle Width=‖xx‖ Height=‖xx‖ Fill=‖xxx‖ Margin=‖xx‖ />
<Ellipse Width=‖xx‖ Height=‖xx‖ Fill=‖xxx‖ Margin=‖xx‖ />
<Button Margin=‖x‖>xxx</Button>
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Width="403" Height="352">
<Button Margin="21,14.5,0,0" HorizontalAlignment="Left" Width="127" Height="30"
VerticalAlignment="Top">
<Button.Background>
<SolidColorBrush>Yellow</SolidColorBrush>
</Button.Background>
Solid Color
</Button>
<Button Margin="21,86,0,0" HorizontalAlignment="Left" Width="127" Height="35.5"
VerticalAlignment="Top">
<Button.Background>
<LinearGradientBrush StartPoint="0,0"
EndPoint="0.5,1.2">
</Button.Background>
<Button.Foreground>White</Button.Foreground>
Image Brush
</Button>
<Button Margin="0,0,77,45" Height="78" HorizontalAlignment="Right"
VerticalAlignment="Bottom" Width="108">
<Button.Background>
<VisualBrush >
<VisualBrush.Visual>
<StackPanel Background="White">
<Rectangle Width="25" Height="25" Fill="LightCoral" Margin="2" />
<Ellipse Width="65" Height="20" Fill="Aqua" Margin="5" />
<Button Margin="2">A Button</Button>
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
</Button.Background>
Visual Brush
</Button>
<Button Margin="0,86,62,146.139" HorizontalAlignment="Right" Width="138">
<StackPanel>
<Border x:Name="reflected">
<Border.Background>Yellow</Border.Background>
<StackPanel>
<Label>Visual Brush 2</Label>
<Rectangle Width="70" Height="15" Margin="2"
Fill="BlueViolet" />
</StackPanel>
</Border>
<Rectangle Height="30">
<Rectangle.Fill>
<VisualBrush Opacity="0.35" Stretch="None"
Visual="{Binding ElementName=reflected}">
<VisualBrush.RelativeTransform>
<TransformGroup>
Click on OK.
Click on OK.
Then the Visual Studio window will be appeared like this:
ASP.NET 4.0
Frequently
Asked
Questions
(FAQ’s)
ASP.NET FAQ's
What is view state and use of it?
The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within
the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted
(sent to the server), which allows you to program accordingly.
User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control.
An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The
ASP.NET page framework compiles a user control on the fly to a class that derives from the
System.Web.UI.UserControl class.
Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
CachingOutput Caching: Caches the dynamic output generated by a request. Some times it
is useful to cache the output of a website even for a minute, which will result in a
better performance. For caching the whole page the page should have OutputCache
Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical
to cache the entire page, in such cases we can cache a portion of page <%@ OutputCache Duration="120"
VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching asp.net provides a cache object for
eg: cache["States"] = dsStates;
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included
only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control:Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be
included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more
than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @
Import Namespace="System.web" %>
@Implements: Indicates that the current page or user control implements the specified .NET framework
interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in custom server control
syntax. <%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes
and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly
Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control
contained in a page
<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None"
Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should be dynamically
compiled and linked against the page in which this directive is declared.
How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't
use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you
want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug
Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe
doesn't appear in the list,check the "Show system processes" box.) Click the Attach button to attach to
aspnet_wp.exe and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET
to build debug executables by placing a <%@ Page Debug="true" %> statement at the top of an ASPX
file or a <COMPILATION debug="true" />statement in a Web.config file.
What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP
True or False: To test a Web service you must create a windows application or Web application to
consume this service?
False.
The idea is to pass a method in the invocation of the web method. When the webmethod has finished it will
call this callback function to process the result
2. Synchronous Call
Application has to wait until execution has completed.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by
uncommenting the line in the <HTTPHANDLERS>section of Machine.config that maps *.vsdisco to
System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission
to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because
they could represent a threat to Web server security.
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this
example, it prevents caching of a Web page that shows the current time.
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM
components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves
the performance of calls that the page places to apartment- threaded COM objects by ensuring that the
page (actually, the thread that processes the request for the page) and the COM objects it creates share an
apartment. AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If
those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the
same STAs as the threads that created them. Without AspCompat="true," request threads run in a
multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when
it's marshaled across apartment boundaries. Do not set AspCompat to true if your page uses no COM
objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered
ThreadingModel=Free or ThreadingModel=Both.
How do I provide information to the Web Service when the information is required as a SOAP Header?
The key here is the Web Service proxy you created using wsdl.exe or through Visual Studio .NET's Add
Web Reference menu option. If you happen to download a WSDL file for a Web Service that requires a
SOAP header, .NET will create a SoapHeader class in the proxy source
file. Using the previous example:
What is WSDL?
WSDL is the Web Service Description Language, and it is implemented as a specific XML vocabulary. While
it's very much more complex than what can be described here, there are two important aspects to WSDL
with which you should be aware. First, WSDL provides instructions to consumers of Web Services to describe
the layout and contents of the SOAP packets the Web Service intends to issue. It's an interface description
document, of sorts. And second, it isn't intended that you read and interpret the WSDL. Rather, WSDL should
be processed by machine, typically to generate proxy source code (.NET) or create dynamic proxies on the
fly (the SOAP Toolkit or Web Service Behavior).
What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
Windows service is an application that runs in the background. It is equivalent to a NT service. The
executable created is not a Windows application, and hence you can't just click and run it. It needs to be
installed as a service, VB.Net has a facility where we can add an installer to our program and then use a
utility to install the service; whereas this is not the case with standard exe