You are on page 1of 58

University of Mumbai

Institute of Distance and Open Learning (IDOL)


Dr. Shankardayal Sharma bhavan, Vidyanagari, Santacruz(E)

PCP CENTER: CKT, PANVEL

Certificate
This is to certify that ________________________of T.Y. M.C.A. Semester-V
has completed the specified term work in the subject of ADVANCED WEB
TECHNOLOGIES satisfactorily within this institute as laid down by University
of Mumbai during the academic year 2016-2017

Staff Member Incharge

MCA Co-ordinator
(Prof. Anjali Kulkarni)

Examiner

University of Mumbai

Institute of Distance and Open Learning (IDOL)


INDEX
Sr. No

Practical Description

Program for Basic Connectivity using Generic Servlet.

Program for Basic Connectivity Programs using Http Servlet

Program on Session Management using Httosession (A Counter).

A Program on Servlet Context.

5.

Write a program to demonstrate Database Connectivity using Servlets

Write a program demonstrating Database Connectivity Online Exam

Implementation of simple JSP program

Implementation of Single Thread Model in JSP

Implementation of Shopping Cart Application using JSP

10

Write a program to demonstrate File Handling in C#

11.

Program to implement Shopping Cart using ASP.NET

12.

Program to implement Online Admission using ASP.NET

Practical No. 1

Page
No.

Date

Sign

Aim : Program for Basic Connectivity using Generic Servlet.


Code :Disp.java
import java.io.*;
import javax.servlet.*;
public class Disp extends GenericServlet
{
public void service(ServletRequest req,ServletResponse resp) throws IOException
{
PrintWriter pw=resp.getWriter();
int no,fact=1;
no=Integer.parseInt(req.getParameter("n1"));
if(no==0)
pw.println("The factorial is "+fact);
else
{
while(no!=1)
{
fact=fact*no;
no--;
}
pw.println("The factorial is "+fact);
}
}
}
Index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="test1" action="Disp" method="POST">
Enter number:- <input type="text" name="n1" value=""
size="10" />
<br><input type="submit" value="show" name="show" />
</form>
</body>
</html>
Output:

Practical No. 2
Aim : Program for Basic Connectivity Programs using Http Servlet

Code : Authenticate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class authenticate extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
String user=req.getParameter("username");
String passwd=req.getParameter("pwd");
validate(user, passwd, out);
}
protected void validate(String user, String passwd, PrintWriter out)
{
if(user.length()==0 || passwd.length()==0 )
out.println("<h1>Fill both the fields</h1>");
else if(user.equalsIgnoreCase("admin") && passwd.equals("admin"))
out.println("<h1>Welcome "+user+", You are an authorized user</h1>");
else
out.println("<h1>You are not an authorized user</h1>");}}
Auth.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="http://localhost:8080/WebApplication/authenticate" method="post">
UserName:
<input type="text" name="username"><br>
Password:
<input type="password" name="pwd" value=""><br><p></p>
<input type="submit" value="Login" name="login" />
</form>
</body>
</html>
Output:

Display Form

After Submission

Practical No. 3
Aim : Program on Session Management using Httosession (A Counter).

Code : httpsession.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class httpsession extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession(true);
// Increment the hit count for this page. The value is saved
// in this client's session under the name "tracker.count".
Integer count = (Integer)session.getValue("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.putValue("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
// Display the hit count for this page
out.println("Count for this page " + count +((count.intValue() == 1) ? " time."
: " times."));
out.println("<P>");
out.println("<H2>Your session data:</H2>");
String[] names = session.getValueNames();
for (int i = 0; i < names.length; i++)
{
out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>");
}
out.println("</BODY></HTML>");
}
}

Output:

Practical No. 4
Aim: A Program on Servlet Context.
Code:

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class servcontext extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("req.getServerName(): " + req.getServerName());
out.println("req.getServerPort(): " + req.getServerPort());
out.println("getServletContext().getServerInfo(): " +getServletContext().getServerInfo());
out.println("getServerInfo() name: " +
getServerInfoName(getServletContext().getServerInfo()));
out.println("getServerInfo() version: " +
getServerInfoVersion(getServletContext().getServerInfo()));
out.println("getServletContext().getAttribute(\"attribute\"): " +
getServletContext().getAttribute("attribute"));
}
private String getServerInfoName(String serverInfo)
{
int slash = serverInfo.indexOf('/');
if (slash == -1)
return serverInfo;
else
return serverInfo.substring(0, slash);
}
private String getServerInfoVersion(String serverInfo)
{
int slash = serverInfo.indexOf('/');
if (slash == -1)
return null;
else
return serverInfo.substring(slash + 1);
}
}
Output:

Practical No: 5

Aim : Write a program to demonstrate Database Connectivity using Servlets


Program Code : Index.jsp
<Html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Registration Form</h1>
<form action="http://localhost:8080/db/DatabaseServlet" method="POST">
<table border="1">
<tr><td>Name</td>
<td><input type="text" name="name" value="" /></td>
</tr>
<tr><td>Roll No.</td>
<td><input type="text" name="rollno" value="" /></td>
</tr>
<tr><td>Email</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr><td>Address</td>
<td><textarea name="address" rows="4" cols="20"></textarea></td>
</tr>
<tr><td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
Code : DatabaseServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DatabaseServlet extends HttpServlet
{

Connection con;
Statement stmt;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:abc","admin","");
stmt=con.createStatement();
String name,roll,adr,email;
name =request.getParameter("name");
roll=request.getParameter("rollno");
email=request.getParameter("email");
adr=request.getParameter("address");
stmt.executeUpdate("insert into regform
values('"+roll+"','"+name+"','"+email+"','"+adr+"')");
out.println("<HTML><HEAD></HEAD><BODY>");
ResultSet theResult=stmt.executeQuery("select * from regform");
out.println("RECORD INSERTED");
out.println("<TABLE border=2>");
while(theResult.next())
{
out.println("<TR>");
out.println("<TD>" + theResult.getString(1) + "</TD>");
out.println("<TD>" + theResult.getString(2) + "</TD>");
out.println("<TD>" + theResult.getString(3) + "</TD>");
out.println("<TD>" + theResult.getString(4) + "</TD>");
out.println("</TR>");
theResult.next();
}
}
catch(ClassNotFoundException c1)
{
out.println("ClassNotFoundException");
}
catch(SQLException s1)

{
out.println("SQLException");
}
finally
{
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}

Output:

After Submission

Practical No. 6
AIM: Write a program demonstrating Database Connectivity
ii) Online Exam

Code : oexam.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class oexam extends HttpServlet
{
String str1,str2;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
String q1,q2;
q1="1";
q2="2";
str1=request.getParameter("pres");
str2=request.getParameter("top");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:demo");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from result");
while(rs.next())
{
String st1,st2;
st1=rs.getString("Ques");
st2=rs.getString("Ans");
if((q1.equals(st1))&&(str1.equals(st2)))
out.print("Ur 1st ans is Correct <br>");
else if((q2.equals(st1))&&(str2.equals(st2)))
out.print("Ur 2nd ans is Correct<br>");
else
out.print("Ur "+st1+" ans is Wrong<br>");
}
}

catch(Exception e)
{
out.print("Caught" + e);
}
finally
{
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
Index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="http://localhost:8080/bo/oexam" >
1. Who is the president of india?<br>
<select name="pres" size="1">
<option>Manmohan Singh</option>
<option>Pratibha Patil</option>
</select><br><br>
2. Who is topper of mca?<br>
<select name="top" size="1">
<option>Seema</option>
<option>Bhavik</option>
</select><br><br>
<input type="submit" value="submit" name="submit" />

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

Output:

After Submission

Practical No. 7
Aim: Implementation of simple JSP program

Code: Form.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<form name="frm1" action="output.jsp">
<h2> Enter Number:</h2>
<input type="text" name="txtnum" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
Output.jsp
<%@page import="java.util.*" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<% int no=Integer.parseInt(request.getParameter("txtnum"));%>
<h1> Table of <% out.print(no);%> </h1>
<table border=1>
<% for(int i=1;i<=10;i++){ %>
<tr> <td>
<% out.print(no+" * "+i+" = ");
out.println(no*i); }
%>
</td></tr>
</table>
</body>
</html>

Output:

After Submission

Practical No. 8
Aim : Implementation of Single Thread Model in JSP

Code:
<%@page contentType="text/html" pageEncoding="UTF-8" isThreadSafe="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!private int idNum=0;%>
<%synchronized(this)
{
String userId="userId "+idNum;
out.println("Your ID is "+userId+".");
idNum=idNum+1;
}
%>
</body>
</html>

Output:

Practical No. 9

Aim : Implementaion of Shopping Cart Application using JSP

Code :
login.html
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="form" action="shopping.jsp" method="POST">
Uesr Name : <input type="text" name="uname" value="" size="10" /><br/>
Password : <input type="password" name="pwd" value="" size="10" /><br/>
<input type="submit" value="Login" name="login" />
</form>
</body>
</html>

shopping.jsp
<%@page import="java.io.*,java.util.*,java.sql.*" contentType="text/html" pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Cookie cookies[] = request.getCookies ();
if (cookies != null)
{
for (int j = 0; j < cookies.length; j++)
{ cookies[j].setValue(""); }
}
%>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:logindb");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from login");
while(rs.next())

