Você está na página 1de 558

D.

HARSHA VARDHAN

Microsoft® .NET Framework 4.0

And

ASP.NET

Author: Mr. Harsha Vardhan


.NET 4.0 and Visual Studio 2010 Page 1 of 558
D. HARSHA VARDHAN

.NET Framework 4.0 and Visual Studio 2010


ASP.NET Training Program Schedule

Trainer: D. Harsha Vardhan Duration: 47 Hours

Chapter – I: Web Programming Basics

Hour 1 Introduction to Web Programming Page 5


Hour 2 HTML Page 12
Hour 3 JavaScript Page 17
Hour 4 ASP Page 32
Hour 5 Web Servers, IIS Page 37

Chapter – II: ASP.NET Web Site Development Basics

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

.NET 4.0 and Visual Studio 2010 Page 2 of 558


D. HARSHA VARDHAN

Chapter – III: Data Access in ASP.NET with ADO.NET support

Hour 13 SQL Server Basics Page 112


Hour 14 ADO.NET Basics, ADO.NET Library and ADO.NET Database Connection Page 123
Hour 15 Sending Commands to the Database using Command Class Page 133
Hour 16 Retrieving Data using Command and DataReader Page 145
Hour 17 Retrieving Data using DataAdapter, DataSet, DataTable, DataRow, Page 157
DataColumn
Hour 18 Working with Stored Procedures and Functions Page 173
Hour 19 Data Controls Page 185
Hour 20 Crystal Reports Page 225

Chapter – IV: Rich ASP.NET Web Sites

Hour 21 Validation Controls Page 235


Hour 22 Navigation Controls Page 242
Hour 23 Login Controls and Configuring E-Mail Server Page 265
Hour 24 WebParts Controls Page 297
Hour 25 State Management with Query String, Cookies Page 306
Hour 26 Session State and Application State, View State, global.asax Page 313
Hour 27 Cascading Style Sheets (CSS), Themes and Skins Page 333
Hour 28 Web User Controls and Master Pages Page 352
Hour 29 Caching Page 370
Hour 30 Displaying Dialog boxes, Popup windows, StatusBar messages using Page 379
JavaScript

.NET 4.0 and Visual Studio 2010 Page 3 of 558


D. HARSHA VARDHAN

Chapter – V: Advanced ASP.NET

Hour 31 LINQ Page 387


Hour 32 LINQ to SQL Page 396
Hour 33 XML Page 406
Hour 34 Web Site Configuration Page 410
Hour 35 Session State Modes, ASP.NET Configuration Tool, Tracing Page 423
Hour 36 Security in ASP.NET, Windows based Authentication Page 442
Hour 37 Forms based Authentication, Role based Authentication Page 447
Hour 38 Localization and Globalization Page 465
Hour 39 Sending E-Mails with SMTP Page 476
Hour 40 Web Services Page 485
Hour 41 Web Services Page 488
Hour 42 WCF Page 494
Hour 43 WCF Page 499
Hour 44 Introduction to AJAX, AJAX Extensions Page 507
Hour 45 AJAX Control Toolkit Page 518
Hour 46 Introduction to WPF, WPF Application Development, XAML Page 535
Hour 47 WPF Design Layouts, Shapes, Brushes, Transformations Page 540

Chapter – VI: Mini Project

Chapter – VII: FAQ’s

.NET 4.0 and Visual Studio 2010 Page 4 of 558


D. HARSHA VARDHAN

Web Programming Basics


 In the modern world, internet is being used by everyone.
 On the internet, we can find so many (around crores) or web sites.
 Those web sites are stored in the web servers and can be accessible from any system
(web client) that is connected with Internet.
 To access the web site, the user requires a software called ―Browser‖.
 We have several browsers available in the market.
 Microsoft Internet Explorer
 Mozilla Firefox
 Google Chrome
 Safari
 Netscape Navigator
etc.
 The user can use any browser, based on his-own choice.
 The first graphical-based browser is Mosaic, which is released in 1993.
 While the web site is being transferred from web server to the web client, it should be
converted in binary format, using a protocol called ―HTTP‖ (Hypertext Transfer Protocol).
 In other words, all the web sites will be maintained using HTTP protocol.
 Let us discuss how we are opening a web site.
 Suppose you want to open Google web site.
 First we open the browser (Microsoft Internet Explorer or any other browser).
 Then we type the URL of the web site in the address bar. Ex: www.google.co.in

.NET 4.0 and Visual Studio 2010 Page 5 of 558


D. HARSHA VARDHAN

 Then press Enter.


 Then a ―Request‖ will be sent to the web site.
 The request will be travelled through the web and will be received by the web server.
 Based on the given URL, the web server serves the home page of the web site to the
web client, as ―Response‖.
 Let me show this interaction visually.

.NET 4.0 and Visual Studio 2010 Page 6 of 558


D. HARSHA VARDHAN

A typical web

Web Server

Web Site

Web Client 1

Browser

Request

Response

Web Web Client 2


(http)

.NET 4.0 and Visual Studio 2010 Page 7 of 558


D. HARSHA VARDHAN

Basic Terminology in Web

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

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

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

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

 Browser:
 In the client system, to open the web sites, a software should be there.
 That software is called as ―Browser‖.
 As you know, there are so many browsers are available in the market.
 Every browser should able to execute the following code:

.NET 4.0 and Visual Studio 2010 Page 8 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 9 of 558


D. HARSHA VARDHAN

Development Process of a Web Site

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

I. Page Designing Stage:


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

II. Client Side Programming Stage:


 This includes with writing some programs for client system.
 These programs will be executed in the client system.
 In other words, as a part of the interaction between the client system and server
system, some programs are needed for the client and some other for server.
 The client level programs are called as ―Client side programs‖ and server level
programs are called as ―Server side programs‖.
 Especially, the browser itself executes the client side programs.
 These client side programs perform the client level operations like client level
calculations, validating the user-input values whether those values are valid or invalid
and sending a request to the web server etc.
 To write the client side programs, we take the support of client side programming
languages:
A. JavaScript
B. VBScript (outdated)

.NET 4.0 and Visual Studio 2010 Page 10 of 558


D. HARSHA VARDHAN

III. Server Side Programming Stage:


 As you know, the server side code will be executed at web server system, and then
the output will be given as response to the client.
 This server side programming includes with receiving the request from the client,
getting some input values from the client, making some operations on the input
values and giving the response to the client.
 To write the server side programs, we take the support of server side programming
languages.
A. ASP (Active Server Pages)
B. ASP.NET (Active Server Pages.NET)
C. JSP (Java Server Pages)
D. PHP (Pre-Hypertext Processive)
 Currently, in our course, we are concentrating on Microsoft technologies like ASP and
ASP.NET.

.NET 4.0 and Visual Studio 2010 Page 11 of 558


D. HARSHA VARDHAN

HTML
(Hyper Text Markup Language)

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

<tag>
some content
</tag>

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


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

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

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


This above example the specified image on the screen.

 It is used to design the static web pages.


 Types of web pages:
1. Static Web Pages: These web pages contain some content, which will
not be changed at run time.
Ex: login page.

.NET 4.0 and Visual Studio 2010 Page 12 of 558


D. HARSHA VARDHAN

2. Dynamic Web Pages: These web pages content can be changed at


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

.NET 4.0 and Visual Studio 2010 Page 13 of 558


D. HARSHA VARDHAN

A Simple Web Page Development using HTML

Application 1: A Simple HTML page

 Open any editor (Notepad or Edit Plus).


 Type the html code as follows:

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


 Open the folder, in which you have saved the file. (Ex: Open Desktop).
 Double click on ―sample.html‖.
 Then the html page will be displayed on the browser.

.NET 4.0 and Visual Studio 2010 Page 14 of 558


D. HARSHA VARDHAN

 You can observe the title bar text as you mentioned in the <title> tag.
 You can observe the web page content, as you written in <body> tag.

Understanding the HTML Syntax

 The html program syntax contains few tags as follows.

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

.NET 4.0 and Visual Studio 2010 Page 15 of 558


D. HARSHA VARDHAN

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

Understanding the concept of Attributes

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


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

The <body> tag attributes

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


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

Important HTML Tags


1) Basic tags:
<HTML>
<HEAD>
<BODY>
<TITLE>
<META>
<SCRIPT>
<STYLE>

.NET 4.0 and Visual Studio 2010 Page 16 of 558


D. HARSHA VARDHAN

2) Text Formatting tags:


<H1>
<H2>
<H3>
<H4>
<H5>
<H6>
<FONT>
<BR>
<DIV>
<CENTER>
<B>
<I>
<U>
<TT>
<STRIKE>
<PRE>
<SUP>
<SUB>
<P>

3) Link tags:
<A>

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

5) Multi-media tags:
<IMG>
<HR>
<BGSOUND>
<MARQUEE>

.NET 4.0 and Visual Studio 2010 Page 17 of 558


D. HARSHA VARDHAN

6) Table tags:
<TABLE>
<CAPTION>
<TR>
<TH>
<TD>

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

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

We understand HTML tags with an example.

Application 2: Demo on important HTML tags

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>

.NET 4.0 and Visual Studio 2010 Page 18 of 558


D. HARSHA VARDHAN

<hr>

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

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


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

<p align="justify">
<font size="4" face="Century Gothic">
<font color="green">
.NET Framework latest version 4.0. .NET Framework latest version
4.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>

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

<div align="right">
This is normal text.<br>

.NET 4.0 and Visual Studio 2010 Page 19 of 558


D. HARSHA VARDHAN

<b>This is bold text.</b><br>


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

<hr>

<center>

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

</center>

<hr>

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

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

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


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

<hr>

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

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

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

.NET 4.0 and Visual Studio 2010 Page 20 of 558


D. HARSHA VARDHAN

<a href="c:\SilverJubilee.wmv">
Click here to watch the video</a><br>

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

</font>

<font face="Tahoma">
<hr>

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


<caption>Students Table</caption>

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

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

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

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

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

</table>
</font>
</body>
</html>

.NET 4.0 and Visual Studio 2010 Page 21 of 558


D. HARSHA VARDHAN

Output:

(Continued…)

.NET 4.0 and Visual Studio 2010 Page 22 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 23 of 558


D. HARSHA VARDHAN

Application 3: Demo on HTML forms

registration.html

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

<h1>ABC Technical Training Institute</h1>


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

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

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

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

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

<input type="checkbox">Documents submitted?<br>

Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>

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

Resume Attachment:
<input type="file">

.NET 4.0 and Visual Studio 2010 Page 24 of 558


D. HARSHA VARDHAN

<input type="button" value="Add">


<br>

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

Select your Course(s):


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

<hr>

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

<hr>

</center>
</form>
</body>
</html>

.NET 4.0 and Visual Studio 2010 Page 25 of 558


D. HARSHA VARDHAN

Output:

.NET 4.0 and Visual Studio 2010 Page 26 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 27 of 558


D. HARSHA VARDHAN

The Syntax of JavaScript Code

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

Application 4: Demo on JavaScript Validations

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>

.NET 4.0 and Visual Studio 2010 Page 28 of 558


D. HARSHA VARDHAN

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

<input type="checkbox">Documents submitted?<br>

Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>

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

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

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

Select your Course(s):


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

<hr>

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

<hr>

</center>
</form>
</body>
</html>

.NET 4.0 and Visual Studio 2010 Page 29 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 30 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 31 of 558


D. HARSHA VARDHAN

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

Client Page (filename.html) Server Page (filename.asp)

Form //receive the values


from the client page

//implement some
server side operations

//send some response


Request to the client (browser)
Submit Query

.NET 4.0 and Visual Studio 2010 Page 32 of 558


D. HARSHA VARDHAN

Application 5: Demo on Login

loginclient.html (save this file in any folder)

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

.NET 4.0 and Visual Studio 2010 Page 33 of 558


D. HARSHA VARDHAN

'Server side logic


If s1="system" And s2="manager" Then
'Give the Response
Response.Write("You are successfully Logged in..")
Else
'Give the Response
Response.Write("Invalid Username / Password..")
End If
%>
</h1>
</center>
</body>
</html>

 To run this application, double click on ―loginclient.html‖. Enter the user name and
password.
 If you enter the correct user name and password (system and manager), it opens the
server page and shows ―You are successfully Logged in…‖ message, otherwise it shows
―Invalid Username / Password‖ message.

.NET 4.0 and Visual Studio 2010 Page 34 of 558


D. HARSHA VARDHAN

After clicking on Submit button…

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

.NET 4.0 and Visual Studio 2010 Page 35 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 36 of 558


D. HARSHA VARDHAN

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

Web Server Root Directory:


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

.NET 4.0 and Visual Studio 2010 Page 37 of 558


D. HARSHA VARDHAN

Web Server

IIS

Web Site

port

Web Client 1 Web Client 2

 Each web technology is having its own supporting web server(s):

Web Technology Web Server


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

Finally, ASP is supported in IIS only; and ASP.NET is supported in IIS and ASP.NET
Development Server also.

.NET 4.0 and Visual Studio 2010 Page 38 of 558


D. HARSHA VARDHAN

IIS (vs) ASP.NET Development Server


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

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


 Try to find the following folder:
C:\Inetpub\wwwroot
 If the above specifies folder is there, and then you can understand that, you have IIS
software on your system; so that your system can act as a web server.

.NET 4.0 and Visual Studio 2010 Page 39 of 558


D. HARSHA VARDHAN

Installing IIS:
 Insert bootable Windows CD / DVD.
 Click ―Start‖ – ―Control Panel‖.
 Open ―Add / Remove Programs‖.
 Click on ―Add / Remove Windows Components‖.

 Check the checkbox for ―Internet Information Services‖ option.

 Click ―Next‖ button.


 Then necessary files will be copied and IIS will be loaded on your system.

.NET 4.0 and Visual Studio 2010 Page 40 of 558


D. HARSHA VARDHAN

Checking the Functionality of IIS, whether it is working properly or not:


 Open the browser.
 Type the following URL:
http://localhost/
 Press Enter.
 Then it shows home of the IIS as follows:

 If you find the above type of screen, then you can understand as IIS is working on your
system.
 If you find the following error page, then you can understand as IIS is not working
properly on your system (or) IIS is not installed on your system.

.NET 4.0 and Visual Studio 2010 Page 41 of 558


D. HARSHA VARDHAN

 Note that, generally when you switch-on your system, then the IIS services also be
started automatically.
 Because of some reasons, sometimes it may not be started by default. Then you need to
start the IIS services manually.

Starting / Stopping the Services of IIS:


 Click on ―Start‖ – ―Run‖.
 Type ―inetmgr‖ and press Enter.
 Then ―Internet Information Services‖ window will be displayed.
 There, expand the local computer.
 Then expand ―Web Sites‖.
 Then observe ―Default Web Site‖.
 If it is already started, no message will be shown there.
 If it is stopped, it will be displayed as ―Default Web Site (Stopped)‖.

.NET 4.0 and Visual Studio 2010 Page 42 of 558


D. HARSHA VARDHAN

 Then you try to start the services, by right clicking on the ―Default Web Site‖ option, and
by clicking on ―Start‖.

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

Clash between IIS and Oracle HTTP Server:


IMP Note: If you have Oracle software also installed in your system, the IIS
services can‘t be started, even though you try to start the IIS services as above; because by
default Oracle HTTP server‘s services will be started automatically; and both of these servers use
the same port no ―80‖. Then IIS will not work, even though you have installed it properly. Then
to solve this problem, first stop the Oracle HTTP Server by click on ―Start‖ – ―Programs‖ – ―Oracle
– OraHome‖ – ―Oracle HTTP Server‖ – ―Stop Oracle HTTP Server power by Apache‖. After that,
you try to start the IIS services, as explained above. Then IIS services will be started for sure. If
not yet, contact any network administrator.

.NET 4.0 and Visual Studio 2010 Page 43 of 558


D. HARSHA VARDHAN

Understanding the URL in IIS:


 When you store a web page in the web server‘s root directory, then only you can access
it from the same system or any other client on the network also.
 Suppose you have stored ―loginclient.html‖ page in the ―c:\Inetpub\wwwroot‖ folder.
Then the file full path can be mentioned as:
c:\inetpub\wwwroot\loginclient.html
 But you can‘t access the web page with the above specified path from other computers;
because it is representing physical hard disk addressing.
 So that you have to access the page with logical address as follows:
Syn: http://<servername>/pagename.extension
Ex: http://myserver/loginclient.html
 Here, you have to mention the name of the server system, in which you have stored the
web page. You can also use the word ―localhost‖, to represent the same system.
Syn: http://localhost/pagename.extension
Ex: http://localhost/loginclient.html

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

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


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

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


 You try to create your own folder in the ―wwwroot‖ folder; then you store the required
files, for your project in that your own folder.
 For example, create a folder called ―test‖ in the ―wwwroot‖ folder.

.NET 4.0 and Visual Studio 2010 Page 44 of 558


D. HARSHA VARDHAN

 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‖.

.NET 4.0 and Visual Studio 2010 Page 45 of 558


D. HARSHA VARDHAN

ASP.NET
(The Modern Generation Web Technology)

 ASP.NET stands for Active Server Pages.NET.


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

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

Types of Web Sites


1) Traditional Web Sites:
 This type of web sites are in usage, before ASP.NET (before 2002).
 According to this, for every interaction, two web pages will be maintained:
 Client Page (.html)
 Server Page (.aspx)

.NET 4.0 and Visual Studio 2010 Page 46 of 558


D. HARSHA VARDHAN

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

Client Page (filename.html) Server Page (filename.aspx)

Form //receive the values


from the client page

//implement some
server side operations

//send some response


Request to the client (browser)
Submit Query

2) Post-backing Web Sites:


 This is introduced in ASP.NET (in 2002).
 In this kind of web sites also, “Submit – Request – Response” operations are
performed; but instead of maintaining two pages, only single page will be
maintained; and that page should be a server page.
 Ex: An ASP.NET server page will be submitted to the same page.
 PostBack: A page will be submitted to itself.
 For example, when we click on a button in ASP.NET, the page will be submitted
to itself. That means ―PostBack‖ is happened there.
 This facilitates us to reduce the no. of pages in the pages; so that maintenance
is easy; and clumsiness will be reduced.
 When compared with ―Traditional web sites‖, these web sites are the next
generation web sites.

.NET 4.0 and Visual Studio 2010 Page 47 of 558


D. HARSHA VARDHAN

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

ASP.NET Server Page (filename.aspx)

Form

Submit
Postback

3) AJAX Web Sites:


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

.NET 4.0 and Visual Studio 2010 Page 48 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 49 of 558


D. HARSHA VARDHAN

Getting Started with ASP.NET


Application 6: Beginning with ASP.NET Web Sites

Creating a new ASP.NET Web Site:


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

 Select the language as ―Visual C#‖.


 Select ―ASP.NET Empty Web Site‖.
 Select Web Location: File System / HTTP / FTP
1. File System: If you select this option, you can give any path for saving
the web site. Ex: D:\MyWebSites\WebSite1. Then your web site will be
configured in ASP.NET Development Server automatically.
2. HTTP: If you select this option, you can give the HTTP URL only. Ex:
http://localhost/WebSite1. Then your web site will be configured in IIS
automatically.

.NET 4.0 and Visual Studio 2010 Page 50 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 51 of 558


D. HARSHA VARDHAN

Adding Web Pages to the Web Site:


 Open the solution explorer.
 Right click on the web site name and choose ―Add New Item‖.
 Then select ―Web Form‖.
 Enter the name of the new page. Ex: Default.aspx
 Then click on ―Add‖.

.NET 4.0 and Visual Studio 2010 Page 52 of 558


D. HARSHA VARDHAN

Adding HTML Pages to the Web Site:


 Open the solution explorer.
 Right click on the web site name and choose ―Add New Item‖.
 Then select ―HTML Page‖.
 Enter the name of the new page. Ex: sample.html / sample.htm.
 The default extension is ―.htm‖.
 Then click on ―Add‖.

