You are on page 1of 98

J2EE and .Net Lab Expt.

No:1 Date:

UNARY OPERATOR OVERLOADING


Aim:
To overload the unary operator to change sign of variables using C#.Net

Program:
using System; class uop { public int a,b; public uop(int a1,int b1) { a=a1; b=b1; } public void disp(){Console.WriteLine(a);Console.WriteLine(b);} public static uop operator -(uop ob) { ob.a=-ob.a; ob.b=-ob.b; return ob; } } class unaryoperator { public static void Main(string[] args) { uop u=new uop(-10,-10); u.disp(); uop u1=-u; u1.disp(); } }

J2EE and .Net Lab

Execution:
Compilation: Z:\m.tech\iii sem\lab\ex\i ii opoverload>csc unaryoperator.cs Runing Z:\m.tech\iii sem\lab\ex\i ii opoverload>unaryoperator -10 -10 10

Result:
Thus the unary operator was overloaded and used to change the sign of the variables using C#.Net

Staff signature

J2EE and .Net Lab Expt.No:2 Date:

BINARY OPERATOR OVERLOADING


Aim:
To overload the binary operator and to use it for real& imaginary value display using C#.Net

Program:
using System; class biop { public int real,im; public biop(){} public biop(int r,int i) { real=r; im=i; } public void disp(){Console.WriteLine(real+"+i"+im);} public static biop operator +(biop ob1,biop ob2) { biop b=new biop(); b.real=ob1.real+ob2.real; b.im=ob1.im+ob2.im; return b; } } class binaryoperator { public static void Main(string[] args) { biop b1=new biop(5,5); b1.disp(); biop b2=new biop(2,2); b2.disp(); biop b3=b1+b2; b3.disp(); } }

J2EE and .Net Lab Execution:


Compilation: Z:\m.tech\iii sem\lab\ex\i ii opoverload>csc binaryoperator.cs Runing Z:\m.tech\iii sem\lab\ex\i ii opoverload>binaryoperator 5+i5 2+i2 7+i7

Result:
Thus the binary operator was overloaded and used as for real& imaginary value displayer using C#.Net

Staff signature

J2EE and .Net Lab

Expt.No:3 Date:

IMPLEMENTING IENUMERABLE INTERFACE


Aim:
To create a simple program to implement IEnumerable interface using C#.Net

Program:
using System; using System.Collections; class car:IEnumerable { private car[] carr; public string name; public car(string s) {name=s;} public car() { carr=new car[3]; carr[0]=new car("san"); carr[1]=new car("man"); carr[2]=new car("van"); } public IEnumerator GetEnumerator() {return carr.GetEnumerator();} } class enumInterface { public static void Main(string[] args) { car o=new car(); foreach(car c in o) { Console.WriteLine(c.name); } } }

J2EE and .Net Lab

Execution:
Compilation: Z:\m.tech\iii sem\lab\ex\3 enumerable>csc enumInterface.cs Runing Z:\m.tech\iii sem\lab\ex\3 enumerable>enumInterface san man van

Result:
Thus a enumerator was created using IEnumerable interface and the values stored were displayed using C#.Net

Staff signature

J2EE and .Net Lab

Expt.No:4 Date:

IMPLEMENTING ICOMPARABLE INTERFACE


Aim:
To create a simple program to implement IComparable interface using C#.Net

