Вы находитесь на странице: 1из 91

+ASP.

NET

Asp.net is technology which provides set of specification for building web


based application towards server side code execution.

Asp.net providing two things:

1.) Dot net language providing towards server side coding.


It supports vb.net/c#.net programming.
2.) Collection of objects called as asp.net intrinsic objects. Response
request, session application ,server and cache

Asp.net=.net language programming + collection of objects

Asp.net supports different types of web based application development.

1. Normal application.

Developing dynamic WebPages like login page.

2. Web services.

Developing bossiness logic to integrate different vendor application

J2EE APPLICATION
.NET APPLICATION
-----
- Class

-----
Oracle Application Business Application

-----
-
3. Ajax [Asynchronous java script and xml] Application:

Developing WebPages implementing Ajax specification, the importance


of Ajax is avoiding complete page submission.
4. Silver Light:

It supports rich internet application development RIA means


implementing shapes, animations video streaming, and transformation
into web pages.

5. MVC [Model View Control] application

Developing web pages with the concept of MVC, the advantage is


testing will become easily.
The current version is Asp.net 4.0 towards .net 4.0 [asp.net 3.5
towards .net 3.5]
ASP.NET 4.0 provides following features
a.) URL rotating.
b.) Chart control
c.) Dynamic data.
d.) Silver light 3.0 integration.
e.) MVC integration.

Request and Response objects:

Request object can be used to read the information comes with client
request

The information can be form data [email id, password], browser


information.

Response object can be used to send the information from server to


client.

Browser web server

Request Object
xyz@gmail.com

Response Object
Registered successfully

The information can be normal text, URL.

1.) Write
It will send text from server to client.
2.) Redirect
It will perform redirect to other web pages.
3.) End
It will stop page processing [no more response will be given client].

Structure of ASP.NET page:

HTML page ASP 3.0 page ASP.NET page

HTML HTML HTML


+ + +
Client side script C.S.S C.S.S
+ +
Server side scripting server side
scripting
[Vb script/java script] [vb.net /C#.net]
Asp 3.0 support scripting languages towards server side programming,
scripting language are interpreter based; this doesn’t provide better
performance and no proper memory management.

ASP.Net support compiler based language; this provides better performance


and proper memory management.

Server code requires unique identification.

<%
--------
--------
%>

Note:
- Asp.net page extension is ASPX [Active Server Pages Extension].
- The server side codes will procedure towards client browser, this
output will not contain any server side statement, and it contains
only html content.
- Asp.net page execution takes at 2 place:
1.) Web server will execute server side code present in page.
2.) Browser will execute html tags and client side script given by
web server.
- Default language for asp.net is vb.net.
Page Directive:
 Directive is an instruction to server; it should be first statement
with in web page.
 Page directive can be used to provide different instruction to
server, it can changing language, attaching theme.
Creating Asp.net webpage using C#.NET:
<%@Page Language =”CS” %>
<Html>
<Body>
<% Response. Write (“ASP.NET PAGE USING C#”) ;%>
</Body>
</Html>
 Save page as hi.aspx.
 Browser http://localhost/hi.aspx.

ASP.NET Page Execution [ASP.NET architecture]:

Browser
 Server system requires IIS installation and .net installation
 .net instillation will configure IIS with asp net _isapi.dll[asp.net
internet server application programming interface]
 asp net _isapi.dll acts like mediator between web server and
.net
 Client Request to web server will be received by inetinfo.exe.it
will verify requested file extension ,if it is html the code will be
copied to client browser ,if it is aspx the request will be forward
to asp.net worker process using asp net _isapi.dll.
 Asp.net worker process [exe file] can be called as asp.net
engine(or) asp.net run time ,it will encapsulate all the .net
service needed for asp.net page execution.
Asp.net worker process will perform following steps:
 It will compile asp.net page into dll file.
 Dll will maintain a webpage in the form of class.
 Web page object will be created to process page execution and
output will be given to client browser.
 Web page dll will be maintained for serving to different clients
requests, this provides better performance.
Location of webpage dll in server system:
A folder will be created with in temporary asp.net files folder to
maintain web pages dll’s

Designer for asp.net:


Designer is an advanced editor compare to notepad editor, this
will reduce lot of coding to developer, this makes
development is easy and faster
There are 2 designers available for asp.net
1.) Visual Web developer[VWD]
2.) Visual Studio [2008/2010]
VWD supports only web applications development and license cheaper
compare to visual studio, the memory consumption will be less compare to
visual studio.

Starting visual studio to develop asp.net pages:


Start  Run devenv.exe [visual studiao.exe]
Go to file menu

Select New website

Select language as Visual C#

Select Location as File system

Add webpage into web site:

Go to website menu add new item  select web form


give the name as default2.aspx

Designer will include default content into web pages [Default2.aspx]

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>
<h1>
<% Response.Write("WELCOME TO ASP.NET") %>
</h1>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>

Press Ctrl+F5 it will activate browser to call web page.

Note :

 Vs 2008/2010 is called multi version envornment .it support


application developre to wards 2.0 to 4.0.
 Visual studi0 will create a folder towards web sites in this all the web
site related files will be stored.
 Vs supports web site development towards 3 locations

1. File system:

The website will be managed by personal web server


called”cassini web server”, this web server is built in the VS, in this
case IIs is not required.

2. HTTP: this website will be managed by web server IIS.

3. FTP [File transfer Protocol):

This website will be managed by FTP server; this is required when the
web server is present in remote location.

Server side Controls:


 The control can be considered as an object. This can be classified into
two types
1. Client side control
2. Server side control.
 The control object created by browser is called client side control.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 It is an instruction to browse to create textbox object.
 This client side control object is not accessible with in the server side
coding.
<% ….%>not accepted.

The solution provided by asp.net is server side controls. These are not
supported in asp 3.0.

The control object created within the server side processing is called
server side control. This makes developer job easier.

Server side control can be classified into two types

1. HTML server controls

2. Web server controls.

HTML server controls:

 HTML server controls will provide similar syntax of client side controls
to make migration easier.
 Providing ruanat =”server” to client side control becomes server side
control. This makes conversion easier.
 HTML server controls are provided based on number client side
controls, this area does not have any changes from asp.net 1.0 to
asp.net 4.0
Web server controls:

Web server controls provides very rich functionality compared to html server
controls. These are very advanced controls.

Web server controls can be sub divided into following things.

1. Standard controls

Label, button, textbox….

2. Validation controls:

Required field validator, range validator…

3. Data controls

Grid view, list view, charts [New in asp.net4.0]…

4. Navigation controls

Menu, tree view…

5. Web part controls

Webpartzone….

6. Login controls

Create user wizard…

7. Ajax extension controls

Script manager…
 Web server control supports extensibility (extensibility means MS
introduce new controls from one version to another version and
developer can create user defined web server controls.

Examples on controls:

EX1: perform the addition using asp.net

Design default.aspx like below [design]:

Source code for design:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 218px; width: 928px">
First
Number&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs
p;&nbsp;&nbsp;
<asp:TextBox ID="TxtFirst" runat="server"></asp:TextBox>
<br />
<br />
Second Number&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<br />
<br />

Result&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
;&nbsp;&nbsp;
<asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click"
Text="Add" />
</div>
</form>
</body>
</html>

Write the code within the default.aspx.cs [Logic]:

using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(TxtFirst.Text);
int b = Convert.ToInt32(txtSecond.Text);
int c = a + b;
txtResult.Text = c.ToString();

}
}