.NET 4.0 and Visual Studio 2010 Page 53 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 54 of 558


D. HARSHA VARDHAN

Development of Web Pages


 The next thing you need to continue is how to develop the web pages.
 Your page development contains two stages:
 Designing
 Coding

i) Development of Web Pages

 At first, try to design the web page with html tags.


 As you know about html tags already try to type some html code in ―Default.aspx‖ file, in
the <form> tag as follows:

 Press F5 to run the web site.


 Then the page will be executed on the browser automatically and it looks like as follows:

.NET 4.0 and Visual Studio 2010 Page 55 of 558


D. HARSHA VARDHAN

 Close the browser and come back to the Visual Studio.


 This is nothing but designing the web page with html tags.
 You can view the web page in 3 views:
1. Source view: By default, you are in ―Source‖ view. It shows the design code in
the form of tags.

.NET 4.0 and Visual Studio 2010 Page 56 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 57 of 558


D. HARSHA VARDHAN

 Without the writing the tags manually, you can design the web page by dragging and
dropping the controls from Toolbox into the page also.
 To practice this, try to do as follows.
 Right click on ―Solution Explorer‖ – ―Add New Item‖ – ―Web Form‖ – ―mypage.aspx‖ -
―Add‖.
 Open Toolbox.
 Drag and drop 3 labels, 3 textboxes and a button into the page as follows:

 Set the following properties:


Label1:
Text: Enter First Number:
Label2:
Text: Enter Second Number:
Button1:
Text: Add
Label3:
Text: Result:

.NET 4.0 and Visual Studio 2010 Page 58 of 558


D. HARSHA VARDHAN

 The screen looks like this:

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

.NET 4.0 and Visual Studio 2010 Page 59 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 60 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 61 of 558


D. HARSHA VARDHAN

Implementation of In-page Technique:


 Open solution explorer.
 Right click on the web site name and choose ―Add New Item‖.
 Select ―Web Form‖.
 Un-check the check box called ―Place code in separate file‖. (By default it will be
checked).
 Enter the name of the new page as ―inpagetest.aspx‖.

 Click on ―Add‖.
 Click on ―Design‖ view.
 Drag and drop a button control.
 Double click on that and see where the Button1_Click event will be generated.
 It will be generated in the ―.aspx‖ file only, instead of ―.aspx.cs‖ file.

.NET 4.0 and Visual Studio 2010 Page 62 of 558


D. HARSHA VARDHAN

 This is the implementation of ―In-page technique‖.

Every page is a class:


In behind of every page, there will be a class; So that when you run the page on the browser, an
object will be created for that class automatically. That means if 5 users open the same page, it
means there are 5 objects for the page class.

.NET 4.0 and Visual Studio 2010 Page 63 of 558


D. HARSHA VARDHAN

Implicit Objects in ASP.NET Serer Pages

 For ASP.NET web page, the following objects are commonly available. That means, you
don‘t require creating these objects.

Object Class Description

Represents the request that is sent by


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

Used to give the response to the


Response System.Web.HttpResponse
client (browser).

Represents the current session state


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

Represents the application state of


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

Understanding the above objects:

1) Request:

Gets the value of the control, submitted from


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

Gets the value of the parameter, submitted


Request.Params[―parameter name‖]
from the previous client or server page.

.NET 4.0 and Visual Studio 2010 Page 64 of 558


D. HARSHA VARDHAN

2) Response:

Writes the text or html tags to the web page


Response.Write(―xxxx‖);
output.

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

3) Session:

Gets the value of the given session state


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

4) Application:

Gets the value of the given application state


Application[―variable name‖]
variable
Gets the total no. of application state
Application.Count
variables.

.NET 4.0 and Visual Studio 2010 Page 65 of 558


D. HARSHA VARDHAN

The Page Life Cycle

 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

Load the content into


memory

Render

Unload

.NET 4.0 and Visual Studio 2010 Page 66 of 558


D. HARSHA VARDHAN

The Page Events


Based on the above page life cycle, the following events will be executed on the page. In
order to implement the code for the following events, follow the below syntax:

protected void Page_eventname(object sender, EventArgs e)


{
//some code
}

Ex:

protected void Page_Load(object sender, EventArgs e)


{
//some code
}

Event Description

PreInit Executes before initializing the implicit objects of the page.


Init Executes after initializing the implicit objects of the page.
PreLoad Executes before loading the web page contents in the memory.
Load Executes after loading the web page contents in the memory.
PreRender Executes before rendering (displaying) the output on the browser.
Unload Executes at the time of closing the web page.

.NET 4.0 and Visual Studio 2010 Page 67 of 558


D. HARSHA VARDHAN

Application 7: Demo on Page Events

Default.aspx.cs

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


{
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("<h1>This is PreInit event.<br>");
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("This is Init event.<br>");
}
protected void Page_PreLoad(object sender, EventArgs e)
{
Response.Write("This is PreLoad event.<br>");
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("This is Load event.<br>");
}

.NET 4.0 and Visual Studio 2010 Page 68 of 558


D. HARSHA VARDHAN

protected void Page_PreRender(object sender, EventArgs e)


{
Response.Write("This is PreRender event.</h1><hr>");
}
protected void Page_Unload(object sender, EventArgs e)
{
//Response.Write("This is Unload event.<br>"); // this message never be displayed,
because the web page already closed.
}
}

protected void Page_Unload(object sender, EventArgs e)


Output:
{
//Response.Write("This is Unload event.<br>"); // this message never be displayed,
because the web page already closed.
}
}

.NET 4.0 and Visual Studio 2010 Page 69 of 558


D. HARSHA VARDHAN

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>

.NET 4.0 and Visual Studio 2010 Page 70 of 558


D. HARSHA VARDHAN

 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>

.NET 4.0 and Visual Studio 2010 Page 71 of 558


D. HARSHA VARDHAN

Application 8: Demo on Client Side Controls and Server Side Controls

Note: Drag the ―Server button‖ from ―Standard‖ category; and ―Client button‖ from ―HTML‖
category.

Default.aspx.cs

protected void Button1_Click(object sender, EventArgs e)


{
Response.Write("<h1>The server button is clicked</h1>");
}

Default.aspx

<script language="javascript" type="text/javascript">


function Button2_onclick()
{
window.alert("The client button is clicked");
}
</script>

.NET 4.0 and Visual Studio 2010 Page 72 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 73 of 558


D. HARSHA VARDHAN

HTML Server Controls:

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

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

 Then above code will work. In fact, when you write the runat=‖server‖ attribute for the
<input> tag, even though the textbox is a HTML control, it is identified and accessible in
the server code. This type of special HTML controls are called as “HTML Server
Controls”.
 Finally, the application looks like this:

.NET 4.0 and Visual Studio 2010 Page 74 of 558


D. HARSHA VARDHAN

Application 9: Demo on HTML Server Controls

Note: Drag the ―Text1‖ control from ―HTML‖ category; and ―Button‖ from ―Standard‖ category.

protected void Button1_Click(object sender, EventArgs e)


{
Text1.Value = DateTime.Now.ToString();
}

.NET 4.0 and Visual Studio 2010 Page 75 of 558


D. HARSHA VARDHAN

ASP.NET Server Controls


i. Standard Controls:
It includes with few most commonly used controls like Button, TextBox,
CheckBox, Image etc.

ii. Data Controls:


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

iii. Validation Controls:


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

iv. Navigation Controls:


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

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

vi. WebParts Controls:


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

vii. AJAX Extensions Controls:


To implement AJAX technology.

viii. Reporting Controls:


To display reports (Microsoft reports / Crystal reports) in the page.

.NET 4.0 and Visual Studio 2010 Page 76 of 558


D. HARSHA VARDHAN

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.

2. Label: Displays a static message.

Properties of Label

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

Events of Label
No Events.

.NET 4.0 and Visual Studio 2010 Page 77 of 558


D. HARSHA VARDHAN

3. TextBox: Used to take input values from the user.

Properties of TextBox

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

Events of TextBox

Event Description
TextChanged Executes on changing the textbox text.

4. Image: Displays a static image.

Properties of Image

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

Events of Image
No Events.

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

Properties of Hyperlink

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

.NET 4.0 and Visual Studio 2010 Page 78 of 558


D. HARSHA VARDHAN

Events of Hyperlink
No Events.

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

Properties of LinkButton

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

Events of LinkButton

Event Description
Click Executes on clicking on the control.

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

Properties of ImageButton

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

Events of ImageButton

Event Description
Click Executes on clicking on the control.

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

Properties of CheckBox

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

.NET 4.0 and Visual Studio 2010 Page 79 of 558


D. HARSHA VARDHAN

Represents the current status of the checkbox, whether is checked or un-


Checked
checked. (true / false)
TextAlign Left / Right

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

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

Properties of RadioButton

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

Events of RadioButton

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

10. CheckBoxList: Contains multiple check boxes as items.

Properties of CheckBoxList

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

Events of CheckBoxList

Event Description
SelectedIndexChanged Executes on clicking on any check box in the list.

.NET 4.0 and Visual Studio 2010 Page 80 of 558


D. HARSHA VARDHAN

Run Time Properties of CheckBoxList

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

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

Properties of RadioButtonList

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

Events of RadioButtonList

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

Run Time Properties of RadioButtonList

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

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

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

.NET 4.0 and Visual Studio 2010 Page 81 of 558


D. HARSHA VARDHAN

Items Specifies the list of items, which is to be displayed in the control.


SelectionMode Single / Multiple

Events of ListBox

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

Run Time Properties of ListBox

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

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

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

Events of DropDownList

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

Run Time Properties of DropDownList

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

.NET 4.0 and Visual Studio 2010 Page 82 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 83 of 558


D. HARSHA VARDHAN

Events of Calendar

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

Run Time Properties of Calendar

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

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

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

Properties of Panel

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

Events of Panel
No Events

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

Properties of BulletedList

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

Events of BulletedList

Event Description
Click Executes on clicking the control.

.NET 4.0 and Visual Studio 2010 Page 84 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 85 of 558


D. HARSHA VARDHAN

Application 10: Demo on Standard Controls

Default.aspx

(Continued…)

.NET 4.0 and Visual Studio 2010 Page 86 of 558


D. HARSHA VARDHAN

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;
(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

protected void LinkButton2_Click(object sender, EventArgs e)


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

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

string outputmsg = "<h1>Your data has been submitted successfully! The submitted
data is:</h1><h2>";

.NET 4.0 and Visual Studio 2010 Page 90 of 558


D. HARSHA VARDHAN

outputmsg += "Student Name: " + studentname + "<br>";


outputmsg += "Age: " + age + "<br>";
outputmsg += "Password: " + password + "<br>";
outputmsg += "Confirm Passowrd: " + confirmpassword + "<br>";
outputmsg += "Address: " + address + "<br>";
outputmsg += "Date of Joining: " + doj.ToShortDateString() + "<br>";
outputmsg += "Documents Submitted? " + doc_submitted + "<br>";
outputmsg += "Is Already Registered? " + already_registered + "<br>";
outputmsg += "Existing Registration Number: " + existing_regno + "<br>";
outputmsg += "Gender: " + gender + "<br>";
outputmsg += "Marital Status: " + maritalstatus + "<br>";
outputmsg += "Preferrable Timings: " + preferrable_timings + "<br>";
outputmsg += "Resume file: " + resume_file + "<br>";
outputmsg += "Course type: " + coursetype + "<br>";
outputmsg += "Course: " + course + "<br>";

string uploadingfilename = Request.PhysicalApplicationPath + FileUpload1.FileName;


FileUpload1.SaveAs(uploadingfilename);

outputmsg += "File uploaded successfully!";


outputmsg += "</h2>";

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

.NET 4.0 and Visual Studio 2010 Page 91 of 558


D. HARSHA VARDHAN

aboutus.aspx

.NET 4.0 and Visual Studio 2010 Page 92 of 558


D. HARSHA VARDHAN

Alignment of Controls

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

1) With HTML Tables:

Application 11: Demo on Good Alignment of Controls

 First, click on ―Table‖ menu – ―Insert Table‖.

.NET 4.0 and Visual Studio 2010 Page 93 of 558


D. HARSHA VARDHAN

 Then it generates a html table and the screen looks like this:

.NET 4.0 and Visual Studio 2010 Page 94 of 558


D. HARSHA VARDHAN

 Then drag and drop the required controls directly into the table cells. For
example you design a login page as follows:

.NET 4.0 and Visual Studio 2010 Page 95 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 96 of 558


D. HARSHA VARDHAN

 Now, the alignment is good. This is how to maintain the controls alignment
better, with HTML tables.

.NET 4.0 and Visual Studio 2010 Page 97 of 558


D. HARSHA VARDHAN

Output:

2) With Absolute Positioning:


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

Syntax for Absolute Positioning:

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

Ex for Absolute Positioning:


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

.NET 4.0 and Visual Studio 2010 Page 98 of 558


D. HARSHA VARDHAN

Output:

.NET 4.0 and Visual Studio 2010 Page 99 of 558


D. HARSHA VARDHAN

The “Wizard” Control

 This is one of the most useful controls.


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

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

Application 12: Demo on Wizard Control

Steps:
 First, drag and drop the ―Wizard‖ control into the page.

.NET 4.0 and Visual Studio 2010 Page 100 of 558


D. HARSHA VARDHAN

 Then click on ―>‖ symbol, and click ―Add/Remove Wizard Steps‖.


 In the dialog box, click on ―Add‖ button and add two more steps. Totally where will be 2
steps.
 Specify the ―Title‖ property for each step.
1. First Step
2. Second Step
3. Third Step
4. Final Step

 Click on ―OK‖.
 Then the screen looks like this:

.NET 4.0 and Visual Studio 2010 Page 101 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 102 of 558


D. HARSHA VARDHAN

 Final Step:

 Then double click on ―Add‖ button and ―Multiply‖ button, and write the following code.

protected void Button1_Click(object sender, EventArgs e)


{
int result = Convert.ToInt32(TextBox1.Text) + Convert.ToInt32(TextBox2.Text);
TextBox3.Text = result.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(TextBox1.Text) * Convert.ToInt32(TextBox2.Text);
TextBox3.Text = result.ToString();
}

 Finally, click on ―First Step‖ at design time and run it.

.NET 4.0 and Visual Studio 2010 Page 103 of 558


D. HARSHA VARDHAN

The “AdRotator” Control

 This is to display ads in your web site.


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

Application 13: Demo on AdRotator Control

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

.NET 4.0 and Visual Studio 2010 Page 104 of 558


D. HARSHA VARDHAN

 Enter the new folder name as ―ads‖.


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

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


<Advertisements xmlns="http://schemas.microsoft.com/AspNet/AdRotator-Advertisement-
File-1.2">
<Ad xmlns="">
<ImageUrl>some image path</ImageUrl>
<AlternateText>some description</AlternateText>
<NavigateUrl>URL that should be opened</NavigateUrl>
</Ad>
</Advertisements>

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

.NET 4.0 and Visual Studio 2010 Page 105 of 558


D. HARSHA VARDHAN

2. <AlternateText>: Contains the text that is to be displayed on the screen, in


place of the image, whenever the image file is not found at run time.
3. <NavigateUrl>: Contains the URL (just like in hyperlink control), which should
be opened when the user clicks an ad at run time.
 With this knowledge, you can write an advertisement descriptive file XML.
 For this application, write the code as follows:

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


<Advertisements xmlns="http://schemas.microsoft.com/AspNet/AdRotator-Advertisement-
File-1.2">
<Ad xmlns="">
<ImageUrl>~/ads/ad1.gif</ImageUrl>
<AlternateText>about.com</AlternateText>
<NavigateUrl>http://www.about.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad2.gif</ImageUrl>
<AlternateText>usedvehicles.com</AlternateText>
<NavigateUrl>http://www.usedvehicles.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad3.gif</ImageUrl>
<AlternateText>wca.com</AlternateText>
<NavigateUrl>http://www.wca.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad4.gif</ImageUrl>
<AlternateText>accentcareers.com</AlternateText>
<NavigateUrl>http://www.accentcareers.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad5.gif</ImageUrl>
<AlternateText>doomed.com</AlternateText>
<NavigateUrl>http://www.doomed.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad6.gif</ImageUrl>
<AlternateText>quantum.com</AlternateText>
<NavigateUrl>http://www.quantum.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad7.gif</ImageUrl>
<AlternateText>rockboard.com</AlternateText>
<NavigateUrl>http://www.rockboard.com</NavigateUrl>
</Ad>
<Ad xmlns="">
<ImageUrl>~/ads/ad8.gif</ImageUrl>

.NET 4.0 and Visual Studio 2010 Page 106 of 558


D. HARSHA VARDHAN

<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:

.NET 4.0 and Visual Studio 2010 Page 107 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 108 of 558


D. HARSHA VARDHAN

Click on Refersh..

.NET 4.0 and Visual Studio 2010 Page 109 of 558


D. HARSHA VARDHAN

Click on Refersh..

.NET 4.0 and Visual Studio 2010 Page 110 of 558


D. HARSHA VARDHAN

In this way, you can have different-different ads using ―AdRotator‖ control.

.NET 4.0 and Visual Studio 2010 Page 111 of 558


D. HARSHA VARDHAN

SQL Server 2005 Basics


1. Open SQL Server:
 Click on ―Start‖ – ―Programs‖ – ―Microsoft SQL Server 2005‖ – ―SQL Server
Management Studio‖.
 It displays ―Connect to Server‖ dialog box.

 Enter the following values:


1. Server type: Database Engine
2. Server name: Name of the system (You can see the computer name in
the ―My Computer‖ properties)
3. Authentication: SQL Server Authentication
 Login: sa
 Password: xxxx (The password can be given at the time of SQL
Server software installation) Ex: 123
(or)
Authentication: Windows Authentication
 After successful login to the server, it displays ―SQL Server Management Studio‖
window.

.NET 4.0 and Visual Studio 2010 Page 112 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 113 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 114 of 558


D. HARSHA VARDHAN

3. Creating a new Database:


 A database is a collection of tables.
 To create a new database, right click on ―Databases‖ and choose ―New
Database‖.
 Then enter the new database name. Ex: mydata
 Click on OK.

.NET 4.0 and Visual Studio 2010 Page 115 of 558


D. HARSHA VARDHAN

4. Creating a new Table:


 Right click on ―Tables‖ option in the ―Object Explorer‖ and choose ―New Table‖.
 Enter the table structure of the new table.

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

 Close the window finally.

.NET 4.0 and Visual Studio 2010 Page 116 of 558


D. HARSHA VARDHAN

5. Important Data Types in SQL Server:


 varchar(width)
 datetime
 numeric(width)
 int
 float
 decimal(width,dec)
 bit
 image

6. Working with “Query window”:


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

.NET 4.0 and Visual Studio 2010 Page 117 of 558


D. HARSHA VARDHAN

 Then the SQL statement will be executed.

7. IMP SQL Statements:


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

2. DROP
 drop table tablename;

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

.NET 4.0 and Visual Studio 2010 Page 118 of 558


D. HARSHA VARDHAN

 alter table tablename alter column columnname


datatype(width);

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

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

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

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

Some exercise on SQL:

use master
drop database test
GO

create database test


GO

use test
GO

create table Products


(ProductID int primary key,
ProductName varchar(40),
Price decimal(18,2))

.NET 4.0 and Visual Studio 2010 Page 119 of 558


D. HARSHA VARDHAN

insert into products values(101,'Monitors',7890)


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

select * from products

select ProductID,ProductName from Products

select Price*10/100 Tax from Products

select * from Products where Productid=104

select * from Products order by price desc

select * from Products where price between 2000 and 8000

select * from Products where price not between 2000 and 8000

select * from Products where price like '%0.00'

select * from Products where price like '___.00'

update products set price=price+1000

select * from products

delete from products where price<1500

select * from products

.NET 4.0 and Visual Studio 2010 Page 120 of 558


D. HARSHA VARDHAN

8. T-SQL (Transaction SQL):


 Procedures:
create procedure procedurename(@variable datatype(width),…)
as begin
declare @variable datatype(width)
…….
…….
end

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

Note: The procedure can’t return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix “@” symbol without fail.

.NET 4.0 and Visual Studio 2010 Page 121 of 558


D. HARSHA VARDHAN

Some exercise on T-SQL:

Procedure:

create procedure ShowSquare(@a int)


as begin
declare @sq int
set @sq = @a * @a
print @sq
end

GO
execute ShowSquare 5

Function:

create function GetCube(@a int) returns int


as begin
declare @cb int
set @cb = @a * @a * @a
return @cb
end

GO

select dbo.GetCube(5)

.NET 4.0 and Visual Studio 2010 Page 122 of 558


D. HARSHA VARDHAN

ADO.NET
(ActiveX Data Objects.NET)

 ADO.NET is known as ―Database Technology‖, which is used to connect with the


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

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


 File Databases:
dBASE, FoxPro, MS Access, MS Excel etc.
 Server Databases:
SQL Server, Oracle, My SQL etc.

.NET 4.0 and Visual Studio 2010 Page 123 of 558


D. HARSHA VARDHAN

What we can do using ADO.NET:

 Insert some data into the database table.


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

ADO.NET Database Connection Architecture

Driver .NET Application


db

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

For various databases, we have respective providers.


Database Provider Released by
SQL Server sqloledb.1 Microsoft Corp.
oraoledb.oracle.1 Oracle Corp.
Oracle
msdaora.1 Microsoft Corp.
MS Access / MS Excel / FoxPro /
microsoft.jet.oledb.4.0 Microsoft Corp.
dBASE
MS Access 2007 / 2010 microsoft.ace.oledb.12.0 Microsoft Corp.

.NET 4.0 and Visual Studio 2010 Page 124 of 558


D. HARSHA VARDHAN

Understanding the Connection String:


 The connection string provides the details about the connection string. That means, if
you want to connect with the database, you have to specify some details about the
connection like:
1. Server
2. User ID
3. Password
4. Provider
 Server: Specify the name of the server system, which you want to connect. If you want
to connect with other server system on the network, you specify the name of that
system. Ex: myserver. If you want to connect with the same system, mention the server
name as ―localhost‖. The server name can also be called as ―data source‖.
 User ID: Specify the user name for logging-in with the database.
 Password: Specify the password for logging-in with the database.
 Provider: Specify the name of the driver / provider, which you want to use with the
connection. You can see the available provider names, in the above table.

Syntax of Connection String:


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

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

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

.NET 4.0 and Visual Studio 2010 Page 125 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 126 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 127 of 558


D. HARSHA VARDHAN

Connecting the Database

 Library: SqlConnection / OleDbConnection

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.

Connecting with SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
Note: The ―initial catalog‖ specifies the name of the SQL Server database, in which
your table exists.
 Open the connection:
cn.Open();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 128 of 558


D. HARSHA VARDHAN

Connecting with Oracle / MS Access / Fox Pro:


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Prepare the Connection string:
cn.ConnectionString = ―provider=oraoledb.oracle.1; data

Oracle source=<name of the server>; user id=<user name>;


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

 Open the connection:


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

Application 14: Demo on ADO.NET with SQL Server Database

 Create a new Web Site.


 Add ―Default.aspx‖ page to the web site.
 Open Solution Explorer. Right click on ―Default.aspx‖ and select ―Set as Start Page‖.
 Design ―Default.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 129 of 558


D. HARSHA VARDHAN

 Set the properties of HyperLink1:


1. Text: Database Connection Demo
2. NavigateUrl: ~/DatabaseConnectionDemo.aspx
 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖.
 Enter the page name as ―DatabaseConnectionDemo.aspx‖.
 Click on ―Add‖.
 Design the ―DatabaseConnectionDemo.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 130 of 558


D. HARSHA VARDHAN

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 131 of 558


D. HARSHA VARDHAN

using System.Data.SqlClient;
using System.Data.OleDb;

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123";
cn.Open();
Label2.Text = "Successfully Connected with SQL Server";
cn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=oraoledb.oracle.1;user id=scott;password=tiger";
cn.Open();
Label2.Text = "Successfully Connected with Oracle";
cn.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data
source=c:\\database1.mdb";
cn.Open();
Label2.Text = "Successfully Connected with MS Access";
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 132 of 558


D. HARSHA VARDHAN

Sending Commands to the Database


 After connecting the database, you can send the commands to the database.
 ADO.NET supports to send the following types of commands.
1. Insertion Command
2. Deletion Command
3. Updation Command
4. Select Command / Query Command
5. Stored Procedure / Function Command

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

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

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

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

5) Stored Procedure / Function Command:


To call a stored procedure / function from the frontend application, that is
already created at backend.
SQL statement: No SQL statement is needed

.NET 4.0 and Visual Studio 2010 Page 133 of 558


D. HARSHA VARDHAN

Understanding the “Command” class:


 In order to send the commands, you need to use ―Command‖ class.
 Library: SqlCommand / OleDbCommand

Connection Command
 ConnectionStrin  CommandText
g  Connection
 Open()  CommandType
 Close()  Parameters
 ExecuteNonQuery()
 ExecuteReader()

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


/ deletion statement / updation statement / select statement)

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


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

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

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


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

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


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

.NET 4.0 and Visual Studio 2010 Page 134 of 558


D. HARSHA VARDHAN

command. Suppose, after executing a delete statement, 2 rows are deleted. So it


returns the integer value ―2‖.

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


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

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statement‖;
 Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
 Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 135 of 558


D. HARSHA VARDHAN

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statement‖;
 Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
 Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 136 of 558


D. HARSHA VARDHAN

Demo:
 Open SQL Server 2005.
 Create a new database, with name as ―demo‖.
 In that database, create a table named ―Customers‖, as shown below.

 Open the previous demo web site.


 Open ―Default.aspx‖ page and add the hyperlinks called ―Insertion‖, ―Deletion‖,
―Updation‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 137 of 558


D. HARSHA VARDHAN

 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

.NET 4.0 and Visual Studio 2010 Page 138 of 558


D. HARSHA VARDHAN

 Design the ―Insertion.aspx‖ page as follows:

 Write the code:

Insertion.aspx.cs

using System.Data.SqlClient;

protected void Button1_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();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(5,'Arun','Male',8000)";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

.NET 4.0 and Visual Studio 2010 Page 139 of 558


D. HARSHA VARDHAN

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:

" + textBox1.Text + "

.NET 4.0 and Visual Studio 2010 Page 140 of 558


D. HARSHA VARDHAN

 Design the ―Deletion.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 141 of 558


D. HARSHA VARDHAN

 Write the code:

Deletion.aspx.cs

using System.Data.SqlClient;

protected void Button1_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();

//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();
}

.NET 4.0 and Visual Studio 2010 Page 142 of 558


D. HARSHA VARDHAN

 Design the ―Updation.aspx‖ page as follows:

 Write the code:

Updation.aspx.cs

using System.Data.SqlClient;

protected void Button1_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";

.NET 4.0 and Visual Studio 2010 Page 143 of 558


D. HARSHA VARDHAN

//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();
}

.NET 4.0 and Visual Studio 2010 Page 144 of 558


D. HARSHA VARDHAN

Retrieving Data from the Database


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

Connection

(provider, data Command


db source, user id, (select stmt, cn)
DataReader
password)

.NET
Application

.NET 4.0 and Visual Studio 2010 Page 145 of 558


D. HARSHA VARDHAN

Library:
 Connection: Maintains the connection with database.
 Command: Sends a SQL statement and executes it at backend.
 DataReader: Acts as a buffer. It holds the data, which is received from database.

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

Classes, to be used in this concept:

Connection
 ConnectionStrin
g
 Open()
 Close()

Command
 CommandText
 Connection
 CommandType
 Parameters
 ExecuteNonQuery()
 ExecuteReader()

DataReader
 Read()
 [“column name”]
 [index]
 Close()

Understanding the “DataReader” class:


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

.NET 4.0 and Visual Studio 2010 Page 146 of 558


D. HARSHA VARDHAN

Ex:

 Library: SqlDataReader / OleDbDataReader

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

dr.Read();

(true)

.NET 4.0 and Visual Studio 2010 Page 147 of 558


D. HARSHA VARDHAN

dr.Read();

(true)

dr.Read();

(true)

dr.Read();

(true)

dr.Read();

(false)

.NET 4.0 and Visual Studio 2010 Page 148 of 558


D. HARSHA VARDHAN

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

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

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

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statement‖;
 Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
 Construct the “DataReader” class object:
SqlDataReader dr;
 Open the connection:
cn.Open();

.NET 4.0 and Visual Studio 2010 Page 149 of 558


D. HARSHA VARDHAN

 Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();
 Read the next row.
dr.Read();
 Get the value at specific column:
dr[column index];
(or)
dr[―column_name‖];
 Close the buffer:
dr.Close();
 Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statement‖;
 Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
 Construct the “DataReader” class object:
OleDbDataReader dr;

.NET 4.0 and Visual Studio 2010 Page 150 of 558


D. HARSHA VARDHAN

 Open the connection:


cn.Open();
 Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();
 Read the next row.
dr.Read();
 Get the value at specific column:
dr[column index];
(or)
dr[―column_name‖];
 Close the buffer:
dr.Close();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 151 of 558


D. HARSHA VARDHAN

Demo:

 Open the previous demo web site.


 Add the hyperlink called ―View Data using Data Reader‖ as shown below:

 Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataReaderDemo.aspx‖. Click on ―Add‖.
 Properties of ―HyperLink5‖:
 Text: View Data using Data Reader
 NavigateUrl: ~/DataReaderDemo.aspx

.NET 4.0 and Visual Studio 2010 Page 152 of 558


D. HARSHA VARDHAN

 Design the ―DataReaderDemo.aspx‖ page as follows:

 Write the Code:

DataReaderDemo.aspx.cs

using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)


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

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

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

.NET 4.0 and Visual Studio 2010 Page 153 of 558


D. HARSHA VARDHAN

//presentation / buffer logic


while (dr.Read() == true)
{
ListBox1.Items.Add(dr[0] + " -- " + dr[1] + " -- " + dr[2] + " -- " + dr[3]);
}

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:

.NET 4.0 and Visual Studio 2010 Page 154 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataReaderDemo_ConditionalData.aspx‖. Click on ―Add‖.
 Properties of ―HyperLink7‖:
 Text: View Data using Data Reader – Conditional Data
 NavigateUrl: ~/DataReaderDemo_ConditionalData.aspx

 Design the ―DataReaderDemo_ConditionalData‖ page as follows:

 Write the Code:

DataReaderDemo_ConditionalData.aspx.cs

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();

.NET 4.0 and Visual Studio 2010 Page 155 of 558


D. HARSHA VARDHAN

cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial


catalog=demo";
cn.Open();

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

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

//presentation / buffer logic


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

dr.Close();
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 156 of 558


D. HARSHA VARDHAN

ADO.NET Disconnected Model


 ADO.NET database connection is of two types:
1. Connected Model:
 Implemented with ―DataReader‖ buffer.
2. Disconnected Model:
 Implemented with ―DataSet‖, ―DataTable‖, ―DataRow‖ buffers.

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


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

Library:
 Connection: Maintains the connection with database.

 DataAdapter: Sends a sql statement and executes it at backend. It‘s just like Command
class, in the connection oriented model. The difference between Command class and
DataAdapter class is, the ―Command‖ class is used to execute any type of statement
(insert statement, delete statement, update statement and select statement). But
adapter executes select statement only.

.NET 4.0 and Visual Studio 2010 Page 157 of 558


D. HARSHA VARDHAN

 DataSet: Holds the data that is received from database, after execution of DataAdapter.
It can hold multiple tables data at-a-time. In other words, it contains an array of tables.

 DataTable: Holds a single table, from the DataSet.

 DataRow: Holds a single row, from the DataTable.

Limitations of Connection Oriented Model


(or)

Advantages of Disconnected Model

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

.NET 4.0 and Visual Studio 2010 Page 158 of 558


D. HARSHA VARDHAN

Diagrammatical View of Disconnected Model:

Connection

(provider, data DataAdapter Fill()


db source, user id, (select stmt, cn)
password)

DataSet

DataTable
0
1
2
3

.NET DataRow
Application 0 1 2

.NET 4.0 and Visual Studio 2010 Page 159 of 558


D. HARSHA VARDHAN

Classes, to be used in this concept:

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”]

Understanding the “DataAdapter” class:


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

 Clear(): Clears all the tables, and makes the dataset empty.

.NET 4.0 and Visual Studio 2010 Page 160 of 558


D. HARSHA VARDHAN

Understanding the “DataTable” class:


 Rows.Count: Gets the no. of rows that exist in the current table.
 Rows[row_index]: Gets the single row at the specified index.
 Columns.Count: Gets the no. of columns that exist in the current table.
 Columns[column_index]: Gets the single column at the specified index.

Understanding the “DataRow” class:


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

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “DataAdapter” class object:
SqlDataAdapter adp = new SqlDataAdapter(―select statement‖,cn);
 Construct the “DataSet” class object:
DataSet ds = new DataSet();
 Construct the “DataTable” class object:
DataTable dt;
 Construct the “DataRow” class object:
DataRow drow;

.NET 4.0 and Visual Studio 2010 Page 161 of 558


D. HARSHA VARDHAN

 Execute the adapter and receive the data into DataSet:


adp.Fill(ds);
 Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];
 Get the total no. of rows in the table:
dt.Rows.Count;
 Get the total no. of columns in the table:
dt.Columns.Count;
 Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
 Get the particular value in the “DataRow”:
 drow[column index];
(or)
drow[―column name‖];
 Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “DataAdapter” class object:
OleDbDataAdapter adp = new OleDbDataAdapter(―select statement‖,cn);
 Construct the “DataSet” class object:
DataSet ds = new DataSet();
 Construct the “DataTable” class object:
DataTable dt;

.NET 4.0 and Visual Studio 2010 Page 162 of 558


D. HARSHA VARDHAN

 Construct the “DataRow” class object:


DataRow drow;
 Execute the adapter and receive the data into DataSet:
adp.Fill(ds);
 Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];
 Get the total no. of rows in the table:
dt.Rows.Count;
 Get the total no. of columns in the table:
dt.Columns.Count;
 Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
 Get the particular value in the “DataRow”:
 drow[column index];
(or)
drow[―column name‖];
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 163 of 558


D. HARSHA VARDHAN

Demo:

 Open the previous demo application.


 Add the hyperlink called ―View Data using Data Set‖ as shown below:

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

.NET 4.0 and Visual Studio 2010 Page 164 of 558


D. HARSHA VARDHAN

 Design the ―DataSetDemo.aspx‖ page as follows:

 Write the Code:

DataSetDemo.aspx.cs

using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)


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

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

.NET 4.0 and Visual Studio 2010 Page 165 of 558


D. HARSHA VARDHAN

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

//presentation / buffer logic


while (dr.Read() == true)
{
ListBox1.Items.Add(dr[0] + " -- " + dr[1] + " -- " + dr[2] + " -- " + dr[3]);
}

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:

.NET 4.0 and Visual Studio 2010 Page 166 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖. Enter the page name as
―DataSetDemo_FlexibleRecords.aspx‖. Click on ―Add‖.
 Properties of ―HyperLink8‖:
 Text: View Data using Data Set – Flexible Records Presentation
 NavigateUrl: ~/DataSetDemo_FlexibleRecords.aspx

 Design the ―DataSetDemo_FlexibleRecords.aspx‖ page as follows:

 Write the Code:

DataSetDemo_FlexibleRecords.aspx.cs

using System.Data;
using System.Data.SqlClient;

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


{
//global declarations
DataTable dt;

.NET 4.0 and Visual Studio 2010 Page 167 of 558


D. HARSHA VARDHAN

static int RowIndex;


DataRow drow;

private void Display()


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

protected void Page_Load(object sender, EventArgs e)


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

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

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

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

if (Page.IsPostBack == false)
{
//display first record
RowIndex = 0;
Display();
}
Label6.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
//display first record
RowIndex = 0;
Display();
}
protected void Button2_Click(object sender, EventArgs e)
{
//display previous record
RowIndex--;

.NET 4.0 and Visual Studio 2010 Page 168 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 169 of 558


D. HARSHA VARDHAN

Sample Output:

We take a demonstration like that:

 Add the hyperlink called ―View Data using Data Set - GridView‖ as shown below:

 Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataSetDemo_GridView.aspx‖. Click on ―Add‖.
 Properties of ―HyperLink9‖:
 Text: View Data using Data Reader
 NavigateUrl: ~/DataSetDemo_GridView.aspx

.NET 4.0 and Visual Studio 2010 Page 170 of 558


D. HARSHA VARDHAN

 Design the ―DataSetDemo_GridView.aspx‖ page as follows:

[Drag and drop the ―GridView‖ control from the ―Data‖ category at the toolbox].

.NET 4.0 and Visual Studio 2010 Page 171 of 558


D. HARSHA VARDHAN

 Write the Code:

DataSetDemo_DataGridView.aspx.cs

using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)


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

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

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

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

//grid logic
GridView1.DataSource = dt;
GridView1.DataBind();
}

.NET 4.0 and Visual Studio 2010 Page 172 of 558


D. HARSHA VARDHAN

Working with Stored Procedures / Functions

 This is to call a procedure / function from the frontend application.


 This includes with:
1. First, create the procedure / function at backend using PL SQL.
2. Call it with its name, from the frontend code.
 Note: PL SQL is supported by SQL Server, Oracle and My SQL.

Purpose / Advantages of Stored Procedures / Functions:


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

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

.NET 4.0 and Visual Studio 2010 Page 173 of 558


D. HARSHA VARDHAN

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)

Implementation Code for SQL Server:


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

.NET 4.0 and Visual Studio 2010 Page 174 of 558


D. HARSHA VARDHAN

 Assign the parameters (if any) to the “Command” class object:


cmd.Parameters.AddWithValue(―parameter_name‖, value);
………………….;
………………….;
 Execute the procedure / function:
cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


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

.NET 4.0 and Visual Studio 2010 Page 175 of 558


D. HARSHA VARDHAN

 Execute the procedure / function:


cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

Demo:

 Open SQL Server 2005.


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

 Click on ―New Query‖ option in the toolbar.

.NET 4.0 and Visual Studio 2010 Page 176 of 558


D. HARSHA VARDHAN

 Then type the following code:

 Then Press ―F5‖.


 It displays the following message:
Command(s) completed successfully.
 Enter some sample data as follows:

.NET 4.0 and Visual Studio 2010 Page 177 of 558


D. HARSHA VARDHAN

 Open the previous demo web site in Visual Studio.


 Add the hyperlink called ―Stored Procedure Demo‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 178 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 179 of 558


D. HARSHA VARDHAN

 Write the Code:

StoredProcedureDemo.aspx.cs

using System.Data;
using System.Data.SqlClient;

protected void Button1_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();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "calculategrades";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();

.NET 4.0 and Visual Studio 2010 Page 180 of 558


D. HARSHA VARDHAN

//presentation logic
Label1.Text = "Procedure Executed..";

cn.Close();
}

Demo on Retrieving Multiple Tables Data using Stored


Procedure:

 Open SQL Server 2005.


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

 Then Press ―F5‖.

.NET 4.0 and Visual Studio 2010 Page 181 of 558


D. HARSHA VARDHAN

 It displays the following message:


Command(s) completed successfully.

 Open the previous demo web site in Visual Studio.


 Add the hyperlink called ―Stored Procedure Demo – Multiple Tables‖ as shown below:

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

 Design the ―StoredProcedureDemo_MultipleTables.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 182 of 558


D. HARSHA VARDHAN

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

 Write the Code:

StoredProcedureDemo_MultipleTables.aspx.cs

using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)


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

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);

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

.NET 4.0 and Visual Studio 2010 Page 183 of 558


D. HARSHA VARDHAN

//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();
}