Program:
using System; class combo:IComparable { public int id; public string name; public combo(string name1,int x) { name=name1; id=x; } public int CompareTo(object o) { combo temp=(combo) o; if(this.id>temp.id) return (1); if(this.id<temp.id) return (-1); else return (0); } } class icomparable { public static void Main(string[] args) {

J2EE and .Net Lab


combo[] c=new combo[3]; c[0]=new combo("aaa",123); c[1]=new combo("bbb",12); c[2]=new combo("ccc",1); Array.Sort(c); foreach(combo m in c) Console.WriteLine(m.name+"\t"+m.id); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\4 icomparable>csc icomparable.cs Runing Z:\m.tech\iii sem\lab\ex\4 icomparable>icomparable ccc 1 bbb 12 aaa 123

Result:
Thus the IComparable interface was implemented and the object of that class was displayed using C#.Net

Staff signature

J2EE and .Net Lab

Expt.No:5 Date: IMPLEMENTING DEEP CLONE USING ICLONEABLE INTERFACE Aim:


To develop a simple program to implement a deep clone of object using ICloneable interface using C#.Net

Program:
using System; public class one{public int a;} public class two:ICloneable { public int b; public one o=new one(); public two(int a1,int b1) { o.a=a1; b=b1; } public void show(){Console.WriteLine(o.a+" "+b);} public Object Clone() { two t=new two(o.a,b); return t; } } class twoclone

J2EE and .Net Lab


{ public static void Main(string[] args) { two t1=new two(1,2); two t2=(two)t1.Clone(); t1.show(); t2.show(); t1.o.a=5; t2.b=5; t1.show(); t2.show(); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\56 cloneable>csc twoclone.cs Runing Z:\m.tech\iii sem\lab\ex\56 cloneable>twoclone 12 12 52 15

Result:
Thus a simple program was developed to implement deep clone of object using C#.Net

10

J2EE and .Net Lab

Staff signature

Expt.No:6 Date:

IMPLEMENTING SHALLOW CLONE USING ICLONEABLE INTERFACE


Aim:
To develop a simple program to implement a shallow clone of object using ICloneable interface using C#.Net

Program:
using System; public class one {public int a;} public class two:ICloneable { public int b; public one o=new one(); public two(int a1,int b1) { o.a=a1; b=b1; } public void show(){Console.WriteLine(o.a+" "+b);} public Object Clone() {

11

J2EE and .Net Lab


return (this.MemberwiseClone()); } } class tth { public static void Main(string[] args) { two t1=new two(1,2); two t2=(two)t1.Clone(); t1.show(); t2.show(); t1.o.a=5; t1.b=5; t1.show(); t2.show(); } }

Execution:
Compilation: Z:\m.tech\iii sem\lab\ex\56 cloneable>csc tth.cs Runing: Z:\m.tech\iii sem\lab\ex\56 cloneable>tth 12 12 55 52

Result:
Thus a simple program was developed to implement shallow clone of object using C#.Net

12

J2EE and .Net Lab

Staff signature

Expt.No:7 Date:

PROGRAM TO ACCESS AND MUTATE NAMED PROPERTIES


Aim:
To develop a simple program to access and mutate named properties using C#.Net

Program:
using System; using System.Collections; public class Car { private string name; public string Name { get{return name;} set{name=value;} } public Car(string n) {name=n;} 13

J2EE and .Net Lab


} public class CarCollection:CollectionBase { public void Add(Car newcar) {List.Add(newcar);} public void Remove(Car oldcar) {List.Remove(oldcar);} public Car this[int index] { get{return (Car)List[index];} set{List[index]=value;} } }

class properties { public static void Main(string[] args) { CarCollection c=new CarCollection(); c.Add(new Car("santro")); c.Add(new Car("suzuki")); c.Add(new Car("nano")); c.Add(new Car("azer")); foreach(Car car in c) { Console.WriteLine(car.Name); } Console.WriteLine(c[2].Name); c[2].Name="zen"; Console.WriteLine(c[2].Name); foreach(Car car in c) { Console.WriteLine(car.Name); } } }

14

J2EE and .Net Lab

Execution:
Compilation: Z:\m.tech\iii sem\lab\ex\7properties>csc properties.cs Runing: Z:\m.tech\iii sem\lab\ex\7properties>properties santro suzuki nano azer nano zen santro suzuki zen azer

Result:
15

J2EE and .Net Lab


Thus a simple program was developed to access and mutate named properties using C#.Net

Staff signature

Expt.No:8(i) Date:

IMPLEMENTING COLLECTIONS INTERFACE USING QUEUE


Aim:
To develop a program to implement collections using queue using C#.Net

Program:
using System; using System.Collections; class queue1 { public static void Main(string[] args) {

16

J2EE and .Net Lab


Queue q1=new Queue(); q1.Enqueue(55); q1.Enqueue(65); q1.Enqueue(75); q1.Enqueue(85); Console.WriteLine(q1.Dequeue()); Console.WriteLine(q1.Peek()); Console.WriteLine(q1.Dequeue()); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\8 collections>csc queue.cs Runing Z:\m.tech\iii sem\lab\ex\8 collections>queue 55 65 65

17

J2EE and .Net Lab

Result:
Thus a simple program was developed to implement collections using queue using C#.Net

Staff signature

Expt.No:8(ii) Date:

IMPLEMENTING COLLECTIONS INTERFACE USING STACK


Aim:
To develop a program to implement collections using stack using C#.Net

Program:
using System; using System.Collections; class stack { public static void Main(string[] args) 18

J2EE and .Net Lab


{ Stack s1=new Stack(); s1.Push(10); s1.Push(20); s1.Push(30); s1.Push(40); Console.WriteLine(s1.Pop()); Console.WriteLine(s1.Peek()); Console.WriteLine(s1.Pop()); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\8 collections>csc stack.cs Runing Z:\m.tech\iii sem\lab\ex\8 collections>stack 40 30 30

19

J2EE and .Net Lab

Result:
Thus a simple program was developed to implement collections using stack using C#.Net

Staff signature

Expt.No:9(i) Date:

IMPLEMENTING ONE DIMENSIONAL INDEXER


Aim:
To develop a simple program to implement one dimensional indexer

Program:
20

J2EE and .Net Lab


using System; public class sid { public int length; int[] a; public sid(int size) { a=new int[size]; length=size; } public int this[int id] { get{return a[id];} set{a[id]=value;} } } class one { public static void Main(string[] args) { sid s=new sid(5); for(int i=0;i<5;i++) { s[i]=i; Console.WriteLine(s[i]); } } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\9.indexer>csc one.cs Runing Z:\m.tech\iii sem\lab\ex\9.indexer>one 0 1 2

21

J2EE and .Net Lab


3 4

Result:
Thus a simple program was developed to implement one dimensional indexer using C#.Net

Staff signature

Expt.No:9(ii) Date:

IMPLEMENTING TWO DIMENSIONAL INDEXER


Aim:
To develop a simple program to implement two dimensional indexer using C#.Net

22

J2EE and .Net Lab Program:


using System; public class twod { public int r,c; int[,] a; public twod(int r1,int c1) { a=new int[r1,c1]; } public int this[int id1,int id2] { get{return a[id1,id2];} set{a[id1,id2]=value;} } } class twodemo { public static void Main(string[] args) { twod d=new twod(3,3); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { d[i,j]=i*j; Console.WriteLine(d[i,j]); } } } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\9.indexer>csc twodemo.cs Runing Z:\m.tech\iii sem\lab\ex\9.indexer>twodemo 0 23

J2EE and .Net Lab


0 0 0 1 2 0 2 4

Result:
Thus a simple program was developed to implement two dimensional indexer using C#.Net

Staff signature

Expt.No:10 Date:

IMPLEMENTING SINGLE & MULTILEVEL INHERITANCE


24

J2EE and .Net Lab

Aim:
To develop a simple program to implement single & multilevel inheritance using C#.Net

Program:
using System; class A { public int a; public A(){a=0;} public A(int x){a=x;} public void Display() { Console.WriteLine("Base class A's value is:" + a); } } class B:A { public int b; public B(){b=0;} public B(int x){b=x;} public void Display1() { Console.WriteLine("Derived class B's value is:" + b); } } class C:B { int c; public C(){b=0;} public C(int x,int y,int z){a=x;b=y;c=z;} public void Display2() { Console.WriteLine("Derived class C's value is:" + c); } } class Class1 { public static void Main() { 25

J2EE and .Net Lab


A a1=new A(10); a1.Display(); Console.WriteLine(); Console.WriteLine("Single Inheritance"); B b1=new B(20); b1.Display(); b1.Display1(); Console.WriteLine(); Console.WriteLine("Multilevel Inheritance"); C c1=new C(30,40,50); c1.Display(); c1.Display1(); c1.Display2(); } }

Execution:
Compilation

26

J2EE and .Net Lab


Z:\m.tech\iii sem\lab\ex\10.Inheritance>csc Inheitance.cs Runing Z:\m.tech\iii sem\lab\ex\10.Inheritance>Inheitance Base class A's value is:10 Single Inheritance Base class A's value is:0 Derived class B's value is:20 Multilevel Inheritance Base class A's value is:30 Derived class B's value is:40 Derived class C's value is:50

Result:
Thus a simple program was developed to implement the single & multilevel inheritance using C#.Net

Staff signature

27

J2EE and .Net Lab Expt.No:1(i) Date: IMPLEMENTING PROVIDER AND ADAPTER OBJECTS USING ADO.NET Aim:
To access the student database and retrieve its contents using provider and adapter objects of ado.net using C#.Net

Program:
//7 OleDB Sample using System; using System.Data; using System.Data.OleDb; using System.Xml.Serialization; public class MainClass { public static void Main () { // Set Access connection and select strings. // The path to student.MDB must be changed if you build // the sample from the command line: #if USINGPROJECTSYSTEM string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\student.mdb"; #else string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=student.mdb"; #endif string strAccessSelect = "SELECT * FROM MyTable"; // Create the dataset and add the MyTable table to it: DataSet myDataSet = new DataSet(); OleDbConnection myAccessConn = null; try { myAccessConn = new OleDbConnection(strAccessConn); } catch(Exception ex) { Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message); return;

28

J2EE and .Net Lab


} try { OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect,myAccessConn); OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand); myAccessConn.Open(); myDataAdapter.Fill(myDataSet,"MyTable"); } catch (Exception ex) { Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message); return; } finally { myAccessConn.Close(); } // A dataset can contain multiple tables, so let's get them // all into an array: DataTableCollection dta = myDataSet.Tables; foreach (DataTable dt in dta) { Console.WriteLine("Found data table {0}", dt.TableName); } // The next two lines show two different ways you can get the // count of tables in a dataset: Console.WriteLine("{0} tables in data set", myDataSet.Tables.Count); Console.WriteLine("{0} tables in data set", dta.Count); // The next several lines show how to get information on // a specific table by name from the dataset: Console.WriteLine("{0} rows in MyTable table", myDataSet.Tables["MyTable"].Rows.Count); // The column info is automatically fetched from the database, // so we can read it here:

29

J2EE and .Net Lab


Console.WriteLine("{0} columns in MyTable table", myDataSet.Tables["MyTable"].Columns.Count); DataColumnCollection drc = myDataSet.Tables["MyTable"].Columns; int i = 0; foreach (DataColumn dc in drc) { // Print the column subscript, then the column's name // and its data type: Console.WriteLine("Column name[{0}] is {1}, of type {2}",i++ , dc.ColumnName, dc.DataType); } DataRowCollection dra = myDataSet.Tables["MyTable"].Rows; foreach (DataRow dr in dra) { // Print the CategoryID as a subscript, then the CategoryName: Console.WriteLine("id = {0} Name = {1} Mark1 = {2} Mark2 = {3} ", dr[0], dr[1],dr[2],dr[3]); } } }

30

J2EE and .Net Lab

Execution:
Compilation C:\ado.net>csc oledb.cs Runing C:\ado.net>oledb Found data table MyTable 1 tables in data set 1 tables in data set 2 rows in MyTable table 4 columns in MyTable table Column name[0] is regno, of type System.Int32 Column name[1] is name, of type System.String Column name[2] is mark1, of type System.Int32 Column name[3] is mark2, of type System.Int32 id = 1 Name = san Mark1 = 100 Mark2 = 100 id = 2 Name = vid Mark1 = 100 Mark2 = 100

Result:
Thus the table name, no of rows and entries of the table were accessed using the provider and adapter objects using C#.Net

Staff signature

31

J2EE and .Net Lab

Expt.No:1(ii) Date:

IMPLEMENTING CONSUMER OBJECT


Aim:
To create two tables using the classes DataTable, DataColumn, Data Row and to relate them and access them.

Program:
using System; using System.IO; using System.Data; class ten { public static void Main(string[] args) { try { DataTable t=new DataTable("student"); DataColumn c1=new DataColumn(); c1.ColumnName="id"; c1.DataType=Type.GetType("System.Int32"); c1.AllowDBNull=false; c1.Unique=true; DataColumn c2=new DataColumn(); c2.ColumnName="name"; c2.DataType=Type.GetType("System.String"); t.Columns.Add(c1); t.Columns.Add(c2); DataRow r1=t.NewRow(); r1["id"]=1; r1["name"]="san"; t.Rows.Add(r1); DataRow r2=t.NewRow(); r2["id"]=2; 32

J2EE and .Net Lab


r2["name"]="vid"; t.Rows.Add(r2); DataRow r3=t.NewRow(); r3["id"]=3; r3["name"]="kar"; t.Rows.Add(r3); DataTable t1=new DataTable("details"); DataColumn c3=new DataColumn(); c3.ColumnName="id"; c3.DataType=Type.GetType("System.Int32"); c3.AllowDBNull=false; c3.Unique=true; DataColumn c4=new DataColumn(); c4.ColumnName="lang"; c4.DataType=Type.GetType("System.String"); t1.Columns.Add(c3); t1.Columns.Add(c4); DataRow r4=t1.NewRow(); r4["id"]=1; r4["lang"]="eng"; t1.Rows.Add(r4); DataRow r5=t1.NewRow(); r5["id"]=2; r5["lang"]="tam"; t1.Rows.Add(r5); DataRow r6=t1.NewRow(); r6["id"]=3; r6["lang"]="hin"; t1.Rows.Add(r6); DataSet s=new DataSet("student details"); s.Tables.Add(t); s.Tables.Add(t1); DataRelation r=new DataRelation("stud",s.Tables["student"].Columns["id"],s.Tables["details"].Columns["id"] ); s.Relations.Add(r); DataRow dr1=null; DataRow[] dr2=null; string stre=""; int i; Console.WriteLine("enter the id"); i=int.Parse(Console.ReadLine());

33

J2EE and .Net Lab

dr1=s.Tables["student"].Rows[i]; stre+=dr1["name"]; dr2=dr1.GetChildRows(s.Relations["stud"]); foreach(DataRow x in dr2) { stre+=x["lang"]; Console.WriteLine(stre); } } catch(Exception ex){Console.WriteLine(ex.ToString());} } }

34

J2EE and .Net Lab

Execution:
Compilation C:\ado.net>csc ten.cs Runing C:\ado.net>ten enter the id 1 vidtam C:\ado.net>ten enter the id 2 karhin

Result:
Thus the tables student and details were created and related using DataSet student detail and their entries were accessed using C#.Net

35

J2EE and .Net Lab Staff signature

Expt.No:2(i) Date:

IMPLEMENTING FILE INPUT


Aim:
To create a new text file and write some text into the file using file io classes like FileStream class using C#.Net

Program:
using System; using System.IO; using System.Text; class exthree { public static void Main(string[] args) { byte[] b=new byte[100]; char[] c=new char[100]; try { FileStream fs=new FileStream(@"D:\a.txt",FileMode.OpenOrCreate); c="hi i am surendran welcome to my page".ToCharArray(); Encoder e=Encoding.UTF8.GetEncoder(); e.GetBytes(c,0,c.Length,b,0,true); fs.Seek(0,SeekOrigin.Begin); fs.Write(b,0,100); } catch(IOException e1){Console.WriteLine(e1.ToString());} }}

36

J2EE and .Net Lab

Execution:
Compilation C:\>csc exthree.cs Runing C:\>exthree a.txt file:

Result:
37

J2EE and .Net Lab


Thus a new file a.txt was created and the given text was added into the file using write () method of FileStream class using C#.Net

Staff signature

Expt.No:2(ii) Date: IMPLEMENTING FILE OUTPUT Aim:


To read the contents of the existing file and display it using read() method of FileStream class using C#.Net

Program:
using System; using System.IO; using System.Text; class extwo { public static void Main(string[] args) { byte[] b=new byte[100]; char[] c=new char[100]; try { FileStream fs=new FileStream(@"D:\a.txt",FileMode.Open); fs.Seek(0,SeekOrigin.Begin); fs.Read(b,0,100); } catch(IOException e){Console.WriteLine(e.ToString());} Decoder d=Encoding.UTF8.GetDecoder(); d.GetChars(b,0,b.Length,c,0); Console.WriteLine(c);

38

J2EE and .Net Lab


} }

Execution:
Compilation C:\>csc extwo.cs Runing C:\>extwo hi i am surendran welcome to my page

Result:
Thus the contents of a.txt file were printed using C#.Net

39

J2EE and .Net Lab

Staff signature

Expt.No:3 Date: EVENT HANDLING IN .NET Aim:


To demonstrate how events are created and handled using delegate methods using C#.Net

(i)Program:
//simple delegate based event handling using System; delegate void disp(); class classi { static void d1(){Console.WriteLine("A");} static void d2(){Console.WriteLine("B");} static void d3(){Console.WriteLine("C");} public static void Main(string[] args) { disp d; d=new disp(d1); d+=new disp(d2); d+=new disp(d3); d(); }

40

J2EE and .Net Lab


}

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\II.3.delegates>csc classi.cs Runing Z:\m.tech\iii sem\lab\ex\II.3.delegates>classi A B C

(ii)Program:
//events handled using event handlers using System; using System.IO; delegate void MyEventHandler(); class ce { public event MyEventHandler someevent; public void onsomeevent(){Console.WriteLine("event called");someevent();} } class h1 { public void handler1(){Console.WriteLine("one");} } class h2 { public void handler2(){Console.WriteLine("two");} } class th { public static void Main(string[] args) { ce c=new ce(); h1 h=new h1(); h2 hob=new h2(); c.someevent+=new MyEventHandler(h.handler1); c.someevent+=new MyEventHandler(hob.handler2); 41

J2EE and .Net Lab


c.onsomeevent(); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\II.3.delegates>csc th.cs Runing Z:\m.tech\iii sem\lab\ex\II.3.delegates>th event called one two

(iii)Program:
//handling mouse events using System; using System.Windows.Forms; class ex4:Form { public ex4() { Top=40; Left=40; Width=100; Height=500; this.MouseUp+=new MouseEventHandler(OnMouseUp); this.MouseMove+=new MouseEventHandler(OnMouseMove); } public void OnMouseUp(Object o,MouseEventArgs e) {string s=string.Format("current:",e.X,e.Y);MessageBox.Show(s);} public void OnMouseMove(Object o,MouseEventArgs e) {if(e.Button==MouseButtons.Left) MessageBox.Show("left"); if(e.Button==MouseButtons.Right) MessageBox.Show("right"); if(e.Button==MouseButtons.Middle) MessageBox.Show("middle"); }

42

J2EE and .Net Lab


public static void Main(string[] args) {Application.Run(new ex4());} }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\II.3.delegates>csc ex4.cs Runing Z:\m.tech\iii sem\lab\ex\II.3.delegates>ex4

Result:
Thus the event handling in .net is demonstrated using delegates using C#.Net

43

J2EE and .Net Lab

Staff signature

Expt.No:4 Date:

SIMPLE APPLICATION USING .NET CONTROLS


Aim:
To create a simple application using menu control of .net using C#.Net

Program:
using System; using System.Windows.Forms; class ex6:Form { public ex6() { MainMenu m1=new MainMenu(); MenuItem m2=new MenuItem("File"); MenuItem m3=new MenuItem("open"); MenuItem m4=new MenuItem("close"); m2.MenuItems.Add(m3); m2.MenuItems.Add(m4); m1.MenuItems.Add(m2);

44

J2EE and .Net Lab


m3.Click+=new EventHandler(OnOpen); m4.Click+=new EventHandler(OnClose); this.Menu=m1; } public void OnOpen(Object o,EventArgs e) {MessageBox.Show("open");} public void OnClose(Object o,EventArgs e) {MessageBox.Show("close");} public static void Main(string[] args) { Application.Run(new ex6()); } }

Execution:
Compilation Z:\m.tech\iii sem\lab\ex\II.4.controls>csc ex6.cs Runing Z:\m.tech\iii sem\lab\ex\II.4.controls>ex6

45

J2EE and .Net Lab

Result:
Thus a simple application is created using menu control to open and close file using C#.Net

Staff signature

Expt.No:5 Date:

SIMPLE APPLICATION USING ASP.NET


Aim:
To create a simple application using ASP.Net

Program:
<%@page language="c#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <html> <head> <script language="c#" runat="server"> void getData(object o,EventArgs e) { OleDbConnection d=new OleDbConnection(); d.ConnectionString="Provider=Microsoft.JET.OLEDB.4.0;"+"Data Source=c:\\ado.mdb"; d.Open();

46

J2EE and .Net Lab


String s="select * from myTable"; OleDbCommand c=new OleDbCommand(s,d); inventoryGrid.DataSource=c.ExecuteReader(); inventoryGrid.DataBind(); d.Close(); } </script> </head> <body> <form id="Form1" method="post" runat="server"> <asp:Label id="Label1" runat="server"> Click on the button below to fill the DataGrid </asp:Label></p> <asp:Button id="btnGetData" OnClick="getData" runat="server" Text="Get the Data!"> </asp:Button></p> <asp:DataGrid id="inventoryGrid" runat="server" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4"> </asp:DataGrid> </form> </body> </html> SAMPLE OUTPUT:

47

J2EE and .Net Lab

Result:
Thus a simple application was created using ASP.Net

Staff signature

Expt.No:6 Date:

CREATE A SIMPLE WEBSERVICE USING .NET


Aim:
To create a simple Web Service using .Net

Program:
<%@ WebService Language="C#" Class="FindNo.oddevenclass" %> namespace FindNo { public class oddevenclass { [System.Web.Services.WebMethod] public string odd_check(int x)

48

J2EE and .Net Lab


{ if(x%2==0) return "even"; else return "odd"; } } }

Explanation:
Folder Name: FindNo Class Name: oddevenclass Function Name: odd_check() (i)Steps to create a Virtual Directory is created Settings ->control panel->Administrative Tools-> Internet Information Services->Double Click->Find Default Web Site icon->Right Click->new->Virtual Directory->click->Next->Alias:FindNo->Dirctory: C:\FindNo->Next->Select Write,Read,Execute,Run,Browse->Finish Virtual Directory is created (ii) load the FindNo.asmx Select Visual Studio 2005->Open Website-> C:\FindNo FindNo.asmx file is loaded (iii)Run the FindNo.asmx file The following page is displayed through asp.net server

49

J2EE and .Net Lab

Click the odd_check link the following page is displayed

50

J2EE and .Net Lab

Given x value & then click the Invoke Button the following xml file is displayed

51

J2EE and .Net Lab

Virtual directory:

Faster development of web servises using Virtual directory.


provide a convenient and organized structure for your Web clients secure web application from virtual directory

Namespaces are C# program elements designed to help you organize your programs. good habit

Use: class myclass, type declarations, class interface

Result:
Thus a simple Web Service was created using .Net

Staff signature

52

J2EE and .Net Lab

Expt No: 1 Date:

LIFE CYCLE OF SERVLET


FREAK SERVLET DEMO STATE HISTORY

Aim:
To display the Life cycle of servlet (ie) State history of Demo Servlet using J2EE

Program:
/* * freak.java */ import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import java.io.IOException; import java.io.PrintWriter; /** * * @author admin * @version */ public class freak extends HttpServlet { java.util.Vector states; java.util.Random random; int waitinterval; public static final int DEFAULT_WAIT_INTERVAL =10; public freak() { states=new java.util.Vector(); random=new java.util.Random(); waitinterval = DEFAULT_WAIT_INTERVAL; 53

J2EE and .Net Lab


states.add(createState("INSTANTIATION")); } public void init() throws ServletException { states.add(createState("INITIALIZATION")); } /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if(random.nextBoolean()) { states.add(createState("Unavaileble from doGet")); throw new UnavailableException("Unavaileble from doGet",waitinterval); } states.add(createState("service")); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>"); out.println("DEMO SERVLET:STATE HISTORY"); out.println("</title></head>"); out.println("<body>"); String waitintervalString = getServletConfig().getInitParameter("waitinterval"); out.println(waitintervalString); out.println("<h1>DEMO SERVLET:STATE HISTORY</H1>"); String u="http://localhost:8080/freak-war/freak"; out.println("<a href =\""+u+"\">Reload</a>"); for(int i=0;i<states.size();i++) { out.println("<P>"+states.elementAt(i)+"</p>"); }

54

J2EE and .Net Lab


out.println("</body></html>"); out.close(); } /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet freak</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet freak at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ public void destroy() { states.add(createState("destroy")); System.out.println("FLUSHING"); for( int i=0;i<states.size();i++) { System.out.println(states.elementAt(i).toString()); } } private String createState(String message) { return "["+ (new java.util.Date()).toString()+ "]"+message; } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response);

55

J2EE and .Net Lab


} /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> } Unavailable.html <body> unavailable temporarily <a href =http://localhost:8080/freak-war/freak>Reload</a> </body> a.html <title>reload</reload> <body> Reloaded </body> web.xml servlets: initialization parameter: waitinterval value :1 pages: error page:unavailable.html Error code:503

