ASP
ASP
net
ASP.NET
Arevolutioninthewebprogrammingworld
CoversConceptsPrograms
Authoredby
B.KANNABABU
ASP.net
Acknowledgements
Iwanttoacknowledgemydeepgratitudeto
Mr.T.S.S.sunil Kumar and Mr.G.Sudhakar who
encouragedmealotfortheircooperation
IamalsothankfultoMr.Ganesh,Mr.satyanarayna
Mr.ThandavaKrishna,Mr.Manikbasava,Mr.Jojibabu
who has provided staunch support throughout the
projectandhelpedmetocompletethisbooksuccessfully
Some errors may have inadvertently crept in this
book.despitemybesteffortstokeepthemout.Readers
are therefore encouragedtopoint out these errors so
that they are not repeated in the next
edition.suggesitions to improve the book are also
[email protected]
ASP.net
AbouttheAuthor
ASP.net
CONTENTS
1. Introduction To MS.net
1.1
1.2
1.3
1.4
ASP.net
1.7.2.5 Memory Management
1.7.2.6 Just In Time Compiler
1.7.2.6.1 Pre JIT
1.7.2.6.2 Standard JIT
1.7.2.6.3 Echno JIT
3
4
ASP.net
7 Internet information service(IIS)
8 Working with ASP.net Applications
8.1 Why ASP.net
8.2 Evolution of ASP.net
8.3 Features of ASP.net
8.4 Difference between ASP and ASP.net
9 Coding Techniques in ASP.net
9.1 Code inline model
9.2 Code behind model
10 Controls in ASP.net
10.1 client side controls
10.2 silverside controls
10.2.1 HTML server controls
10.2.2 Web server controls
10.2.3 Common properties with webserver controls
10.3 Different Types of controls in ASP.net
10.3.1 Standard controls and examples
10.3.1.1 Label
10.3.1.2 TextBox with Example
10.3.1.3 CheckBox with Example
10.3.2 Redirecting The user Request
10.3.2.1 Hyperlink Button with Example
10.3.2.2 Link Button with Example
10.3.2.3 Image Button with Example
10.3.2.4 Differences b/n button controls
10.3.2.5 Response. Redirect
10.3.2.6 Server. Transfer
10.3.3 Button controls
10.3.3.1 Events with Button Controls
10.3.3.2 Click Event with Example
10.3.3.3 Command Event with Example
10.3.4 Listing Controls
10.3.4.1 ListBox
10.3.4.2 DropDownList
10.3.4.3 RadioButtonList
10.3.4.4 CheckBoxList
10.3.4.5 Panel control
11 Validation Controls
11.1 Difference b/n client side and server side validation
11.2 Different Types of validation controls
11.2.1 Required Field validator with Example
11.2.2 Range validator with Example
11.2.3 Regular Expression Validator with Example
11.2.4 Compare validator with Example
6
ASP.net
11.2.5 Validation Summary with Example
11.2.6 Custom validator with Example
12 Navigation Controls
12.1 Menu Controls with Example
12.2 Treeview Controls with Example
13 Calendar control with example
14 ADO.net
14.1 introduction to ADO.net
14.1.1 I-layered approach
14.1.2 II-layered approach
14.1.3 III-layered approach
14.2 ADO vs ADO.net
14.3 ADO.net architecture diagram
14.4 Connection oriented architecture
14.4.1 Data Providers in ADO.net
14.4.2 Objects in ADO.net
14.4.3 Steps to work with connection architecture
14.4.4 Example with Connection object
14.4.5 Command object
14.4.6 Steps to work with command object
14.4.7 Differences between Execute methods
14.4.8 Example with command object to delete .
14.4.9 Example with insert, update and delete
14.4.10 disadvantages with connection oriented.
14.5 Disconnected Architecture
14.5.1 Disconnected Data cycle
14.5.2 Dataset
14.5.2.1 Steps to work with Dataset
14.6 Data Bound Controls
14.6.1 Templates
14.6.2 Types Of Data Bound Controls
14.6.2.1 Repeater Control
14.6.2.2 Data list Control
14.6.2.3 Grid view Control
14.7 Repeater Control
14.7.1 Designing Repeater Control in Table
14.8 Data List Control
14.8.1 Events associated with Data List Control
14.8.2 Displaying Data in Datalist Control
14.8.3 Deleting with Data List Control
14.8.4 Editing with Data List Control
14.9 Grid View Controls
14.9.1 Displaying Data in GridView
14.9.2 Paging with GridView
14.9.3 Check Boxes with Grid View
14.9.4 Radio Buttons with Gridview
7
ASP.net
15
16
17
18
19
20
Ad Rotator Control
CSS in ASP.net
Themes and Skins
Master Pages
State Management in ASP.net
15.1 View state
15.2 URL encoding
15.3 Cookies
15.4 Sessions
15.5 Application
15.6 Caching
15.7 Query String
500 Frequently asked questions
MICROSOFT.NET
8
ASP.net
VERSIONS OF .NET:
MS.NET
MS.NET
MS.NET
MS.NET
MS.NET
MS.NET
MS.NET
1.0:-introduced
1.0:-introduced
1.1:-introduced
2.0:-introduced
2.0:-introduced
3.0
3.5
in
in
in
in
in
the
the
the
the
the
year
year
year
year
year
2000
2002
2003
2004
2005
(beta)
(alpha)
(alpha)
(beta )
(alpha)
Note: Microsoft has given a statement that some new frameworks are
Released under winfx named later renamed as Microsoft.net3.0
Features according to versions of .net:
MS.net1.0
many application support
Separate installation
Crystal report installation
Mobile application
MS.net1.1
Crystal report and Mobile application are inbuilt
MS.net2.0
64-bit compatibility
Along SQLserver Enterprise edition Generic
Classes,Generic methods, nullable types etc
ASP.net
MICROSOFT.NET
.NETFRAMEWORK
Itisthelayerbetween
ApplicationandOS
Itconsistsof
1. CLR
2. BCL
.NETServices
.NETPRODUCTS
Passportservice
MSVisualstudioeditor
Calendarservice
MSSimulator
ContactService
AlertService
Webservice
Etc.
.NETServers
MSSQLServer
BizTalkserver
IIS
MobileIIS
Exchangeserver
InternetSecurityServer
Etc..
Tools:compiler
Interpreter
Debugger
Assemblerand
disassembler
10
ASP.net
ASP.net
ADO.NET is used for database handling
WEBSERVICES are used for complete distributed applications
ARCHITECTURE OF MS.net
C#.net
Applicationlayer
Windows
applicat
Web
applicat
Data
Baseclasslayer
Vb.net
Mobileweb
applicat
IO
XML
Memory
management
ARCHITECTUREOFMS.NET
Service
applicat
Security
Threading
CLR
Security
checking
Translatinglayer
J#.net
Monitoring
The
Lifecycle
OS
12
ASP.net
LIFE CYCLE EXECUTION OF .NET APPLICATION
.net application----compilation----IL---CLR---OS
METADATA
CODE
PEWRAPPER
RESOURCE
MANIFEST
METADATA: it is used to describe the data of the IL file i.e. it provides the
structure of the program like class names, method names etc
CODE: it provides the actual instructions of IL file
RESOURCE: it provides the additional information like images, cursors, icons et
MANIFEST: it provides documentary information like product name, company
name, and version no, strong name etc.
PE WRAPPER: it contains some executable format which invokes the CLR.
Note: if you want to view the complete IL file then ILDASM.exe
13
ASP.net
ILDASM.exe: it is a build-in tool of .net used to show the wrapper file or IL file
CLR
ILLOADER
ACCESSCONTROLER
CTS
CAS
CLS
RBS
MEMORYMANAGEMENT
JITCOMPILER
14
ASP.net
1. CTS:common type system :it provides common data types for all .net
languages and checks whether IL file is using those data types are not
2. CLS:common language specification: it provides some common rules
for all .net languages and check whether IL file is following those rules
are not
3. CAS:code access security: it checks whether the code is executing on
the O.S and if it is invalid code it displays error message
4. RBS: role based security: it checks whether the login user is valid or
invalid and it provides permissions for accessing and executing .net
applications.
by
default
administrator
have
the
privileges
for
Echno JIT:
it is used to convert
machine
15
ASP.net
Webapplications
DevWebPages
Staticwebpage
Dynamicwebpage
HTML
PHOTOSHOP
clientside
DHTML
FLASH
Serverside
ASP
ASP.NET
ISP
SERVELETS
16
ASP.net
Server side dynamic webpage: the webpage which generates diff o/p
by processing every request on server machine which can be generated
by some technologies like ASP, ASP.NET, JSP, SERVELETS etc.
Ex:RTF,HTML
Features of HTML:
Syn :<cmd>
Tag contains two elements starting element and ending element
Starting element
<command>
Ending element
</command>
17
ASP.net
Tags are of two types container tags and non container tags
The tag which contains both starting element and ending elements is
called container tags
Ex: <html> </html>
<p></p>etc.
Tags which provides only starting elements are called non container
tags
Ex :<br>break line
<hr>horizontal ruler etc
TAG REFERENCES
Different types of tag references are
1. BASIC TAG
2. TEXT FORMATING TAG
3. LINK TAG
4. LIST TAG
5. FRAME TAG
6. TABLE TAG
7. FORM TAG
8. MULTIMEDIA TAG
Basic tags: these tags will provide the structure of the document
Ex:
<html>
<head>
<title>HELLO</title>
18
ASP.net
WELCOME TO HTML
</head>
<body
bgcolor="#CCCCCC"
background="F:\WALLPAPERS\Ganesh.jpg">
THIS IS HTML DOCUMENT
THIS IS MY FIRST PROGRAM
</body>
</html>
Link tag: it is used for linking one document with another document
Or different parts of same document
Hyper link: it is used for linking two documents
link
h1
F1.html
F2.html
19
ASP.net
<head>
<title>HELLO</title>
WELCOME TO HTML
</head>
<body
bgcolor="cyan"
background="F:\WALLPAPERS\All
Pictures\14.jpg" >
THIS IS HTML DOCUMENT
<a href="E:\TECHNOLOGIES\6pm\HTML\basictag.html">
click here to show basic tag
</a>
</body></html>
Text formatting tags: these tags are used to formatting the text by
applying font style, size and font names etc
Ex:
<B>
BOLD
<I>
ITALIC
<U>
UNDERLINE
<SMALL> SMALL FONT
<BIG>
Big FONT
<STRONG>
<S><SUP><SUB>
<FONT>
<HR><BR><P>
<PRE>
LIST TAGS:
It is used to display the information in bulleted format or numbered format
etc..
<ul> unordered list
<ol >ordered list
<li >list item
<dd>data definition
<dl>data list
<dt >data table
20
ASP.net
source code:
<Html>
<h1>
MEMORY
<UL TYPE="SQUARE">
<LI>PRIMARY MEMORY
<OL TYPE="1">
<LI>RAM
<LI>ROM
</OL>
<LI>SECONDARY MEMORY
<OL TYPE="I">
<LI>HARD DISC
<LI>COMPACT DISC
</OL>
</UL>
</H1>
</html>
MULTIMEDIA TAGS: this tag is used to display the images on the text
<MARQUEE>=SCROLLING
21
ASP.net
<MARQUEE>
<H1> WELCOME</H1>
</MARQUEE>
PROPERTIES:
<MARQUEE DIRECTION=
RIGHT
LEFT
UP
DOWN
BEHAVIOUR=ALTERNATE
SCROLL
LOOP=SOME NO
SCROLL AMOUNT=MILLISEC SCROLLDELAY=MILLISEC
BG COLOR=SOME COLOR
WIDTH=SOMENO HT=SOME NO BORDER=SOME NO>
22
ASP.net
Source code:
<HTML>
<IMG SRC="D:\KANNA PICS\SP_A0101.jpg"
WIDTH=200HT=50 BORDER=5>
<MARQUEE DIRECTION="left" BEHAVIOUR="alternate" LOOP="-1"
SCROLLAMOUNT=100 SCROLLDELAY=1000 BGCOLOR="RED">
<H1>WELCOME</H1>
</MARQUEE>
</HTML>
Font tags:
Syn :<font face=value size=value color=value>
</font>
23
ASP.net
Fonttags:
Syn :<fontface=valuesize=valuecolor=value>
</font>
Arial
MonotypeCorsiva
TimesNewRoman
1leastsize
2
3defaultsize
4
5
6
7highestsize
View source
<Html>
24
ASP.net
<Body>
<font face="ariel" size="10" color="red">
HI KANNABABU
</FONT>
<BR><BR><BR>
<FONT FACE="TAHONA" SIZE="7" COLOR="BLUE">
HTML IS MARKUP LANGUAGE
<BR><BR><BR>
<FONT FACE="VERDANA" SIZE="5" COLOR="GREEN">
HTML SUPPORTS FONT TAGS
</FONT>
</body>
</html>
FRAME TAGS:
These tags are used to divide the webpage into different webpartsFrameset tags
has two optional attributes
ROWS ATTRIBUTES: it is used to divide the webpage in to horizontal parts
COLUMNS ATTRIBUTE: it is used to divide the webpage into vertical parts
To assign the name to a frame frameset tag contains a sub tag known as
frame
any matter we want to display within aframe we will store in a html file and
25
ASP.net
View source:
<? Code for frame.html...>
<HTML>
<FRAMESET ROWS="30%,70%">
<FRAME NAME="a" src="kanna.html">
<FRAMESET cols="25%, 75%">
<FRAME NAME="b" src="link.html">
<FRAME NAME="c" src="home.html">
</FRAMESET>
</FRAMESET>
</HTML>
Form Tags:
FORM TAGS: it is used to design some webpage by placing some controls
26
ASP.net
It used to provide a container where we can place some controls like
Textboxes, buttons, RadioButton,etc.
<Form>
Properties: method=get\post
name=some text
action=some path
<input type=text>
Name=some path
Value=number
Read-only
Disabled
Textbox is the data entry control
Password textbox:it is used to accept some text but hides the text with some
symbol like *
Properties are same as textbox
Multiline textbox: it is used for accepting multiple lines of text
<text area>
Name=some text
Value=some text
Rows=some no
Columns=some no
Note: text area tag is noncontainer tag
Radio button control: this control is used for providing a group of options
from which we can select anyone.
27
ASP.net
Syn: <input type=radio name=some text>
Checkbox control: it is used for selecting and deselecting an item
Syn: <input type=checkbox name=some text>
Dropdown list :it is used for providing some list of items from which we
can select any one in a dropdown fashion.
Syn: <select name=some text>
<option selected>..
</select>
Listing Controls: it provides list of items in a box format from which we can
select single or multiple items by holding control key
Syn: <select name=some text size=no multiple>
<option selected>..
</select>
28
ASP.net
View source:
<HTML>
<HEAD>
<H1 ALIGN="CENTER">KANNA TECHNOLOGIES </H1>
<H2 ALIGN="CENTER"> HYDERABAD </H2>
</HEAD>
<HR COLOR="BLUE">
<BODY>
<B><U> <FONT SIZE="4" COLOR="RED">
PERSONAL DETAILS FORM </FONT></U></B>
<FORM NAME="F1"
action="" method=get>
<table align="center">
<tr>
<td>ENTER YOUR NAME : </td>
<td><INPUT TYPE="TEXT" NAME="T1"></td>
</tr>
<tr>
<td>ENTER USER NAME :</td>
<td><INPUT TYPE="TEXT" NAME="T2"></td>
</tr><tr>
<td>ENTER PASSWORD :</td>
<td><INPUT TYPE="PASSWORD" NAME="T3"></td>
<tr><BR><tr>
<td>SELECT GENDER : </td>
29
ASP.net
<td><INPUT TYPE="RADIO"
NAME="GENDER" VALUE="MALE">MALE
<INPUT TYPE="RADIO" NAME="GENDER"
VALUE="FEMALE"> FEMALE </td><BR>
</tr><tr>
<td>SELECT QUALIFICATION </td>
<td><SELECT NAME="CB1">
<OPTION> SSC </OPTION>
<OPTION> 10+2 </OPTION>
<OPTION> DEGREE</OPTION>
<OPTION> PG </OPTION>
<OPTION> OTHERS </OPTION>
</SELECT></td>
</tr>
<BR><tr><td>SELECT HOBBIES :</td><nbsp>
<td><INPUT TYPE="CHECKBOX" NAME="C1" VALUE="DANCING"> DANCING
<INPUT TYPE="CHECKBOX" NAME="C2" VALUE="PLAYING"> PLAYING
<INPUT TYPE="CHECKBOX" NAME="C3" VALUE="BROWSING"> BROWSING
<INPUT
TYPE="CHECKBOX"
NAME="C4"
VALUE="CHATTING">
CHATTING
</td></tr>
<tr><td>DESCRIBE YOUR SELF :</td>
<td> <TEXTAREA NAME="TA1" ROWS="5" COLS="10"> </TEXTAREA> </td>
</tr><BR><tr><td><INPUT TYPE="SUBMIT" NAME="B1"
VALUE="SUBMIT"></td>
<td><INPUT TYPE="RESET" NAME="B2"
VALUE="RESET"></td></tr>
</FORM>
</BODY>
</HTML>
BUTTON CONTROLS
30
ASP.net
Syn :<input type=reset>
Reset Button: this tag is used for invoking some functions of scripting
languages
Syn :<input type=button value=click>
SCRIPTING LANGUAGES:
SCRIPTING LANGUAGES: these are used for dynamic client side web
applications
31
ASP.net
Pearl script
Python script
Provides animations
Java script
32
ASP.net
Its widely used in tasks ranging from the validation of form data
to the creation of complex user interfaces.
It is platform independent
33
ASP.net
<html>
<script Language=JavaScript>
Document. Write (welcome)
</script>
</html>
VARIBLES IN JAVASCRIPT
JavaScript doesnt support any predefined data types thats why
JavaScript is known as loosely typed programming language
To declare variable in JavaScript we use 2 methods
Variable=value
Var variable=value
Ex:
S=welcome
S=10
S=10.5
var s=welcome
var s=10
var s=10.5
S is global variable
s is local variable
Variable names are case sensitive
There is no limit for data to store in a variable we can store up to 32
bytes any amount of data
Working with variables
<Html>
<script Language=JavaScript>
S=<h1>WELCOME</h1>
or
document.write(s)
document.write(<h1+s+</h1>)
</script>
</html>
Functions in javascript:
Prompt function:
It is used to accept any data from the user.
Variable=prompt (message)
34
s=welcome
ASP.net
Ex:
A=prompt (enter first number)
Return type of prompt is string
Eval function:
This is used to convert any number from string form to number form
Ex:
Eval (10)
Eval (10.5)
Alert function:
It is used to display the message in dialogue box with ok button
WORKING WITH JAVASCRIPT
Syntax:
[return type]
35
ASP.net
c=a+b
document.write("<font size=5>sum is :"+c+"</font>")
}
</script>
</head>
<body>
<script language="JavaScript">
Add()
</script></body></html>
Function overloading: assigning additional work to the function
other than the existing work is called function overloading
In any programming language we overload a function in two situations.
1. When no of arguments are changed
2. When data types of arguments are changed
}
We can call the function by passing 2 args like Add(10,20)
36
ASP.net
37
ASP.net
38
ASP.net
bgColor:this property is used to change the background color of the
document
Usage document.fgColor=color value
document.fgColor=blue
document.bgColor=color value
document.bgColor=yellow
Methods with document object:
1. Write method within one argument
Write (message)
This method is used to print the required message within the document
Ex: document.write (welcome)
Ex with document object
39
ASP.net
Syntax:
Property name: Property value
Types of Style Sheets:
1. Inline Style sheet
2. Embedded Style sheet
3. External Style sheet
4. Imported Style sheet
style
sheet
whose
style
definition
is
placed
under
tag
40
ASP.net
View source
<Html>
<h1 style="color: red; font-family:'verdana'; font-weight: bolder; text-align:
center">
Welcome to css
</h1>
<input type=text
style="font-size:11;color:blue;border-color:maroon;border-width:5;borderstyle:dotted">
</html>
Embedded style sheet: the style sheet whose style definition is placed
under style tag which automatically apply the styles on the html tags used in
the program
Syntax :< style type=text/css>
..
..
</style>
Embedded style sheets are of three types
1. Tag as a selector
2. Id as a selector
3. Class as selector
Tag as a selector: it is used for grouping the similar tags and
applying the style definition
Syn:<style type=text/css>
tag name{
41
ASP.net
..
}
Example:
View source:
<html>
<style type=text/css>
h1{
background-color:khaki;color:red;
}
h3{
background-color:blue;color:green;
}
</style>
<h1>CASCADEING
<h1>CASCADEING
<h3>CASCADEING
<h2>CASCADEING
</html>
STYLE
STYLE
STYLE
STYLE
SHEETS</h1>
SHEETS</h1>
SHEETS</h3>
SHEETS</h2>
42
ASP.net
</style>
<tag name class=t>
}
Example:
View source:
<html>
<style type=text/css>
input{
font-size:10;
}
.t{
background-color:yellow
}
</style>
<center>
<h1>LOGIN FORM</h1>
43
ASP.net
<h2>
<form>
Enter user name:<input type=text class=t>
<br><br>
Enter password:<input type=password >
<br><br>
<input type=button value=signin class=t>
</form>
</h2>
</center>
</html>
Syntax:
<style type=text/css>
#id{
.
</style>
<tag name id=some id>
}
Example
44
ASP.net
View source:
<html>
<style type=text/css>
#p{
font-size:30;
}
#p1{
background-color:green;
}
#p2{
background-color:lavender;
}
</style>
<p id=p1>this is id selector</p>
<p id=p2>this is id selector</p>
<p id=p1>this is id selector</p>
<p id=p>this is id selector</p></html>
45
ASP.net
Imported style sheet: it is used for importing one css program program
into another css program and also import one css program into html
program.
Imported style sheet works with a notation called as @import
Syn:@import url(path of css);
This notation is used within style tag under under .html program
Example:
View source:
Code for p1.html
<html>
<link rel=style sheet href="style1.css">
<h1>EXTERNAL STYLE SHEET</h1>
<p>welcome to technologies</p>
</html>
Code for style1.css
h1, h2,h3,h4,h5,h6{
Color: red;
}
p{
background-color: pink;
}
Example2 with imported style sheet
46
ASP.net
View source:
Code for p2.html
<html>
<style type=text/css>
@import url('style3.css');
</style>
<h1>EXTERNAL STYLE SHEET</h1>
<p>welcome to technologies</p>
</html>
Code for style3.css
47
ASP.net
@import url('style2.css');
p{
background-color:pink;
font-size:30;
font-family:arial;
}
Code for style3.css
h1,h2,h3,h4,h5,h6
{
color:red;
}
ASP. Net
WHY ASP. Net:
Originally web development started with HTML but the pages designed
using HTML are static WebPages because HTML is used only for
designing the WebPages
Html cannot be used to perform the validations and to execute events
In the below figure we can design the complete webpage using html
but we cannot perform The validations like Whether user entered
username, password or not and events like when user clicks on
button,What to do etc.
To overcome this drawback we got DHTML
DHTML:it is the combination of HTML and client side
48
ASP.net
Enterusername
Enterpassword
login
cancel
Scripting language
Client side scripting code:
In the above example if user is not entering username and password we
should not submit the request to the server so to check user entered
username and password etc code should be executed within the
browser only
Code that is executed within the browser only. code that is executed
within the browser window to perform the events and validations is known
as client side scripting code.
Programming language that is used to write client side scripting code is
known as client side scripting language
Ex: javascript, vbscript, jscript etc.
49
ASP.net
50
ASP.net
o ASP. net is the compiled technology but not interpreted due to
this application execution will be faster and increases the
performance of the application.
o ASP. net supports multiple languages of .net it makes component
development easy and it will be OS independent due to IL
format.
o Note:ASP1.1 compiles complete web applications at once .only
on language can be used.
o ASP2.0 compiles complete web application in page by page
pattern. so multiple languages can be used
o .Multidevice or multibrowser support:
ASP. net supports device
detection due to which ASP. net Supports device detection due
to which ASP. net can develop diff types o/p for different types of
browsers.
o ASP. net uses easy way for configuration and deployment of the
application.ASP.net maintains all its configuration settings in an
xml based file which automatically configures IIS before
executing the application and it uses the easy way for
deployment by developing a setup file
o ASP. net is integrated under .net environment ASP. net can use
all the base class libraries of .net framework for developing the
web based applications
o ASP. net 1.1 class libraries are added with new class libraries and
introduced in ASP. net 2.0
o ASP. net applications run under .net runtime environment i.e.
CLR
o ASP. net 2.0 important feature for executing the web based
application by using some concepts of the CLR like
o MEMORY MANAGEMENT:CLR will allocates memory for every user
and removes its object when it is not accessible
through
garbage collector
o TYPE CASTING: checking the data types conversions and
providing the functionalities required for execution.
o MULTITHREADING: as web applications are multi users CLR has
to identify every client and allocate separate memory for it which
is possible only through Threading
o ASP. net has introduced nearly 50 new controls for developing
advanced web application with easy and efficient way without
writing any code
o ASP. net 2.0 has provided a new technique for simplifying the
application designing by introducing master pages ,themes, and
skins
o ASP. net provides structural error handling ,tracing, and
debugging of the application to avoid the unpredictable
termination of the program.
51
ASP.net
s.no
1.
ASP
It is object based technology
2.
3.
ASP is bounded
language
ASP. Net
It
is
object
oriented
technology
It is strongly typed language
scriptingASP.net
is
language
independent which supports
scripting language and .net
language
It uses difficult configuration on IIS
ASP.net maintains is req
configuration in an xml file
It supports three web servers forASP.net supports only IIS
execution IIS,PEARL,PERSONAL web
server
4.
5.
with
6.
7.
9.
10.
.asp
8.
.aspx
About IIS
Webserver:it is a tool which is used to
One or more websites within it
Takes the request from the client process the request and sends the
result back to the client
Ex:for windows OS
Personal web server
Peers web server
we cannot run ASP. net
IIS
used for ASP. net
For UNIX os
Tomcat
52
ASP.net
Apache
IIS: internet information System: it will automatically come along with O.S
To check whether IIS is present in the system or not within the system
Click on start
If a window is opened named IIS console then IIS is present within the
machine
If any error window appears then IIS is not present in the machine
Installing the IIS if not present:
Go to run prompt
Type appwiz.cpl
Click on Add windows components
Check IIS and put O.S cd and follow the steps
Order of installation of software:
O.S
IIS
Database (sql server/oracle)
VS. net 2005
If IIS is installed after visual Studio.NET then ASP. net applications will not
run properly becoz ASP. net is not registered at IIS
To reinstall the ASP. net and to register at IIS we have a separate tool as
aspnet-regIIS-I
To work with this tool use the following steps
Click start
click on programs click on MS.NET framework sdkv2.0
Click on sdk cmd prompt type aspnet_regIIS-I
Note: this will reinstall asp.net s/w and will register asp.net with
IIS
type IISreset this will stop the iis and restarts iis
click on file
53
click on new
click on website
ASP.net
54
ASP.net
Select ASP. net website template select the programming language with
C#.net
Select
the
location
as
HTTP
type
the
website
name(http://localhost/websitename) ok
Then automatically different windows will open
Design window
Source code window
Business logic window
Solution explorer window
Server explorer window
Tool box
Property window
Error List
55
ASP.net
56
ASP.net
re q u e s t
h ttp ://lo ca lh o s t/c o d e 1 .a s p x
c lien t
IIS
In e tin fo .e x e
a s p n e t_ is a p i.d ll
a s p n e t_ w p .e xe
A S P .n e t w o rk p ro chetts ps p ip e lin e s
p ro c e s s
O /p d is pla y
o /p
w p .e xw
e o rk p ro c e s s
CLR
s erv er
When a client gives the url the request is forwarded to the specified
web server i.e. IIS
IIS forward the request to inetinfo.exe file it checks the type of the
request and forward the request to the respective engines
57
ASP.net
If the request is ASP. net then it forward the request to ASPnetisapi.dll this file is mapped on IIS to identify asp. net request
location i.e. virtual directory
ASPnet-isapi.dll is forward the information through ASPnetwp.exe(web process)
ASPnet-wp.exe file allocates memory which is called as ASP. net
work process where the execution of the request is done
The execution of the request will uses the compilers by identifying
the language used and generates the o/p by combining with user
interface
This complete process is done under CLR which sends back the
response to IIS
The communication b/n work process and web server uses pipelines
When the response is send back to the client by IIS the complete
information about the request and its process is removed from the
web server
The above point confirms that ASP. net is stateless technology
init
load
custom
prerender
unload
For every lifecycle execution of a web form .these events are fired
page_init event: used for initializing the component
Page_load used to load the web form
Custom event: the events which are fired by the controls of a web form
Prerender:used to send the o/ p the client by combining user interface
and
the code
Unload: as the o/p is send it is called to remove the memory of the web
form
ASP.net
Application
Server
Cache
Trace
Ispostback etc..
Codingtechniques
Codeinlinemodel
.
A
S
P
x
Codebehind
Designing
code
Designing
code
.aspx
Programming
code
modell
Programming
code
.aspx.cs
59
ASP.net
Programmer need to wait until web designer completes designing so
programmers time will be wasted
There wont be any security for programming code from the designer
Maintenance of the code is difficult
Application development will take more time
No reusability of business logic
Code behind model: this method separates the user interface and
business logic in two files
1. User interface in .aspx file
2. Business logic in .cs or .vb file
It reduces the maintaince cost
increases the performance by reusability of the code
To develop a code file we should define a class inherited from
System.Web.UI.page Class
For web based applications there are two important namespaces in
asp.net
using System.Web.dll;
using System.Web.UI.dll;
Advantages of code behind:
60
ASP.net
Controlsinasp. net
Controls
Clientside
serverside
HTML
1.
2.
1.
2.
HTML
server
Webserver
61
ASP.net
s n o C o n tro ln a m e C la s sn a m e
Tag
In p u t(b u tto
) n
H tm lin p u tB u tto n
In p u t(R e )s e t
H tm lin p u tB u tto n
In p u t(T e) x t
In p u t(file
)
H tm lin p u tF ile
In p u t(C h e) c k
H tm lin p u tC h e c k B o x
In p u t(R a )d io
Im a g e
H tm lIm a g e
< im a g e >
10
T a b le
H tm lT a b le
H tm lT a b le C e ll
H tm lT a b le R o w
11
12
D iv
13
S e le c t
H T M L S e le c t
14
T e xtA r e a
H T M LT e xta r e a
< T e x ta re a >
15
N am espace
U s in g
S y s tem .W eb .U I.H tm lC o n t
S y s tem .W eb .U I.H tm lC oro
n tro
ls.HlsT M lC o n tro l
H tm lin p u tT e xt
62
ASP.net
All the HTML controls are inherited from System.Web.UI.Html.Htmlcontrol
names
System.Web.UI.HtmlControls .HTMlControl
HTMLinputcontrol
HTMLcontainercontrol
HtmlInputButton
HtmlInputText
HtmlInputFile
HtmlInputCheckBox
HtmlinputradioButton
HtmlGenericControl
HtmlinputImage
HtmlinputTable
HtmlinputTableCell
HtmlinputTablerow
ASP.net
All asp. net controls will provide state management
All asp. net controls will support object oriented programming features
To create asp. net control we use the following syntax
<tag prefix: Class name id=any id runat=server>
<asp: Textbox id=TextBox1 runat=server>
For every asp. net standard control equivalent HTMl code is generated
on rendering
Difference between HTML controls and web server controls
64
ASP.net
Standard controls
Data controls
Validation controls
Navigation controls
Login controls
Ajax extensions
General controls
Discussing each control with an example:
65
ASP.net
WELCOMETOASP.NET
LABEL2
ENTERYOURNAME
LABEL1
TEXTBOX1
LABEL3
Properties:
textbox1:autopostback=true
view source:
Protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label3.Text = "hi" + TextBox1.Text;
}
Checkbox: this control is used to provide selection of more than one options
from
the
given
group
of
options
properties:
Autopostback--------->true,
false
Checked.>true/false
Auto postback:when set to true page will be posted back to web server
whenever user activates the checkbox
When set to false page will not be posted back to web server when
user activates checkbox
Checked: stores true whenever checkbox is activated otherwise stores
false.
Default event of checkbox control is checked changed event
66
ASP.net
Exampleforcheckbox:
Enterurname
Enterhobbies
dancing
Browsing
playing
chatting
LABEL 3
SUBMIT
View source:
protected void cmdsubmit_Click(object sender, EventArgs e)
{
string s = txtsample.Text + "Hobbies are";
if (Chkdancing.Checked==true)
{
s = s + Chkdancing.Text + "";
}
if (Chkplaying.Checked == true)
{
s = s + Chkplaying.Text + "";
}
if (Chkbrowsing.Checked == true)
{
s = s + Chkbrowsing.Text + "";
}
if (Chkchatting.Checked == true)
{
s = s + Chkchatting.Text + "";
}
lbldisplay.Text = s;
67
ASP.net
}
example-2:
view source:
protected void Button1_Click(object sender, EventArgs e)
{
//REGISTER
int rent = 0; int acost = 0;
//verify room type selectede by user
if (R1.Checked)
//deluxe
rent = 1000;
else if (R2.Checked)
//ordinary
//verify amenities selected by user
if (C1.Checked)
acost = 3000;
if (C2.Checked)
acost = acost + 200;
//calculate the rent
rent = rent + acost;
Label4.Text ="registered <br> rent/day:"+rent;
}
68
ASP.net
Using design
controls
Hyperlink
Link button
Image button
Using coding
Response. Redirect
Server. Transfer
69
ASP.net
Example:
70
ASP.net
71
ASP.net
Image Button: this control is used to redirect the user request to the
required webpage or website
Properties:
Command name
Command arguments
Image url
Image url:this property is used to set the path of the image using
which we want to create hyper link
Postback url:this property is used to set the url address path to
which we would like to redirect the user request when user clicks on
image button
Using image button control we can create the hyperlink only
for images not for text
This control will support both command name and command
arguments properties
Ex:select image button----properties----image url property----click
on elipse button-------------select the req image file---------0k
Go to postback url-----------click on ellipse button and select
default.aspx
Run the app and check
72
ASP.net
Hyperlin
k
Link button
Image Button
Link
can Link can be created to theLink can be created to the
be created text only and cannot beimage only and cannot be
to the text created to the image
created to the text
and
also
to
the
image
It doesnot support command namesupport command name an
support
an command argumentscommand
arguments
command properties
properties
name an
command
arguments
properties
73
ASP.net
Response.Redirect
Used
to redirect
to any
webpage
in
any
website
present in the same webserver
or in different webserver
Execution is fast
Execution is slow
Cannot be user to pass any values to Can be user to pass any values
the destination page
to the destination page
Button Controls:
74
ASP.net
BUTTONS
PUSH BUTTON
LI NK BUTTON
I MAGE BUTTON
75
ASP.net
events
person
Eating
Drinking
singing
Whenever person gets hungry then only eating event will fire
Events associated with button controls:
Click event
Command event
Click event: this event will be fired when user clicks on the button
This event does not support command name and command argument
properties
Command event: this event is fired whenever user clicks on the
button
This event supports command name and command argument
Example with Click event:
textbox1
RED
Green
BLUE
View source:
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Red;
}
protected void Button2_Click(object sender, EventArgs e)
{
76
ASP.net
TextBox1.BackColor = System.Drawing.Color.Green;
}
protected void Button3_Click(object sender, EventArgs e)
{
TextBox1.BackColor = System.Drawing.Color.Blue;
}
Example2 with click event:
Arithmeticproblem.aspx
Enterfirstno
txtNum1
Entersecondno
txtNum2
Result
txtResult
Add
cmdAdd
subtract
cmdSubtract
Multiply
cmdMultiply cmdDivide
View source:
int a, b, c;
protected void Button1_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a+b;
TextBox3.Text=c.ToString();
}
77
Divide
ASP.net
protected void Button2_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a-b;
TextBox3.Text=c.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a*b;
TextBox3.Text=c.ToString();
}
protected void Button4_Click(object sender, EventArgs e)
{
a= Convert.ToInt32(TextBox1.Text);
b= Convert.ToInt32(TextBox2.Text);
c=a/b;
TextBox3.Text=c.ToString();
}
Example with command event:
Calling same function from two or more buttons
Select button1--properties--click on event---and type F1 and press
enter
Select button2--properties--click on event---and type F1 and press
enter
Enteranytext
button1
button2
View source
78
ASP.net
Arithmeticproblem.aspx
Enterfirstno
txtNum1
Entersecondno
txtNum2
Result
txtResult
Add
cmdAdd
subtract
cmdSubtract
79
Multiply
Divide
cmdMultiply cmdDivide
ASP.net
80
ASP.net
81
ASP.net
82
ASP.net
Validation controls
Validation: it is a process of restricting the control by accepting the
proper input from the user i.e. it is a process of checking the values are
valid or not
Validations are of two types
Client side validations
Server side validations
s.no
1.
2.
3.
4.
Browser dependent
Browser independent
1.
2.
3.
4.
5.
6.
validation
error
ASP.net
Example
Properties:
Design: drag and drop required field validator
Properties of required field validator are
Control to Validate=TextBox1
Error Message=TextBox should contain some Text
84
ASP.net
Range validator: this control is used to check or validate user entered
data within the given range or not
Extra properties:
Maximum Value :this property is used to set the highest value with
which we would like to compare the user entered data
Minimum Value: this property is used to set the highest value with
which we would like to compare the user entered data
Type: this property is used to set the required datatype with which we
would like to compare the user entered data
Type=integer/string/double/date etc.
example
Properties:
Design: drag and drop range validator
Properties of range validator are
Control to Validate=TextBox2
Error Message=invalid age
Maximum value=25
85
ASP.net
Minimum Value=18
Type=integer
Compare validator: this control is used for comparing to controls or
used for comparing a control with the value
If both the controls contents are same then compare validator will
return true otherwise false
Properties:
Example
Properties:
Go to toolbox drag and drop compare validator
Control to validate=TextBox2
Control to compare =TextBox1
Operator=equal
Type: string,
86
ASP.net
Properties:
Go to toolbox drag and drop Regular expression validator.
Validation expression=select internet url address
Validation Expression: this property is used to set the required
expression f
format with which we want to compare
There are predefined expressions available to compare and also we
can write our own expressions
This control is used to perform the validations whenever existing
validation controls donot make the user requirements
87
ASP.net
This control is used to perform both client side and server side
validations
This is the only control in complete validation controls which is used to
perform both client side and server side validations
Properties
Control to validate
Client validation functions
Error message
Validation summary: it is used to display all the error messages in
that webpage This control is not used to perform any validations rather
it will display all other validation controls error messages as a group
together
Username
Requiredfielsvalidator
password
Requiredfielsvalidator
Retypepassword
Comparevalidator
Age
Rangevalidator
Submit
Validationsummary
Example:
Drag and drop validation summary
88
ASP.net
Enterusername
Enterpassword
Customvalidator
submit
Properties
Control to validate=textbox2.text
Error message=passw ord should contain min of 6 characters
Client validation functions =F1
Go to source part of the html page and write the JavaScript function
code like
<head >
<script type="text/javascript">
function F1(X,Y)
{
if(Y.Value.length>=6)
{
Y.IsValid=true;
}
else
{
Y.IsValid=false;
}}
</script>
</head>
Button1_Click
{ Response.Redirect("page submitted");}
89
ASP.net
1st arg will store the type of the control from which function has been
called
2nd arg contain 2 important properties
Value
IsValid
Value: property stores the data entered by user in the control that we
are validating
IsValid:this is a boolean property stores True/false and will return either
true or false to custom validator control when function execution is
completed
Example to perform server side validations using custom validator
control
In the above example we perform the validation to check password is
kanna or not
If user enters password > kanna then we display a message as
page submitted otherwise error message displayed
Enterusername
Enterpassword
Customvalidator
submit
Properties
Control to validate=textbox2.text
Error message=password
Select custom validator ..> goto properties window..>click on events
button..>double click on server validate event write the following code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value == "kanna")
{
args.IsValid = true;
}
else
90
ASP.net
{
args.IsValid = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
Response.Write("page is submitted");
}
}
Navigation controls: these controls are used for fast navigation between
the web page on
a website
Some of the navigation controls are
MENU
TREE VIEW
SITEMAP PATH CONTROL
These controls are introduced only in 2.0 which we have to develop
using scripting languages or we have to download from Microsoft
control gallery in the previous versions of Asp. Net
MENU CONTROL:
Properties:
Disappear After=some millisecond
Items=Root, adding root, adding child, removing item
Items-----text, navigate url,image url,value
Dynamic menu style=some color
Example :
Step1: go to toolbox drag and drop menu control
Step2: select menu controls properties
Items=add root item----select new item---Text=HOME
similarly
Add ABOUTUS,CONTACT US
Step3: select HOME navigate url=home.aspx
select ABOUTUS navigate url=aboutus.aspx
select CONTACTUS navigate url=contactus.asp
step4:add home.aspx aboutus.aspx contactus.aspx to the existing
project
91
ASP.net
Example:
92
ASP.net
SITE MAP PATH CONTROL: this control is used for providing the
navigation information information of a menu or a tree view control
It helps to navigate between the pages by providing navigation
information on the top or bottom of the web page
This control requires a sitemap file which is based on xml
We cannot directly work with sitemap path control to work with
sitemap we have to go either menu control or tree view control
Steps to work with sitemap path control
Step1: drag and drop menu control
Step2: go to website--- add new item- select sitemap---ok
Step3:then automatically website map is added
Step4: write the following code
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMapFil1.0">
<siteMapNode url="home.aspx" title="HOME"
description="WELCOME TO HOME PAGE">
<siteMapNode url="contactus.aspx" title="CONTACTUS"
description="WELCOME TO CONTACTUS PAGE" />
<siteMapNode url="" title="" description="" />
</siteMapNode>
</siteMap>
93
ASP.net
Step-5: select menu copntrol --properties---datasourceid=new
datasource---select sitemap---ok.
Step-6: debug and check the output
94
ASP.net
Calendar control example:
ADO.net
95
ASP.net
Introduction to ADO.net
ADO. net:
Front end application: the application with which user interact like
forms, reports etc.
Front end tools :the software using which we design front end
application is known as front end tool
Dbase
FoxPro
MSAccess
Visual basic
Power Builder
D2K/oracle forms
.net
Java
96
ASP.net
I-layered approach
F
E
a
p
p
lic
a
tio
n
B
E
a
p
p
lic
a
tio
n
II-layered approach:
FEapplication
BEapplication
II-layered approach:
.
Disadvantages of II-layered approach:
As there are many front end tools and many back end tools
available in the market native drivers designed in any
Front tool for one back end tool cannot be used to interact
with other back end tool so every front end tool need to have one
Separate set of native drivers to interact with back end tool
II-layered approach:
97
ASP.net
In the same way every back end tool need to have one separate set of
native drivers for each front end tool
To overcome this disadvantage we use III-layered approach
III-layered approach
FEapp
DAO
RDO
ADO
ADO.net
Ex:VB,powerbuilder,
D2k/oracleforms
JAVA,.net
Nativedrivers
middleware
Nativedrivers
BEapplications
Ex:OLEDB
ODBC
JDBC
Ex:MSACCESS
MSSQLSERVER
ORACLE
MYSQLetc
Machine2/tool2
ADO. Net
98
ASP.net
F
E
a
p
p
lica
tio
n
O
b
je
ctm
o
d
e
l
D
rive
r
D
A
O
R
D
O
A
D
O
A
D
O
.n
e
t
D
a
ta
b
a
se
O
D
B
C
O
L
E
D
B
S
Q
L
C
L
IE
N
T
O
R
A
C
E
C
L
IE
N
T
99
ASP.net
ADOversusADO.NET(continued)
Feature
ADO
ADO.NET
XML
capabilities
XMLaware
XMListhenativetransfer
mediumfortheobjects
Firewalls
Firewallsblocksystemlevel
COMmarshalling
XMLflowsthroughthefirewall
viaHTTP
Code
Coupledtothelanguage
used,variousimplementation
Managedcodelibrary Uses
CommonLanguageRuntime,
therefore,languageagnostic
ADOversusADO.NET
Feature
PrimaryAim
ADO
ADO.NET
Client/servercoupled
Disconnectedcollectionof
datafromdataserver
Formofdatain UsesRECORDSETobject
memory
(containsonetable)
UsesDATASETobject
(containsoneormore
DATATABLEobjects)
Disconnected
access
UsesCONNECTION object
andRECORDSETobjectwith
OLEDB
UsesDATASETCOMMAND
objectwithOLEDB
Disconnected
accessacross
multitiers
UsesCOMtomarshal
RECORDSET
TransfersDATASETobjectvia
XML.Nodataconversions
required
100
ASP.net
ADO.NETArchitecture Diagram
101
ASP.net
1.Makesaconnection
2.Passsomequeryandgetresultback
3.Disconnectedfromthedatabasesystem
client
server
4.Makestheconnectionagain
5.Passsomeotherqueryandgetresultback
6.Disconnectedfromthedatabasesystem
2nd method:
In this method first we establish the connection to the database
Then send request for required data
And client requested data will be transferred to the network buffer at
server
And client will accessing data from the network buffer only
1
UI
2
4
5
db
3
N/W
buffer
3
N/W
buffer
Client1
2
4
UI
Client2
server
Step-1:connection is established to the server
Step-2:client sends the request for the required data
Step-3:client request is processed and result is transferred to the
separate memory allotted to the server for the client this memory is
known as network buffer
Step4:link will be created from network buffer to client
Step-5:client will be reading data from the network buffer
102
ASP.net
Provider
name
Namespace
Sqlclient
Database
connection
Only
sqlserver
Only oracle
Code
execution
Execution
speed
Architectura
l
Complexity
Others
Managed
code
Faster
Managed
code
Faster
Unmanaged code
Not complex
Not complex
Complex
---------------
Namespace
-----------------is not
Available
directly
required
to
add
reference
System.Data.
sqlclient
Oracle
OLEDB
ODBC
client
System.Data. System.Data.Oledb System.Dat
oracleclient
a.Oledb
103
Slow
Unmanage
d code
Slow
Most
complex
Included
from
.net
framework
2.0 version
ASP.net
OBJECTSINADO.Net
sno
Objectname
Classname
1.
Connection
SqlConnection
OracleConnection
OledbConnection
ODBCConnection
2.
Command
SqlCommand
OracleCommand
OledbCommand
ODBCCommand
3.
Parameter
SqlParameter
OracleParameter
OledbParameter
ODBCParameter
4.
Transaction
SqlTransaction
OracleTransaction
OledbTransaction
ODBCTransaction
sno
Object name
Class name
5.
Data Reader
6.
Data Adapter
104
ASP.net
7.
Command Builder
8.
Dataset
Dataset
9.
DataTable
DataTable
10.
Data Relation
Data Relation
11.
Data Row
Data Row
ASP.net
Close( ): This method is used to close an opened connection
Steps to work with connection object:
Step-1:include namespaces
Eg :using System. Data;
using System. Data.SqlClient;
Step-2: declare connection object
Syntax: Class name object name;
Ex: SqlConnection con;
Step-3: define connection object
syntax:objectname=new Classname(connectionstring);
Ex: con=new SqlConnection(connectionstring);
Step-4: open the connection
syntax: objectname.Open();
Ex: con.Open();
Step-5 close the connection
Ex: con.Close();
note: we can also use server name=. Or server name=local host if the
database is present on the same machine
Server name=IP address is given in real-time
IP address:127.0.0.1 i.e. IP address of local machine
Types of authentication modes in sqlserver:
Sqlserver supports two types of authentications
1. Sqlserver Authentication
2. Windows Authentication
Sqlserver Authentication :in this method we need to have separate
user id and password with sqlserver database then only we will be able
to connect to the sqlserver database
Windows Authentication: in this mode no need to have user id and
password by default it will take system authorized user
Sqlserver/oledb
Sqlserver/sqlclient
label1
View source:
using System.Data.SqlClient;
106
ASP.net
using System.Data.OleDb;
Button1_Click
{
//sqlserver authentication
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=model;data source=localhost");
//windows authentication
//SqlConnection con = new SqlConnection("initial
catalog=master;data source=localhost;integrated security=yes");
con.Open();
Label1.Text = "connected to sqlserver authentication";
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
//oledb connection
OleDbConnection con = new
OleDbConnection("provider=sqlOleDb;user
id=sa;password=sa;database=master");
con.Open();
Label1.Text = "connected to sqlserver with OLEDB";
con.Close(); }
2. Command object: this object is used to perform various operations on
database objects like tables,views,stored procedures etc
Command object will work with connection oriented object so first we
establish connection to database perform the required operation s and
close the connection to the database
Properties with command object:
Command Type: we will set command type value based on command
text
Command text : this property is used to set the required value
Command text can be
Sqlquery
Stored procedure name
Table name
If command text is sqlquery then command type is text
If command text is stored procedure then command type is stored
procedure
If command text is Table name then command type is table
Default value is text
Connection: this property is used to set the connection object name
using which we send the command object to the database server
parameters: This is collection property used to send required parameters
and their values with the database stored procedure
Steps to work with command object:
107
ASP.net
1. Declare command object
syntax:Classname object name;
Ex:sqlcommand cmd;
2.
Define command object
syntax: object name=new Classname(command text,
connection object);
ex: cmd=new sqlcommand(Delete from Empdetails where
empid=117,con);
3. Mention command type:
Syntax: objectname.commandType=commandType.Value; //
Text(default),s.p,table
ex:cmd.CommandType=CommandType.Text
4. Execute command object
syntax: objectname.Executemethod();
ex:cmd.ExecuteNonQuery();
Differences between execute methods
s.no
Execute Nonquery
Execute Reader
Execute scalar
1.
It works with only actionIt works with only non-It works with only
queries
action queries
non-action
queries
that
include
INSERT,UPDATE,DELETE
aggregate function
2.
3.
4.
108
ASP.net
la b e l1
DELETE
Create database
create database kanna
use created database
use kanna
create table
create table emp_detail(emp_no int primary key,emp_name
varchar(10),emp_designation varchar(10),emp_salary
varchar(10),emp_deptno int)
insert records into database
insert into emp_detail values(101,'kanna','PL','40000',20)
insert into emp_detail values(102,'sunil','PL','40000',20)
109
ASP.net
insert into emp_detail values(103,'murali','PL','40000',20)
insert into emp_detail values(104,'chakri','PL','40000',20)
insert into emp_detail values(105,'nagaraju','PL','40000',20)
insert into emp_detail values(106,'bobby','PL','40000',20)
selecting records
select * from emp_detail
Step-3: go to C# code window an write the following code
using System.Data.SqlClient
Button1_Click
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("delete employee where
empid=102",con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = i + "records deleted";
}
Example2:
110
ASP.net
E n t e r e m p i d
D E LE TE
la b e l2
View source:
using System.Data.SqlClient;
Button1_Click
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
con.Open( );
SqlCommand cmd;
cmd = new SqlCommand("Delete employee where
empid="+TextBox1.Text,con);
cmd.CommandType = CommandType.Text;
111
ASP.net
int i = cmd.ExecuteNonQuery( );
con.Close( );
Label2.Text = i + "records deleted";
}
Example3:
Insert, update and delete
Design:
112
ASP.net
Enterempid
Enterempname
Enterdesignation
EnterDOJ
Entersalary
Enterdeptno
label7
insert
update
Delete
View source:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
SqlCommand cmd;
String s = "insert into emp_details values('" + TextBox1.Text + "','"
+ TextBox2.Text + "','" + TextBox3.Text + "',
'" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text +
"')";
cmd = new SqlCommand(s,con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label7.Text = i + "records inserted"; }
protected void Button2_Click(object sender,EventArgs e)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
SqlCommand cmd;
113
ASP.net
String s = "update emp_details set empname='" +
TextBox2.Text + "',designation='" + TextBox3.Text + "',
Doj='" + TextBox4.Text + "',salary='" + TextBox5.Text +
"',deptno='" + TextBox6.Text + "
where empid='" + TextBox1.Text + "'";
cmd = new SqlCommand(s, con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
Label7.Text = i + "records updated"; }
Button3_Click {
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
SqlCommand cmd;
String s="delete emp_details where
empid='"+TextBox1.Text+"'";
cmd=new SqlCommand(s,con);
con.Open();
int i=cmd .ExecuteNonQuery();
con.Close();
Page.RegisterStartupScript("aa","<script> alert('record is
succesfully deleted')</script>");
}
114
ASP.net
In this method it is not required to establish prior connection to the
database whenever client sends request for any data connection will be
maintained automatically
UI
db
3
3
PA
PA
4
Client
UI
Client
Step
-1:client sends the request to the server for required data
Step-2:client request is processed and requested data is dumped into
client machines memory known as process area once the data is dumped
in to process area connection is no more maintained to the database
Step-3:user will be interacting with the data present in process area.
Step-4:after completion of the user interaction process area data will be
updated back to database at the time of updation connection is
automatically maintained
Second method:
115
ASP.net
DISCONNECTEDDATACYCLE
req
client
dataadapter
application
respo
dataadapter
dataset
Client1
ADO.net
C
O
N
N
E
C
T
I
O
N
db
Dbserver
Applicationserver
116
E m p id
E m p d e t a il s
E n a m e D e s i g n a t iDo on j
S a la ry
D e p tn o
0 101
K a n n a P r o j e c t l e a1 d/ 1 / 2 0 0 7 4 0 0 0 0
10
1 102
S u n il
T e a m l e a d2 / 2 / 2 0 0 7 3 0 0 0 0
10
103
M u r a l i P r o g r a m m3 /e3r/ 2 0 0 7 2 0 0 0 0
10
104
C h a k r i D e v e l o p e 5r / 5 / 2 0 0 7 1 0 0 0 0
10
105
bobby DBA
30
1 /1 /2 0 0 8 2 2 0 0 0
dept
D e p tn o D n a m e
L o c a tio n
10
Kanna
H yd
20
S u n il
B a n g lo re
30
M u ra li
D e lh i
40
C h a k ri
V iz a g
D a ta s e t
1 .D s . T a b le s E m p d e t a i l s
dept
D s . T a b[ 0l e] s
or
D s . T a b lEe ms [pd e ta] i l s
D s . T a b[ 0l e] s
O r D s . T a b[ El e ms p d e t a] i l s
D s . T a b[ 1l e] s
O r D s . T a b[ l eD se p t ]
E m p D e t a ils
D e p t
E m p D e t a ils
Id e n t if ic a t io n o f t a b l e s
Dept
A s d a t a s e t c o n t a i n s c o l l e c t i o n o f t a b l e s e a c h t a b l e i s i d e n t i f i e
2 . i d e n t i f i c a t i o n o f r o w s
A s e v e r y t a b l e c o n t a i n s c o l l e c t i o n o f r o w s e a c h r o w i s i d e n t i f
Ex:
D s . T a b[ 0l e] .sR o w s [ 1 ]
E m p id E n a m e D e s ig n a t ioD no j S a la r y D e p t n o
101
K a n n a P r o j e c t le a1 d/1 /2 0 0470 0 0 0 1 0
D s .T a b le s [ 1 ] .R o Dw Ns [O1 ] D n a m e
30
r a ju
lo c a t io n
d e lh i
3.
I dentification of columns:as every table contains collection each column is identified using index value or
column name
ex:Ds.Tables[0].columns[2]
Programmer
TL
SA
4.
identification of cell or a cell data: a cell is identified using matrix notation by using either row s collection
PL
or columns collection
ex:Ds.Tables[0].columns[3][1]
DBA
or
Ds.Tables[0].columns[1][3]
Kumar
1
Edit
Empid
Ename Designation
DOJ
Salary
Deptno
Edit
101
Sunil
Programmer
1/1/07
8000
10
Edit
102
Kanna
TL
2/1/07
20000
20
Update
cancel
103
Murali
PM
3/3/07
30000
10
Edit
104
chakri
testing
4/1/07
10000
20
Edit
105
Karee
developer
6/1/07
8000
10
Addnew
Repeater control
Data list
Grid view
Forms view
Details view
Repeater control: this control is used to display the data in
plain text format to the user
Repeater control doesnt provide designing facilities
Repeater control doesnt provide editing facilities
Repeater control doesnt provide sorting facilities
Repeater control execution is faster as compared with data list
and grid view controls
Repeater controls is best to be used to display the data just in
plane format
Example :
Designing repeater control in table:
VIEW CODE:
STEP1: go to source and write the following code
<div>
<table>
<asp:Repeater ID="rpt1" runat="server">
<HeaderTemplate>
<tr><th>EMPID</th>
<th>EMP NAME</th>
<th>DESIGNATION</th>
<th>DOJ</th>
<th>SALARY</th>
<th>DEPTNO</th></tr>
</HeaderTemplate>
<ItemTempla <tr>
<td><%#DataBinder.Eval(Container.DataItem,"empid")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"empname")
%></td><td><
%#DataBinder.Eval(Container.DataItem,"designation")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"doj")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"salary")
%></td>
<td><%#DataBinder.Eval(Container.DataItem,"deptno")
%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
Step-2: go to c# code window and write the following code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{ //step-2 prepare datasource
con
=
new
SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
rpt1.DataSource = ds;
rpt1.DataMember = "emp_details";
rpt1.DataBind();
}}
DATALIST
Data list control is similar to repeater control
Data list control provides very good designing facilities
It provides editing facilities
It provide adding new record facilities
We can also delete any record using data list control
It does not provide sorting facilities
It does not provides paging facilities
Execution of data list control is faster as compared with grid
view and slow as compared with repeater control
Properties with data list control:
Data Source
Data Member
EditItemIndex
Gridlines
Selected Index
Show Header
Show Footer
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class datalist : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
//step-2 prepare datasource
con
new
SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
dl1.DataSource = ds;
dl1.DataMember = "emp_details";
dl1.DataBind();}}
example 2 to delete a record from database using datalist
contro with command arguments
Step-1:
Go to source and write the following code:
<div>
<asp:DataList ID="dl1" runat="server"
OnItemCommand="dl1_ItemCommand" GridLines="Both">
<HeaderTemplate>
EMPID EMP NAME DESIGNATION DOJ SALARY DEPTNO
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="b1" runat="server" Text="Delete"
CommandArgument='<%#DataBinder.Eval(Container.DataItem,"empid")
%>' />
<%#DataBinder.Eval(Container.DataItem,"empid") %>
<%#DataBinder.Eval(Container.DataItem,"empname") %>
<%#DataBinder.Eval(Container.DataItem,"designation") %>
<%#DataBinder.Eval(Container.DataItem,"doj") %>
<%#DataBinder.Eval(Container.DataItem,"salary") %>
<%#DataBinder.Eval(Container.DataItem,"deptno") %>
</ItemTemplate>
</asp:DataList></div>
note: we can include any standard control within the data list
control by writing the code in item template or Header template
like
<ItemTemplate>
<asp:Button ID="b1" Text="Delete" runat ="server" />
</ItemTemplate>
Step1:designing
using
using
using
using
using
using
using
using
using
using
using
System;
System.Data;
System.Configuration;
System.Collections;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
System.Data.SqlClient;
con.Close();
GetData();
}
}
N o te :
t o t r a p t h e r o w : d a t a l i s t c o m m a n d e v e n t a r g s c l a s s h a s a p r o p e
p r o p e r t y S O E . I t e m w i l l s t o r e t h e r e s p e c t i v e r o w i n w h i c h u s e r
i . e . i f u s e r c l i c k s o n 1 0 3 e m p i d r e c o r d d e l e t e b u t t o n t h e n e . I t e m
d e le t e
103
K a n n a T L 1 2 / 1 1 / 2 0 0 9 4 0 0 0 0
T o t r a p t h e la b e l:
W e u s e a f u n c t io n k n o w n a s F in d C o n t r o l w it h I t e m P r o p e
e . I t e m . F in d( Cl b olenmt r po) id
l 1 0 3
F in d c o n t r o l f u n c t io n w ill r e t u r n ad na yt a ct yo pn et r o l w it h c o n t r o l
E d i t i n g t h e d a t a u s i n g d a t a l i s t c o n t r o l :
n o t: ea s l o n g a s E d i t I t1e m
D Ien ds e xt ei sd i t i t e m d a t a l i s t d a t a i s d i s p l
m ode
T o d i s p l a y d a t a l i s t d a t a i n e d i t a b l e m o d e t h e n s e t
D A T L I S T I N S T A T I C M O D E
E D I T / S AE MV EP I DE N A M DE E S I G N A TDI OO NJ s a l a r y D e p t n o
E D IT 1 0 1 X x x
E D IT 1 0 2 X x x
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
E D IT 1 0 3 X x x
E D IT 1 0 4 X x x
E D IT 1 0 5 X x x
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
Xxx
xxx
D A T A L I S T I N E D IT A B L E M O D E
Example-4:
Editing with datalist control
Step-1: design
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
DL4.DataSource=ds;
DL4.DataMember = "emp_details";
DL4.DataBind();
}
protected void DL4_ItemCommand(object source,
DataListCommandEventArgs e)
{
if(e.CommandName.ToString()=="edit")
{
DL4.EditItemIndex=e.Item.ItemIndex;
GetData();
}
else if(e.CommandName.ToString()=="cancel")
{
DL4.EditItemIndex=-1;
GetData();
}
else if(e.CommandName.ToString()=="update")
{
TextBox t1=(TextBox)e.Item.FindControl("txtename");
string mename=t1.Text;
t1=(TextBox)e.Item.FindControl("txtdesignation");
string mdesig=t1.Text;
t1=(TextBox)e.Item.FindControl("txtdoj");
string mdoj=t1.Text;
t1=(TextBox)e.Item.FindControl("txtsalary");
string msalary=t1.Text;
t1=(TextBox)e.Item.FindControl("txtdeptno");
string mdeptno=t1.Text;
Label l1 = (Label)e.Item.FindControl("lblempid");
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
string s="update emp_details set
empname='"+mename+"',designation='"+mdesig+"',doj='"+mdoj+"',
salary='"+msalary+"',deptno='"+mdeptno+"' where
empid="+l1.Text;
SqlCommand cmd=new SqlCommand(s,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DL4.EditItemIndex=-1;
GetData();
}}
}
GRIDVIEW CONTROL
s.no
1.
EventName
Page
IndexChanging
ClassName
GridViewPageEven
tArgs
Properties
NewPageIndex
Description
Will be fired when
user clickson any
2.
Sorting
GridViewSortEvent
Args
SortExpression
3.
RowDeleting
GridView
DeleteEventArgs
RowIndex
4.
RowEditing
GridView Edit
EventArgs
NewEditIndex
5.
RowUpdating
GridviewUpdate
EventArgs
RowIndex
6.
RowCancellingE
dit
GridviewCancelEdi
tEventArgs
RowIndex
page no
Will be fired when
user clicks on any
column heading link
button created
automatically when
AllowSorting is true
Will be fired when
user clicks on delete
button created
automatically
AutoGenerate
Delete Button is
true
Will be fired when
user clicks on Edit
button created
automatically when
AutoGenerate Edit
Button is set to true
It will be fired when
user clicks on
update button
created
automatically when
AutoGenerate Edit
Button is set to true
It will be fired when
user clicks on cancel
button created
automatically when
AutoGenerate Edit
Button is set to true
<div>
<asp:GridView ID="gv1" runat="server" Height="337px">
<Columns>
<asp:BoundField HeaderText="EMPID" DataField="empid" />
<asp:BoundField HeaderText="EMPNAME" DataField="empname"
/>
<asp:BoundField HeaderText="EMPDESIGNATION"
DataField="designation" />
<asp:BoundField HeaderText="EMPDOJ" DataField="doj" />
<asp:BoundField HeaderText="EMPSALARY" DataField="salary" />
<asp:BoundField HeaderText="EMPDEPTNO" DataField="deptno" />
</Columns>
</asp:GridView>
</div>
using System.Data.SqlClient;
public partial class gridview1 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
con = new SqlConnection("user
id=sa;password=sa;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from emp_details", con);
ds = new DataSet();
da.Fill(ds, "emp_details");
//step-3 attach database to databound control
gv1.DataSource = ds;
gv1.DataMember = "emp_details";
gv1.DataBind();
}
}
<div>
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging" >
</asp:GridView>
using System.Data.SqlClient;
public partial class gridview2 : System.Web.UI.Page
{
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
GetData();
}
}
private void GetData()
{
<div>
<asp:GridView ID="GridView1" runat="server"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
Height="194px" Style="z-index: 100;
left: 316px; position: absolute; top: 71px" Width="444px"
AutoGenerateColumns="False">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399"
HorizontalAlign="Left" />
<HeaderStyle BackColor="#003399" Font-Bold="True"
ForeColor="#CCCCFF" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%-- <asp:RadioButton ID="r1" runat="server" />--%>
<asp:CheckBox ID="c1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="productid"
DataField="productid" />
<asp:BoundField HeaderText="productname"
DataField="prname" />
<asp:BoundField HeaderText="cost" DataField="cost" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" BackColor="Gray"
OnClick="Button1_Click"
Style="z-index: 101; left: 481px; position: absolute; top:
321px" Text="TOTAL"
Width="100px" />
<asp:Label ID="Label1" runat="server" BackColor="Lavender"
Font-Bold="True" ForeColor="Maroon"
Style="z-index: 103; left: 328px; position: absolute; top:
387px" Text="Label"
Visible="False" Width="431px"></asp:Label>
</div>
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
SqlConnection con = new SqlConnection("user
id=sa;password=sa;database=gridview");
SqlDataAdapter da = new SqlDataAdapter("select * from
product", con);
DataSet ds = new DataSet();
da.Fill(ds, "product");
GridView1.DataSource = ds.Tables["product"];
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string s="";
int tot = 0;
foreach(GridViewRow r in GridView1.Rows)
{
CheckBox c = (CheckBox )r.FindControl("c1");
if (c.Checked!=false)
{
s = s + r.Cells[2].Text + "<br>";
tot = tot + int.Parse(r.Cells[3].Text);
}
}
Label1.Visible = true;
Label1.Text = "products sale:<br>" + s + "total:" + tot;
}
}
Display radio buttons in grid view:
Step-1:
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
Height="194px" Style="z-index: 100;
left: 322px; position: absolute; top: 82px" Width="444px"
AutoGenerateColumns="False">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True"
ForeColor="#CCFF99" />
using
using
using
using
using
using
using
using
using
System.Data;
System.Configuration;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
System.Data.SqlClient;
ADROTATOR CONTROL
It will rotate different functions to different clients
This requires two steps
1. preparing advertisement files
2. providing advertisement file file to adrotator
Structure of advertisement file::
In asp 3.0 advertisement file is text file in asp.net it is xml file this
provides more flexibility compares to text file
<Advertisements>
<Ad>
<imageurl>ad image file</imagefile>
<NavigateUrl>ad info page</NavigateUrl>
<Alternate Text>..<Alternate Text>
<Height>.</Height>
<Width>.</Width>
<impressions></impressions>
<description></description>
</Ad>
</Advertisements>
Xml is case sensitive the tag name is casesensitive
imageUrl:it will represent advertisement file
<NavigateUrl> it will represent advertisement info page
<Alternate Text> it will represent tooltip text for ad or it will be
displayed when image is not downloaded
<impressions> it will specify priority for advertisement the add with
more impressions will be given to more no of clients
The add with more impressions will be given to more no of clients
Example:
Step-1: create website--add existing item--add three
image
Step 2: add advertisement webpage files
Website--add new item--html pagename=pocketpc.html---.add and write the following code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
POCKET PC INFO PAGE
</body>
</html>
Similarly add handycom.html and speakers.html
Step-3: place advertisement file into website
Website menu--add new item--XMLFile.xml---add. And write the
following code
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>ASP.jpg</ImageUrl>
<NavigateUrl>pocketpc.html</NavigateUrl>
<AlternateText>pocketpcinfo</AlternateText>
<Impressions>5</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description>latest arrival ofg pocket pc</description>
</Ad>
<Ad>
<ImageUrl>KANNAASP.jpg</ImageUrl>
<NavigateUrl>speakers.html</NavigateUrl>
<AlternateText>speakersinfo</AlternateText>
<Impressions>5</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description>speakers at lowestcots grab offer</description>
</Ad>
<Ad>
<ImageUrl>KANNAASPWITHFAQS.jpg</ImageUrl>
<NavigateUrl>handycom.html</NavigateUrl>
<AlternateText>handycoms info</AlternateText>
<Impressions>2</Impressions>
<Heigth>150</Heigth>
<Width>150</Width>
<description></description>
</Ad>
</Advertisements>
Step-4:
Go to default.aspx and design
body
{
background-color:Blue;
}
.myStyle
{
font-size:xx-large;
color:Red;
}
To apply this style sheet take a asp. net webpage i.e. .aspx page
Go to html window place the cursor in the head tag-----go to
solution explorer
---drag and drop style sheet file in the head tag
This tag automatically adds a link tag in the HTML code window
To apply the class as a selector on the control i.e. my style block
definition
Add a button control on the form-------.properties of button
---cssclass=myStyle
DRAWBACKS OF CSS:
CSS is browser dependent
It applies the styles on the client machine
It is not supportable by the ASP .net control properties
To overcome this problems of CSS ASP .net 2.0 has introduced a
new concept called
THEMES
SKINS
MASTER PAGES
MASTER PAGES:
1.
2.
3.
4.
5.
6.
String ename;
public employee(int no, String en)
{
eno = no;
ename = en;
}
public int Empno
{
get
{
return eno;
}}
public String Empname
{
get
{
return ename;
} }}
Design:
store
label1
Button1_Click
{
String lb = ListBox1.SelectedItem.Text;
bool cb = CheckBox1.Checked;
//Response.Redirect("urlencodeing2.aspx? L="+lb+"&C="+cb+);
Server.Transfer("urlencodeing2.aspx");
}
Page_Load
{
// String lb = Request.QueryString["L"];
// String cb = Request.QueryString["C"];
String lb = Request.Params["ListBox1"];
String cb = Request.Params["CheckBox1"];
This isvalue
check
box
Item1 = "ListBox
Label1.Text
is:"
+ lb;
Item2
Label1.Text += "<br>CheckBox Value is :" + cb;
Item3
}
Item4
submit
item5
label
1.
2.
3.
cookies
in memory
Out memory
Single value
multi value
Single value Multi value
When the client gives the request cookie is created on the server
but it is stored on the client by sending along with the response
and for the next request and the response cookie is taken to the
server and the client
Single value in memory cookie: a cookie which holds only one
value with one name is called as single value in memory cookie.
syn for creating cookie: to create or to retrieve information
from a cookie asp. net has provided Http Cookie class
syn 1:HttpCookie object=new
HttpCookie(cookiename,cookievalue);
Response.Cookies.Add(object);//to store the cookies on client
machine
syn2:HttpCookie object=new
HttpCookie(cookiename);
request1
Browser
Object. Value=cookie value;
Res1+cookie
Response.Cookies.Add(object);//to
store cookie
the cookies on client
cookie
machine
Request2+cookie
client1
server
client2
Res2+cookie
server
Ex:
create
display
label1
Button1_Click
{
HttpCookie h = new HttpCookie("a");//create a cookie
h.Value = "1000";
Response.Cookies.Add(h);//to store the cookie on client
machine
Label1.Text = "cookie is created";
}
Button2_Click
{
HttpCookie h = Request.Cookies["a"];
Label1.Text = "cookie value is :" + h.Value.ToString();
}
Object.Values.GetKey(index);
To get key value:
Object.Values[index];
Object.Values.Get(index);
create
display
label1
Button1_Click
{
HttpCookie h = new HttpCookie("color");
h.Values["red"] = 10;
h.Values["blue"] = 20;
h.Values.Add("green", "30");
Response.Cookies.Add(h);
Label1.Text = "cookie is created";
}
Button2_Click
{
HttpCookie h = Request.Cookies["color"];
label1.Text="";
for (int i = 0; i < h.Values.Count; i++)
{
Label1.Text += h.Values.GetKey(i) + "=" + h.Values[i].ToString()
+ "<br>";
}
}
Browser
requ
s
Re
est1
ie
ok
o
c
1+
hard disc
cookie
Browser
2+
q
e
ki
o
co
cookie
cookie
When the client gives the first request cookie is created on the
server and along with the response it is send back to the client
and stores on the clients hard disc at the same time a copy of
that cookie is maintained on the browser process memory so
that it is reused along with the next request and the responses
The persistent cookies are maintained on the clients hard disc in
terms of a text file
The persistent cookie life span should be given by the
programmer and it automatically destroyed by the os of the
client machine when the life span is completed
Location: all the persistent cookies are store on
C:\documents and settings\administrator\cookies
Page_Load
{
if (Request.Cookies["uname"] != null &&
Request.Cookies["pwd"] != null)
{
if (Request.Cookies["uname"].Value.ToString() == "asp.net"
&& Request.Cookies["pwd"].Value.ToString() == "asp.net")
Response.Redirect("valid.aspx");
}
}
Button1_Click
{
if (TextBox1.Text = "asp.net" && TextBox2.Text == "asp.net")
{
if (CheckBox1.Checked == true)
{
HttpCookie u = new HttpCookie("uname", TextBox1.Text);
u.Expires = DateTime.MaxValue;
Response.Cookies p = new HttpCookie("pwd",
TextBox2.Text);
p.expires = DateTime.MaxValue;
Response.Cookies.Add(p);
}
Response.Redirect("invalid.aspx");
}
}
We have to create valid.aspx and invalid.aspx
Drawbacks of cookie:
Cookies can be easily deleted on the client machine because
there is no security for cookies on the client
Cookies are not supported by all the browsers
Only limited no of cookies can be maintained on a client machine
i.e. 400 for every website only 20 cookies are allowed to create
Each cookie size should not exceed 1024 bytes
Maintaining the state in ASP .net
Default.aspx
Source page
Default2.aspx
Target page
Key
Value
10
B
Uname
20
kanna
Default.aspx
Entervaluefora
Entervalueforb
submit
Entervaluefora
Entervalueforb
submit
Default3.aspx
Examplewithdatabase
Enterdeptno
submit
Default4.aspx
Default3.aspx
Designatio
Ename
Doj
n
Xxx
Sal
Deptno
Xxx
Xxx
xxx
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con
=
new
SqlConnection("integrated
security=yes;database=kanna;data source=localhost");
da = new SqlDataAdapter("select * from empdetails where
deptno="+Request.QueryString["dno"].ToString(),con);
ds = new DataSet();
da.Fill(ds, "empdetails");
GridView1.DataSource = ds;
GridView1.DataMember = "empdetails";
GridView1.DataBind();}
Default.aspx
Enter username
pkey
Enter password
label3
Empid
pkey
cancel
Login.asmails
px:
submit
Cookie
Sessionid
Request1
Session
Response+SessionID
Sessionid
Asp.netsessionid
ID
n
o
i
s
Ses
+
2
t
ues
q
onID
i
e
s
R
s
e
2 +S
e
s
n
po
Res
2.
3.
4.
5.
6.
RemoveAt
7. properties:Cookiemode
Count
Mode
IsCookieless
SessionId
Keys
TimeOut
(specified the life span for session default life span for session is 20
minutes)
Creating a session:
Syn : Session[name of the session]=some value;
To get value variable=Session[name];
label1
button1
ALLTHEBEST
B.KANNABABU.