.NET 4.0 and Visual Studio 2010 Page 184 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 185 of 558


D. HARSHA VARDHAN

 It‘s like an express-style. Within minutes, we can finish our work. It‘s
very much easy to use, when compared with programming model.
 But it‘s much difficult to implement any additional new style of database
manipulations, which are not defined in the existing data controls.

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


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

Application 15: Demo on Data Controls

 Open Visual Studio 2010.


 Create a new web site.
 Take a new web page.
 Design the page like this:

.NET 4.0 and Visual Studio 2010 Page 186 of 558


D. HARSHA VARDHAN

 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‖.

.NET 4.0 and Visual Studio 2010 Page 187 of 558


D. HARSHA VARDHAN

 Click on ―Create‖.
 It shows ―Table1‖ like this:

.NET 4.0 and Visual Studio 2010 Page 188 of 558


D. HARSHA VARDHAN

 Right click on ―Table1‖ and choose ―Design View‖.


 Enter the table name as ―Regions‖.

 Click on OK.
 Then type the table structure as follows:

.NET 4.0 and Visual Studio 2010 Page 189 of 558


D. HARSHA VARDHAN

 Save the table.


 Right click on ―Regions‖ table at left side, and choose ―Open‖ option.
 Type some sample data as follows:

.NET 4.0 and Visual Studio 2010 Page 190 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 191 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 192 of 558


D. HARSHA VARDHAN

 Then click on ―Browse‖.

.NET 4.0 and Visual Studio 2010 Page 193 of 558


D. HARSHA VARDHAN

 Then select the ―Database1.accdb‖ file, which is already copied into the web site folder.

.NET 4.0 and Visual Studio 2010 Page 194 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 195 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 196 of 558


D. HARSHA VARDHAN

 Finally, click on ―Finish‖ button.


 Now the ―AccessDataSource1‖ control is configured properly. This control can serve the
data to other controls like GridView etc.
 Now, drag and drop the ―GridView‖ control, again from the toolbox.
 Select the ―GridView1‖ control and click on ―>‖ button.

.NET 4.0 and Visual Studio 2010 Page 197 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 198 of 558


D. HARSHA VARDHAN

 At design time, it shows a preview of data.


 At run time, it shows the actual data.
 Now, run the web site. The present output will be like this:

.NET 4.0 and Visual Studio 2010 Page 199 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 200 of 558


D. HARSHA VARDHAN

 It shows a dialog box as follows:

.NET 4.0 and Visual Studio 2010 Page 201 of 558


D. HARSHA VARDHAN

 Then in the dialog box, click on ―New Connection‖ option.


 Click on ―Change‖.

.NET 4.0 and Visual Studio 2010 Page 202 of 558


D. HARSHA VARDHAN

 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

.NET 4.0 and Visual Studio 2010 Page 203 of 558


D. HARSHA VARDHAN

 Click on ―Test Connection‖, whether above connection details are accepted or not. If it is
successfully connected, then it shows the following message.

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

.NET 4.0 and Visual Studio 2010 Page 204 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 205 of 558


D. HARSHA VARDHAN

 Click on ―Next‖ to continue.


 Click on ―Next‖.
 Then just like in the AccessDataSource, select the required table name and required
columns.

.NET 4.0 and Visual Studio 2010 Page 206 of 558


D. HARSHA VARDHAN

 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‖.

.NET 4.0 and Visual Studio 2010 Page 207 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 208 of 558


D. HARSHA VARDHAN

 Run the web site, to see the output.


 Then output will be like this:

.NET 4.0 and Visual Studio 2010 Page 209 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 210 of 558


D. HARSHA VARDHAN

 After selecting the auto format styles, the grid looks like this:

.NET 4.0 and Visual Studio 2010 Page 211 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 212 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 213 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 214 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 215 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 216 of 558


D. HARSHA VARDHAN

 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:

protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)


{
int ind = GridView2.SelectedIndex;
string CustomerName = GridView2.Rows[ind].Cells[2].Text;
Label2.Text = "The selected row index is: " + ind;
Label2.Text += "<br>The selected customer name is: " + CustomerName;
}

.NET 4.0 and Visual Studio 2010 Page 217 of 558


D. HARSHA VARDHAN

 The output will be like this:

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

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

 Now, let us continue with ―DetailsView‖ control.


 Drag and drop the ―DetailsView‖ control from the toolbox into the page.
 Just like in the grid control, choose the data source as ―SqlDataSource1‖.
 This control displays the data in a single-record view.
 Then user can navigate among the records, by clicking on the page numbers.

.NET 4.0 and Visual Studio 2010 Page 218 of 558


D. HARSHA VARDHAN

 In this control also, you have the common options like:


 Auto Format
 Enable Paging
 Enable Inserting
 Enable Editing
 Enable Deleting
 When the ―Inserting‖ feature is enabled, by clicking on ―New‖ option, the user can insert
a new row at run time. For this also we don‘t require to write any code.
 The output of DetailsView control is as follows:

 Next, you drag and drop the ―FormView‖ control.

.NET 4.0 and Visual Studio 2010 Page 219 of 558


D. HARSHA VARDHAN

 The ―FormView‖ control is similar to the ―DetailsView‖ control.


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

 Now, the DetailsView and FormView controls are looking almost all same.
 But you can change the design of FormView control. To do so, click on ―>‖ button and
choose ―Edit Templates‖ option.
 Then the control looks like this:

.NET 4.0 and Visual Studio 2010 Page 220 of 558


D. HARSHA VARDHAN

 Now, you can make some changes.


 For example, suppose you want to display the gender in a RadioButtonList control,
instead of the label control.
 Then delete the ―GenderLabel‖ control in the above design and drag the
―RadioButtonList‖ control from the toolbox into the ―ItemTemplate‖ directly.
 Then select the following properties of RadioButtonList1 control:
 Items: Male
Female
 RepeatDirection: Horizontal
 RepeatLayout: Flow

 Then select that radiobuttonlist control and click on ―>‖ button.


 Click on ―Edit Data Bindings‖ option.

.NET 4.0 and Visual Studio 2010 Page 221 of 558


D. HARSHA VARDHAN

 Select the property as ―SelectedValue‖.


 Select ―Bound to‖ as ―Gender‖.
 Click on OK.
 Then to close the template editing, click on ―>‖ button and choose ―End Template
Editing‖ option.
 Then the output will be like this:

 Now, let us continue with ―ListView‖ control.


 Drag and drop the ―ListView‖ control into the page. This control displays the data in a
variety format.
 Select the ―ListView1‖ control and click on ―>‖ button.
 Select the Data Source as ―SqlDataSource1‖.

.NET 4.0 and Visual Studio 2010 Page 222 of 558


D. HARSHA VARDHAN

 Again click on ―>‖ button and choose ―Configure ListView‖ option.


 Select the required Layout. Ex: Tiled.
 Select any auto format style. Ex: Professional.
 Select any additional options like ―Enable Editing‖, ―Enable Inserting‖ etc.

 Finally click on OK.


 The output will be like this:

 Now, let us use the ―Chart‖ control. This ―Chart‖ control is introduced in ASP.NET 2010
version. It‘s not available in the older versions.

.NET 4.0 and Visual Studio 2010 Page 223 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 224 of 558


D. HARSHA VARDHAN

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.

Application 16: Demo on Crystal Reports

Implementation of Crystal Reports

1. Create a Crystal Report.

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖.
 Select ―Reporting‖ – ―Crystal Report‖.
 Enter the name of the new report. Ex: StudentsReport.rpt.
 Click on ―Add‖.
 A wizard will be displayed.

.NET 4.0 and Visual Studio 2010 Page 225 of 558


D. HARSHA VARDHAN

 Select the report type as


―Standard‖ and click on OK.
 The ―Standard Report Creation
Wizard‖ dialog box will be
appeared.
 There, expand the option ―Create
New Connection‖ and expand ―OLE
DB (ADO)‖
 Then ―OLE DB (ADO)‖ dialog box
will be appeared.
 There, select the appropriate driver
/ provider name, based on the
database which you want to
connect.
 Sql Server  Microsoft OLE DB Provider for SQL Server
 Oracle  Microsoft OLE DB Provider for Oracle
 MS Access  Microsoft Jet OLE DB 4.0 Provider

.NET 4.0 and Visual Studio 2010 Page 226 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 227 of 558


D. HARSHA VARDHAN

 To add all the columns, click on ―>>‖ button. To add the columns one-by-one, select
the column first and click on ―>‖ button.
 Click on ―Next‖.
 Select the grouping column, based on which you want to group-up the data
(optional). If you don‘t want to group the data, simply leave it blank.
 Click on ―Finish‖.
 Then the report wizard will be completed and the report will be generated
automatically.
 The report will be displayed in the design view. This can be called as ―Report Design
View‖.
 Then the report file will be added into the ―Solution Explorer‖. Ex: studentsreport.rpt

2. Design the Crystal Report.


 The ―Report Design View‖ offers to change the design of the report.
 The report design view contains 5 sections like:

.NET 4.0 and Visual Studio 2010 Page 228 of 558


D. HARSHA VARDHAN

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‖ /

.NET 4.0 and Visual Studio 2010 Page 229 of 558


D. HARSHA VARDHAN

―Picture‖. After selecting any one of these options, click anywhere, where you want to
insert that object.

3. Invoke it in the Web Page.


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

 There, select the ―studentsreport.rpt‖ file from the drop down list.

.NET 4.0 and Visual Studio 2010 Page 230 of 558


D. HARSHA VARDHAN

 Then click on OK.


 Then the page looks like this:

.NET 4.0 and Visual Studio 2010 Page 231 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 232 of 558


D. HARSHA VARDHAN

Output:

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

.NET 4.0 and Visual Studio 2010 Page 233 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 234 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 235 of 558


D. HARSHA VARDHAN

Validation Controls in ASP.NET


A. Client Side Validation Controls
1) RequiredFieldValidator
2) RangeValidator
3) RegularExpressionValidator
4) CompareValidator
5) ValidationSummary
B. Server Side Validation Controls
6) CustomValidator

Implementation of Validation Controls

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

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

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


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

Properties of RangeValidator
Property Description
Contains the reference of the control (textbox, 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.

.NET 4.0 and Visual Studio 2010 Page 236 of 558


D. HARSHA VARDHAN

MinimumValue Contains the minimum value in the range.


MaximumValue Contains the maximum value in the range.
Specifies the data type of value. (Integer / Double / Currency /
Type
String / Date)

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


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

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

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

A. Comparison with a fixed value.


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

.NET 4.0 and Visual Studio 2010 Page 237 of 558


D. HARSHA VARDHAN

B. Comparison with another control’s value.


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

C. Data Type Comparison.


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

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


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

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


includes with some code to be executed. For example, in a form, there is a textbox, to

.NET 4.0 and Visual Studio 2010 Page 238 of 558


D. HARSHA VARDHAN

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.

Application 17: Demo on Validation Controls

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

.NET 4.0 and Visual Studio 2010 Page 239 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 240 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 241 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 242 of 558


D. HARSHA VARDHAN

Application 18: Demo on Navigation Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Design the ―Default.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 243 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Aboutus.aspx‖ – Click on Add.
 Design the ―Aboutus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 244 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Contactus.aspx‖ – Click on Add.
 Design the ―Contactus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 245 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―registration.aspx‖ – Click on Add.
 Design the ―registration.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 246 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―login.aspx‖ – Click on Add.
 Design the ―login.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 247 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―ConsumerProducts.aspx‖ – Click on Add.
 Design the ―ConsumerProducts.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 248 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―HomeAppliances.aspx‖ – Click on Add.
 Design the ―HomeAppliances.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 249 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―PrepaidServices.aspx‖ – Click on Add.
 Design the ―PrepaidServices.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 250 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―PrepaidVouchers.aspx‖ – Click on Add.
 Design the ―PrepaidVouchers.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 251 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―PostpaidServices.aspx‖ – Click on Add.
 Design the ―PostpaidServices.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 252 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―PostpaidPlans.aspx‖ – Click on Add.
 Design the ―PostpaidPlans.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 253 of 558


D. HARSHA VARDHAN

 Come back to the ―Default.aspx‖.


 Drag and drop the ―Menu‖ control from the toolbox into the page.

 Then click on ―>‖ button and select ―Edit Menu Items‖ option.
 Then it displays Menu Item Editor dialog box.

.NET 4.0 and Visual Studio 2010 Page 254 of 558


D. HARSHA VARDHAN

 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

.NET 4.0 and Visual Studio 2010 Page 255 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 256 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 257 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 258 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 259 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 260 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 261 of 558


D. HARSHA VARDHAN

 Again select the ―TreeView1‖ control and click on ―>‖ button. Click on ―Auto Format‖
option. Select any one of the auto format styles:

.NET 4.0 and Visual Studio 2010 Page 262 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 263 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 264 of 558


D. HARSHA VARDHAN

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.

Application 19: Demo on Login Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Design the ―Default.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 265 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 266 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 267 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 268 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 269 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 270 of 558


D. HARSHA VARDHAN

 Enter some sample details and click on ―Create User‖ button.

.NET 4.0 and Visual Studio 2010 Page 271 of 558


D. HARSHA VARDHAN

 Ex:

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


 Note: While you are entering the password, you need to enter at least one non-alpha
numeric character (special character), such as #, $, @, *, & etc.
 Ex: satya123#

.NET 4.0 and Visual Studio 2010 Page 272 of 558


D. HARSHA VARDHAN

 Click on ―Continue‖.
 Then it shows the ―login.aspx‖ page.

.NET 4.0 and Visual Studio 2010 Page 273 of 558


D. HARSHA VARDHAN

 Close the web site and run it again.


 Just for demonstration purpose, register one more user as follows:

.NET 4.0 and Visual Studio 2010 Page 274 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 275 of 558


D. HARSHA VARDHAN

 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

.NET 4.0 and Visual Studio 2010 Page 276 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 277 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 278 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 279 of 558


D. HARSHA VARDHAN

 Let us test this control whether it is working or not.


 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 280 of 558


D. HARSHA VARDHAN

 Click on ―Forgot Password – Click here‖ option.


 Enter the username. Ex: satya

.NET 4.0 and Visual Studio 2010 Page 281 of 558


D. HARSHA VARDHAN

 Click on ―Submit‖.
 Then it shows the security question, which is given at the time of user registration.
 Enter the proper answer. Ex: green

.NET 4.0 and Visual Studio 2010 Page 282 of 558


D. HARSHA VARDHAN

 Click on ―Submit‖ button.


 In fact, an E-mail is automatically would be sent to the user, with the password
information.
 But now, it would not be sent properly. You will get this type of error message:

.NET 4.0 and Visual Studio 2010 Page 283 of 558


D. HARSHA VARDHAN

 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 ―ASP.NET Configuration‖ option.


 Then it displays ―ASP.NET Web Site
Administrative Tool‖.
 It‘s an inbuilt feature of ASP.NET, which is used
to customize the settings of the web site.

.NET 4.0 and Visual Studio 2010 Page 284 of 558


D. HARSHA VARDHAN

 Click on ―Application‖ tab.

.NET 4.0 and Visual Studio 2010 Page 285 of 558


D. HARSHA VARDHAN

 Click on ―Configure SMTP e-mail settings‖ option.


 Then it displays the following options:

.NET 4.0 and Visual Studio 2010 Page 286 of 558


D. HARSHA VARDHAN

 Then type the following details:


1. Server name: name of the SMTP server / localhost
2. Server Port: 25 (a fixed port no of SMTP protocol)
3. From: The e-mail address, from which the password recovery e-mail is to
be sent. For ex type customercare@peerstech.com.

.NET 4.0 and Visual Studio 2010 Page 287 of 558


D. HARSHA VARDHAN

 Click on ―Save‖ button.


 Then the above specified SMTP settings will be saved.

.NET 4.0 and Visual Studio 2010 Page 288 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 289 of 558


D. HARSHA VARDHAN

 But still, it won‘t work, because the mail domain (peerstech.com), which you are using
in the above mentioned mail address doesn‘t exist actually.
 So that we have to create a alias domain (dummy domain), with the name of
―peerstech.com‖.
 To create it, click on ―Start‖ – ―Run‖.
 Then type ―inetmgr‖ and click on OK.

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


 There, expand the local computer name.
 Expand ―Default SMTP Virtual Server‖.

.NET 4.0 and Visual Studio 2010 Page 290 of 558


D. HARSHA VARDHAN

 Select the option ―Domains‖.


 Then it shows existing list of domains, which are configured currently in the IIS server.
 Right click on ―Domains‖ – choose ―New‖ – ―Domain‖.

 Then select ―Alias‖.

.NET 4.0 and Visual Studio 2010 Page 291 of 558


D. HARSHA VARDHAN

 Click on Next.
 Specify the name as ―peerstech.com‖.

 Click on Finish.
 Then it will be added to the existing domains list.

.NET 4.0 and Visual Studio 2010 Page 292 of 558


D. HARSHA VARDHAN

 That‘s it. It‘s ready.


 Close the IIS window and come back to Visual Studio.
 Run the web site and test the ForgotPassword option. Now it works.
 After entering the correct username and correct answer for the question, it displays the
following message at run time.

.NET 4.0 and Visual Studio 2010 Page 293 of 558


D. HARSHA VARDHAN

 To find out the E-mail, open the following folder.


c:\Inetpub\mailroot\Drop
 There, you can find a file that contains the E-mail.

.NET 4.0 and Visual Studio 2010 Page 294 of 558


D. HARSHA VARDHAN

 Double click on that file.


 Then you can read the e-mail.

.NET 4.0 and Visual Studio 2010 Page 295 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 296 of 558


D. HARSHA VARDHAN

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

Application 20: Demo on WebParts Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Drag and drop the ―WebPartManager‖ control from the toolbox into the page (at the
top).

.NET 4.0 and Visual Studio 2010 Page 297 of 558


D. HARSHA VARDHAN

 Drag and drop the two or the ―WebPartZone‖ controls.

.NET 4.0 and Visual Studio 2010 Page 298 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 299 of 558


D. HARSHA VARDHAN

 Drag the drop any controls (like labels, buttons, textboxes, checkbox, calendars etc.) into
the web part zones.

.NET 4.0 and Visual Studio 2010 Page 300 of 558


D. HARSHA VARDHAN

(Continued…)

.NET 4.0 and Visual Studio 2010 Page 301 of 558


D. HARSHA VARDHAN

 Run the web site.


 You can observe ―Minimize‖ and ―Close‖ options for each control, at right side corner.

.NET 4.0 and Visual Studio 2010 Page 302 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 303 of 558


D. HARSHA VARDHAN

 Set the Dropdownlist items as follows:

.NET 4.0 and Visual Studio 2010 Page 304 of 558


D. HARSHA VARDHAN

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

 Run the web site.


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

 This is the advantage of ―Design‖ mode.

.NET 4.0 and Visual Studio 2010 Page 305 of 558


D. HARSHA VARDHAN

State Management in ASP.NET


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

Transferring Information between Pages


With Query String

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

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

.NET 4.0 and Visual Studio 2010 Page 306 of 558


D. HARSHA VARDHAN

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.

Application 21: Demo on State Management

 Create a new web site.


 Add the ―Default.aspx‖ page.
 Design the ―Default.aspx‖ page as shown:

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 307 of 558


D. HARSHA VARDHAN

Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
Response.Redirect("display1.aspx?uname=" + s);
}

 Add the ―display1.aspx‖ page.


 Design the ―display1.aspx‖ page as shown:

 Write the code:

display1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Params["uname"];
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 308 of 558


D. HARSHA VARDHAN

 Set the ―Default.aspx‖ as Start Page.


 Run the web site.

Limitations of Passing Information with Query String:

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

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

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

.NET 4.0 and Visual Studio 2010 Page 309 of 558


D. HARSHA VARDHAN

Implementation:
A. Assign value to the Cookie:
Create cookie object:
HttpCookie obj = new HttpCookie(―variable_name‖, ―value‖);
Assign the cookie object to Response:
Response.Cookies.Add(obj);
B. Get value from the Cookie:
Request.Cookies[―variable_name‖].Value