Button control:

This control supports page submission.

Page submission is the concept of clients submitting data to web server.

This can be classified into two things

1. Post back submission:

The page submitting to it is called Post back submission.

2. Cross page submission:

One page submitting to another page is called Cross page submission.

Example for cross page submission: Design login.aspx like below


Source code for design in login.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="login.aspx.cs" Inherits="login" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
uname&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtUid" runat="server"></asp:TextBox>
<br />
<br />
password&nbsp;
<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
<br />
<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
;&nbsp;
<asp:Button ID="Button1" runat="server"
PostBackUrl="~/Welcome.aspx"
Text="Button" />
</div>
</form>
</body>
</html>
Create welcome.aspx and write the code in source

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Welcome.aspx.cs" Inherits="Welcome" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<% string uname = Request.Form["txtUid"];
string pwd = Request.Form ["txtPwd"];
Response.Write("welcome to " + uname);
%>
</div>
</form>
</body>
</html>

Press F5

Web server

Raju Welcome.aspx

*** Request object

SUBMIT Uname=raju

Uname =Request. Form [“txtUid”]

WELCOME TO RAJU

Output
WELCOME TO RAJU
Analyzing page submission:

Page submission depends on two things:

1.) Arrangement of data for transmission


2.) Reading data

Arrangement of data:

1.) Post method


2.) Get method
Difference between the Post and Post method
Post Get

The data will be arranged with in The data will be arranged with in
http message body http header

It support large amount of data It support small amount of data


arrangement arrangement [max of 2kb]

It provides security for password It doesn’t provides security for


type data password type

Transmission will be slow Transmission will be faster

The button will perform arrangement based on method type for sending to
server.

Reading submitted data on server.

The Reading procedure will be based on arrangement type.

Post Arrangement Request. Form [“Control Id”]

Get arrangement Request.QueryString [“Control Id”]

Ex: get method program:

Design defaut.aspx like below:


Write the code in source default1.aspx:

<body>
<form id="frm_get" action="Default2.aspx" method="get" >
<table>
<tr>
<td>Name: </td> <td><input type="text" id="txtName" name="name"
/></td>
</tr>
<tr>
<td>Address: </td> <td><input type="text" id="txtAddr" name="addr"
/></td>
</tr>
<tr>
<td></td> <td><input type="submit" value="Send Using Get" /></td>
</tr>
</table>
</form>

</body>

Design default2.aspx like below

Write the code in source default2.aspx:

<body>
<table border=”2″ cellpadding=”7″ cellspacing=”2″ >
<tr>
<th>Name</th> <th>Address</th>
</tr>
<tr>
<td><% Response.Write(Page.Request.QueryString["name"]); %></td>
<td><% Response.Write(Page.Request.QueryString["addr"]); %></td>
</tr>
</table>
</body>
Note:

The default method type in ASP.NET is Post.

Check Box and Radio Button Controls:

Among collection of check boxes user can select more than one check
box.

Among collection of Radio button user can select only one Radio
button.

Ex: for online room booking application

Design default.aspx like below

Source code for default.aspx:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<p>
COSTMER NAME
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
<p>
NO OF DAYS
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</p>
<p>
ROOM TYPE</p>
<p>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="g"
Text="A/C" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="g"
Text="NON A/C" />
</p>
<p>
FACILITIES</p>
<p>
<asp:CheckBox ID="CheckBox1" runat="server" Text="T.V" />
<asp:CheckBox ID="CheckBox2" runat="server"
Text="COMPUTER" />
</p>
<p>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click"


Text="SUBMIT" />
</p>
<p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</p>
<p>
&nbsp;</p>
<div>
</div>
</form>
</body>
</html>

Write the code in default.aspx.cs page [ in submit button]

protected void Button1_Click(object sender, EventArgs e)


{
int tr = 0;
int fr = 0;
int rt = 0;
int nod = Convert.ToInt32(TextBox2.Text);
if (RadioButton1.Checked)
{
rt = 1500;
}
else
{
rt = 1000;
}
if (CheckBox1.Checked)
{
fr = fr + 800;
}
if (CheckBox2.Checked)
{
fr = fr + 900;
}
tr = (rt + fr) * nod;
lable1.Text=”Welcome to ”+TextBox1.Text+” Total Rent ”+tr; }

Positioning of Controls on to Web-page:

By default designer does not support absolute positioning of controls.

They are two options:

1. Table arrangement (or) enter and space bar.


2. Setting option with designer

Go to tool menu----select options--select html designer---


select css styling--select last check box----click ok.

Web-page creation techniques:

1. Web-page development goes with designing part and logic part.


2. Web designer duty is design part; web developer duty is logic part.
3. In asp 3.0 design and logic part will be placed into one file[asp file].
4. This file will be shared by web designer and web developer.
5. Parallel development is not possible this makes development slow.
6. No security for logic part.

Solution in asp.net is “code behind” technique.

Asp.net supports two techniques

1. In page technique
2. Code behind technique

In page technique:

Placing design part and logic part into aspx file is called “In page
technique”.

In page technique is, mostly used towards migration projects.

.Asp

Design Logic

Web Design Web Developer


+

Code behind technique:

Placing design part coding into aspx file and logic part code into
cs/vb file is called” Code behind technique”.

The code behind file will be attached to aspx file using page directive.

Design Logic

+
Web Design Web Developer

Image control:

It will display image on web page, the recommended image


formats are “gif” and “jpg”.
 Gif can be normal image (or) animated image.
 Jpg is normal image.

Hyperlink Control:

Hyperlink allows user to download the file from server system to


client system.
The file can be html page, asp.net page, video file, audio file.
Hyperlink can be “text” or “image”.

Designing web page to implementing the hyperlink concept:

 Place required files into website


Go to web site menu select Existing item go to image location
select some images click ok

 Create Html pages


Go to web site menu  select add new itemselect html page
template  give the name as about us.html
And write the code in about us.html page

<body>
<h1>
This is a html page
</h1>
</body>

 Similar to create sonycam.html


<body>
<h1>
This is a new sony cam
</h1>
</body>
 Place a asp.net web page into website
Go to web site menu  select add new itemselect web form
template

Place a 1 image control and 2 hyperlink control on the defaut2.aspx

Image control properties: image URL  select image  click ok.

Hyperlink 1 properties: text=about us

Navigate URL: about us .html

Hyperlink 2 properties: text=cam details

Navigate URL: sonycam .html

Note:

 When user clicks on hyperlink, navigate URL fill will be download.


 Button click will perform page submission.
 Hyper link click will not perform page submission.

Redirection between web pages through coding:


This is possible in 2 ways

1.) Server. Transfer ()


2.) Response. Redirect ()

Server.Transfer (): it will perform redirection from one page to another page
with in server side processing without information to browser.

Web server

Web page 1
------

Browser Web page 2 Server.Transfer ()

------

Response. Redirect ():

Redirect will instruct browser to call a particular page by sending URL


[Uniform Recourse Locator].Server.Transfer provides better performance to
response. Redirect

Server.Transfer support redirection only within website response. Redirect


support redirection within website and between web sites.