{
if((request.getParameter("uname").equalsIgnoreCase(rs.getString(1)) &&
(request.getParameter("pwd").equals(rs.getString(2)))))
{
session = request.getSession(true);
%>
<jsp:forward page="products.jsp"/>
<%
break;
}
else
{ out.println("Invalid Login"); }
}
st.close();
con.close();
%>
</body>
</html>

products.jsp
<%@page import="java.io.*,java.util.*,java.sql.*" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
Cookie cookies[];
Cookie myCookie;
int a;
String str;
%>
<form name="form1" action="receipt.jsp" method="post">
<table border="1" cellpadding="5">
<thead>
<tr>
<th>No</th>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>

</thead>
<tbody>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:logindb");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from Products");
a = 1;
while(rs.next())
{
cookies = request.getCookies ();
myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (Integer.toString(a)))
{
myCookie = cookies[i];
}
}
}
%>
<tr>
<td align="center"><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td align="right"><%=rs.getInt(3)%></td>
<td align="right"><input type="text" size="6" name="<%=a%>"
<%
if(myCookie==null)
str = "";
else
str = myCookie.getValue();
%>
value="<%=str%>">
</td>
</tr>
<%
a++;
}
st.close();
con.close();

%>
</tbody>
</table>
<br/>
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>

receipt.jsp
<%@page import="java.io.*,java.util.*,java.sql.*" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:logindb");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from Products");
int i = 1,total=0;
String str;
while(rs.next())
{
response.addCookie(new Cookie(Integer.toString(i),request.getParameter(Integer.toString(i))));

if(!(request.getParameter(Integer.toString(i)).equals("")))
{
str = request.getParameter(Integer.toString(i));
total = total + (rs.getInt(3)*Integer.parseInt(str));
}
i++;
}
st.close();
con.close();
%>

<h1>Your bill is = <%=total%></h1>


<a href="products.jsp">Continue Shopping</a><br/><br/>
<form method="post" action="login.html">
<input type="submit" value="Logout"action="<%session.invalidate();%>;"/>
</form>
</body>
</html>

Output:

After Login

Practical No. 10