Demo:

 Open the previous demo web site.


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

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 310 of 558


D. HARSHA VARDHAN

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

 Add the ―display2.aspx‖ page.


 Design the ―display2.aspx‖ page as shown:

 Write the code:

display2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Cookies["uname"].Value;
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 311 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 312 of 558


D. HARSHA VARDHAN

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;

.NET 4.0 and Visual Studio 2010 Page 313 of 558


D. HARSHA VARDHAN

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

Demo:

 Open the previous demo web site.


 Add the ―Submit using Session State‖ button in the Default.aspx as shown:

.NET 4.0 and Visual Studio 2010 Page 314 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button3_Click(object sender, EventArgs e)
{
Session["uname"] = TextBox1.Text;
Response.Redirect("display3.aspx");
}

 Add the ―display3.aspx‖ page.


 Design the ―display3.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 315 of 558


D. HARSHA VARDHAN

 Write the code:

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;

.NET 4.0 and Visual Studio 2010 Page 316 of 558


D. HARSHA VARDHAN

B. Get value from the Application (gets the application state variable value in
“Object” type):
Application[―name‖]

C. Clear all the values in the Application state:


Application.Clear();

Demo:

 Open the previous demo web site.


 Add the ―Submit using Application State‖ button in the Default.aspx as shown:

.NET 4.0 and Visual Studio 2010 Page 317 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button4_Click(object sender, EventArgs e)
{
Application["uname"] = TextBox1.Text;
Response.Redirect("display4.aspx");
}

 Add the ―display4.aspx‖ page.


 Design the ―display4.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 318 of 558


D. HARSHA VARDHAN

 Write the code:

display4.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Application["uname"]);
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 319 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 320 of 558


D. HARSHA VARDHAN

 Open Solution Explorer; right click on ―viewstatedemo.aspx‖ and click ―View in Browser‖.
 Enter some values.

.NET 4.0 and Visual Studio 2010 Page 321 of 558


D. HARSHA VARDHAN

 Click on the button. Then the ―post backing‖ will be done. But the no values will be lost.

.NET 4.0 and Visual Studio 2010 Page 322 of 558


D. HARSHA VARDHAN

Global.asax
 This file contains the events, related to entire web site.
 Here is the list of events, written in global.asax file:
1. Application_Start: This event executes automatically, whenever the
―Application State‖ is created. The Application State will be created automatically,
whenever the web server is started.

2. Application_End: This event executes automatically, whenever the ―Application


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

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


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

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


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

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


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

Demo
 Open the previous demo web site.
 Open Solution Explorer. Right click on the web site name and click on ―Add New Item‖ –
select ―Global Application Class‖ – Click on ―Add‖.
 It generates the following events automatically.

.NET 4.0 and Visual Studio 2010 Page 323 of 558


D. HARSHA VARDHAN

 Type the code as follows:

Global.asax
<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup
Application["usercount"] = 0;
}

void Application_End(object sender, EventArgs e)


{
// Code that runs on application shutdown

void Application_Error(object sender, EventArgs e)


{
// Code that runs when an unhandled error occurs

.NET 4.0 and Visual Studio 2010 Page 324 of 558


D. HARSHA VARDHAN

Response.Redirect("errorpage.aspx");
}

void Session_Start(object sender, EventArgs e)


{
// Code that runs when a new session is started
int n = Convert.ToInt32(Application["usercount"]);
n++;
Application["usercount"] = n;
}

void Session_End(object sender, EventArgs e)


{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

</script>

 Add ―usercountpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 325 of 558


D. HARSHA VARDHAN

 Write the code:

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

 Open Solution Explorer; right click on ―usercountpage.aspx‖ and click on ―View in


Browser‖.

.NET 4.0 and Visual Studio 2010 Page 326 of 558


D. HARSHA VARDHAN

 Copy the URL from the address bar; open another browser; and paste the URL.

.NET 4.0 and Visual Studio 2010 Page 327 of 558


D. HARSHA VARDHAN

Note: Every time you run the page, the user count will be incremented automatically.

 Come back to Visual Studio.


 Add ―errorpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 328 of 558


D. HARSHA VARDHAN

 Add ―errortestpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 329 of 558


D. HARSHA VARDHAN

 Write the code:

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

.NET 4.0 and Visual Studio 2010 Page 330 of 558


D. HARSHA VARDHAN

 Click on the button.


 Then it shows the ―errorpage.aspx‖ automatically, because of the code that you have
written in ―Application_Error‖ event at global.asax file.

.NET 4.0 and Visual Studio 2010 Page 331 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 332 of 558


D. HARSHA VARDHAN

Uniformity of the Content


 This concept target is to maintain uniformity (looks similar) for the content or controls.
 Suppose you have 10 main headings your web page. Which would the better one? Either
displaying all those 10 headings with different styles (fonts, colors, borders etc.); or
displaying all those with common and uniform style..?
 The correct answer is second option. That means it‘s a good and professional way, if you
plan to give the common styles for all the headings. Of course, not only for headings; for
textboxes, labels, list boxes, menu items etc., it is better to apply common styles only.
 At the this situation, this uniformity maintenance is possible in many ways:
1. CSS
2. Themes
3. Skins

CSS
(Cascading Style Sheets)

 This is to overcome the limitations of HTML and also to apply common style among
several controls on the same or different web pages.
 This can also be called as ―DHTML‖ (Dynamic Hypertext Markup Language).
 DHTML offers better designing features, which are not supported by classic HTML.
 This also used to implement common design styles among different types of controls.
 It contains no new tags. It contains several attributes for better designing.
 In fact, CSS is not only related to ASP.NET. It is the generalized web page designing
concept, which is available in PHP and J2EE etc., also.
 In ASP.NET, these styles can be applied for both HTML tags and ASP.NET controls also.

.NET 4.0 and Visual Studio 2010 Page 333 of 558


D. HARSHA VARDHAN

Implementation Models of CSS


1) Inline Styles: The styles are limited to the currently element (tag) only.
2) Internal Styles: The styles are limited to the tags, used in the same page.
3) External Styles: The styles can be applied to the tags, within the same web site
(multiple web pages).

Important CSS Attributes:

Attribute Possible Values


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

.NET 4.0 and Visual Studio 2010 Page 334 of 558


D. HARSHA VARDHAN

Implementation of CSS Styles


1) Inline Styles:
Syn: <tag Style=‖attribute1:value1; attribute2:value2;….‖>
Description: The CSS styles can be applied for the current tag only.

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

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


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

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

Description: The CSS styles can be applied for every instance of the specified
tag in the current page.

.NET 4.0 and Visual Studio 2010 Page 335 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 336 of 558


D. HARSHA VARDHAN

Adding “.css” files to the Web Site

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


Select ―StyleSheet‖ option.
Enter the name of the css file. Ex: StyleSheet.css
Click on ―Add‖.
Then the css file will be added to the web site.

CSS Classes

In the ―Internal Styles‖ and ―External Styles‖, common styles will be applied for every
instance of particular tag. Instead, you can have a choice for applying the CSS styles for
the required instances only, with the concept called ―CSS classes‖.
Finally, the ―CSS Classes‖ concept can be used in two situations:
1) To apply common CSS styles for selective instances of a tag.
2) To apply common CSS styles for selective instances of multiple tags.
To create a CSS class, follow the syntax:
.classname
{
attribute1:value1; attribute2:value2;….
}
To apply the CSS style for the required html tag, follow the syntax:
<tag class=‖classname‖>
To apply the css style for the required server tag, follow the syntax:
<asp:tag CssClass=‖classname‖>

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

.NET 4.0 and Visual Studio 2010 Page 337 of 558


D. HARSHA VARDHAN

font-size: 30px;
border-style: double;
}
</style>
</head>

Invoke the class:


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

Application 22: Demo on Uniformity Maintenance

 Create a new web site.


 Add the ―cssdemo.aspx‖ page.
 Design the ―cssdemo.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 338 of 558


D. HARSHA VARDHAN

 Open Solution Explorer – right click on the web site name and click on ―Add New Item‖.
 Select ―Style Sheet‖.
 Enter the any file name. Ex: StyleSheet.css
 Click ―Add‖.
 Then the screen looks like this:

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

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

 Then it displays the following dialog box.

.NET 4.0 and Visual Studio 2010 Page 339 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 340 of 558


D. HARSHA VARDHAN

 Then it shows ―Modify Style‖ dialog box.


 Select any formatting effects that you want.

 Click on OK.
 Then it automatically generates the style sheet code as below:

.NET 4.0 and Visual Studio 2010 Page 341 of 558


D. HARSHA VARDHAN

 Come back to the ―cssdemo.aspx‖ page.


 Drag the ―StyleSheet.css‖ file from the Solution Explorer, into the page and drop it in the
page.
 Then it links the CSS file to the web page. That means, it generates the <link> tag
automatically in the code.
 Next, specify the following property for all the textboxes.
CssClass: MyTextBox
 Run the web site.
 Finally your page looks like this:

.NET 4.0 and Visual Studio 2010 Page 342 of 558


D. HARSHA VARDHAN

 This is how to apply CSS styles in ASP.NET.

.NET 4.0 and Visual Studio 2010 Page 343 of 558


D. HARSHA VARDHAN

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‖ />

.NET 4.0 and Visual Studio 2010 Page 344 of 558


D. HARSHA VARDHAN

 To impose the theme in the required .aspx page, simply write the Theme=”theme
name” attribute the <%@ Page> directive.

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

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

Demo:

 Open the previous demo web site.


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

 Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
 Select ―Skin File‖.

.NET 4.0 and Visual Studio 2010 Page 345 of 558


D. HARSHA VARDHAN

 Enter the file name as ―MyTheme.skin‖.


 Click on ―Add‖.
 It asks a confirmation, whether you want to place the skin file in the ―App_Themes‖
folder or not. You click on ―Yes‖.

 Then the screen looks like this:

 Delete all the commented code and type the code manually as follows:

.NET 4.0 and Visual Studio 2010 Page 346 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 347 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 348 of 558


D. HARSHA VARDHAN

Skins
 Skins are similar to CSS classes.
 Similar to CSS class, the skin has a name.
 It can be written in the ―.skin‖ file.
 One skin file may contain any no. of skins.

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

Demo:

 Open the previous demo web site.


 Add the ―skinsdemo.aspx‖ page and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 349 of 558


D. HARSHA VARDHAN

 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" />

.NET 4.0 and Visual Studio 2010 Page 350 of 558


D. HARSHA VARDHAN

 Come back to the ―skinsdemo.aspx‖ page.


 Open the properties window and choose ―DOCUMENT‖ option from the list, which is
displayed at the top of the properties window.
 Select the ―Theme‖ property as ―MyTheme2‖ from the list.
 For the first five textboxes, set the following property:
SkinID: PinkAndRed
 For the remaining five textboxes, set the following property:
SkinID: BisqueAndBlue
 Then run the web site.
 At run time, the theme will be applied, and the page looks like this on the browser:

 Note: If you don‘t apply the SkinID property, no style will be applied.
 So finally, we have few textboxes with one style, and few other textboxes with another
style.
 This is possible using Skins.

.NET 4.0 and Visual Studio 2010 Page 351 of 558


D. HARSHA VARDHAN

Web User Controls


 Similar to ―User Controls‖ in windows applications, you can develop user controls in the
web sites also.
 As you know already, the advantage of user controls is, those can be used in any web
page, and avoids designing repetitive content in multiple pages.
 That means you need to design the content once and you can use it any no. of times in
any page.

Implementation of Web User Controls

1. Add the User Control to the Web Site:


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Web User Control‖.
Enter the name of the user control and click on ―Add‖.
Note: The file extension for web control file is ―.ascx‖. (Active Server Control
Extended).
Then the user control will be created with the following statement in the
―Source‖ view.
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>

2. Design and Develop the User Control


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

3. Link the User Control with the Web Page


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

4. Invoke the User Control


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

.NET 4.0 and Visual Studio 2010 Page 352 of 558


D. HARSHA VARDHAN

Demo:

Application 23: Demo on Web User Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Design the ―Default.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 353 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Aboutus.aspx‖ – Click on Add.
 Design the ―Aboutus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 354 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Contactus.aspx‖ – Click on Add.
 Design the ―Contactus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 355 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―registration.aspx‖ – Click on Add.
 Design the ―registration.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 356 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 357 of 558


D. HARSHA VARDHAN

 Come back to the ―Default.aspx‖.


 Drag the ―WebUserControl.ascx‖ and drop it into the page.
 Then the control will be added to the page.

.NET 4.0 and Visual Studio 2010 Page 358 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 359 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 360 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 361 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 362 of 558


D. HARSHA VARDHAN

 Run the web site.

Note: To avoid the repetition of design like above example, you can use another concept called
as ―Master Pages‖.

.NET 4.0 and Visual Studio 2010 Page 363 of 558


D. HARSHA VARDHAN

Master Pages
 Similar to ―User Controls‖, the common design can be shared among multiple web pages
using ―Master Pages‖ concept.
 A master page is similar to web page, but it‘s not a web page.
 The master page file extension is ―.master‖.
 It also contains some design and code in the ―.cs‖ file.
 It can be executed on the browser directly.
 This is meant for re-usability only.
 That means the master page content can be re-usable by other web pages (.aspx
pages).

Implementation of Master Pages

1. Add the Master Page to the Web Site:


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Master Page‖.
Enter the name of the master page and click on ―Add‖. Ex: MasterPage.master

2. Design and Develop the Master Page:


Design the required content in the master page before ―ContentPlaceHolder‖ tag,
and write the necessary code in the ―.master.cs‖ file.
The ―ContentPlaceHolder‖ tag represents the content in the other web pages. In
the master page, it should be empty.

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


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Web Form‖. Enter the name of the new web page.
Select the option ―Select Master Page‖.
Click on ―Add‖.
Then it displays the list of all available master pages in the project. Select the
master page name and click on ―OK‖.
In this content page, you design any content in the ―ContentPlaceHolder‖ tag.

.NET 4.0 and Visual Studio 2010 Page 364 of 558


D. HARSHA VARDHAN

Demo:

Application 24: Demo on Master Pages

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Master Page‖ – Type the name as
―MasterPage.master‖ – Click on Add.
 Design the ―MasterPage.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 365 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖.


 Type the name as ―Default.aspx‖.
 Select the option ―Select Master Page‖.
 Click on Add.
 Select ―MasterPage.master‖.
 Click on OK.
 Design it shows the screen like this:

 Design the new content in content place holder as follows:

.NET 4.0 and Visual Studio 2010 Page 366 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖.


 Type the name as ―Aboutus.aspx‖.
 Select the option ―Select Master Page‖.
 Click on Add.
 Select ―MasterPage.master‖.
 Click on OK.
 Design it shows the screen like this:

.NET 4.0 and Visual Studio 2010 Page 367 of 558


D. HARSHA VARDHAN

 Design the new content in content place holder as follows:

.NET 4.0 and Visual Studio 2010 Page 368 of 558


D. HARSHA VARDHAN

 Run the web site.


 The common content, which you have designed in the master page, will be repeated in
―Aboutus‖ page and ―Default‖ page.
 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 369 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 370 of 558


D. HARSHA VARDHAN

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.

Application 25: Demo on Caching

 Create a new web site.


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

.NET 4.0 and Visual Studio 2010 Page 371 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}

 Open the ―Source‖ view.


 Type the <%@ OutputCache %> tag at the top, after <Page> directive as follows:

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>

.NET 4.0 and Visual Studio 2010 Page 372 of 558


D. HARSHA VARDHAN

 Run the web site.


 When you click the button for the web site, current system time will be displayed.
 But when you click the button every time, the time will not be displayed, because it
executes no code for the second time onwards.
 If you click on the button after 20 seconds, the time will be refreshed. Again, that output
will remain up to another 20 seconds.
 This is the effect of output caching.

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

Fragment caching demo:

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

.NET 4.0 and Visual Studio 2010 Page 373 of 558


D. HARSHA VARDHAN

 Write the code:

WebUserControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}

 Open the ―Source‖ view.


 Type the <%@ OutputCache %> tag at the top, after <Control> directive as follows:

WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>

.NET 4.0 and Visual Studio 2010 Page 374 of 558


D. HARSHA VARDHAN

 Add the ―fragmentcachingdemo.aspx‖ and design it as shown:

 Write the code:

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:

.NET 4.0 and Visual Studio 2010 Page 375 of 558


D. HARSHA VARDHAN

 Run the web site.


 Click on the Submit button. In fact, (if you are not implementing the caching feature),
when you click on the button, the complete page will be posted-back (re-loaded). That
means Page_Load() event also will be executed. At the same time, Page_Load() of Web
User Control also will be executed.
 But in the label, which you have designed in the web page, displays the latest system
time.
 But the user control will not be re-loaded. So that, in the label, which you have designed
in the WebUserControl, latest system time will not be displayed.
 This is the effect of ―fragment caching‖.

.NET 4.0 and Visual Studio 2010 Page 376 of 558


D. HARSHA VARDHAN

Data Caching Demo:

 To continue the demo application with ―Data caching‖, add the ―datacachingdemo.aspx‖
and design it as shown:

 Write the code:

datacachingdemo.aspx.cs
using System.Data.SqlClient;
using System.Data;

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


{
protected void Page_Load(object sender, EventArgs e)
{
//some code for loading the data...
if (Cache["mydata"] == null)
{
SqlConnection cn = new SqlConnection();

.NET 4.0 and Visual Studio 2010 Page 377 of 558


D. HARSHA VARDHAN

cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial


catalog=demo";

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


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

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();
}
}

 Run the web site.


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

.NET 4.0 and Visual Studio 2010 Page 378 of 558


D. HARSHA VARDHAN

Common Tasks in JavaScript

i. Displaying pop-up windows:


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

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


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

Demo:

Application 26: Demo on Common Tasks in JavaScript

 Create a new web site.


 Add the ―popupdemo.aspx‖ and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 379 of 558


D. HARSHA VARDHAN

 Add the ―myad.aspx‖ page and design it as follows with an image control:

.NET 4.0 and Visual Studio 2010 Page 380 of 558


D. HARSHA VARDHAN

 Select the ―DOCUMENT‖ properties in the ―properties window‖ and set the following
property:
Title: Ad
 Type the <body> tag as follows:
<body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>

 Come back to the ―popupdemo.aspx‖.


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

 Run the web site and click on the button. It shows the popup ad automatically.

.NET 4.0 and Visual Studio 2010 Page 381 of 558


D. HARSHA VARDHAN

ii. Displaying dialog boxes:


 JavaScript supports two types of dialog boxes:
1) Alert Boxes (Message Boxes):
Syntax: window.alert("message");

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

Demo:

 Open the previous demo web site.


 Add the ―dialogboxes.aspx‖ and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 382 of 558


D. HARSHA VARDHAN

 Set the button1 properties:


OnClientClick: javascript:window.alert("Hello, World!");
 Set the button2 properties:
OnClientClick: return window.confirm("Are you sure?");

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

.NET 4.0 and Visual Studio 2010 Page 383 of 558


D. HARSHA VARDHAN

 Come back to the ―dialogboxes.aspx‖.


 Double click on button2 and write the code:

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.

.NET 4.0 and Visual Studio 2010 Page 384 of 558


D. HARSHA VARDHAN

iii. Displaying Status Bar Messages on the Browser:


 Syntax:
window.status=‖message‖;

Demo:

 Open the previous demo web site.


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

 Open the page in ―Source‖ view.


 Change the <body> tag as follows:

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

 Change the <asp:Image> tag as follows:

.NET 4.0 and Visual Studio 2010 Page 385 of 558


D. HARSHA VARDHAN

<asp:Image ID="Image1" runat="server" ImageUrl="laptop.jpg"


onMouseOver="javascript:window.status='Click the Image';"
OnMouseOut="javascript:window.status='Move the mouse pointer on to the image...';"
onClick="javascript:window.alert('You have clicked in the image');" />

 Come back to the Design view.


 Run the web site and observe the status bar on the browser.