Creating website to implement redirection using transfer method:

Design Default.aspx page like below

Write the code in login button

protected void Button1_Click(object sender, EventArgs e)


{
if (txtUname.Text == "user" && txtPwd.Text == "user")
{
Server.Transfer("User.aspx");
}
else if (txtUname.Text == "Admin" && txtPwd.Text == "Admin")
{
Server.Transfer("Admin.aspx");

}
else
{
Response.Write("<script>alert('invalid ')</script>");
}

User.aspx
----
Login.aspx -
Admin.aspx
----
----
-
-

List control:

List control will provide rich functionality towards web page creation. These
controls are required in maximum websites.

 The main feature of list control is displaying more no of values, this


control support adding/removing values dynamically
 ASP.NET providing 5 types List control
1.) Listbox control
2.) Dropdownlist control
3.) checkbox list control
4.) Radio button list control
5.) Bulleted list control

ListBox Control:

0 ABC List item


XYZ
PQR
1
2
ListBox

Index Value

Listbox is collection of list items each list item is identify with unique index.

List item will represent text and value, text will be visible to user and value
can be used with in programming.

List Box properties:

1.) Selection mode : Single[default]


Multiple.
2.) Items: add items as per requirement.
3.) Selected item :return selected list item value
4.) Selected index return selected index value.
5.) Auto post back :false[default]
True.

Methods for list controls:

1.) Add (): by using this method add items into the list control.
Syn <list control name>.Items. Add (value);

Ex DropDownList1.Items.Add (1);

2.) Insert (): by using this method add items into the list
control at a specific position.

Syn <list control name>.Items. Insert (index


value, value);

Ex DropDownList1.Items.Insert (1, 2);


3.) Remove (): by using this method remove items from the list
control based on item value.
Syn <list control name>.Items. Remove (value);

Ex listbox1.Items.Remove (1);
4.) Remove At (): by using this method remove items from the
list control based on index value.

Syn <list control name>.Items. Remove At (Index


value);
Ex listbox1.Items.RemoveAt (1);

5.) Clear (): by using this method clear all items from the list
control.

Syn <list control name>.Items. Clear ();


Ex listbox1.Items.Clear ();

Post back control and non post back control:

The control which can be performing Post back submission is called “Post
back control”.

Ex: button link button and image button.

Link button is similar to button control with hyperlink appearance.

Image button is similar to button which can display image.

The control which cannot perform Post back submission is called as non Post
back control.

Ex: Check box, radio button, list control.

Non post back control can be converted to post back control by setting auto
Post back property is true

When user select list items selected index changed subprogram will be
executed on server

Dropdownlist control:
Dropdownlist is similar to Listbox control it will display only list items by
default and doesn’t allow multiple items selection

Creating website for online books purchase

Design default.aspx like below:

Properties for controls:

CONTROL NAME PROPERTIE

Drop Downlist1 1.) Id=Ddl1


2.) Autopostback=True
3.) Items-select publisher
Microsoft
Wirax
apress

ListBox1 1.) Id=lstOne


2.) Selection Mode=Multiple

ListBox2 1.) Id=lstTwo


2.) Selection Mode=Multiple

Button1 1.) Text=>


Button2 1.) Text=>>

Button3 1.) Name=btnReg


2.) Text=Register

Write the code in Dropdown list:

protected void Ddl1_SelectedIndexChanged(object sender, EventArgs e)


{
lstOne.Items.Clear();
switch (Ddl1.SelectedIndex)
{
case 1:
//microsoft is selected
lstOne.Items.Add(new ListItem("vb.net step by step","300"));
lstOne.Items.Add(new ListItem("asp.net step by step","400"));
break;
case 2:
//wrox is selected
lstOne.Items.Add(new ListItem("professional vb.net", "600"));
lstOne.Items.Add(new ListItem("professional Cs.net", "500"));
break;
case 3:
//apress is selected
lstOne.Items.Add(new ListItem("Asp.net latest", "300"));
lstOne.Items.Add(new ListItem("vb.net latest", "200"));
break;
}
}

Write the code in button1, button2,button 3[btnReg] :

protected void Button1_Click(object sender, EventArgs e)


{
lstTwo.Items.Add(lstOne.SelectedItem);
}
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i <lstOne.Items.Count; i++)
{
if (lstOne.Items[i].Selected)
{
lstTwo.Items.Add(lstOne.Items[i]);
}
}
}

protected void btnReg_Click(object sender, EventArgs e)

{
int total = 0;
for (int i = 0; i < lstTwo.Items.Count; i++)
{
total = total + Convert.ToInt32(lstTwo.Items[i].Value);
}
Label1.Visible = true;
Label1.Text = "Total cost " + total;
}

Wizard Control:

Step 0 Content Area

Step 1
Steps
Step 2

Next
Wizard
Control
Wizard control collection of steps each step will represent certain
information.

Wizard control allows step by step navigation or random navigation.

Creating web page to display different types of information using wizard


control:

Place a wizard control on the default page go to properties for wizard control
select wizard steps properties and add the step as student details, contact
details, show details

Edit student details content area like below

Edit Contact details content area like below:


Edit Show details content area likes below:

And right click on show Details step select properties do to events tab double
click on Active step Changed event:

And write the below code in event:

protected void Wizard1_ActiveStepChanged(object sender, EventArgs e)


{
Label1.Text = TextBox1.Text;
Label2.Text = TextBox2.Text;
Label3.Text = TextBox3.Text;
Label4.Text = TextBox4.Text;
Label5.Text = TextBox5.Text; }
Note:
Wizard control is recommended when small amount of information is
required in each step.

Fileupload control:

Sending file from client system to server system is called file uploading.

EX upload resumes, images

Asp.net is providing “file upload control” towards uploading file.

Properties:

1.) HasFile: this property is used for checking while file is selected or
not. I.e. file is posted are not.
2.) Content Type: this property is used for checking the format of the
posted file.
The format like below
Text/plain normal text file.
Text/XMl  XMl file
Image/gif
Image/jpeg

3.) Filename: this property used for assign the filename for posted
file.
Method:
1.) Save As (): using this method save the files into the
server from client location.

Server.mappath:

It will return physical path of web site, this approach provides better
maintenance.

Directory of class:

Directory info class can be used to read files present in particular folder.

Directory n=info class is present with in system.io name space

Directory info obj=new Directory info (“c:\\dir”);

Obj.GetFiles () it return all the file in the form of array


Obj.GetFiles (“*.gif”) it return only gif files presented in particular drive.

Creating website to maintain image gallery with client’s uploaded images:

Design default.aspx like below:

Write the code in uploads button:

protected void btnUpload_Click(object sender, EventArgs e)


{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "image/jpg")
{
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "\\" +
FileUpload1.FileName);
Label1.Text = "upload successfully....."
+FileUpload1.PostedFile.ContentType;
}
else
{
Label1.Text = "upload jpg file only";
}
}
else
{
Label1.Text = "Select file for upload..";
}
}

Hyper link properties text= Show gallery navigate URL=Default2.aspx.

Place a bulleted list control on to the default2.aspx like below.


Write the code in page_load

Import the Name space as

Using System.IO;

protected void Page_Load(object sender, EventArgs e)


{

BulletedList1.DataSource = Directory.GetFiles(Server.MapPath("."),
"*.jpg");
BulletedList1.DataBind();
}