Aim : Write a program to developed Calculator Application using C#


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cal
{
class oper
{
int n1, n2;
public void getdata()
{
Console.Write("\nEnter 1st no:");
n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter 2nd no:");
n2 = Convert.ToInt32(Console.ReadLine());
}
public void add()
{
Console.WriteLine("\n{0} + {1}:{2}",n1,n2, (n1 + n2));
}
public void sub()
{
Console.WriteLine("\n{0}-{1}:{2}", n1,n2,(n1-n2));
}
public void mul()
{
Console.WriteLine("\n{0}*{1}:{2}",n1,n2,(n1 * n2));
}
public void div()
{
Console.WriteLine("\n{0}/{1}:{2}",n1,n2,(n1 / n2));
}
}
class calculator
{
static void Main(string[] args)
{
int ch;
oper o = new oper();
Console.WriteLine("1:+");

Console.WriteLine("2:-");
Console.WriteLine("3:*");
Console.WriteLine("4:/");
do
{
Console.Write("\nEnter ur option:");
ch = Convert.ToInt32(Console.ReadLine());
o.getdata();
switch (ch)
{
case 1: o.add();
break;
case 2: o.sub();
break;
case 3: o.mul();
break;
case 4: o.div();
break;
default: Console.WriteLine("Invalid choice.");
break;
}
Console.ReadLine();
} while (ch < 5);
}
}

Output:

Practical No. 11
Aim : Write a program on Program on Generics
Code :
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace gen
{
class Program
{
static void Main(string[] args)
{
MyList<int> lst = new MyList<int>();
MyItem<int> i0 = new MyItem<int>(1);
MyItem<int> i1 = new MyItem<int>(2);
MyItem<int> i2 = new MyItem<int>(3);
MyItem<int> i3 = new MyItem<int>(4);
MyItem<int> i4 = new MyItem<int>(5);
MyItem<int> i5 = new MyItem<int>(6);
lst.append(i0);
lst.append(i1);
lst.append(i2);
lst.append(i3);
lst.append(i4);
lst.append(i5);
lst.display();
Console.WriteLine("Total count in list : " + lst.getCount());
lst.removeAt(3);
Console.WriteLine("\nNew Count after deletion : " +
lst.getCount());
lst.display();
Console.ReadKey();
}
}
class MyItem<T>
{
private T data;
private MyItem<T> next;
public MyItem(T t)
{
data = t;
next = null;
}
public void setData(T t)
{
data = t;
}
public void setNext(MyItem<T> n)
{
next = n;

}
public T getData()
{
return (data);
}
public MyItem<T> getNext()
{
return (next);
}

}
class MyList<T>
{
private MyItem<T> head;

public MyList()
{
head = null;
}
public void append(MyItem<T> item)
{
if (head == null)
{
head = item;
}
else
{
MyItem<T> ptr = head;
while (ptr.getNext() != null)
ptr = ptr.getNext();
ptr.setNext(item);
}
}
public int getCount()
{
if (head == null)
return (0);
int cnt = 0;
MyItem<T> ptr = head;
while (ptr.getNext() != null)
{
ptr = ptr.getNext();
cnt++;
}
return (++cnt);
}
public void display()
{
if (head == null)
return;
MyItem<T> ptr = head;
Console.Write("Contents in the List:");
while (ptr.getNext() != null)
{
Console.Write(ptr.getData() + " ");
ptr = ptr.getNext();
}

Console.WriteLine(ptr.getData());
return;
}
public void removeAt(int index)
{
if (index < 0 || index >= getCount())
return;
else
{
if (index == 0)
{
if (getCount() == 1)
head = null;
else
head = head.getNext();
return;
}

}
}
}

MyItem<T> ptr = head;


for (int i = 0; i < (index - 1); i++)
ptr = ptr.getNext();
ptr.setNext(ptr.getNext().getNext());

Output:

Practical No. 12
Aim : Write a program to demonstrate File Handling in C#
Code:
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
System.IO;

namespace filhandling
{
class operation
{
long phno;
string name, add, str;
public void readfile()
{
FileStream fs = new FileStream("c:\\Milind\\abc.txt",
FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
str = sr.ReadLine();
Console.WriteLine(str);
Console.WriteLine("\nRecords in the file:");
while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
sr.Close();
fs.Close();
}
public void writefile()
{
FileStream fs = new FileStream("c:\\Milind\\abc.txt",
FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.Write("\nEnter name:");
name = Console.ReadLine();
Console.Write("Enter add:");
add = Console.ReadLine();
Console.Write("Enter phone no:");
phno = Convert.ToInt64(Console.ReadLine());
sw.Write("\n");
sw.Write(name + " ");
sw.Write(add + " ");
sw.Write(phno + " ");
sw.Close();

fs.Close();
}
}
class Program
{
static void Main(string[] args)
{
int ch;
char ans;
operation o = new operation();
Console.WriteLine("1:Append record.");
Console.WriteLine("2:Read records.");
do
{

Console.Write("\nEnter your choice:");


ch = Convert.ToInt32(Console.ReadLine());
switch (ch)
{
case 1: o.writefile();
break;
case 2: o.readfile();
break;
default: Console.WriteLine("Invalid choice.");
break;
}
Console.Write("\nDo you want to continue:");
ans = Convert.ToChar(Console.ReadLine());

} while (ans == 'y');


Console.ReadLine();
}
}

Output:
Writing to file:

Reading Data From File

Practical No: 13
Program to implement Shopping Cart using ASP.NET
Code:
CartItem.cs
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace WebApplication3
{
public class CartItem
{
public Product Product;
public int Quantity;
public string Display()
{
return Product.Name + " (" + Quantity.ToString() + " at Rs." + Product.UnitPrice +
" each)";
}
}

Product.cs
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace WebApplication3
{
public class Product
{
public string ProductID;
public string Name;
public string ShortDescription;
public string LongDescription;
public decimal UnitPrice;
public string ImageFile;
}
}

Order.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Order.aspx.cs"
Inherits="WebApplication3.Order" %>
<!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 id="Head1" runat="server">
<title>My Shopping Cart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br /><br />
<asp:Label ID="Label1" runat="server"
Text="Please select a product:"></asp:Label>
<asp:DropDownList ID="ddlProducts" runat="server" Width = "150px"
DataSourceID="AccessDataSource1" DataTextField="Name"
DataValueField="ProductID" AutoPostBack="True">
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/my_products.mdb"
SelectCommand="SELECT [ProductID], [Name], [ShortDescription],
[LongDescription], [ImageFile], [UnitPrice]
FROM [Products] ORDER BY [Name]">
</asp:AccessDataSource>
<br />
<table>
<tr >
<td style="width: 250px; height: 22px">
<asp:Label ID="lblName" runat="server"
Font-Bold="False" Font-Size="Larger">
</asp:Label>
</td>
<td style="width: 20px" rowspan="4">
</td>
<td rowspan="4" valign="top">
&nbsp;</td>
</tr>
<tr>
<td style="width: 250px">
<asp:Label ID="lblShortDescription" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td style="width: 250px">
<asp:Label ID="lblLongDescription" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td style="width: 250px">
<asp:Label ID="lblUnitPrice" runat="server"
Font-Bold="True" Font-Size="Larger">
</asp:Label>

<asp:Label ID="Label2" runat="server" Text="each"


Font-Bold="True" Font-Size="Larger">
</asp:Label>
</td>
</tr>
</table>
<br />
<asp:Label ID="Label3" runat="server" Text="Quantity:"
Width="80px" BorderWidth = "0px"></asp:Label>
<asp:TextBox ID="txtQuantity" runat="server" Width="80px">1</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity is a required field.">
</asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txtQuantity" Display="Dynamic"
ErrorMessage="Quantity must range from 1 to 500."
MaximumValue="500" MinimumValue="1" Type="Integer">
</asp:RangeValidator><br /><br />
<asp:Button ID="btnAdd" runat="server" Text="Add to Cart" OnClick="btnAdd_Click"
/>&nbsp;
<asp:Button ID="btnCart" runat="server" CausesValidation="False"
PostBackUrl="~/Cart.aspx" Text="Go to Cart" />
</div>
</form>
</body>
</html>

Order.cs

using
using
using
using
using
using
using

Microsoft.VisualBasic;
System;
System.Collections;
System.Collections.Generic;
System.Data;
System.Diagnostics;
System.Web.UI;

namespace WebApplication3
{
partial class Order : System.Web.UI.Page
{
private Product SelectedProduct;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
ddlProducts.DataBind();
}
SelectedProduct = this.GetSelectedProduct();
lblName.Text = SelectedProduct.Name;
lblShortDescription.Text = SelectedProduct.ShortDescription;
lblLongDescription.Text = SelectedProduct.LongDescription;

lblUnitPrice.Text = "Rs." + SelectedProduct.UnitPrice.ToString();

private Product GetSelectedProduct()


{
DataView dvProduct =
(DataView)AccessDataSource1.Select(DataSourceSelectArguments.Empty);
dvProduct.RowFilter = "ProductID = '" + ddlProducts.SelectedValue + "'";
Product Product = new Product();
Product.ProductID = dvProduct[0]["ProductID"].ToString();
Product.Name = dvProduct[0]["Name"].ToString();
Product.ShortDescription = dvProduct[0]["ShortDescription"].ToString();
Product.LongDescription = dvProduct[0]["LongDescription"].ToString();
Product.UnitPrice = Convert.ToDecimal(dvProduct[0]["UnitPrice"]);
Product.ImageFile = dvProduct[0]["ImageFile"].ToString();
return Product;
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
CartItem CartItem = new CartItem();
CartItem.Product = SelectedProduct;
CartItem.Quantity = Convert.ToInt32(txtQuantity.Text);
this.AddToCart(CartItem);
Response.Redirect("Cart.aspx");
}
}
private void AddToCart(CartItem CartItem)
{
SortedList Cart = GetCart();
string sProductID = SelectedProduct.ProductID;
if (Cart.ContainsKey(sProductID))
{
CartItem = (CartItem)Cart[sProductID];
CartItem.Quantity += Convert.ToInt32(txtQuantity.Text);
}
else
{
Cart.Add(sProductID, CartItem);
}
}
private SortedList GetCart()
{
if (Session["Cart"] == null)
{
Session.Add("Cart", new SortedList());
}
return (SortedList)Session["Cart"];
}
public Order()
{
Load += Page_Load;
}

}
}

Cart.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Cart.aspx.cs"
Inherits="WebApplication3.Cart" %>
<!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 id="Head1" runat="server">
<title>Shopping Cart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
Your shopping cart:<br />
<table style="width: 500px" cellspacing="0"
cellpadding="0" border="0">
<tr>
<td style="width: 286px; height: 153px">
<asp:ListBox ID="lstCart" runat="server"
Width="267px" Height="135px">
</asp:ListBox>
</td>
<td style="height: 153px">
<asp:Button ID="btnRemove" runat="server"
Width="100px" Text="Remove Item" OnClick="btnRemove_Click" /><br /><br />
<asp:Button ID="btnEmpty" runat="server"
Width="100px" Text="Empty Cart" OnClick="btnEmpty_Click" />
</td>
</tr>
</table>
<br />
<asp:Button ID="btnContinue" runat="server"
PostBackUrl="~/Order.aspx" Text="Continue Shopping" />&nbsp;
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out"
OnClick="btnCheckOut_Click" /><br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>
</div>
</form>
</body>
</html>

Cart.cs
using System;
using System.Collections;
using System.Collections.Generic;

using
using
using
using

System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;

namespace WebApplication3
{
partial class Cart : System.Web.UI.Page
{
private SortedList Carts;
protected void Page_Load(object sender, System.EventArgs e)
{
Carts = GetCart();
if (!IsPostBack)
{
this.DisplayCart();
}
}
private SortedList GetCart()
{
if (Session["Cart"] == null)
{
Session.Add("Cart", new SortedList());
}
return (SortedList)Session["Cart"];
}
private void DisplayCart()
{
lstCart.Items.Clear();
CartItem CartItem = default(CartItem);
DictionaryEntry CartEntry = default(DictionaryEntry);
foreach (DictionaryEntry CartEntry_loopVariable in Carts)
{
CartEntry = CartEntry_loopVariable;
CartItem = (CartItem)CartEntry.Value;
lstCart.Items.Add(CartItem.Display());
}
}
protected void btnRemove_Click(object sender, System.EventArgs e)
{
if (lstCart.SelectedIndex > -1 & Carts.Count > 0)
{
Carts.RemoveAt(lstCart.SelectedIndex);
this.DisplayCart();
}
}
protected void btnEmpty_Click(object sender, System.EventArgs e)
{
Carts.Clear();
lstCart.Items.Clear();
lblMessage.Text = "";
}

protected void btnCheckOut_Click(object sender, System.EventArgs e)


{
lblMessage.Text = "Please Wait Checking out...";
}
public Cart()
{
Load += Page_Load;
}

Output:

Practical No: 14

Program to implement Online Admission using ASP.NET


Code:
Login.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;

namespace OnlineLibrary
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "admin" && txtPwd.Text == "admin")
{
Response.Write("<script>alert('Login Successfull')</script>");
Response.Redirect("option.aspx");
}
else
{
Response.Write("<script>alert('Login
Unsuccessfull')</script>");
}
}
}
}

Bookentry.aspx.cs
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;

using
using
using
using
using
using

System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;
System.Data.OleDb;

namespace OnlineLibrary
{
public partial class bookentry : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
int isbn;
bool isnum = int.TryParse(txtIsbn.Text, out isbn);
int ed;
isnum = int.TryParse(txtEdition.Text, out ed);
int c;
isnum = int.TryParse(txtCost.Text, out c);
int co;
isnum = int.TryParse(txtCopies.Text, out co);
OleDbConnection conn = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents
and Settings\MAHESH\My Documents\Visual Studio
2008\Projects\OnlineLibrary\Library.mdb");
conn.Open();
String insertQuery = "insert into [book1] ([isbn], [subject],
[name], [author], [publisher], [edition], [cost], [copies]) values(" +
isbn + ",'" + txtSubject.Text + "','" + txtName.Text + "','" +
txtAuthor.Text + "','" + txtPublisher.Text + "'," + ed + "," + c + "," + co +
") ";
OleDbCommand cmd = new OleDbCommand(insertQuery, conn);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Book details entered
successfully.')</script>");
reset();
}
catch (Exception ex)
{

"')</script>");
}

Response.Write("<script>alert('" + ex.Message +

}
public void reset()
{
txtAuthor.Text = "";
txtCopies.Text = "";
txtCost.Text = "";
txtIsbn.Text = "";
txtName.Text="";
txtPublisher.Text = "";
txtSubject.Text = "";
txtEdition.Text = "";
}
protected void btnReset_Click(object sender, EventArgs e)
{
reset();
}
}
}