.NET 4.0 and Visual Studio 2010 Page 386 of 558


D. HARSHA VARDHAN

LINQ
 LINQ (pronounced link) stands for ―Language Integrated Query‖.
 This concept is introduced in .NET Framework 3.5.
 This is a ―query writing technology‖.
 This is most useful while working large amount of data in the live projects.

Introduction:

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

The following example shows a small demo on LINQ:

Application 27: Demo on LINQ

 Create a new web site.


 Add the ―linqtoarraysdemo.aspx‖ page.
 Write the code:

.NET 4.0 and Visual Studio 2010 Page 387 of 558


D. HARSHA VARDHAN

protected void Page_Load(object sender, EventArgs e)


{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 9, 99, 4, 62 };

//ling query
var result = from n in numbers where n < 10 select n;

//output
foreach (var x in result)
Response.Write(x + ", ");
}

 Run the web site.


 You get the output as follows:

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

LINQ Syntax:

from … in … let … where … orderby … select … group by …

.NET 4.0 and Visual Studio 2010 Page 388 of 558


D. HARSHA VARDHAN

 The above syntax consists of 7 clauses.


 from clause
 in clause
 let clause
 where clause
 orderby clause
 select clause
 group by clause

 Mandatory clauses:
 from clause
 in clause
 select clause

Clause: A part of the query.

Understanding Clauses:

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

.NET 4.0 and Visual Studio 2010 Page 389 of 558


D. HARSHA VARDHAN

Note: The LINQ query returns the result in the form of IEnumerable<data type> type.
IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable

Demo on LINQ to Objects:

 Open the previous demo web site.


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

Student.cs

public class Student


{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;

//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}

.NET 4.0 and Visual Studio 2010 Page 390 of 558


D. HARSHA VARDHAN

 Add the ―linqtoobjectsdemo.aspx‖ page.


 Write the code:

linqtoobjectsdemo.aspx.cs

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


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

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

//linq query with compound where clause


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

//linq query with let and where clauses


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

//linq query with orderby clause


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

.NET 4.0 and Visual Studio 2010 Page 391 of 558


D. HARSHA VARDHAN

//linq query with orderby clause (descending)


var result5 = from s in stu orderby s.Marks descending select s;
Response.Write("<br>Students (sort on marks - descending):" + "<br>");
foreach (Student r in result5)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with group clause


var result6 = from s in stu group s by s.Course;
Response.Write("<br>Students with grouping:" + "<br>");
foreach (var StuGrp in result6)
{
Response.Write(StuGrp.Key + ":" + "<br>");
foreach (Student r in StuGrp)
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:

.NET 4.0 and Visual Studio 2010 Page 392 of 558


D. HARSHA VARDHAN

LINQ with Lambda Expressions


 LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
 The previously written linq queries are written with ―General Query Syntax‖.
 Syntax for Lambda Expression:
DataSource.Clause(range_variable_name => Expression)
 Ex:
stu.Where(s => s.Marks < 300)

goes to

.NET 4.0 and Visual Studio 2010 Page 393 of 558


D. HARSHA VARDHAN

Demo on LINQ with Lambda Expressions:

 Open the previous demo web site.


 Add the ―linqwithlambda.aspx‖ page.
 Write the code:

linqwithlambda.cs

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


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

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

//linq query with where clause


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

//linq query with compound where clause


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

//linq query with orderby clause


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

//linq query with orderby clause (descending)


var result5 = stu.OrderByDescending(s => s.Marks);

.NET 4.0 and Visual Studio 2010 Page 394 of 558


D. HARSHA VARDHAN

Response.Write("<br>Students (sort on marks - descending): <br>");


foreach (Student r in result5)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with group clause


var result6 = stu.GroupBy(s => s.Course);
Response.Write("<br>Students with grouping: <br>");
foreach (var StuGrp in result6)
{
Response.Write(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Response.Write(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks + "<br>");
}

Response.Write("</font>");
}
}

.NET 4.0 and Visual Studio 2010 Page 395 of 558


D. HARSHA VARDHAN

LINQ to SQL
 This is to get the database data and perform LINQ queries on database data.

Demo on LINQ to SQL:

 Open SQL Server 2005.


 Create the ―Customers‖ table as follows:

 Enter some sample data:

.NET 4.0 and Visual Studio 2010 Page 396 of 558


D. HARSHA VARDHAN

 Create the ―Orders‖ table as follows:

.NET 4.0 and Visual Studio 2010 Page 397 of 558


D. HARSHA VARDHAN

 Enter some sample data:

.NET 4.0 and Visual Studio 2010 Page 398 of 558


D. HARSHA VARDHAN

 Right click on ―Database Diagrams‖ and click on ―New Database Diagram‖.


 It displays ―Add Table‖ dialog box.

 Select ―Customers‖ table and click on ―Add‖.

.NET 4.0 and Visual Studio 2010 Page 399 of 558


D. HARSHA VARDHAN

 Select ―Orders‖ table and click on ―Add‖.


 Click on ―Close‖.
 Drag the ―CustomerID‖ column from ―Customers‖ table and drop it on ―CustomerID‖
column in ―Orders‖ table.
 Click on OK.
 Click on OK.
 Save the diagram.

 Open Visual Studio 2010.


 Open the previous demo web site.
 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―LINQ to SQL Classes‖.
 Enter the file name as ―MyDB.dbml‖. (DBML stands for Database Markup Language).
 It asks for confirmation, whether you want to place the file in the ―App_Code‖ folder or
not. Click on ―Yes‖.
 Open the ―Server Explorer‖ by clicking on ―View‖ menu – ―Server Explorer‖.
 Right click on ―Data Connections‖ and click on ―Add Connection‖.
 Click on ―Change‖.
 Select the required database. Ex: ―Microsoft SQL Server‖.
 Enter the following details:
1. Server name: localhost
2. Use SQL Server Authentication:
 User name: sa
 Password: 123
3. Database name: demo
 Click on ―Test Connection‖. It displays connection succeeded message.
 Click on OK.
 Then a connection component will be created in the ―Server Explorer‖.
 Expand the ―demo‖ database in the server explorer.
 Expand ―Tables‖.
 Drag and drop the ―Customers‖ table into the DBML designer.
 In the same way, drag and drop the ―Orders‖ table into the DBML designer.

.NET 4.0 and Visual Studio 2010 Page 400 of 558


D. HARSHA VARDHAN

 Click on the plain area and observe the properties window.


 It shows the DataContext name, associated with this DBML file.
Ex: MyDBDataContext
 This is the class name, using which you can create the object while you write the code.
 Using with that object, you can access the ―Customers‖ and ―Orders‖ tables data.
 But you don‘t require writing any code for database connection and retrieving the data
from the database.
 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―Web Form‖.
 Enter the name as ―linqtosqldemo.aspx‖.
 Click on ―Add‖.
 Design the ―linqtosqldemo.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 401 of 558


D. HARSHA VARDHAN

 Write the code:

linqtosqldemo.aspx.cs:

protected void LinkButton1_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from c in db.Customers select c;

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

.NET 4.0 and Visual Studio 2010 Page 402 of 558


D. HARSHA VARDHAN

protected void LinkButton3_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Where(c => c.Gender == "Female");

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

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

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

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

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

.NET 4.0 and Visual Studio 2010 Page 403 of 558


D. HARSHA VARDHAN

var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);

var customerslist = customerslist1.Union(customerslist2);

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

var customerslist = customerslist1.Intersect(customerslist2);

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

var customerslist = customerslist1.Except(customerslist2);

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

GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}

.NET 4.0 and Visual Studio 2010 Page 404 of 558


D. HARSHA VARDHAN

protected void LinkButton12_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var Sum = db.Customers.Select(ct => ct.Amount).Sum();
var Avg = db.Customers.Select(ct => ct.Amount).Average();
var Min = db.Customers.Select(ct => ct.Amount).Min();
var Max = db.Customers.Select(ct => ct.Amount).Max();
var Count = db.Customers.Select(ct => ct.Amount).Count();

Label2.Text = "Sum: " + Sum + "<br>";


Label2.Text += "Average: " + Avg + "<br>";
Label2.Text += "Minimum: " + Min + "<br>";
Label2.Text += "Maximum: " + Max + "<br>";
Label2.Text += "Count: " + Count + "<br>";

GridView1.DataSource = null;
GridView1.DataBind();
}

 Run the web site and click on the link buttons.

.NET 4.0 and Visual Studio 2010 Page 405 of 558


D. HARSHA VARDHAN

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

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


<employees>
<emp>
<empid>101</empid>
<empname>Ram</empname>
<salary>8739</salary>
</emp>
<emp>
<empid>102</empid>
<empname>Sita</empname>
<salary>6782</salary>
</emp>
<emp>
<empid>103</empid>
<empname>Laxman</empname>
<salary>7832</salary>
</emp>
</employees>

.NET 4.0 and Visual Studio 2010 Page 406 of 558


D. HARSHA VARDHAN

Application 28: Demo on XML Usage in ASP.NET

 Create a new web site.


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

employees.xml

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


<employees>
<emp>
<empid>101</empid>
<empname>Ram</empname>
<salary>8739</salary>
</emp>
<emp>
<empid>102</empid>
<empname>Sita</empname>
<salary>6782</salary>
</emp>
<emp>
<empid>103</empid>
<empname>Laxman</empname>
<salary>7832</salary>
</emp>
</employees>

 Design the ―Default.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 407 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

using System.Data;

protected void Page_Load(object sender, EventArgs e)


{
DataSet ds = new DataSet();
string filename = Request.PhysicalApplicationPath + "\\employees.xml";
ds.ReadXml(filename);
GridView1.DataSource = ds;
GridView1.DataBind();
}

 Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 408 of 558


D. HARSHA VARDHAN

 Output:

.NET 4.0 and Visual Studio 2010 Page 409 of 558


D. HARSHA VARDHAN

Web Site Configuration


 For every application, some settings will be there.
 For example, for MS Word, there is an option called ―Word Options‖, where you can set
some settings related to MS Word software. For another example, for winamp also some
settings will be there like last opened play list, last played media file, last used theme,
status of ―Repeat‖ and ―Shuffle‖ options etc.
 For the ASP.NET web sites also, some settings are there.
 Those settings are written in a file called ―web.config‖.
 In fact, there are two files:
1. web.config
2. machine.config
 The above two are called as web configuration files in ASP.NET.

Sl. No web.config machine.config


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

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


 To open the machine.config file, open the following folder.
C:\WINDOWS\Microsoft.NET\Framework\ v4.0.30319\Config
 Double click on ―machine.config‖ file.

.NET 4.0 and Visual Studio 2010 Page 410 of 558


D. HARSHA VARDHAN

 Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.

Application 29: Demo on Web Site Configuration

Understanding the web.config file:


 Create a new web site.
 When you create the web site, automatically this file will be created.
 To open this, open Solution Explorer and double click on ―web.config‖ file.

.NET 4.0 and Visual Studio 2010 Page 411 of 558


D. HARSHA VARDHAN

 The xml document starts with XML prologue, which specifies the xml version.

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

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

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

.NET 4.0 and Visual Studio 2010 Page 412 of 558


D. HARSHA VARDHAN

 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>

 Open the ―Default.aspx‖ page and design it as follows:

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 413 of 558


D. HARSHA VARDHAN

using System.Configuration;

protected void Page_Load(object sender, EventArgs e)


{
Label2.Text = ConfigurationManager.AppSettings["CompanyLocation"];
Label3.Text = "Ph: " + ConfigurationManager.AppSettings["PhoneNo"];
}

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

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

.NET 4.0 and Visual Studio 2010 Page 414 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 415 of 558


D. HARSHA VARDHAN

 Write the code:

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
cn.Open();
Label4.Text = "Connected Successfully!!";
cn.Close();
}

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


 This tag specifies the mode of debug (true / false).

<compilation debug="true">

.NET 4.0 and Visual Studio 2010 Page 416 of 558


D. HARSHA VARDHAN

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

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

 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:

.NET 4.0 and Visual Studio 2010 Page 417 of 558


D. HARSHA VARDHAN

<error statusCode="404" redirect="FileNotFound.htm" />

 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‖.

.NET 4.0 and Visual Studio 2010 Page 418 of 558


D. HARSHA VARDHAN

 Enter the file name as ―FileNotFound.htm‖.


 Click on ―Add‖.
 Design the ―FileNotFound.htm‖ page as follows:

 Change the <customErrors> mode as ―On‖.

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

 Run the web site and enter the non-existing file name as follows:

.NET 4.0 and Visual Studio 2010 Page 419 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 420 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 421 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 422 of 558


D. HARSHA VARDHAN

Session State Modes in web.config file


 Let us continue with the discussion of web.config file.
 In that file, you can configure the session state modes using <sessionState> tag.

<sessionState mode="InProc">
</sessionState>

 The session state modes are:


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

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

Demo on Session States:

 Open the previous demo application.


 Add the ―sessiontest.aspx‖ page and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 423 of 558


D. HARSHA VARDHAN

 Write the code:

sessiontest.aspx.cs

protected void Button1_Click(object sender, EventArgs e)


{
Session["uname"] = TextBox1.Text;
Response.Redirect("display.aspx");
}

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

.NET 4.0 and Visual Studio 2010 Page 424 of 558


D. HARSHA VARDHAN

 Write the code:

display.aspx.cs

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "The session value is: " + Convert.ToString(Session["uname"]);
}

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


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

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

.NET 4.0 and Visual Studio 2010 Page 425 of 558


D. HARSHA VARDHAN

 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‖.

 Then the service will be started.


 Come back to Visual Studio and run the ―sessionstate.aspx‖ page now. It works properly
now. So that currently session state is being maintained in ASP.NET State Server only.
 Open the web.config file and change the <sessionState> tag as follows:

<sessionState mode="SQLServer">
</sessionState>

.NET 4.0 and Visual Studio 2010 Page 426 of 558


D. HARSHA VARDHAN

 Now, run the ―sessiontest.aspx‖ page. It won‘t work properly; because you have
specified that session state is to be maintained in SQL Server database. But by default,
that SQL Server is not configured to store the sessions. You have to configure it
manually.
 To do so, open the following folder:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

 Double click on ―InstallSqlState.sql‖ file.


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

.NET 4.0 and Visual Studio 2010 Page 427 of 558


D. HARSHA VARDHAN

<sessionState mode="SQLServer" sqlConnectionString="data source=localhost;user


id=sa;password=123;">
</sessionState>

 Then sesssiontest.aspx page works properly.

Working with ASP.NET Configuration Tool:

 This is the in-built features of Visual Studio.


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

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

.NET 4.0 and Visual Studio 2010 Page 428 of 558


D. HARSHA VARDHAN

 There, we have three major options.


1. Security
2. Application Configuration
3. Provider Configuration
 Click on ―Security‖.

.NET 4.0 and Visual Studio 2010 Page 429 of 558


D. HARSHA VARDHAN

 There, you have three options.


1. Users: To create or modify the users-information, who are registered with
―Login Controls‖.
2. Roles: To create or manage the user roles like ―admin‖ role, ―customer‖ role and
―guest‖ role etc.
3. Access Roles: To apply the privileges of the users that specifies ―which users
can access which pages‖.
 Note: We will discuss about this ―Security‖ concepts in the next chapters more in-depth.
 Come back to ―Home‖ and click on ―Application Configuration‖. Then it opens the
―Application‖ tab.

.NET 4.0 and Visual Studio 2010 Page 430 of 558


D. HARSHA VARDHAN

 Here, we have four options:


1. Application Settings
2. SMTP Settings
3. Application Status
4. Debugging and Tracing
 Application Settings: Using this option, you can create or modify the application
settings (just like <appSettings> tag in web.config file).
 Click on ―Manage application settings‖. Then it shows application settings, which are
already configured in web.config file.

.NET 4.0 and Visual Studio 2010 Page 431 of 558


D. HARSHA VARDHAN

 To add a new application setting, click on ―Create new application setting‖ option.
 Enter the name and value of the application setting.

.NET 4.0 and Visual Studio 2010 Page 432 of 558


D. HARSHA VARDHAN

 Click on ―Save‖.
 Click on OK.

.NET 4.0 and Visual Studio 2010 Page 433 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 434 of 558


D. HARSHA VARDHAN

 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>

.NET 4.0 and Visual Studio 2010 Page 435 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 436 of 558


D. HARSHA VARDHAN

 Here, you can select any other page, which acts as default error page.
 Click on ―Save‖.
 Provider: Always, it should be ―AspNetSqlProvider‖ only.

.NET 4.0 and Visual Studio 2010 Page 437 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 438 of 558


D. HARSHA VARDHAN

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

Application 30: Demo on Tracing

 Create a new web site.


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

 Open the ―DOCUMENT‖ properties and set the following property:


Trace: true

.NET 4.0 and Visual Studio 2010 Page 439 of 558


D. HARSHA VARDHAN

 Run the web site.


 It displays the output as follows:

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


1. Details about the request.
2. Trace information (execution flow of all the page level events).
3. Information about the controls, used in the page.
4. Session state variables details.
5. Application state variables details.
6. Cookies details, which are added to the ―Request‖ object.
7. Cookies details, which are added to the ―Response‖ object.
8. Headers collection.
9. Form collection (the values come from the previous client page, if any)
10. Other server side details.
 Just for information, you see all those details. Note that, all this information is read-only.
 Close the browser.
 To enable the tracing feature for all the web pages in your web site, open the
―web.config‖ file and write the following tag:

.NET 4.0 and Visual Studio 2010 Page 440 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 441 of 558


D. HARSHA VARDHAN

ASP.NET Web Site Security


 This is to make the web site secured, which would not be accessible by un-authorized
users.
 Currently your web site is accessible by everyone. Now, our target is to make the web
site to be secured, which is accessible by authorized users, and not accessible by
unauthorized users.
 For this task, ASP.NET provides some security models:
1. Windows based authentication
2. Forms based authentication
3. Role based authentication
 Windows based authentication: For maintenance of user names and passwords, we
depend on Windows O/S. That means, for some of the windows users, the web site
accessible; and for other windows users, the web site is inaccessible.
 Forms based authentication: For maintenance of user names and password, we
depend on ―ASPNETDB‖ database, which will be created by ASP.NET automatically, when
we use Login controls. Anyway, identifying the genuine user can be done using the
above maintained users database. In other words, for users who logged-in properly only,
the web site accessible; if the user is not logged-in properly, any of the web pages are
not accessible.
 Role based authentication: According to this, we need to maintain the different user
roles like administrator, manager, customer, normal user, guest etc. At run time, if any
user logs-in, ASP.NET checks the type of the user, and allows to access the related web
pages only; other pages are inaccessible. For example, if manager logs-in, the ―manager‖
related pages only are accessible. He can‘t access administrator pages or customer
related pages.
 To demonstrate these authentication modes practically, we start with an example.

Application 31: Demo on Web Site Security

.NET 4.0 and Visual Studio 2010 Page 442 of 558


D. HARSHA VARDHAN

 Create a new web site.


 Add the ―Default.aspx‖ and design it as shown:

Windows based Security:


 First, let us start with understanding the windows based security.
 To do so, first open the ―Control Panel‖ – ―User Accounts‖ and create some users.

.NET 4.0 and Visual Studio 2010 Page 443 of 558


D. HARSHA VARDHAN

For this demo, create 3 users named ―ram‖, ―sita‖ and ―laxman‖.

.NET 4.0 and Visual Studio 2010 Page 444 of 558


D. HARSHA VARDHAN

 Come back to our web site in Visual Studio.


 Now, you have to specify the list of windows users, who are eligible or permitted to
access this web site.
 Syn: systemname\username
 Ex: development01\admin
 Here, ―development01‖ is the system name; ―admin‖ is the user name.
 Note: To know your system name, right click on ―My Computer‖ and click on