Adrotator control:

Adrotator will display different ad’s to different clients.

Browser

Ad 1 web page

Browser Adrotator Advertisement file

Ad 2 Ad1

---

Ad 2

---

Adrotator implementation requires 3 steps:

1.) Preparing advertisement file.


2.) Providing advertisement file to Adrotator.
3.) Ad rotation will generate add randomly towards client request.

Structure of advertisement file:

Microsoft is providing set of XML tags to prepare advertisement file.

Xml is case sensitive.

<Advertisements>
<Ad>
<ImageUrl>ad image name</ImageUrl>
<NavigateUrl>ad information page</NavigateUrl>
<AlternateText> tool tip text</AlternateText>
<Height>---------</Height>
<Width>---------</Width>
</Ad>
</Advertisements>
ImageUrl: this tag used to specify the advertisement image name.

NavigateUrl: This tag used to specify webpage name that provide


entire info about the advertisement on which client is click.

AlternateText: this tag is used to provide tool tip for the


advertisement as soon as mouse point is placed on the advertisement.

Height: this tag is used the height of the advertisement.

Width: this tag is used the Width of the advertisement.

Ex: Ad Rotator control

Place a Ad Rotator control on default page like below.

 Place a ad image into website


 Place ad information web pages into web sites
Go to  Web site Menuadd new itemselect html pagegive the
name as car1.htm
And write information about the car in body tag like below.
<body>
New Bugatti-Car
</body>
 Similar to create car2.htm and write information about the car
<body>
New WideScreen car
</body>
 Similar to create Bike.htm and write information about the Bike

<body>
New sports bike
</body>

 Place a adds.Xml file and write the code :


<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>Bugatti-Car-Wallpaper.jpg</ImageUrl>
<NavigateUrl>car1.html</NavigateUrl>
<AlternateText>New</AlternateText>
<Height>300</Height>
<Width>300</Width>
</Ad>
<Ad>
<ImageUrl>Sports-Bike-Wallpapers-4.jpg</ImageUrl>
<NavigateUrl>Bike.htm</NavigateUrl>
<AlternateText>New</AlternateText>
<Height>300</Height>
<Width>300</Width>
</Ad>
<Ad>
<ImageUrl>widescreen-cars-italia-ferrari.jpg</ImageUrl>
<NavigateUrl>car2.htm</NavigateUrl>
<AlternateText> Widescreen car</AlternateText>
<Height>300</Height>
<Width>300</Width>
</Ad>
</Advertisements>
 For repeat the ads automatically write the code in source page[Head
tag]
<head runat="server">
<title>Untitled Page</title>
<meta http-equiv="refresh" content="2" />
</head>

Validation control:

 Ensuring proper entry of data is called “Validation”.


 Asp 3.0 requires manual coding to perform validations this avoided in
asp.net by providing validation controls
 Validation controls support different types of validations towards client
side (or) server side, this will reduce coding burden on developer and
makes development is faster.
 For performing the validations M.S provide 6 different types of
validation controls. Those are
1. Required field Validator.
2. Range Validator.
3. Compare Validator.
4. Regular Expression Validator.
5. Custom Validator.
6. Validation summary.
Required field Validator:
The Validator control will validate the text
where as the textbox empty or not.
Range Validator:
Its Validator control will validate text box
value with the specified range of values.
Compare Validator:
The Validator control can perform 3 types of
validations
1.) The textbox value will be checked with certain data type.
2.) Textbox value checked with certain value by using any
relationally operations. ex t1>150
3.) Used to compare to 2 textboxes
ex old password
New password
Conform password
Regular Expression Validator:
The Validator control is use to compare textbox
value with certain expression.
Most of the expressions provide by M.S.
If required expressions can be provide by the
developers
Ex \d{8}
Compare textbox value with 8digit
numbers
Ex \d{4, 8}
Compare textbox value with 4digit number to
8digit numbers
Ex \D{5}
Compare textbox value with a 5 char’s
string
{a,e,I,o,u}[1-5]
Compare the textbox value with 1 char
string to 5 char’s string which consist only vowels.
Custom Validator:
Custom validator doesn’t provide logic to perform
validation; the developer should inject logic to custom validation to perform
required validation.
Custom validator supports client side validation and server
side validation.

Validation summary:
This control is used to print the entire error messages at a single
place that are providing by other Validator control.

Common properties to all validation controls [1st five only]:


1.) Control to validate:

This requires control id to be validate [which control on the web


page to be validate.

2.) Text :
This requires content to be displayed with validation control if
validation falls.
3.) Error Message:
This requires content to be displayed with validation summary control
if validation fails.
4.) Set Focus on Error: True (or) False
True Cursor will be placed into textbox control to validate.

Creating Registration web page towards online polling this web page will
perform different validations using validation controls?

Design Default page like below:

Properties for validation controls:

RequiredFieldValidator 1.) Control to Validate=TextBox1.


2.) Text=*
3.) Error Message=name cannot
be Empty
RangeValidator 1.) Control to validate=TextBox2.
2.) Text=*
3.) Error Message=Invalid age
4.) Min value=18
5.) Max value=60

CompareValidator 1.) Control to validate =TextBox3


2.) Text=*
3.) Error Message=Invalid Format
4.) Operator=DataTypeCheck
5.) Type=Date

RegularExpressionValidator1 1.) Control to validate =TextBox4


2.) Text=*
3.) Error =Invalid Phone no
4.) Valid Expression=\d{10}

RegularExpressionValidator2 1.) Control to validate =TextBox5


2.) Text=*
3.) Error =Invalid Mail ID
4.) Valid Expression=select Email
id format

CustomValidator 1.) Control to validate=TextBox6


2.) Text=*
3.) Error Message=invalid number
4.) Client Validation Function=C1

ValidationSummary1 1.) Header Text=Errors occurred


2.) Display Mode=Bullet
list(Default)
3.) Show Summary =true(Default)
4.) Show message Box(Default)

Button 1.) Text=Submit


2.) Id=btnSubmit

Create Function For Custom Validator write the code in head tag.

<script language="JavaScript">
function validateNumber (oSrc, args)
{
args.IsValid = (args.Value % 2 == 0);
}
</script>

Write the code in Button

protected void Button1_Click(object sender, EventArgs e)


{
Response.Write("reg is complted successfully");
}

Client-Side validations v/s Server-Side validations:

The importance of client-side validation is reducing processing


burden on web-server. The problem is no reliability, where client can disable
scripting with browser or down level web-browser [older version of browsers
are called as down level browser, ex ie1.0] Does not support scripting in this
case of validation will not take place [i.e reliability problem].

The major importance of server side validation is 100% reliability.

If browser supports scripting validation will be performed at client side else


server side.

StateManagement :

HTTP is called “Stateless protocol”. The behavior is go, get, forget.

Go:

It will establish connection for sending request.

Get:

It will get response from server to client.

Forget:

It will close connection between client and server.


Stateless nature of HTTP is considered as on advantage where it will reduce
burden on web server. The requirement is web server should remember
user’s information the solution is state management.

State management is a concept of web server remembering users


information, this can implemented through various techniques.

1. Context
2. Query String
3. Cookies
4. Session
5. Application Memory
6. Cache
7. View State