Issue.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;
System.Data.OleDb;

namespace OnlineLibrary
{
public partial class issue : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
int no;
bool isnum = int.TryParse(txtBook.Text, out no);
int id;
isnum = int.TryParse(txtId.Text, out id);

try
{
OleDbConnection conn = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents
and Settings\MAHESH\My Documents\Visual Studio
2008\Projects\OnlineLibrary\Library.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM book1 where bno=" + no;
OleDbDataReader dbReader = cmd.ExecuteReader();
//Response.Write("<script>alert('" + dbReader.Read()

+"')</script>");

//return;
if (!dbReader.Read())
{
Response.Write("<script>alert('Book no doesnt
exist.')</script>");

return;

}
dbReader.Close();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM student where sid=" + id;
dbReader = cmd.ExecuteReader();
if (!dbReader.Read())
{
Response.Write("<script>alert('Student id doesnt

exist.')</script>");
}

return;

String insertQuery = "insert into [issue] ([bno], [sid],


[idate]) values(" +
no + "," + id + ",'" + txtDate.Text + "') ";
cmd = new OleDbCommand(insertQuery, conn);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Book issued
successfully.')</script>");

bno=" + no;

String updateQuery = "update [book1] set issued=issued+1 where


cmd = new OleDbCommand(updateQuery, conn);
cmd.ExecuteNonQuery();
reset();

}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message +
"')</script>");
}
}
public void reset()
{
txtBook.Text = "";
txtId.Text = "";
}
protected void btnReset_Click(object sender, EventArgs e)
{
reset();
}
protected void Page_Load(object sender, EventArgs e)
{
txtDate.Text = System.DateTime.Now.ToShortDateString();
}
}