―Properties‖. Select ―Computer name‖ and then observe the ―Full computer name‖.
 Open the web.config file and type the <authentication> tag as follows:

<authentication mode="Windows">
</authentication>

<authorization>
<allow users="localhost\ram"/>
<allow users="localhost\sita"/>
<deny users="*"/>
</authorization>

.NET 4.0 and Visual Studio 2010 Page 445 of 558


D. HARSHA VARDHAN

 Now, if you login as ―ram‖ or ―sita‖, the web site can be accessed normally.
 If other users logged-in, the web site is inaccessible. If you try to open the web site,
while you are in other user name (other than ram and sita), then it shows the following
type of message on the browser:

 This is nothing but ―Windows based security‖.

.NET 4.0 and Visual Studio 2010 Page 446 of 558


D. HARSHA VARDHAN

Forms based Security:

 Open the previous demo web site.


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

 Set the properties of ―CreateUserWizard1‖:


 ContinueDestinationPageUrl: mainpage.aspx
 Set the properties of ―Login1‖:
 DestinationPageUrl: mainpage.aspx

.NET 4.0 and Visual Studio 2010 Page 447 of 558


D. HARSHA VARDHAN

 Add the ―mainpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 448 of 558


D. HARSHA VARDHAN

 Add the ―AboutUs.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 449 of 558


D. HARSHA VARDHAN

 Add ―ContactUs.aspx‖ page and design it as shown:

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

<authentication mode="Forms">
<forms loginUrl="Default.aspx"></forms>
</authentication>

<authorization>
<deny users="?"/>
</authorization>

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


without login. Those can‘t be executed. It automatically reverts to ―Default.aspx‖ page.
 After you login properly, you can open any page.

.NET 4.0 and Visual Studio 2010 Page 450 of 558


D. HARSHA VARDHAN

Role based Security:

 To understand this, do the following steps:


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

 Right click on ―guest‖ folder and click on ―Add New Item‖. Select ―Web Form‖. Enter the
file name as ―guestwelcome.aspx‖. Click on ―Add‖. Then the page will be added in
―guest‖ folder.
 Design the ―guestwelcome.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 451 of 558


D. HARSHA VARDHAN

 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‖.

.NET 4.0 and Visual Studio 2010 Page 452 of 558


D. HARSHA VARDHAN

 It shows the no. of ―Existing Users‖ as ―3‖.


 You can click on ―Create User‖ option to register a new user. To modify the details of
existing users, you can click on ―Manage Users‖.
 Now, click on ―Select authentication type‖.

.NET 4.0 and Visual Studio 2010 Page 453 of 558


D. HARSHA VARDHAN

 Select ―From the internet‖ option.


 Click on ―Done‖.
 Click on ―Enable Roles‖. Then user roles will be enabled.
 Now, you have to create two roles. (admin and guest).
 To do so, click on ―Create or Manage Roles‖.

.NET 4.0 and Visual Studio 2010 Page 454 of 558


D. HARSHA VARDHAN

 Enter the role name as ―admin‖ and click on ―Add Role‖.


 Enter one more role name as ―guest‖ and click on ―Add Role‖.

.NET 4.0 and Visual Studio 2010 Page 455 of 558


D. HARSHA VARDHAN

 Click on ―Manage‖ option, which is at right side of ―admin‖ role.

.NET 4.0 and Visual Studio 2010 Page 456 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 457 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 458 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 459 of 558


D. HARSHA VARDHAN

 Click on ―Create Access Rules‖ option. Click on ―SecurityDemo‖ (web site name). Select
―All Users‖ – Select ―Allow‖. Click on OK.

.NET 4.0 and Visual Studio 2010 Page 460 of 558


D. HARSHA VARDHAN

 Click on ―Create Access Rules‖ option again. Click on ―admin‖ folder in the tree structure.
Select ―admin‖ role – Select ―Allow‖. Click on OK.

.NET 4.0 and Visual Studio 2010 Page 461 of 558


D. HARSHA VARDHAN

 Click on ―Create Access Rules‖ option again. Click on ―admin‖ folder in the tree structure.
Select ―guest‖ role – Select ―Deny‖. Click on OK.

.NET 4.0 and Visual Studio 2010 Page 462 of 558


D. HARSHA VARDHAN

 Click on ―Create Access Rules‖ option again. Click on ―guest‖ folder in the tree structure.
Select ―admin‖ role – Select ―Deny‖. Click on OK.

.NET 4.0 and Visual Studio 2010 Page 463 of 558


D. HARSHA VARDHAN

 Click on ―Create Access Rules‖ option again. Click on ―guest‖ folder in the tree structure.
Select ―guest‖ role – Select ―Allow‖. Click on OK.

 Now, all the access rules are created.


 Finally admin role users can access admin pages only and guest role users can access
guest pages only.
 Close the browser and come back to Visual Studio.
 Right click on ―adminwelcome.aspx‖ and click on ―View in Browser‖. It shows the
Default.aspx page. Login as ―satya‖. After login, adminwelcome.aspx page will be
displayed. Here ―adminwelcome.aspx‖ page is allowed, because ―satya‖ is in ―admin‖
role.
 Close the browser.
 Right click on ―adminwelcome.aspx‖ and click on ―View in Browser‖. It shows the
Default.aspx page. Login as ―syam‖ or ―sridhar‖. After login, adminwelcome.aspx page
will not be displayed. Here ―adminwelcome.aspx‖ page is not allowed, because ―syam‖
and ―sridhar‖ are in ―guest‖ role.
 In the same way, test the ―guestwelcome.aspx‖ also.
 This is the implementation of Role based security.

.NET 4.0 and Visual Studio 2010 Page 464 of 558


D. HARSHA VARDHAN

Localization and Globalization


 Localization: Displaying a page contents in the selected regional language.
 Globalization: Displaying all pages in the selected regional language.
 To specify the required language culture, you require the culture code. The culture code
contains 4 alphabets, separated with hyphen (-).
Ex: hi-IN (Hindi – India)
te-IN (Telugu – India)
en-US (English – US)
etc.
 Changing the culture will be automatically effected in number formats, default date and
time formats, week names, calendar control, currency styles etc.

Application 32: Demo on Localization and Globalization

 Create a new web site.


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

.NET 4.0 and Visual Studio 2010 Page 465 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)


{
Label2.Text = DateTime.Now.ToString();
Label3.Text = DateTime.Now.ToLongDateString();
double amount = 4359020;
Label4.Text = amount.ToString("C");
}

 Run the web site. Output:

.NET 4.0 and Visual Studio 2010 Page 466 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 467 of 558


D. HARSHA VARDHAN

 Run the web site. Output:

.NET 4.0 and Visual Studio 2010 Page 468 of 558


D. HARSHA VARDHAN

 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:

.NET 4.0 and Visual Studio 2010 Page 469 of 558


D. HARSHA VARDHAN

 Now, you can observe the output in telugu language, by following the Indian date & time
formats and currency formats.
 This concept is called as ―Localization‖.

Allowing the user to change the culture at run time:

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

.NET 4.0 and Visual Studio 2010 Page 470 of 558


D. HARSHA VARDHAN

 Write the code, same as ―Default.aspx‖ page.

UserSelectedCulture.aspx.cs

protected void Page_Load(object sender, EventArgs e)


{
Label2.Text = DateTime.Now.ToString();
Label3.Text = DateTime.Now.ToLongDateString();
double amount = 4359020;
Label4.Text = amount.ToString("C");
}

 Set the following property of DOCUMENT object:


Culture: auto:hi-IN
 Hi = Hindi
 IN = India
 Note: The word ―auto‖ allows ASP.NET, to display the contents in user-selected culture.
 Run the web site. By default it displays the contents in Hindi language as usual.

.NET 4.0 and Visual Studio 2010 Page 471 of 558


D. HARSHA VARDHAN

 Click on ―Tools‖ menu – ―Internet Options‖ – ―Languages‖ – ―Add‖.


 Select the required language. Ex: ta-IN
 ta = Tamil
 IN = India

.NET 4.0 and Visual Studio 2010 Page 472 of 558


D. HARSHA VARDHAN

 Click on OK.
 Move the culture to up; because top culture only be considered in the list.

.NET 4.0 and Visual Studio 2010 Page 473 of 558


D. HARSHA VARDHAN

 Click on OK.
 Click on OK.
 Click on ―Refresh‖.
 Then the contents will be displayed in Tamil language.

.NET 4.0 and Visual Studio 2010 Page 474 of 558


D. HARSHA VARDHAN

 This also comes under ―Localization‖.

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

<globalization culture="fr-CA"/>
(or)
<globalization culture="auto:fr-CA"/>

 fr = French and CA = Canada


 Note: Don‘t specify any culture in the web page.
 Run the web site. Then the output will be displayed in specified culture.
 This is nothing but globalization.

.NET 4.0 and Visual Studio 2010 Page 475 of 558


D. HARSHA VARDHAN

Sending E-Mails using SMTP Protocol


 SMTP stands for Simple Mail Transfer Protocol.
 Using SMTP protocol, you can send E-Mails to any mail domain like yahoo, gmail, hotmal
etc.
 In the modern world, being a developer, usually you may require to send automatic E-
Mails through your application. There, you require to use this SMTP protocol.
 SMTP depends on a web server called IIS. In other words SMTP is used to send the E-
mails, by taking the support of IIS server.
 Library: System.Net.Mail.SmtpClient
 This class object act as a client for SMTP protocol, which can send a request to SMTP
server, to send an E-mail.

Implementation Code:

 Import the namespace:


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

Application 33: Demo on SMTP Protocol

 Create a new web site.


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

.NET 4.0 and Visual Studio 2010 Page 476 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

using System.Net.Mail;

protected void Button1_Click(object sender, EventArgs e)


{
SmtpClient sc = new SmtpClient("localhost");
sc.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
sc.Send(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text);
Label6.Text = "E-Mail Sent Successfully!!";
}

 Run the web site and test it:

.NET 4.0 and Visual Studio 2010 Page 477 of 558


D. HARSHA VARDHAN

 Check the mail: Open the following directory:


C:\Inetpub\mailroot\Drop

.NET 4.0 and Visual Studio 2010 Page 478 of 558


D. HARSHA VARDHAN

 Double click on the E-mail file.

.NET 4.0 and Visual Studio 2010 Page 479 of 558


D. HARSHA VARDHAN

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

Understanding MailMessage Class:

MailMessage
 MailMessage(“from”, “to”, “subject”, “message
body”)
 Attachments

.NET 4.0 and Visual Studio 2010 Page 480 of 558


D. HARSHA VARDHAN

 MailMessage(―from‖, ―to‖, ―subject‖, ―message body‖)


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

Demo on E-Mails with Attachments:

 Open the previous demo web site.


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

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 481 of 558


D. HARSHA VARDHAN

EMailsWithAttachmentsDemo.aspx.cs

using System.Net.Mail;

protected void Button1_Click(object sender, EventArgs e)


{
SmtpClient sc = new SmtpClient("localhost");
sc.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

string AppPath = Request.PhysicalApplicationPath;


FileUpload1.SaveAs(AppPath + FileUpload1.FileName);
FileUpload2.SaveAs(AppPath + FileUpload2.FileName);

Attachment att1 = new Attachment(AppPath + FileUpload1.FileName);


Attachment att2 = new Attachment(AppPath + FileUpload2.FileName);

MailMessage mail = new MailMessage(TextBox1.Text, TextBox2.Text, TextBox3.Text,


TextBox4.Text);

mail.Attachments.Add(att1);
mail.Attachments.Add(att2);

sc.Send(mail);
Label8.Text = "E-Mail Sent Successfully!!";
}

 Run the web site:

.NET 4.0 and Visual Studio 2010 Page 482 of 558


D. HARSHA VARDHAN

 Test the e-mail:

.NET 4.0 and Visual Studio 2010 Page 483 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 484 of 558


D. HARSHA VARDHAN

ASP.NET Web Services


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

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

.NET 4.0 and Visual Studio 2010 Page 485 of 558


D. HARSHA VARDHAN

 In this case, web services are used to solve the problem; and indirectly the web service
allows you to get connected with the bank database and also to perform necessary
validations.

Purpose of Web Services:


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

Important Tips related to Web Services:


 A web service doesn‘t contain any user interface. In other words, it doesn‘t contain any
web pages.
 It contains only the re-usable code (similar to ClassLibrary Project).
 Web Services run based on SOAP (Simple Object Access Protocol).
 After compiling your web service, visual studio gives an URL for your web service. With
that URL, any other programmer can link the web service from his/her web site through
online.
 The methods written in the web service are called as ―Web Methods‖.
 Those web methods directly can be called from any other web sites.
 While executing the web methods online, necessary arguments can be passed from the
web site. After executing the web method, the return value will be passed to the web
site.
 As above, the arguments and return values can be transferred through web in XML
format.

.NET 4.0 and Visual Studio 2010 Page 486 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 487 of 558


D. HARSHA VARDHAN

Application 34: Demo on Web Services

Development of ASP.NET Web Services


 Creating a new ASP.NET Web Service:
 Click on ―File‖ – ―New‖ – ―Web Site‖.
 Select the template as ―ASP.NET Web Service‖.
 Select the
Location as
―File System‖.
 Select the
Language as
―Visual C#‖.
 Enter the
path and
name of the
web service,
where it is to
be saved.
 Ex: SimpleWebServiceDemo
 Click on OK.
 Then the specified web service will be created.

 Understanding the Web Service Directory Structure:


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

 Syntax of Web Method:


[WebMethod]

.NET 4.0 and Visual Studio 2010 Page 488 of 558


D. HARSHA VARDHAN

public returntype methodname(arguments)


{
//some code
return(value);
}
Note: The line [WebMethod] provides the information to the compiler, that the next coming
method is a web method, that should be invoked through SOAP protocol.

.NET 4.0 and Visual Studio 2010 Page 489 of 558


D. HARSHA VARDHAN

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

 Testing the Web Methods:


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

 Click on the web method name, which you want to execute. Ex:
GetRandomNumber.
 Then enter the values for the arguments (for min and max).

.NET 4.0 and Visual Studio 2010 Page 490 of 558


D. HARSHA VARDHAN

 Then click on ―Invoke‖ button.


 Then a request to
the web service will
be passed and the
web method will be
executed.
 Finally, you can get
the returned value
in xml format.

 Having the URL of Web Services:


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

Invoking the ASP.NET Web Services from a Web Site


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

 Create a new ASP.NET Web Site:


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

 Link the Web Service, with your Web Site:


 Click on ―Web Site‖ menu – ―Add Web Reference‖.
 Then enter the URL of your web service.
 Ex: http://localhost:1360/SimpleWebServiceDemo/Service.asmx

.NET 4.0 and Visual Studio 2010 Page 491 of 558


D. HARSHA VARDHAN

 Click on ―GO‖.
 Then it displays
the ―service.asmx‖
page.
 After that, you
have to enter the
web reference
name. Ex: MyRef
 A web reference
acts as
representation for
web service.
 Finally click on ―Add Reference‖.
 Then the web service will be linked with your web site; and the necessary files will be
copied into the web site folder.

 Call the Web Methods:


 Design the ―Default.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 492 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

using MyRef;

protected void Page_Load(object sender, EventArgs e)


{
Service s = new Service();
Response.Write(s.HelloWorld());
}
protected void btnGetRandomNumber_Click(object sender, EventArgs e)
{
Service s = new Service();
int min = Convert.ToInt32(txtMinimum.Text);
int max = Convert.ToInt32(txtMaximum.Text);
int r = s.GetRandomNumber(min, max);
txtRandomNumber.Text = Convert.ToString(r);
}

 Run the web site and test it.

.NET 4.0 and Visual Studio 2010 Page 493 of 558


D. HARSHA VARDHAN

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.

With so many options available to a Microsoft developer, it can be tough to


decide which path to take with the applications you are trying to build. With this in mind,
Microsoft has created the Windows Communication Foundation (WCF). WCF is a new framework
for building service-oriented applications. Microsoft wanted to provide its developers with a
framework to quickly get a proper service-oriented architecture up and running.

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.

.NET 4.0 and Visual Studio 2010 Page 494 of 558


D. HARSHA VARDHAN

The Larger Move to SOA


Upon examining WCF, you will find that it is part of a larger movement that
organizations are making toward the much talked about service-oriented architecture, or SOA. An
SOA is a message-based service architecture that is vendor agnostic. As a result, you have the
capability to distribute messages across. a system, and the messages are interoperable with
other systems that would otherwise be considered incompatible with the provider system.

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

.NET 4.0 and Visual Studio 2010 Page 495 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 496 of 558


D. HARSHA VARDHAN

Building a WCF Service


Building a WCF service is not hard to accomplish. If you are working from a .NET
Framework 2.0 environment, you need to install the .NET Framework 3.0. If you have installed
the . NET Framework 3.5, then you will find that both the .NET Framework 2.0 and 3.0 have
been installed also. From there, it is easy to build WCF services directly in Visual Studio 2008
because it is already geared to work with this application type. If you are working with Visual
Studio 2005, you need to install the Visual Studio 2005 extensions for .NET Framework 3.0 (WCF
and WPF). Download these Visual Studio extensions, if you are using Visual Studio 2005.
Installing the extensions into Visual Studio 2005 adds a WCF project to your IDE. If you are using
Visual Studio 2008, the view of the project from the New Web Site dialog box.

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.

What Makes a WCF Service?


When looking at a WCF service, it is important to understand that it is made up
of three parts: the service, one or more endpoints, and an environment in which to host the
service. A service is a class that is written in one of the .NET-compliant languages. The class can
contain one or more methods that are exposed through the WCF service. A service can have one
or more endpoints. An endpoint is used to communicate through the service to the client.
Endpoints themselves are also made up of three parts. These parts are usually defined by

.NET 4.0 and Visual Studio 2010 Page 497 of 558


D. HARSHA VARDHAN

Microsoft as the ABC of WCF. Each letter of WCF means something in particular in the WCF
model, including the following:

❑ ‗‗A‘‘ is for address


❑ ‗‗B‘‘ is for binding
❑ ‗‗C‘‘ is for contract

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.

.NET 4.0 and Visual Studio 2010 Page 498 of 558


D. HARSHA VARDHAN

Creating Your First WCF Service

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.

Working with the Interface


To create your service, you need a service contract. The service contract is the interface of the
service. This consists of all the methods exposed, as well as the input and output parameters
that are required to invoke the methods. To accomplish this task, turn to the IService.cs and write
the method definitions there. Then come back to the ―Service‖ class, inherit it from ―IService‖;
then implement the method definitions in that ―Service‖ class.

Application 35: Demo on WCF Services

 Open Visual Studio 2010.


 Click on ―File‖ menu – ―New‖ – ―Web Site‖.
 Select the language as ―Visual C#‖.
 Select ―WCF Service‖.
 Select the location as HTTP or File System.
 Enter the name of the WCF Service. Ex: D:\MyWCFService

.NET 4.0 and Visual Studio 2010 Page 499 of 558


D. HARSHA VARDHAN

 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);

.NET 4.0 and Visual Studio 2010 Page 500 of 558


D. HARSHA VARDHAN

[OperationContract]
CompositeType GetSquareAndCube(int n);

// TODO: Add your service operations here


}

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

 Come back to the ―Service.cs‖ file and write the code:

Service.cs

public class Service : IService


{
public int Add(int a, int b)
{
return (a + b);
}

public int Subtract(int a, int b)


{
return (a - b);
}

public int Multiply(int a, int b)


{

.NET 4.0 and Visual Studio 2010 Page 501 of 558


D. HARSHA VARDHAN

return (a * b);
}

public int Divide(int a, int b)


{
return (a / b);
}

public CompositeType GetSquareAndCube(int n)


{
CompositeType ct = new CompositeType();
ct.Square = n * n;
ct.Cube = n * n * n;
return (ct);
}
}

 Run the service.


 On the browser you can see some URL.

 Copy that URL and close the browser.

.NET 4.0 and Visual Studio 2010 Page 502 of 558