Context:
The user information can be maintained from one webpage to
another webpage using context memory.

When re-direction takes place using Server.Transfer ().

Content object will be accessible to different web pages only for the re
direction with Server.Transfer.

Context.Items.Add (“N“, 100) placing variable into content.

Content. Items [“N”] - reading variable from context

Design default.aspx like below:

Write the code in Button control:

protected void Button1_Click(object sender, EventArgs e)


{
string s = "";
int total = 0;
for(int b=0;b<Cbl1.Items.Count;b++)
{
if (Cbl1.Items[b].Selected)
{
s = s + Cbl1.Items[b].Text + "<br>";
total = total + Convert.ToInt32(Cbl1.Items[b].Value);
}
}
Context.Items.Add("SCS", s);
Context.Items.Add("Total", total);
Server.Transfer("Display.aspx");
}

Create and Design Display.aspx like below:

Write code in page load:

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "courses selected :<br>" +
Context.Items["SCS"].ToString() + "Total fee for courses :" +
Context.Items["Total"].ToString();
}

Note:context will be erased once response will be given to client[browser].

Query String:

The user information will maintained from one webpage to


another webpage using Query String.

When the re-direction is using response.redirect.

The data appended to URL is called “Query String”.

Response.redirect (“Welcome.aspx? Uname=Siva & n=1”)


Cookies:

Cookie is small amount of memory used by web server which is


client system. The purpose of cookie is placing certain personal information
of client with in client system this will reduce burden on server.

The personal information can be username, session id, and security token.

Cookies can be classified into two types.

1. In memory Cookie
2. Persistent Cookie

In memory Cookie:
 The cookie placed within browser process memory is called
Inmemory cookie.
 It is a temporary cookie; once browse is closed cookies will be
erased.
 Asp.net is providing HttpCookie class to work with cookies.

Placing cookies information into client system requires following steps:

1. Creation of HTTPcookie class object:


HttpCookie obj=new Httpcookie (“N”)
Cookie
variable

obj.Value=100;

2. Provide HTTP cookie class object to response object:

Response.AppendCookie (obj);

It will send cookie to browser.

Browser web server


N=100 http cookie object
N=100

Inmemory variable Response object

Reading cookie

Reading cookie submitted by browser:

Browser request to web server will submit cookies. Cookies will be accessible
in all the WebPages of website towards client request.

Browser Webpage1

N=100 webpage2

Webpage3

Request object is required to read cookie submitted by client browser.

HttpCookie obj=null;
Obj=Request. Cookies [“N”];
If (obj.Value! =”null”)
{
Cookies data submitted by the client;
}
Else
{
Cookies data is not submitted by the
client;
}
Creating website towards online examination:

Add web form:

Coding for Next button click:

protected void btnNext_Click(object sender, EventArgs e)


{
HttpCookie obj = new HttpCookie("q1");
if (R1.Checked)
obj.Value = "y";
else
obj.Value = "n";
Response.AppendCookie(obj);
Server.Transfer("Default2.aspx");
}

Add webform Default2.aspx:

Coding for Next button click:


protected void btnNext_Click(object sender, EventArgs e)
{
HttpCookie obj = new HttpCookie("q2");
if (R3.Checked)
obj.Value = "n";
else
obj.Value = "y";
Response.AppendCookie(obj);
Server.Transfer("Default3.aspx");
}

Add web form Default3.aspx:

Coding for ShowResult button click:

protected void btnShowResult_Click(object sender, EventArgs e)


{
HttpCookie obj = new HttpCookie("q3");
if (R5.Checked)
obj.Value = "y";
else
obj.Value = "n";
Response.AppendCookie(obj);
Server.Transfer("Result.aspx");
}

Add webform Result.aspx


Code in Page load:

protected void Page_Load(object sender, EventArgs e)


{
HttpCookie obj;
int tot = 0;
string s = "";
for (byte i = 0; i < Request.Cookies.Count; i++)
{
obj = Request.Cookies[i];
s = s + "q" + (i + 1) + "." + obj.Value + "<br>";
if (obj.Value == "y")
tot = tot + 1;
}
lblResult.Text = "result sheet <br>" + s + "total corrected:" + tot;
}

Disable back button of browser, so that user cannot get back to previous
questions:

Disabling back button of IE:

Go to online examination site

Go to default2.aspx source view

----

<head runat="server">
<title>Untitled Page</title>
<script language="javascript">
function f1()
{
window.history.forward()
}

</script>
</head>

<body onload="f1()">

similarly place in all the webpages


 press F5

Clicking on back button will not display previous page.

Note:

 Browser will maintain user navigated web pages with in history object
internally.
Back and forward buttons of browser will provide navigation
between web pages using history object.
 Windows.history.forward method will inform browser not to maintain
webpage name with in history.
This does not allow displaying previous page with back button.

Persistent cookie:

The cookie placed on hard disk of client system is called “persistent cookie”.

Persistent cookie will be maintained with a particular lifetime, it will be


available after closing the browser.

Httpcookie obj=new Httpcookie (“Uname”);

Obj.value=”…”

Obj. Expires=Datetime.Now.AddDays (2);

Datetime.Nowreturns system date and time.

Response.AppendCookie (obj);

Example for Persistent cookie:

[Providing remembers my login with login page, server will use Persistent
cookies to remember login parameters]
Add webform:

Code for submit button click:

protected void btnSubmit_Click(object sender, EventArgs e)


{
if (txtUname.Text == "orbit" && txtPassword.Text == "orbit")
{
if (C1.Checked)
{
HttpCookie obj1 = new HttpCookie("Uname");
HttpCookie obj2 = new HttpCookie("pwd");
obj1.Value = txtUname.Text;
obj2.Value = txtPassword.Text;
obj1.Expires = DateTime.Now.AddDays(2);
obj2.Expires = DateTime.Now.AddDays(2);
Response.AppendCookie(obj1);
Response.AppendCookie(obj2);
}
Server.Transfer("Welcome.aspx");

}
else
Response.Write("invalid username and password");
}

Location of cookie with in client system:

C:\Documents and Settings\Administrator\Cookies


administrator@syst.txt

Open with notepad

Uname#orbit

Password#orbit

Browser will read cookies information from text file for submitting to web
server [website].

Note:

 In our case the client will not be authenticated for 2 days. After 2 days
client system will erase cookies.
 Cookies supports maximum of 4kb data, it should be in the form of
string.
 Cookies does not provide security, client can modify cookie value or
client can remove cookie or deleting text file.
 Browser will create separate text file to each website to maintain
cookies.
<>@gmail.txt
<>@msn.txt
 Browser supports maximum of 20 cookies towards a website
 Browser supports maximum of 300 cookies towards different websites.
 One browser stored cookies will not be used by another browser.

Requirement [online shopping site]:

In online shopping site different users selected products will be remembered


by server.

Browser web server

Camera---add to cart Memory

TV ---- add to cart Object


Camera..

Tv…
Cookie is not applicable to above requirement for following reasons

1. It cannot store object

[Cookie variable can represent only plain text]

2. It is having limitation in memory size [maximum 4mb] and count


[browser supports maximum 20 cookie variables]

The solution is session memory.

Session Memory:

Session can be defined as set of client communications to different


WebPages of website identified uniquely by web server.

This is implemented through session memory.

Browser web server memory