Option.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;

namespace OnlineLibrary
{
public partial class option : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (rbStudent.Checked)
{
Response.Redirect("studententry.aspx");

}
}

}
else if (rdBook.Checked)
{
Response.Redirect("bookentry.aspx");
}
else if (rbIssue.Checked)
{
Response.Redirect("issue.aspx");
}
else
{
Response.Redirect("return.aspx");
}

Return.aspx.cs
using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;
System.Data.OleDb;

namespace OnlineLibrary
{
public partial class _return : System.Web.UI.Page
{

protected void btnSubmit_Click(object sender, EventArgs e)


{
try
{
int no;
bool isnum = int.TryParse(txtBook.Text, out no);
int id;
isnum = int.TryParse(txtId.Text, out id);

OleDbConnection conn = new


OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents
and Settings\MAHESH\My Documents\Visual Studio
2008\Projects\OnlineLibrary\Library.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM book1 where bno=" + no;
OleDbDataReader dbReader = cmd.ExecuteReader();
//Response.Write("<script>alert('" + dbReader.Read()
+"')</script>");
//return;
if (!dbReader.Read())
{
Response.Write("<script>alert('Book no doesnt
exist.')</script>");
return;
}
dbReader.Close();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM student where sid=" + id;
dbReader = cmd.ExecuteReader();
if (!dbReader.Read())
{
Response.Write("<script>alert('Student id doesnt
exist.')</script>");
return;
}
String insertQuery = "insert into return ([bno], [sid], [rdate])
values(" +

no + "," + id + ",'" + txtDate.Text + "') ";

cmd = new OleDbCommand(insertQuery, conn);


cmd.ExecuteNonQuery();
Response.Write("<script>alert('Book returned
successfully.')</script>");
String updateQuery = "update [book1] set issued=issued-1 where
bno=" + no;

cmd = new OleDbCommand(updateQuery, conn);


cmd.ExecuteNonQuery();
reset();
}
catch (Exception ex)

Response.Write("<script>alert('" + ex.Message +
"')</script>");
}
}
public void reset()
{
txtBook.Text = "";
txtId.Text = "";
}

}
}

protected void btnReset_Click(object sender, EventArgs e)


{
reset();
}
protected void Page_Load(object sender, EventArgs e)
{
txtDate.Text = System.DateTime.Now.ToShortDateString();
}

Output:

You might also like