D. HARSHA VARDHAN

Creating the client application:


 Take a new windows forms application / web site.

 Click on ―Web Site‖ menu – ―Add Service Reference‖.

.NET 4.0 and Visual Studio 2010 Page 503 of 558


D. HARSHA VARDHAN

 Paste the URL that you have copied already.


 Enter any namespace name. Ex: ServiceReference1.
 Click on OK.
 Then the ServiceReference1 namespace contains the classes, which are defined in the
WCF Service.
 Design the ―Default.aspx‖ page:

.NET 4.0 and Visual Studio 2010 Page 504 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

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


{
ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();

protected void Button1_Click(object sender, EventArgs e)


{
int result = sc.Add(10, 3);
Label1.Text = result.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
int result = sc.Subtract(10, 3);
Label1.Text = result.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
int result = sc.Multiply(10, 3);
Label1.Text = result.ToString();
}

.NET 4.0 and Visual Studio 2010 Page 505 of 558


D. HARSHA VARDHAN

protected void Button4_Click(object sender, EventArgs e)


{
int result = sc.Divide(10, 3);
Label1.Text = result.ToString();
}
protected void Button5_Click(object sender, EventArgs e)
{
ServiceReference1.CompositeType ct;
ct = sc.GetSquareAndCube(10);
Label1.Text = "Square: " + ct.Square;
Label1.Text += " Cube: " + ct.Cube;
}
}

 Run the web site and test it.

.NET 4.0 and Visual Studio 2010 Page 506 of 558


D. HARSHA VARDHAN

AJAX
(Asynchronous JavaScript and XML)

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


 AJAX is the new Web Development Technology offered by ASP.NET.
 It is the most powerful feature of ASP.NET, which dramatically reduces stress on web
servers.
 In the year of 2007, Microsoft Corporation introduces ATLAS, which is renamed as AJAX in
late 2007.
 AJAX is a client technique, which internally uses two languages like JavaScript and XML.
 Already you know that JavaScript is the client side language, which can be executed by
browser. XML is a data descriptive language, which describes the data values in a
structured manner.
 In the same way, already you know that web sites development models are 3 types totally.
1. Traditional Web Sites
2. Post-Backing Web Sites
3. AJAX Web Sites
 The limitations of Traditional web sites are overcome with Post-backing web sites.
 The main limitation of post-backing web sites is: the web page will be post-backed for
every user action like clicking the buttons, selecting a date in the calendar, clicking on a
node in the TreeView, selecting an item in the list box etc.
 In post-backing, the entire page will be refreshed / re-loaded.
 So that, web server has to give response for every post-back. This leads to heavy stress on
the web server. Dramatically, this makes the web site executing very slowly.
 This problem can be solved with the introduction of AJAX. With the support of AJAX
technology,

.NET 4.0 and Visual Studio 2010 Page 507 of 558


D. HARSHA VARDHAN

Web Page Execution in AJAX Technology:


 On clicking on the ―Submit‖ button, a request will be sent to the server. But that request is
not the traditional request. With the traditional request, you were submitting the complete
page. So now, instead of submitting the complete page to the web server, part of the page
will be submitted.
 Then execution flow will be reached to the web server. There, the server side code will be
executed. (For ex: button1_Click code).
 As usual, it comes back with some response. The response will be updated on the UI.
 So, the main differences between post-backing web sites and AJAX web sites is:
 In post-backing web sites, entire page will be closed and re-loaded. But in AJAX
web sites, the will not be closed or re-loaded. The page will be as it is only. But
some part of the web page will be submitted to the server and it gets re-loaded.
This is called as ―Asynchronous Server Call‖.
 If the full page is getting submitted and re-loaded it can be called as ―Post-back‖.
If partial page is getting submitted and re-loaded, then it can be called as ―Call
back‖. So in AJAX web sites, callback will be there, instead of post-back.

Client Web Server

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

.NET 4.0 and Visual Studio 2010 Page 508 of 558


D. HARSHA VARDHAN

The ASP.NET AJAX

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

A. AJAX Extension Controls:


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

B. AJAX Toolkit Controls:


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

.NET 4.0 and Visual Studio 2010 Page 509 of 558


D. HARSHA VARDHAN

Implementation of AJAX Extensions


I. ScriptManager:
This control should be placed, at the top of all the AJAX extensions / toolkit controls,
after <form> tag.
This enables the AJAX technology in your web page.
When you drag the control, you can see the following tag in the ―Source‖ view.

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


</asp:ScriptManager>

II. UpdatePanel:
This control contains the content, which is to be updated in AJAX model, on the post
back.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>
The <ContentTemplate> tag contains the actual content. In this tag, you drag and
drop the controls, that you want.
If any control in the UpdatePanel requires post back, the entire page would not be
re-loaded. Just the required content would be updated with the support of call-back.
So, this feature improves the execution speed of the page.

Application 36: Demo on AJAX

Create a new web site.


Add ―ajaxdemo1.aspx‖ page and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 510 of 558


D. HARSHA VARDHAN

Write the code:

ajaxdemo1.aspx.cs

protected void Button1_Click(object sender, EventArgs e)


{
int sum = Convert.ToInt32(TextBox1.Text) + Convert.ToInt32(TextBox2.Text);
TextBox3.Text = sum.ToString();
}

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

.NET 4.0 and Visual Studio 2010 Page 511 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 512 of 558


D. HARSHA VARDHAN

Write the code:

ajaxdemo2.aspx.cs

protected void button1_Click(object sender, EventArgs e)


{
Label1.Text = DateTime.Now.ToLongTimeString();
}
protected void button2_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}

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.

.NET 4.0 and Visual Studio 2010 Page 513 of 558


D. HARSHA VARDHAN

III. UpdateProgress:
This control is helpful, if it is taking much time to execute large amount of code,
while a call-back is being performed in an UpdatePanel.
This control contains the content, which is to be displayed while the page is getting
call back.
This improves the user-friendly nature.
This is useful, when you have large amount of code in the UpdatePanel.
By default, it contains some link with the UpdatePanel control.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>

</ProgressTemplate>
</asp:UpdateProgress>

Demo on UpdateProgress:

Open the previous demo web site.


Add ―ajaxdemo3.aspx‖ page and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 514 of 558


D. HARSHA VARDHAN

Write the code:

ajaxdemo3.aspx.cs

protected void button1_Click(object sender, EventArgs e)


{
System.Threading.Thread.Sleep(3000);
Label1.Text = DateTime.Now.ToLongTimeString();
}

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:

.NET 4.0 and Visual Studio 2010 Page 515 of 558


D. HARSHA VARDHAN

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>

.NET 4.0 and Visual Studio 2010 Page 516 of 558


D. HARSHA VARDHAN

Demo on Timer:

Open the previous demo web site.


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

Set the Timer1 Properties:


Enabled: true
Interval: 1000
Write the code:

ajaxdemo3.aspx.cs

protected void Timer1_Tick(object sender, EventArgs e)


{
Label1.Text = DateTime.Now.ToLongTimeString();
}

Run the web site.

.NET 4.0 and Visual Studio 2010 Page 517 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 518 of 558


D. HARSHA VARDHAN

Design the ―AjaxToolkitDemo.aspx‖ page as shown:

Continued…

.NET 4.0 and Visual Studio 2010 Page 519 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 520 of 558


D. HARSHA VARDHAN

Click on OK.
That‘s all. A shadow will be displayed at run time, under the ―first name‖ textbox.
Output:

.NET 4.0 and Visual Studio 2010 Page 521 of 558


D. HARSHA VARDHAN

Close the browser and come to Visual Studio.


Select the RequiredFieldValidator of ―first name‖.
Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―ValidatorCalloutExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 522 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 523 of 558


D. HARSHA VARDHAN

Select the ―date of birth‖ textbox.


Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―TextBoxWatermarkExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 524 of 558


D. HARSHA VARDHAN

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

.NET 4.0 and Visual Studio 2010 Page 525 of 558


D. HARSHA VARDHAN

Run the web site and observe the date of birth textbox. The watermark text will be
displayed in specified CSS style. Output:

Select the ―date of joining‖ textbox.


Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―CalendarExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 526 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 527 of 558


D. HARSHA VARDHAN

Select the ―password‖ textbox.


Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―PasswordStrengthExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 528 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 529 of 558


D. HARSHA VARDHAN

Select the ―medicines‖ dropdown list.


Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―ListSearchExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 530 of 558


D. HARSHA VARDHAN

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:

.NET 4.0 and Visual Studio 2010 Page 531 of 558


D. HARSHA VARDHAN

Click in the dropdown list and start typing.


Select the ―globe‖ image.
Click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―AlwaysVisibleControlExtender‖ option.

.NET 4.0 and Visual Studio 2010 Page 532 of 558


D. HARSHA VARDHAN

Click on OK.
Run the web site. Even though you scroll the web page, the image always will be
displayed on the screen.
Output:

.NET 4.0 and Visual Studio 2010 Page 533 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 534 of 558


D. HARSHA VARDHAN

WPF
(Windows Presentation Foundation)

This is meant for advanced graphics presentation.


This is introduced to attract the user with better UI design.
The windows forms depend on window boundaries in the form of pixels; whereas WPF
application is similar to windows forms application, which depends on ―DirectX‖.
It uses ―XAML‖ (Extensible Application Markup Language).

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.

.NET 4.0 and Visual Studio 2010 Page 535 of 558


D. HARSHA VARDHAN

Development of WPF Applications


 Open Visual Studio 2010.
 Click on ―File‖ – ―New‖ – ―Project‖ – ―WPF Application‖.
 Enter the name and location of the project.

 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

.NET 4.0 and Visual Studio 2010 Page 536 of 558


D. HARSHA VARDHAN

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>

.NET 4.0 and Visual Studio 2010 Page 537 of 558


D. HARSHA VARDHAN

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.

.NET 4.0 and Visual Studio 2010 Page 538 of 558


D. HARSHA VARDHAN

Application 37: A simple demo on WPF Application

Window1.xaml.cs

private void Window_Loaded(object sender, RoutedEventArgs e)


{
MessageBox.Show("Welcome");
}

.NET 4.0 and Visual Studio 2010 Page 539 of 558


D. HARSHA VARDHAN

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" />

Application 38: Demo on Shapes

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

.NET 4.0 and Visual Studio 2010 Page 540 of 558


D. HARSHA VARDHAN

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

Note: The above tag is to be typed within the required tag.

Application 39: Demo on Transformation

.NET 4.0 and Visual Studio 2010 Page 541 of 558


D. HARSHA VARDHAN

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>

.NET 4.0 and Visual Studio 2010 Page 542 of 558


D. HARSHA VARDHAN

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‖ />

.NET 4.0 and Visual Studio 2010 Page 543 of 558


D. HARSHA VARDHAN

</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>

.NET 4.0 and Visual Studio 2010 Page 544 of 558


D. HARSHA VARDHAN

Application 40: Demo on Brushes

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

.NET 4.0 and Visual Studio 2010 Page 545 of 558


D. HARSHA VARDHAN

<GradientStop Color="Red" Offset="0"></GradientStop>


<GradientStop Color="Blue" Offset="0.2">
</GradientStop>
<GradientStop Color="BlanchedAlmond" Offset="0.7">
</GradientStop>
<GradientStop Color="DarkOrange" Offset="1">
</GradientStop>
</LinearGradientBrush>
</Button.Background>
Linear Gradient Brush
</Button>
<Button Margin="21,159,0,143" HorizontalAlignment="Left" Width="138">
<Button.Background>
<RadialGradientBrush Center="0.5,0.5" GradientOrigin="0.5,0.5"
RadiusX="0.5" RadiusY="0.5" SpreadMethod="Pad">
<GradientStop Color="White" Offset="0" />
<GradientStop Color="LightBlue" Offset="0.4" />
<GradientStop Color="DarkBlue" Offset="1" />
</RadialGradientBrush>
</Button.Background>
Radial Gradient Brush
</Button>
<Button Margin="21,0,0,45" HorizontalAlignment="Left" Width="120" Height="48"
VerticalAlignment="Bottom">
<Button.Background>
<DrawingBrush>
<DrawingBrush.Drawing>
<GeometryDrawing Brush="LightBlue">
<GeometryDrawing.Geometry>
<GeometryGroup>
<EllipseGeometry RadiusX="30" RadiusY="30" Center="20,20" />
<EllipseGeometry RadiusX="4" RadiusY="4" Center="10,10" />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen>
<Pen.Brush>Red
</Pen.Brush>
</Pen>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</Button.Background>
Drawing Brush
</Button>
<Button Margin="0,14.5,76,0" Height="56" VerticalAlignment="Top"
HorizontalAlignment="Right" Width="109">
<Button.Background>
<ImageBrush ImageSource="C:\globe.jpg" />

.NET 4.0 and Visual Studio 2010 Page 546 of 558


D. HARSHA VARDHAN

</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>

<ScaleTransform ScaleX="1" ScaleY="-1" />


<TranslateTransform Y="1" />
</TransformGroup>
</VisualBrush.RelativeTransform>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
</StackPanel>
</Button>
</Grid>
</Window>

.NET 4.0 and Visual Studio 2010 Page 547 of 558


D. HARSHA VARDHAN

Development of Silver Light Applications


 Open Visual Studio 2010.
 Click on ―File‖ – ―New‖ – ―Project‖ – ―Silver Light Application‖.
 Enter the name and location of the project.

 Click on OK.
 Click on OK.
 Then the Visual Studio window will be appeared like this:

.NET 4.0 and Visual Studio 2010 Page 548 of 558


D. HARSHA VARDHAN

 The same XAML code works here also.


 The silver light applications can be hosted in the web sites.

.NET 4.0 and Visual Studio 2010 Page 549 of 558


D. HARSHA VARDHAN

ASP.NET 4.0

Frequently
Asked
Questions
(FAQ’s)

.NET 4.0 and Visual Studio 2010 Page 550 of 558


D. HARSHA VARDHAN

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.

What are user controls and custom controls?


Custom controls:
A control authored by a user or a third-party software vendor that does not belong to the .NET Framework
class library. This is a generic term that includes user controls. A custom server control is used in Web Forms
(ASP.NET pages). A custom client control is used in Windows Forms applications.

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.

What are the validation controls?


A set of server controls included with ASP.NET that test user input in HTML and Web server controls for
programmer-defined requirements. Validation controls perform input checking in server code. If the user is
working with a browser that supports DHTML, the validation controls can also perform validation using client
script.

What's the difference between Response.Write() andResponse.Output.Write()?


The latter one allows you to write formattedoutput.

What methods are fired during the page load? Init()


When the page is instantiated, Load() - when the page is loaded into server memory,PreRender () - the
brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.

.NET 4.0 and Visual Studio 2010 Page 551 of 558


D. HARSHA VARDHAN

Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page

Where do you store the information about the user's locale?


System.Web.UI.Page.Culture

What's the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?


CodeBehind is relevant to Visual Studio.NET only.

What's a bubbled event?


When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell,
button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid
event handler to take care of its constituents. Suppose you want a certain ASP.NET function executed on
MouseOver over a certain button.

Where do you add an event handler?


It's the Attributesproperty, the Add function inside that property.
e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

What data type does the RangeValidator control support?


Integer,String and Date.

What are the different types of caching?


Caching is a technique widely used in computing to increase performance by keeping frequently accessed or
expensive data in memory. In context of web application, caching is used to retain the pages or data across
HTTP requests and reuse them without the expense of recreating them. ASP.NET has 3 kinds of caching
strategiesOutput CachingFragment CachingData

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

.NET 4.0 and Visual Studio 2010 Page 552 of 558


D. HARSHA VARDHAN

directive.<%@ OutputCache Duration="60" VaryByParam="state" %>

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;

What do you mean by authentication and authorization?


Authentication is the process of validating a user on the credentials (username and password) and
authorization performs after authentication. After Authentication a user will be verified for performing the
various tasks, It access is limited it is known as authorization.

What are different types of directives in .NET?

@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" %>

.NET 4.0 and Visual Studio 2010 Page 553 of 558


D. HARSHA VARDHAN

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

Can a user browsing my Web site read my Web.config or Global.asax files?


No. The <HTTPHANDLERS>section of Machine.config, which holds the master configuration
settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other
file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the
associated file. You can modify it by editing Machine.config or including an section in a local
Web.config file.

What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?


RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript
is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when
the page is loaded. The latter positions script blocks near the end of the document so elements on the page
that the script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>

.NET 4.0 and Visual Studio 2010 Page 554 of 558


D. HARSHA VARDHAN

WebServices and Windows Services

Opposed to non-serviced .NET component


Web service is one of main component in Service Oriented Architecture. You could use web services when
your clients and servers are running on different networks and also different platforms. This provides a
loosely coupled system. And also if the client is behind the firewall it would be easy to use web service since
it runs on port 80 (by default) instead of having something else in Service Oriented Architecture
applications. What is the standard you use to wrap up a call to a Web service "SOAP”.

What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP

What does WSDL stand for?


"WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe that creates a .wsdl Files which
defines how an XML Web service behaves and instructs clients as to how to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx"

Where on the Internet would you look for Web Services?


www.uddi.org

What does WSDL stand for?


Web Services Description Language

True or False: To test a Web service you must create a windows application or Web application to
consume this service?
False.

What are the various ways of accessing a web service ?


1. Asynchronous Call
Application can make a call to the Webservice and then continue todo watever oit wants to do.When the
service is ready it will notify the application.Application can use BEGIN and END method to make
asynchronous call to the webmethod.We can use either a WaitHandle or a Delegate object when making
asynchronous call. The WaitHandle class share resources between several objects. It provides several
methods which will wait for the resources to become available The easiest and most powerful way to to
implement an asynchronous call is using a delegate object. A delegate object wraps up a callback function.

.NET 4.0 and Visual Studio 2010 Page 555 of 558


D. HARSHA VARDHAN

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.

What are VSDISCO files?


VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following
VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO
files in the host directory and any subdirectories not noted in
<EXCLUDE> elements:
<DYNAMICDISCOVERY xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<EXCLUDE path="_vti_cnf" />
<EXCLUDE path="_vti_pvt" />
<EXCLUDE path="_vti_log" />
<EXCLUDE path="_vti_script" />
<EXCLUDE path="_vti_txt" />
</DYNAMICDISCOVERY>

How does dynamic discovery work?


ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host directory and
subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client
who requests a VSDISCO file gets back what appears to be a static DISCO document.

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.

Is it possible to prevent a browser from caching an ASPX page?


Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property,
as demonstrated here:

<%@ Page Language="C#" %>


<%

.NET 4.0 and Visual Studio 2010 Page 556 of 558


D. HARSHA VARDHAN

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.

What does AspCompat="true" mean and when should I use it?


AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in
any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered
ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should
also be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP
objects such as Request and Response. The following directive sets AspCompat to true:

<%@ Page AspCompat="true" %>

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.

Can two different programming languages be mixed in a single ASMX file?


No.

What namespaces are imported by default in ASMX files?


The following namespaces are imported by default. Other namespaces must be imported manually.· System,
System.Collections,System.ComponentModel,System.Data,
System.Diagnostics,System.Web,System.Web.Services

.NET 4.0 and Visual Studio 2010 Page 557 of 558


D. HARSHA VARDHAN

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:

public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol


{
public AuthToken AuthTokenValue;
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://tempuri.org/",
IsNullable=false)]
public class AuthToken : SoapHeader { public string Token; }}
In this case, when you create an instance of the proxy in your main application file, you'll also
create an instance of the AuthToken class and assign the string:
Service1 objSvc = new Service1();
processingobjSvc.AuthTokenValue = new AuthToken();
objSvc.AuthTokenValue.Token = <ACTUAL token value>;
Web Servicestring strResult = objSvc.MyBillableWebMethod();

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

How can a win service developed in .NET be installed or used in Win98?


Windows service cannot be installed on Win9x machines even though the .NET framework runs on machine.

.NET 4.0 and Visual Studio 2010 Page 558 of 558

Você também pode gostar