Website Data Sessions

Browser WebPages Memory


Data

 Web server will allocate a block of memory unique to client on server


system; this is called “session memory”.
 Web server will maintain session memory with the timeout of 20 mins
by default. [Time out will be considered from last communication].
 If session is idle for 20 mins, web server will erase session memory.
 Session object can be used in asp.net webpage to access session
memory, this object is providing following methods.

1. Add (varname, value)

Session. Add (“n”, 100)


Or

Session [“n”] =100

It will place variable ‘n’ into session memory.

2. Remove (varname)

3. Abandon () it will close session.

Example for session memory concept:

Add wbform

Coding:

int n = 0;
protected void btnWrite_Click(object sender, EventArgs e)
{
n = 0;
Session["n"] = 0;
}
protected void btnRead_Click(object sender, EventArgs e)
{
n = n + 1;
Session["n"] = (int)Session["n"] + 1;
//session["n"] returns value in the form of object,it should be
type casted to int type.
Response.Write("page var n=" + n);
Response.Write("session var n="+ Session["n"].ToString());
}

Note:

 Page variable memory will be initialized towards each request with


0, it will be incremented by 1 and response will be given to client,
after page var n memory will be erased.
 Session memory will be maintained for 20 mis, this will be
incremented towards each request, and this will provide different
values [1, 2, 3...]For session var n.

ADO.NET

Ado.net is a set of libraries provided in .net towards different types of data


communication.

.net app Database


ADO.Net
……… ……

Ado.net is providing following libraries.

System.data.dll

System.data.sqlclient.dll

System.data.oracleclient.dll

……..

System.data.dll is considered as a core library of ado.net.

Ado.net comes with two major components:

1. Dot net data provider

2. Dataset.

1. Dot net data provider:


Dotnet data provider is a collection of classes required for different
operations towards database.

Ex:

Connection class

Command class

…….

Microsoft providing five .net data providers with .net installation.

1. Oledb.net data provider

2. Sqlserver.net data provider

3. Oracle .net data provider

4. Oledb .net data provider

5. Sqlserverce .net data provider [required for smart devices].

Note: oracle .net data provider is deprecated from .net 4.0.

Other companies provided .net data providers are called “third party .net
data providers”.

ODP.net given by Oracle Corporation towards oracle 9i or later


communication.

Mysqldirect .net is given by core lab software towards mysql communication.

……

Complete flow of .net application with different .net data providers:


Protocol

Oledb.net ---provider ---- different databases

.Net Sqlserver .net ---TDS------Sqlserver7.0 or later


App
Oracle.net------ TNS --- Oracle8i or later versions

ODBC.net--- ODBC driver---- different databases.

 Each database will have its own set of rules for communication,
 This is called database protocol.
 TDS [tabular data stream] is a protocol of sqlserver.
 TNS [tabular network substrate] is a protocol of oracle.
 Provider [Oledb provider] and odbc driver is a o/s specific
programming [com based programming]to implement native protocol
programming of databases.
 .net data provider implementing native protocol programming is called
“managed .net data provider”.
 .net data provider implementing Oledb provider/odbc driver
programming is called “unmanaged .net data provider”.

Conclusion:

The developer choice will be managed data provider, in case there is no


managed .net data provider towards any database then go with unmanaged
.net data provider.

Oledb.net data provider:


This is required in following cases.

Connecting to local database [Access...]

Connecting sqlserver<7.0

Connecting to oracle<8i

----

Oledb.net classes are provided with in

System.data.oledb namespace

Oledbconnection class

Oledb command class

Oledb data reader class

Oledb connection class:

.net app database

Sql statement

Oledb connection will establish bridge between .net application and


database.

Ex:

OledbConnection con=new OledbConnection(“provider=provider


name;uid=..;pwd=..;datasource=servername”);

Con.open()it will establish connection between .net application and


database.
Con.close()it will close connection by releasing network level resources.

Con.dispose()it will close connection by erasing connection string.

The input given to constructor of oledb connection class is called


“connectionstring”.

Provider name will specify to which database connectivity is required.

Provider name

Msdaora.1 oracle

Sqloledb.1 sqlserver

Microsoft.jet.oledb.4.0 Access 2003

Microsoft.ace.oledb.12.0 Access 2007

User id and password are database login parameters.

Data source will specify the system name in which database is running.

Oledb command class:

It will represent sqlstatement/stored subprogram for sending to database.

Ex:

oledbCommand cmd=new OledbCommand(“select/insert….”,con)

OledbCommand class is provided with following methods:

1.ExecuteScalar():

This is required when select statement returns one value.

Ex:

OledbCommand cmd=new oledbCommand(“select count(*) from emp”,con).


cmd.ExecuteScalar ()

2. ExecuteReader ():

This is required when select statement returns more than one value.

This method will return data reader object to read records into application.

3. ExecuteNonquery ():

This is required if sqlstatement is other than select statement.

[Insert, delete, update, stored subprogram…]

Data reader: data reader is read-only forward only.

Read-onlydata reader does not support manipulations.

Forward onlyit supports reading data only once.

Data reader is strongly recommended when the application requirement is


reading data only once without manipulations.

It will fetch record by record into application process, it will consume only
one record memory at a time with in application process, this will reduce
memory burden on application process.

Data reader methods:

1. read:

It will fetch record into application process by moving record pointer to next
record.

It return true if record is fetched else false.

2.Reading record info[column data]

dr.getstring(0)it returns first column data


------

Dr.get<datatype>(columnindex)

Note:dr[columnindex/column name]can be used to read any type of column


data.

Ex:

dr[“prodid”] or dr[0]

3.close

It will release temporary memory[RAM]

dr.close()

4.Fieldcount

It return number of columns.

Access:

Access comes with MS office installation.

Create database with access

 Start programsms-officeselect office access


 Goto filemenu and select newselect blank databasename-
bank.mdb [Microsoft database file]
 Double click on create table using design view

Accno number
Nametext
Balnumber
Phnonumber.

 Close create table window


Name  customer.
 Double click on customer table

1 xyz 5000 1234


2 abc 6000 5678
 Close database

Communicating with access from asp.net website:

There is no managed data provider for access connectivity this requires


unmanaged data provider as Oledb.net data provider.

Designing webpage to display customer details based on accno, allowing


user to modify only phoneno.

Code:

using System.Data.OleDb;
public partial class Display : System.Web.UI.Page
{
protected void btnDisplay_Click(object sender, EventArgs e)
{
OleDbConnection con = new
OleDbConnection("provider=Microsoft.Jet.Oledb.4.0;Datasource=H:\bank.m
db");
OleDbCommand cmd = new OleDbCommand("select
Accno,Name,Bal,PhoneNo from Customer where Accno=" + TextBox1.Text,
con);
OleDbDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["Name"].ToString();
TextBox5.Text = dr["Bal"].ToString();
TextBox6.Text = dr["PhoneNo"].ToString();
}
else
Response.Write("<h2>invalid account no....</h2>");
dr.Close();
con.Close();
}
protected void btnModify_Click(object sender, EventArgs e)
{
OleDbConnection con = new
OleDbConnection("provider=Microsoft.Jet.Oledb.4.0;Datasource=H:\bank.m
db");
OleDbCommand cmd = new OleDbCommand("update customer set
PhoneNo=" + TextBox6.Text + " where Accno=" + TextBox1.Text, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
Response.Write("<h2>record modified</h2>");
}
}

.Net Application connecting to sqlserver:

Sqlserver .net data provider is a managed .net data provider to


communicate with sqlserver 7.0 or later.

Sqlserver .net classes are provided with in

System.Data.Sqlclient

Sqlconnection class

Sqlcommand class

------

Creating webpage with login related WebPages:


Goto Compare validator properties

Control to validate—t3

Control to compare—t2

Operator—equal

Text—incorrect

Code:

using System.Data.SqlClient;

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


{
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju");
SqlCommand cmd = new SqlCommand("insert into login values('" +
TextBox1.Text + "','" + TextBox2.Text + "')", con);
Response.Write(cmd.CommandText);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Server.Transfer("RegisteredSuccess.aspx");
}
}

Add webform
RegisteredSuccess.aspx

Navigate url—Login.aspx

Add webform
Login.aspx

Navigateurl—Register.aspx

Coding:
using System.Data.SqlClient;

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


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju");
SqlCommand cmd = new SqlCommand("select count(*) from login
where UserName='" + TextBox1.Text + "' and Password='" + TextBox2.Text
+ "'", con);
con.Open();
int n = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (n == 1)
Server.Transfer("welcome.aspx");
else
Response.Write("invalid..");
}
}

Add webform Welcome.aspx

F5[login.aspx]

Requirement:
Webpage should read particular table data more number of times,in this
case datareader requires more number of database communications,this will
effect performance of webserver.

The solution is dataset.

Clients webserver sqlserver

Product.aspx Product

dataReader ------
100 requests

100 times 100 communications

Dataset

Product

--------
1 connection

Data Reader in the above requirement requires more number of database


communications, this will burden on web server.

Data reader is connection oriented; it cannot read data without having


database connection, once connection is closed data reader is invalid.

The solution is dataset.

In distributed technology[webservices],the requirement is transmitting data


from one platform to another platform.

System System

[Linux] [Windows] Oracle


App Memory[Object] Category

---- -----
C
----
XML Sqlserver
P
Product
----
------
Data reader is not applicable to above requirement for following reasons.

1. It cannot maintain multiple tables from different databases.

2. It does not support manipulations.

3. It does not support relations [Constraints].

4. It does not support xml storage for cross platform transmission.

The solution is dataset.

The major concentration of designing dataset is towards distributed


technology.

Dataset:

 Dataset acts like in memory database for client application process


[desktop app process or webpage process].
 Dataset will maintain collection of tables called “datatables”, each data
table can be identified with name or index.
 Dataset is a class provided with in System. Data namespace.
 Dataset supports bidirectional navigation and manipulationals.
 Dataset supports relation between tables [applying unique key and
foreign key constraint].
 Dataset internal storage is XML; it supports cross platform
transmission [this is very much useful towards remoting and web
services].
 Dataset is purely disconnected, it will never connect database.
 Data Adapter acts like a mediator between dataset and database.
 Data Adapter makes dataset purely disconnected by performing 2
things:
1. Reading data from database into dataset.
2. Updating dataset manipulations to database.
Data Adapter is not required without dataset, where as dataset can be
used without data adapter.
Dataset can be created in 3 ways.
1. Building dataset from database [Required data Adapter]
2. Building dataset from XML.
3. Building Dataset Manually.

Placing Data into Dataset using Data Adapter:

Sqldataadapter da=new Sqldataadapter (“select * from EMP”, con);


Dataset ds=new Dataset ();
Da. Fill (ds,”p”);

Fill method will perform 3 things

1. It will establish connection.


2. It will send select statement to database, using data reader it will
read records into dataset memory in the form of data table.[data table
name need not be same as database table name].
3. It will close the connection.
Dataset table can be accessed based on name or index.
Ds.tables [“name”]
Or
Ds.tables [“index”]
Creating webpage to display student’s info from sqlserver:
Dataset site

Add web form default.aspx

Add grid view to the web form.

Coding:

using System.Data.SqlClient;

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


{

protected void Page_Load(object sender, EventArgs e)


{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju");
SqlDataAdapter da = new SqlDataAdapter("select * from student",
con);
System.Data.DataSet ds = new System.Data.DataSet();
da.Fill(ds, "s");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}

Note:

 Data source property of grid view requires address of memory


location, where the records are available.
 Data bind method will arrange records in a tabular format for
presenting to user.
 Grid view supports multiple records display in a tabular format.
It allows sorting, paging,..

Component based approach towards database connectivity:

Writing database connectivity code with in a class under dll is called


component based approach for database connectivity.

This provides reusability of code in different WebPages.

Creating dll with database connectivity logic:

Select class library project

Name—dabaselib

Goto class1.cs

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

namespace databaselib
{
public class Mycomponent
{
public DataSet getdata(string s)
{
SqlConnection con=new
SqlConnection("uid=sa;pwd=prasad;database=raju");
SqlDataAdapter da = new SqlDataAdapter(s,con);
System.Data.DataSet ds = new DataSet();
da.Fill(ds,"d");
return ds;

}
}

Build menu –- Build database lib – it will produce databaselib.dll

This dll can be used in website [webpage’s] for connecting to database.

Creating website to access class present in dll:

Ispostback site

Add webform

Place gridview and button.

protected void Page_Load(object sender, EventArgs e)


{
if (Page.IsPostBack == false)
{
databaselib.Mycomponent ob = new databaselib.Mycomponent();
GridView1.DataSource = ob.getdata("select * from student");
GridView1.DataBind();
Response.Write("<h2>non postback request</h2>");
}
else
Response.Write("<h2>postback request</h2>");
}

Note:

 When client request comes to webpage, webserver [asp.net engine]


will initialize ispostback property of page object with true/false.
 Developer can read ispostback property to identify the type of request.
 The property returns true if the request is post back request, it returns
false for non post back request.
 In the above example page load logic towards database connectivity
will be executed only for non post back request, towards button click
[post back request] code will not be executed.

Customizing grid view for sorting:

Grid view allows sorting implementation based on column header click, this
requires two steps.

1. Setting allow sorting property to true

This will place link buttons for column heading.

2. Handling sorting event procedure of grid view.


Creating webpage to display student info allowing user to view info in a
sorted order.

Add webform—place gridview control

Allow sorting—true

Code:

protected void Page_Load(object sender, EventArgs e)


{
if (Page.IsPostBack == false)
fillgrid("sname");
}
private void fillgrid(string name)
{
databaselib.Mycomponent obj = new databaselib.Mycomponent();
GridView1.DataSource = obj.getdata("select * from student order by
"+name );
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs
e)
{
Response.Write(e.SortExpression);
fillgrid(e.SortExpression);
}

Grid view with paging:


Paging is a concept of splitting bulk amount of content into smaller blocks,
these blocks are called pages, and only one page info at a time will be
downloaded.

The main importance of paging is less amount of download. This makes


downloading faster and less memory consumption in client system.

Grid view support paging implementation, this requires following steps:

 Setting allows paging property true and providing page size.


 Setting navigation buttons with grid view towards navigation between
pages.
 Handling page index changing event.

Creating webpage to display student info using paging concept:

Grid view page site

Add web form default.aspx

Place gridview, dropdownlist and label

Goto gridview properties

Allowpaging—true
Pagesize—3

Pagersettings

Mode-nextprevfirstlast

Firstpagetext-First

Nextpagetext--Next

Prevpagetext--Prev

Lasttpagetext—Last

Position—top and bottom

Note :mode will specify navigation buttons,this allows navigation between


pages.

Dropdownlist properties

Autopostback—true

Code:

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

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


{

public void fillgrid(int pno)


{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju;");
SqlDataAdapter da = new SqlDataAdapter("select * from student",
con);
DataSet ds = new DataSet();
da.Fill(ds, "st");
GridView1.DataSource = ds.Tables[0];
GridView1.PageIndex = pno;
GridView1.DataBind();

}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillgrid(0);
Label1.Text = "1 out of" + GridView1.PageCount;
for (byte i = 1; i <= GridView1.PageCount; i++)
DropDownList1.Items.Add(i.ToString());
}
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
Response.Write(e.NewPageIndex);
fillgrid(e.NewPageIndex);
Label1.Text = (e.NewPageIndex + 1) + "out of" +
GridView1.PageCount;

}
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
fillgrid(DropDownList1.SelectedIndex);
Label1.Text = (DropDownList1.SelectedIndex + 1) + "out of" +
GridView1.PageCount;
}
}