After Compile & Run,

Output:

56

J2EE and .Net Lab

Press Reload Link,

57

J2EE and .Net Lab

Press Reload Link,

58

J2EE and .Net Lab

Result:
Thus the state history of Demo Servlet was displayed ie life cycle of servlet displayed suceessfully using J2EE.

Staff signature

59

J2EE and .Net Lab

Expt No: 2 Date:

SESSION LIFE CYCLE SERVLET Aim:


To create a different sessions from a Session Life Cycle Servlet with current date &time Using J2EE

Program:
/* SessionLifeCycleServlet.java */ import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; /** * * @author admin * @version */ public class SessionLifeCycleServlet extends HttpServlet { /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 60

J2EE and .Net Lab


String action=request.getParameter("action"); if(action!=null && action.equals("invalidate")) { HttpSession session=request.getSession(); session.invalidate(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title> SessionLifeCycle</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>ur Session has been invalidated </p>"); String lifecycleurl="http://localhost:8080/SessionLifeCycleServletwar/SessionLifeCycleServlet"; out.println("<a href=\""+ lifecycleurl + "?action=newsession\">"); out.println("create new session </a>"); out.println("</body>"); out.println("</html>"); } else { HttpSession session=request.getSession(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SessionLifeCycleServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet SessionLifeCycleServlet </h1>"); out.println("session status"); if(session.isNew()){ out.println("new session");} else{out.println("old session");} out.println("sid"); out.println(session.getId()); out.println("creation time"); out.println(new Date(session.getCreationTime())); out.println(session.getMaxInactiveInterval()); String lifecycleurl="http://localhost:8080/SessionLifeCycleServletwar/SessionLifeCycleServlet"; out.println("<a href=\""+ lifecycleurl + "?action=invalidate\">"); out.println("invalidate </a>");

61

J2EE and .Net Lab


out.println("<a href=\""+ lifecycleurl + "\">"); out.println("reload </a>"); out.println("</body>"); out.println("</html>"); out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }

62

J2EE and .Net Lab

After Compile & Run, Output:

Press the reload link

63

J2EE and .Net Lab

Press invalidate Lin k

64

J2EE and .Net Lab

Press create new session link

65

J2EE and .Net Lab

Result: Thus different sessions are created from a Session Life Cycle Servlet with current date &time using J2EE.

Staff signature

66

J2EE and .Net Lab

Ex No: 3 Date:

DISPLAY DATA IN JSP Aim:


To display the data from a database in a JSP with current time using J2EE

Program:
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%-The taglib directive below imports the JSTL library. If you uncomment it, you must also add the JSTL library to the project. The Add Library... action on Libraries node in Projects view can be used to add the JSTL 1.1 library. --%> <%-<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> --%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%--This is the HTML content--%> <!-comment appears-> <%@ page language="java" import="java.sql.*" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>JSP Page</h1> <% java.util.Date now=new java.util.Date();%> <%= now.getHours()%>: <%= now.getMinutes()%>:<%= now.getSeconds()%> <%-This example uses JSTL, uncomment the taglib directive above. To test, display the page like this: index.jsp?sayHello=true&name=Murphy --%> <%-67

J2EE and .Net Lab


<c:if test="${param.sayHello}"> <!-- Let's welcome the user ${param.name} --> Hello ${param.name}! </c:if> --%> <% Connection con=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:dsn"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from datas"); %> <table><% while(rs.next()){ %> <tr><td><%=rs.getString(1) %></td> </tr><%}%></table> <% } catch(Exception d){out.println("cannot display records");} %> </body> </html>

68

J2EE and .Net Lab

After Compile & Run, Output

Result:
Thus data base data was displayed in JSP with current time using J2EE

69

J2EE and .Net Lab


Staff signature

Ex No: 4 Date:

Shopping cart Aim:


To add & display the items in a shopping cart using J2EE

Program:
cart.java /* * cart.java * * Created on July 31, 2008, 8:58 AM */ import java.io.*; import java.net.*; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator * @version */ public class cart extends HttpServlet {

70

J2EE and .Net Lab


/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response);} protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(true); ArrayList cart=(ArrayList) session.getAttribute("cart"); if(cart==null) { cart=new ArrayList(); session.setAttribute("cart",cart); } response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet cart</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet cart at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ String[] itemselected; String itemname; itemselected=request.getParameterValues("item"); if(itemselected != null) { for (int i=0;i<itemselected.length;i++) { itemname=itemselected[i]; cart.add(itemname); } } out.println("<html>"); out.println("<head>"); out.println("<title>shopping cart contents</title>");

71

J2EE and .Net Lab


out.println("</head>"); out.println("<body>"); out.println("<h1>Items in ur cart</h1>"); out.println("<hr>"); Iterator iterator = cart.iterator(); while(iterator.hasNext()) { out.println("<p>"+iterator.next()+"</p>"); } String u="http://localhost:8080/shoppingcart-war/catalog"; out.println("<a href =\""+u+"\">back to cart</a>"); out.println("</body>"); out.println("</html>"); out.close(); } } catalog.java /* * catalog.java * * Created on July 31, 2008, 9:02 AM */ import java.io.*; import java.net.*; import java.io.PrintWriter; import java.io.IOException; import java.util.ArrayList; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator * @version */ public class catalog extends HttpServlet { /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request

72

J2EE and .Net Lab


* @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); int itemcount=0; ArrayList cart=(ArrayList) session.getAttribute("cart"); if(cart!=null) { itemcount=cart.size(); } response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet catalog</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>you have"+itemcount+"items in your cart</p>"); out.println("<form action=\""); out.println(response.encodeURL("/shoppingcart-war/cart")); out.println("\" method=\"post\">"); out.println("add to cart"); out.println("<input type=\"checkbox\" name=\"item\"" + " value=\"java\">"); out.println("java"); out.println("<input type=\"checkbox\" name=\"item\"" + " value=\"j2EE\">"); out.println("j2ee"); out.println("<input type=\"checkbox\" name=\"item\"" + " value=\"C#\">"); out.println("C#"); out.println("<input type=\"checkbox\" name=\"item\"" + " value=\"ASP\">"); out.println("asp"); out.println("<input type=\"checkbox\" name=\"item\"" + " value=\"netbeans\">"); out.println("net beans"); out.println("<input type=\"submit\" name=\"btn_submit\"" + " value=\"add to cart\">"); // out.println("<h1>Servlet catalog at " + request.getContextPath () + "</h1>");

73

J2EE and .Net Lab


out.println("</form> </body>"); out.println("</html>"); /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet catalog</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet catalog at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); */ out.close(); } }

After Compile & Run, Output:

74

J2EE and .Net Lab

75

J2EE and .Net Lab

76

J2EE and .Net Lab

77

J2EE and .Net Lab

78

J2EE and .Net Lab

Result:
Thus the items was added & displayed in a shopping cart using J2EE

Staff signature

79

J2EE and .Net Lab

Ex No: 5 Date:

Java Mail Aim:


To implement the java mail process using J2EE

Program:
Sentsmtp.java import javax.mail.*; import javax.activation.*; import javax.mail.internet.*; import java.util.*; /** * * @author admin */ public class sentsmtp extends Object { /** Creates a new instance of Main */ /** * @param args the command line arguments */ public static void main(String[] args) { try { Properties props=new Properties(); props.put("mail.transport.protocol","smtp"); props.put("mail.smtp.host"," "); props.put("mail.smtp.port","25"); Session mailsession=Session.getInstance(props); Message msg=new MimeMessage(mailsession); msg.setFrom(new InternetAddress("surendran_mtech_it@yahoo.co.in")); msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("tamilvizhi@g mail.com")); msg.setSentDate(new Date()); msg.setSubject("hi tamil how r u where r u now???"); msg.setText("first mail");

80

J2EE and .Net Lab


//Transport.send(msg); msg.writeTo(System.out); } catch(Exception e){System.out.println(e);} } }

After Compile & Run, Output:


run-main: Message-ID: <22485126.1217476943936.JavaMail.Administrator@com1> Date: Thu, 31 Jul 2008 09:32:23 +0530 (IST) From: surendran_mtech_it@yahoo.co.in To: tamilvizhi@gmail.com Subject: hi tamil how r u where r u now??? MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit first mail

Result:
Thus the java mail process was implemented successfully using J2EE

81

J2EE and .Net Lab


Staff signature

Ex No: 6 Date:

Web services in J2EE Aim:


To implement the Web services concept using J2EE

Program:
calculator_webservice.java * * To change this template, choose Tools | Templates * and open the template in the editor. */ package calculatorpack; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; /** * * @author Administrator */ @WebService() public class calculator_webservice { /** * Web service operation */

82

J2EE and .Net Lab


@WebMethod(operationName = "addition") public Integer addition(@WebParam(name = "a") final int a, @WebParam(name = "b") final int b) { //TODO write your implementation code here: return a+b; } /** * Web service operation */ @WebMethod(operationName = "subtraction") public Float subtraction(@WebParam(name = "x") final float x, @WebParam(name = "y") final float y) { //TODO write your implementation code here: return x-y; } /** * Web service operation */ @WebMethod(operationName = "multification") public Integer multification(@WebParam(name = "a") final int a, @WebParam(name = "b") final int b, @WebParam(name = "c") final int c) { //TODO write your implementation code here: return a*b*c; } /** * Web service operation */ @WebMethod(operationName = "division") public Float division(@WebParam(name = "x") final float x, @WebParam(name = "y") final float y) { //TODO write your implementation code here: return x/y; } }

83

J2EE and .Net Lab

After Compile & Run, Output:

Click WSDL File Link

84

J2EE and .Net Lab

Click the addition Link

85

J2EE and .Net Lab

Click the subtraction Link

86

J2EE and .Net Lab

Click the multification Link

87

J2EE and .Net Lab

Click the division Link

88

J2EE and .Net Lab

Result:
Thus the Web services concept was implemented successfully using J2EE

Staff signature

89

J2EE and .Net Lab

Ex No: 7 Date:

Enterprise Java Bean (EJB) Aim:


To implement the EJB concept using J2EE

Program: ejbssessionBean.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ejbspack; import javax.ejb.Stateless; /** * * @author admin */ @Stateless public class ejbssessionBean implements ejbssessionRemote { public Integer add(int x, int y) { return x+y; } // Add business logic below. (Right-click in editor and choose // "EJB Methods > Add Business Method" or "Web Service > Add Operation") }

ejbsservlet.java
package ejbspack; import java.io.*; //import java.net.*;

90

J2EE and .Net Lab


import javax.ejb.EJB; import javax.servlet.*; import javax.servlet.http.*; //import ejbspack.ejbssessionRemote; /** * * @author Administrator */ public class ejbsservlet extends HttpServlet { @EJB private ejbssessionRemote ob; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); int x=Integer.parseInt(request.getParameter("one")); int y=Integer.parseInt(request.getParameter("two")); out.println("The answer of "+x+" added with "+y+" is : "+ob.add(x,y)); } }

index.jsp
<%-Document : index Created on : Aug 11, 2008, 9:03:53 AM Author : admin --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

91

J2EE and .Net Lab


"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> <h2>EJB DEMO</h2> <form action="ejbsservlet" method="get"> ENTER FIRST NUMBER &nbsp; <input type="text" name="one" value="" /><br> ENTER SECOND NUMBER &nbsp; <input type="text" name="two" value="" /><br> <input type="submit" value="submit" /> </form> </body> </html>

Note:
project Name:ejbs EJB Name: ejbssession Package Name: ejbpack Servlet Name: ejbsservlet

92

J2EE and .Net Lab

After Compile & Run, Output:

Click the submit Button

93

J2EE and .Net Lab

Result:
Thus the EJB concept was implemented successfully using J2EE

Staff signature

94

J2EE and .Net Lab

First Cycle
..Using C#&.Net

95

J2EE and .Net Lab

Second Cycle
..Using C# & ASP.Net

96

J2EE and .Net Lab

Third Cycle
..Using J2EE

97

J2EE and .Net Lab

Mini Project

98

You might also like