Grid view Fields [Columns]:


Grid view is providing different types of fields for customization.
1. Bound Field
2. Template Field
3. Image Field
4. Hyperlink Field
5. Command Field.

Bound Field: it will display normal text based on dataset table column
values, this is considered as default field for grid view.
Properties:
Header text—it will represent column heading
Data field—it will represent dataset table column name.
Template Field:
This field acts like container for placing web server control into grid view.
This comes with item template.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="c1" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Sid sname
Rows[0] 1 s1 c1

Rows[1] 2 s2 c1

Rows[2] 3 s3 c1

cells[0] cells[1]

gridview1.rows [0].find control (“c1”);selected[checked].

Gridview1.rows [0].cells [1].text;returns cell data.

Grid view row is providing “find control” method to access control present in
template field, this returns control type, and it should be type casted to
required control type.

Create webpage to display selected student info:

Add web form and place grid view and button.

Code:
using System.Data.SqlClient;
using System.Data;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju;");
SqlDataAdapter da = new SqlDataAdapter("select * from student",
con);
DataSet ds = new DataSet();
da.Fill(ds, "s");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
}
}
Customizing gridview with templatefield

Gridview properties

Alternate columns – false

Colums—select the 2 bound fields and one template field.

bound field—header text—sid

datafield—sid

goto source view


<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="c1" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Note: autogenerate columns false will inform grid view not to generate
columns automatically; in this case grid view will consider columns specified
by developer.

Coding (button click):

protected void Button1_Click(object sender, EventArgs e)


{
CheckBox cc;
string s = "";
for (byte i = 0; i < GridView1.Rows.Count; i++)
{
cc = (CheckBox)GridView1.Rows[i].FindControl("c1");
if (cc.Checked)
s = s + GridView1.Rows[i].Cells[1].Text+"<br>";
}
Context.Items.Add ("sps", s);
Server. Transfer ("display.aspx");
}
Add webform display.aspx and place a label.

Coding (page load):

protected void Page_Load(object sender, EventArgs e)


{
Label1.Text = "selected student:<br>" +
Context.Items["sps"].ToString();
}

Database designing:

Sqlserver—raju database—create product table

Insert records like this

Analyzing different types of fields required for presentation:

1. Image field:
This will display image with in grid view reading image name from
dataset table column, the image file should be present with in website.

Ex:<asp:imagefield dataimageurlfield=”prodimage”/>

command field:

this will provide special typeof buttons into gridview[i.e select button,edit
button].
In our requirement “add to cart” requires select button.

Select button click will execute selected index changed event of grid view.

Hyperlink field:

This will place hyperlink with in gridview, hyperlink creation requires text
and webpage name [navigateurl page].

Creating website for online shopping using different types of grid view fields:

Online shopping site

Place product images into website.

Place html pages with product info.

Girl.html

<body>
<h1>girl picture</h1>
</body>
Baby.html<body>
<h1>baby picture</h1>
</body>
Add webform default.aspx

Showcart[hyperlink]

Navigateurl—cart.aspx

Code:

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

protected void Page_Load(object sender, EventArgs e)


{
if (Page.IsPostBack == false)
{
SqlConnection con = new
SqlConnection("uid=sa;pwd=prasad;database=raju;");
SqlDataAdapter da = new SqlDataAdapter("select * from product",
con);
DataSet ds = new DataSet();
da.Fill(ds, "p");
//Session["ds"] = ds;
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

}
}

Customizing gridview with required fields:

Goto gridview1 properties

Autogeneratecoumns – false

Columns—

Select imagefield—headertext—prodimage

Dataimageurlfield—prodimage

Controlstyle

Height—100
Width—100

Note:height and width will be applied to all the images with in gridview.

Select bound field

Headertext—proddesc

Datafield—proddesc

Select bound field

Headertext—prodprice

Datafield—prodprice

Select template field

Select command field—select “select button”.

Select text—add to cart

Button type—link

Select hyperlink field

Header text—moreinfo

Datatextfield—prodtext

Datanavigateurlfields—prodpage

Goto source view to place textbox into template field:

<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="t1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Right click on gridview and select auto format option.

Select colorful option

Providing logic for addtocart button:

Addtocart button click will perform postback,selected index changed event of


gridview will be executed.

Double click on gridview

protected void GridView1_SelectedIndexChanged(object sender, EventArgs


e)
{
//perform lookup for dataset with in session
DataSet ds = null;
ds = (DataSet)Session["ds"];
if (ds == null)
{
//no dataset in session
ds = new DataSet();
DataTable dt = new DataTable("trans");
dt.Columns.Add("desc", typeof(string));
dt.Columns.Add("price", typeof(int));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("total", typeof(int),"price*qty");
//total will be calculated implicitly based price and quantity for
newrow.
//place datatable into dataset.
ds.Tables.Add(dt);
}
//reading product selected by user
string desc1 = GridView1.SelectedRow.Cells[1].Text;
decimal price1 =
Convert.ToDecimal(GridView1.SelectedRow.Cells[2].Text);
TextBox tt = (TextBox)GridView1.SelectedRow.FindControl("t1");
int qty1 = int.Parse(tt.Text);
Response.Write(desc1 + "" + price1 + "" + qty1);
//placing product info into dataset.
DataRow r = ds.Tables["trans"].NewRow();

r["desc"] = desc1;
r["price"] = price1;
r["qty"] = qty1;
ds.Tables["trans"].Rows.Add(r);
Session["ds1"] = ds;

}
Note:

Selected row property of gridview will provide access to row selected by user
by clicking on add to cart button.

Dataset is created with manual approach to place products selected by user.

Add webform cart.aspx


Code:

protected void Page_Load(object sender, EventArgs e)


{
if (Page.IsPostBack == false)
{

DataSet ds = (DataSet)Session["ds1"];
if (ds != null)
{
GridView1.DataSource = ds.Tables["trans"];
GridView1.DataBind();
}
}

Note: if inner condition is not place, it will be an error if user is selecting


show cart link without products section.

Вам также может понравиться