You are on page 1of 217

Deccan Education Society’s

Navinchandra Mehta Institute of Technology


and Development

M.C.A SEMESTER IV (CBCGS)


[AWT & DMBI]
Roll Number [MC1944]
DES’s NMITD AWT Journal MC1944

Deccan Education Society’s


Navinchandra Mehta Institute of Technology
and Development

C E R T I F I C A T E

This is to certify that Mr. SHANBHAG SAGAR RAVIKIRAN of

M.C.A. Semester IV (CBCGS) with Roll No. MC1944 has

completed AWT Lab Practical under my supervision in this college

during the year 2020-2021.

REMARKS:

Practical In Charge Associate Director


(NMITD)

1|Page
DES’s NMITD AWT Journal MC1944

AWT INDEX  DATE SIG



C# 
I  A. C# application to read and display user information     
B. C# application to demonstrate the use of various numeric  
data types   
C. C# application to Calculate gross salary   
D. C# application to demonstrate String functions & properties    
E. C# application to display date in  various formats    
F. C# application  to Display numbers from 1 to 20 except multiples
of 3 
G. C# application  to create an Array of integers and perform search
operation on it 
H. C# application to demonstrate the use of namespaces 
I. C# application to pass parameters to Main() 
J. C# application to create a class Rectangle and write public function
(Area) which returns the area of rectangle 
K. C# application which SWAPs two numbers 
L. C# application with Employee class with some public properties 
M. C# application to create a class Student to demonstrate the use of
parametrized constructors 
N. C# application to make square a partial class 
O. C# application to derive Employee class from Person class. 
P. C# application to demonstrate the use of Interfaces  
Q. C# application to pass and return array from a function 
R. C# application to use array of Employee class 
S. C# application to create and use multidimensional array 
T. C# application to create and use jagged array 
U. C# application to change the lowerbound of an array 
V. C# application to use Copy and Clone functions 
W. C# application to sort Employee array based on their Names 
II  A. C# application to simulate a Bank Account with exception handling     
B. C# application to calculate Simple Interest and Compound Interest  
with Exception handling   
C. C# application to simulate a simple calculator   
D. C# application to simulate a TODO app using ArrayList   
E. C# application to create a generic Swap function   
F. C# application to implement generic Stack class 
III  A. FileInformation Application     
B. Read and Write Files using FILE class 
C. Read and Write Files using FileStream 
D. Read and Write Files using StreamReader and StreamWriter 
E. Notepad Application
with MenuStrip, ToolStrip, FontDialog, ColorDialog, OpenFileDialog, Sav
eFileDialog 
IV  A. Bank Application Connected DB     
B. Bank Application Disconnected DB 

2|Page
DES’s NMITD AWT Journal MC1944

C. Data Tools(GridView, ToolStrip, BindingNavigator) 
V  A. LINQ Application to query     
a. int array 
b. var multidimensional array 
c. Access DB 
 ASP .NET 
VI  A. PageEvents     
B. PostBack and CrossPage Posting 
C. Web Server Controls 
D. Validation Controls 
E. Design an e-Commerce WebSite using MasterPage, Theme and Skins. 
F. Use AJAX controls to change Banner AD’s after every second, make use
of  Adrotator Control. 
VII  A. Login and CreateUserWizard     
B. GridView with AccessDataSource 
C. GridView with SQLDataSource 
D. GridView with ObjectDataSource  
 
VIII  A.   ViewState Example     
B. Cookies with multiple keys 
C. Login Application with Cookies 
D. Application to change Background Color based on selection. (Cookie) 
E. Application to change Background Color based on selection. (Session) 
F. Login Application with Session 
G. Out-of-process Session State 
H. SqlServer Session State 
I. Cookieless Session 
J. Application State 
K. Output Cache: 
 VaryByParam 
 VaryByControl 
 VaryByCustom 
L. Cache Object 
 Cache an ArrayList 
 Cache a DataSet 
M. Shopping Cart Example 

Web Services 
IX  A. Create an XML Web Service to add two integers. Consume    
this service through a Web Client. 
B. Create an XML Web Service with methods to calculate the
area and perimeter of a Rectangle. Consume this service through
a Windows client application. 
C. Create an XML Web Service that returns all the branch details
from BranchTB. Write a Windows application that uses this
service to display branch details in a datagridview control. 
D. Create an XML Web Service that returns the selected branch’s

3|Page
DES’s NMITD AWT Journal MC1944

information from BranchTB. Write a Windows application that


uses this service to display branch details in
a datagridview control. Also add a web method to insert new
branch information entered by the user into the branch table. 
E. Create an XML Web Service that calculates the sum of two
double variables. Call this method and continue the execution of
client application while the sum is being calculated.
(Asynchronous call to Web Service) 
F. Create an XML Web Service that checks for Login credentials
entered by user with values in LoginTB. Write a Windows client
that uses this web service to Login. 
G. Create a WCF web service to provide calculator services. 
I. Create a WCF web service to calculate age in no. of days 
 

4|Page
DES’s NMITD AWT Journal MC1944

C#

5|Page
DES’s NMITD AWT Journal MC1944

PRACTICAL NO.1
A. C# application to read and display user information
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Example1
{
public partial class Question1 : Form
{
public Question1()
{
InitializeComponent();
}

private void displayName_Click(object sender, EventArgs e)


{
textBox2.Text = "Welcome " + textBox1.Text;
MessageBox.Show("Welcome " + textBox1.Text);
}
}
}

Output:

B. C# application to demonstrate the use of various numeric data types

6|Page
DES’s NMITD AWT Journal MC1944

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Example1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private void convert_Click(object sender, EventArgs e)


{
if(Convert.ToInt16(textBox1.Text)>255)
{
textBox2.Text = ((byte)
(Convert.ToInt16(textBox1.Text))).ToString();
}
else
{
textBox2.Text = (Convert.ToByte(textBox1.Text)).ToString();
}
textBox4.Text = (Convert.ToInt32(textBox3.Text) / 3).ToString();
textBox6.Text = (Convert.ToDouble(textBox5.Text)/3).ToString();
textBox8.Text = (float.Parse(textBox7.Text) / 3).ToString();
textBox10.Text = (Convert.ToDecimal(textBox9.Text) / 3).ToString();
}
}
}

Output:

7|Page
DES’s NMITD AWT Journal MC1944

C. C# application to add two numbers


using System;

8|Page
DES’s NMITD AWT Journal MC1944

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Example1
{
public partial class Question1 : Form
{
public Question1()
{
InitializeComponent();
}
private void displayName_Click(object sender, EventArgs e)
{
num2.Text = "Welcome " + num1.Text;
MessageBox.Show("Welcome " + num1.Text);
}

private void add_Click(object sender, EventArgs e)


{
int n1 = Convert.ToInt32(num1.Text);
int n2 = Convert.ToInt32(num2.Text);
MessageBox.Show("Addition of " + n1 +" and " + n2 + " is: " +( n1 +
n2)); } }}

Output:

D. Design a C# application to calculate gross_salary


a. gross_salary = BASIC – PF*BASIC + HRA*BASIC

9|Page
DES’s NMITD AWT Journal MC1944

b. BASIC, PF, HRA being symbolic constants.(Assume appropriate


values)
c. Use appropriate data types
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Eg1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cal_gross_salary_Click(object sender, EventArgs e)
{
string name1 = myname.Text;
double basic = Convert.ToDouble(bsalary.Text);
const double PF = 0.10, HRA = 0.15;
double gsalary1 = basic - PF * basic + HRA * basic;
gsalary.Text = "Hello " + name1 + "\n Your Gross salary is: " +
gsalary1;
}}}
Output:

E. C# application to demonstrate String functions & properties


using System;

10 | P a g e
DES’s NMITD AWT Journal MC1944

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class StringFunctionsProperties : Form
{
public StringFunctionsProperties()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string myname1 = myname.Text;
string str1 = @"C:\Users\ABC\Desktop";

outputText.Text = "UpperCase: " + myname1.ToUpper() +


Environment.NewLine +
"LowerCase: " + myname1.ToLower() +
Environment.NewLine +
"Remove(2,1): " + myname1.Remove(2, 1) +
Environment.NewLine +
"Equals(CBA): " + myname1.Equals("CBA") +
Environment.NewLine +
"LastIndexOf(Hello): " + myname1.LastIndexOf('l') +
Environment.NewLine +
"Length " + myname1.Length + Environment.NewLine +
"Goto " + str1;

}
}
}

Output:

11 | P a g e
DES’s NMITD AWT Journal MC1944

12 | P a g e
DES’s NMITD AWT Journal MC1944

F. C# application to display date in various formats


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Prac1_Q6 : Form
{
public Prac1_Q6()
{
InitializeComponent();
}

private void label1_Click(object sender, EventArgs e)


{

private void button1_Click(object sender, EventArgs e)


{
DateTime d = new DateTime();
d = DateTime.Now;
textBox1.Text = d.ToString();
textBox2.Text = d.ToShortDateString();
textBox3.Text = d.ToString("F");
textBox4.Text = d.ToString("D");
textBox5.Text = d.ToLongTimeString();
int days;
DateTime newyear = new DateTime(d.Year, 12, 31);
days = newyear.DayOfYear - d.DayOfYear;
textBox6.Text = days.ToString();
}
}
}

13 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

14 | P a g e
DES’s NMITD AWT Journal MC1944

G. C# application to display a message notifying the user if its weekday


or weekend
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Prac1_Q7 : Form
{
public Prac1_Q7()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string weekday;
weekday = textBox1.Text;
switch(weekday)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
label2.Text = "It's a weekday";
break;
case "Saturday":
case "Sunday":
label2.Text = "It's a weekend";
break;
default:
label2.Text = "No such day";
break;
}
}
}
}

15 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

16 | P a g e
DES’s NMITD AWT Journal MC1944

H. Design a C# application to Display numbers from 1 to 20 except


multiples of 3 using while loop and

a. continue
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
string msg = "Numbers from 1 to 20 which are not divisible by 3
are:"+Environment.NewLine;
while(i<=20)
{
if(i%3==0)
{
i++;
continue;
}
else
{
msg += " " + i;
}
i++;
}
textBox1.Text = msg;
}
}
}

17 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

18 | P a g e
DES’s NMITD AWT Journal MC1944

b. goto
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
string msg = "Numbers from 1 to 20 which are not divisible by 3
are:"+Environment.NewLine;
mylabel: while(i<=20)
{
if(i%3==0)
{
i++;
goto mylabel;
}
else
{
msg += " " + i;
}
i++;
}
textBox1.Text = msg;
}
}
}

19 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

20 | P a g e
DES’s NMITD AWT Journal MC1944

I. Design a C# application to create an Array of 10 integers

a. Populate the array with random numbers.

b. Search a number in the array, number entered by user.

c. If found display message and use “break” to jump out of loop.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Example1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] arr = new int[10];
private void add_to_array_Click(object sender, EventArgs e)
{
string[] strarr = textBox1.Text.Split(' ');
for(int i=0;i<strarr.Length;i++)
{
arr[i] = Convert.ToInt16(strarr[i]);
}
MessageBox.Show("Number are added to array successfully.");
textBox2.Focus();
}

private void search_Click(object sender, EventArgs e)


{
bool found = false;
for(int i=0;i<arr.Length;i++)
{
if(arr[i]==int.Parse(textBox2.Text))
{
found = true;
MessageBox.Show("Number " + textBox2.Text + " is found at
position " + (i + 1));
textBox2.Focus();
textBox2.SelectAll();
}
}
if(!found)

21 | P a g e
DES’s NMITD AWT Journal MC1944

{
MessageBox.Show("Number " + textBox2.Text + " not found. ");
textBox2.Focus();
textBox2.SelectAll();
}
}

private void close_Click(object sender, EventArgs e)


{
Application.Exit();
}
}
}

Output:

22 | P a g e
DES’s NMITD AWT Journal MC1944

23 | P a g e
DES’s NMITD AWT Journal MC1944

J. Design a C# application to demonstrate use of namespaces a. Create


two classes. classA under namesapace deptA.courseA and classB
under namespace deptB.courseB. b. Both classes should have
respective display methods displayA and displayB with appropriate
messages. c. Use “using” directive to include classB in classA file. d.
Call displayB method from displayA method.

B.cs(Class File)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
namespace deptB
{
namespace courseB
{
class B
{
public static void Display()
{
MessageBox.Show("Inside namespace
deptB.courseB.classB.Display()","Inside B", MessageBoxButtons.OKCancel);
}
}
}
}
}
A.cs (Class File)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eg1.deptB.courseB;
using System.Windows.Forms;

namespace Eg1
{
namespace deptA
{
namespace courseA
{
class A
{
public static void Display()

24 | P a g e
DES’s NMITD AWT Journal MC1944

{
MessageBox.Show("Inside namespace
deptA.courseA.classA.Display()", "Inside A", MessageBoxButtons.OKCancel);
B.Display();
}
}
}
}
}
NamespaceDemo.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eg1.deptA.courseA;
using System.Windows.Forms;

namespace Eg1
{
public partial class NamespaceDemo : Form
{
public NamespaceDemo()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
A.Display();
}

private void button2_Click(object sender, EventArgs e)


{
Eg1.deptB.courseB.B.Display();
}
}
}

25 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

26 | P a g e
DES’s NMITD AWT Journal MC1944

K. Design a C# application to pass 2 parameters to Main() and display


them.

To pass parameter to Main():

Debug Menu->Project Properties-> Write down argument to passed as


follows:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
static class Program
{
public static string[] sub;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(String[] args)
{
sub = args;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Prac1_Q11());
}
}
}

27 | P a g e
DES’s NMITD AWT Journal MC1944

Prac1_Q11.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Prac1_Q11 : Form
{
public Prac1_Q11()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
for (int i=0;i<Program.sub.Length;i++)
{
MessageBox.Show(Program.sub[i]);
}
} }}
Output:

28 | P a g e
DES’s NMITD AWT Journal MC1944

L. Design a C# application to create a class Rectangle with 2 private


data members (Length and Width).Initialize these members. Also
create a public member function (Area) which returns the area of
rectangle.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical2 : Form
{
public Practical2()
{
InitializeComponent();
}

private void areaBtn_Click(object sender, EventArgs e)


{
double len = Convert.ToDouble(height_txt.Text);
double wid = Convert.ToDouble(width_txt.Text);
Rectangle rect_obj = new Rectangle(len, wid);
MessageBox.Show("Area of rectangle: length= " + len + " and
width= " + wid + " is: " + rect_obj.Area());
}
}
class Rectangle
{
private double len, wid;
public Rectangle(double len, double wid)
{
this.len = len;
this.wid = wid;
}
public double Area()
{
return len * wid;
}
}
}

29 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

30 | P a g e
DES’s NMITD AWT Journal MC1944

M. Design a C# application to swap two numbers using a SWAP function.

a. Pass parameters by value

b. Pass parameters by reference. Use ref keyword.

c. Display the values before and after calling the swap function.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class SwapExample : Form
{
public SwapExample()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
MessageBox.Show("Before swapping: " + Environment.NewLine +
"A: " + a + Environment.NewLine + "B: " + b);
swap(a, b);
MessageBox.Show("Value at memory location: " +
Environment.NewLine + "A: " + a + Environment.NewLine + "B: " + b);
}
static void swap(int a,int b)
{
int t;
t = a;
a = b;
b = t;
MessageBox.Show("After swapping: " + Environment.NewLine + "A:
" + a + Environment.NewLine + "B: " + b);
}
static void swap(ref int a, ref int b)
{
int t;
t = a;
a = b;
b = t;

31 | P a g e
DES’s NMITD AWT Journal MC1944

MessageBox.Show("After swapping: " + Environment.NewLine + "A:


" + a + Environment.NewLine + "B: " + b);
}

private void button2_Click(object sender, EventArgs e)


{
int a = int.Parse(textBox1.Text);
int b = int.Parse(textBox2.Text);
MessageBox.Show("Before swapping: " + Environment.NewLine +
"A: " + a + Environment.NewLine + "B: " + b);
swap(ref a, ref b);
MessageBox.Show("Value at memory location: " +
Environment.NewLine + "A: " + a + Environment.NewLine + "B: " + b);
}
}
} Output:

Swap by value

32 | P a g e
DES’s NMITD AWT Journal MC1944

Swap by reference

33 | P a g e
DES’s NMITD AWT Journal MC1944

N. Design a C# application to create a class Employee.

a. Private Data Members: name, salary.

b. Public properties: Name, Age, Salary.

i. Set Name only if length of value is less than 10.

c. Salary property should be read-only.(only get)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical2_Q3 : Form
{
public Practical2_Q3()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Employee emp = new Employee();
emp.Ename = nameTxt.Text;
emp.Eage = Convert.ToInt32(ageTxt.Text);
MessageBox.Show("Name: " + emp.Ename + " Salary: " +
emp.Esalary + " Age: " + emp.Eage);
}
}
class Employee
{
private string ename;
private int salary = 25000;
public string Ename
{
get { return ename; }
set
{
if(value.Length>10)
{
MessageBox.Show("Name too long");
}
else
{

34 | P a g e
DES’s NMITD AWT Journal MC1944

ename = value;
}
}
}
public int Esalary
{
get { return salary; }
}
public int Eage
{
get;
set;
}
}
}

Output:

35 | P a g e
DES’s NMITD AWT Journal MC1944

O. Design a C# application to create a class Student.

a. Private Data Members: name and course.

b. Public function GetInfo() to display the name and course.

c. Two Constructors.

i. First constructor taking name as parameter.

ii. Second constructor taking name and course as parameter.

d. Call the 2-parameter constructor from 1-parameter constructor


(use constructor initializer and this keyword)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical2_Q4 : Form
{
public Practical2_Q4()
{
InitializeComponent();
}

private void GetInfo_Click(object sender, EventArgs e)


{
string sname = nameTxt.Text;
string course = courseTxt.Text;
Student s;
if(course.Equals(""))
{
s =new Student(sname);
}
else
{
s = new Student(sname, course);
}
s.getInfo();
}
}
class Student
{
public string sname;
public string course;

36 | P a g e
DES’s NMITD AWT Journal MC1944

public Student(string sname, string course)


{
this.sname = sname;
this.course = course;
MessageBox.Show("2 params");
}
public Student(string sname) : this(sname, "MCA")
{
MessageBox.Show("1 param");
}
public void getInfo()
{
MessageBox.Show("Name: " + sname + ", Course: " + course);
}
}
}

Output:

37 | P a g e
DES’s NMITD AWT Journal MC1944

P. Design a C# application to create a structure Manager

a. Private Data Members: name and age.

b. Constructor taking name and age as parameter.

c. A public function to Display the details of Manager.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class StructureExample : Form
{
public StructureExample()
{
InitializeComponent();
}

private void label1_Click(object sender, EventArgs e)


{

private void button1_Click(object sender, EventArgs e)


{
Manager m1;
m1.mname = nameTxt.Text;
m1.age = Convert.ToInt32(ageTxt.Text);
m1.Display();
}
}
public struct Manager
{
public int age;
public string mname;
public Manager(string mname,int age)
{
this.mname = mname;
this.age = age;
}
public void Display()
{
MessageBox.Show("Name: " + this.mname + Environment.NewLine
+ "Age: " + this.age);

38 | P a g e
DES’s NMITD AWT Journal MC1944

}
}
}

Output:

39 | P a g e
DES’s NMITD AWT Journal MC1944

Q. Design a C# application to make square a partial class.

a. Add a function to calculate its Area in one file.

b. Add another function to calculate its Perimeter in second file.

ClassArea.cs(Class File)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Eg1
{
class ClassArea
{
}
partial class Square
{
public Square(double side)
{
this.side = side;
}
public void Area()
{
System.Windows.Forms.MessageBox.Show("Area= " + side * side +
" sq.cm");
}
}
}
ClassPeri.cs(Class File)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Eg1
{
class ClassPeri
{
}
partial class Square
{
private double side;
public void Peri()
{
System.Windows.Forms.MessageBox.Show("Perimeter= " + 4*side +
" cm");
}

40 | P a g e
DES’s NMITD AWT Journal MC1944

}
}
Practical2_Q6(Windows Form File)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical2_Q6 : Form
{
Square s;
public Practical2_Q6()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
s = new Eg1.Square(Convert.ToDouble(sideTxt.Text));
s.Area();
}
private void button2_Click(object sender, EventArgs e)
{
s = new Eg1.Square(Convert.ToDouble(sideTxt.Text));
s.Peri();
}
}
}

41 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

42 | P a g e
DES’s NMITD AWT Journal MC1944

R. Design a C# application to derive Employee class from Person class.


a. Person class will have name and uid fields. Also virtual GetInfo()
method to display name and uid.
b. Employee class will have eid as an additional data member.
Override GetInfo() method to display name, uid and eid.
c. Call GetInfo() method of Person class from GetInfo() of Person
class (use base keyword)
d. Also add a 2-parameter constructor to Person class and 3-
parameter constructor to Employee class. (call base class constructor
from Employee class using Constructor initializer and base keyword)

Person.cs(Class File)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Eg1
{
class Person
{
protected string sname;
protected int uid;
public Person(string sname,int uid)
{
this.sname = sname;
this.uid = uid;
}
public virtual void getInfo()
{
MessageBox.Show("Inside Base Class getInfo");
MessageBox.Show("Name: " + sname + " UID: " + uid);
}
}
}
Employee1.cs(Class File)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
class Employee1:Person
{
protected int eid;
public Employee1(string sname,int uid,int eid):base(sname,uid)

43 | P a g e
DES’s NMITD AWT Journal MC1944

{
this.eid = eid;
}
public override void getInfo()
{
base.getInfo();
MessageBox.Show("Inside Derived Class getInfo");
MessageBox.Show("Name: " + sname + " UID: " + uid+" EMPID:
"+eid);
}
}
}
Practical2Q7.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical2Q7 : Form
{
public Practical2Q7()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string sname = nameTxt.Text;
int uid = Convert.ToInt32(uidTxt.Text);
int empid = Convert.ToInt32(empidTxt.Text);

Employee1 e1 = new Employee1(sname, uid, empid);


e1.getInfo();
}
}
}

44 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

45 | P a g e
DES’s NMITD AWT Journal MC1944

S. C# application to demonstrate the use of Interfaces


RetrieveProperties.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
interface IFormPropD
{
void getFormColD(Form F);
}
interface IButtonPropD
{
void getBtnColB(Button B);
}
class RetrieveProperties:IFormPropD,IButtonPropD
{
public void getFormColD(Form F)
{
MessageBox.Show("Form Color: " + F.BackColor.ToString());
}
public void getBtnColB(Button B)
{
MessageBox.Show("Button Color: " + B.BackColor.ToString());
}
public void Display()
{
MessageBox.Show("Inside display");
}
}
}
InterfaceExamplecs.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class InterfaceExamplecs : Form
{
public InterfaceExamplecs()
{

46 | P a g e
DES’s NMITD AWT Journal MC1944

InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Button B = (Button)sender;
RetrieveProperties c = new RetrieveProperties();
c.getBtnColB(B);
c.getFormColD(B.FindForm());
c.Display();

/*IFormPropD c1 = new RetrieveProperties();


IButtonPropD c2 = new RetrieveProperties();
c1.getFormColD(B.FindForm());
c2.getBtnColB(B);*/
}
}
}

47 | P a g e
DES’s NMITD AWT Journal MC1944

T. Design a C# application to take names of 5 students and marks of


each student in 2 subjects (separate array for each subject). Display
the names and marks. Also write a function (pass 2 arrays as
parameter) to find total marks of each student and to return the
array of total marks.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical3_Q1 : Form
{
TextBox[] txtnames = new TextBox[5];
TextBox[] txtsub1 = new TextBox[5];
TextBox[] txtsub2 = new TextBox[5];
public Practical3_Q1()
{
InitializeComponent();
}

private void Practical3_Q1_Load(object sender, EventArgs e)


{
for (int i=0;i<5;i++)
{
txtnames[i] = new TextBox();
txtnames[i].Name = "txtNames" + i.ToString();
txtnames[i].Location = new System.Drawing.Point(20, 20 + 54 *
i);
this.Controls.Add(txtnames[i]);

txtsub1[i] = new TextBox();


txtsub1[i].Name = "txtsub1" + i.ToString();
txtsub1[i].Location = new System.Drawing.Point(170, 20 + 54 *
i);
this.Controls.Add(txtsub1[i]);

txtsub2[i] = new TextBox();


txtsub2[i].Name = "txtsub2" + i.ToString();
txtsub2[i].Location = new System.Drawing.Point(320, 20 + 54 *
i);
this.Controls.Add(txtsub2[i]);
}

48 | P a g e
DES’s NMITD AWT Journal MC1944

private void button1_Click(object sender, EventArgs e)


{
int[] sub1 = new int[5];
int[] sub2 = new int[5];
for(int i=0;i<5;i++)
{
sub1[i] = Convert.ToInt32(txtsub1[i].Text);
sub2[i] = Convert.ToInt32(txtsub2[i].Text);
}
int[] tt1 = Total(sub1, sub2);
for (int i=0;i<5;i++)
{
MessageBox.Show("Name: " + txtnames[i].Text + " Total Marks:
" + tt1[i]);
}
}
private int[] Total(int[] a, int[] b)
{
int[] total = new int[5];
for(int i=0;i<5;i++)
{
total[i] = a[i] + b[i];
}
return total;
}}}

49 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

50 | P a g e
DES’s NMITD AWT Journal MC1944

U. Design a C# application to create an array of 4 Employees. An


Employee will have Name, Id and BasicPay as data members.
Calculate the total of BasicPay of all the employees.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical3_Q2 : Form
{
public Practical3_Q2()
{
InitializeComponent();
}
Emp2[] emp = new Emp2[4];
int count = 0;

private void addEmp_Click(object sender, EventArgs e)


{
if(count<=3)
{
emp[count] = new Emp2
{
Name = nameTxt.Text,
EmpID = Convert.ToInt32(empidTxt.Text),
BasicPay = Convert.ToInt32(basicpayTxt.Text)
};
MessageBox.Show("Name: " + nameTxt.Text + " Employee ID: " +
empidTxt.Text + " Basic Pay: " + basicpayTxt.Text);
nameTxt.Text = "";
empidTxt.Text = "";
basicpayTxt.Text = "";
count++;
}
else
{
MessageBox.Show("You cannot insert more than 4 employees");
}
}

private void totalPay_Click(object sender, EventArgs e)


{
int total = 0;
foreach(var i in emp)

51 | P a g e
DES’s NMITD AWT Journal MC1944

{
total += i.BasicPay;
}
MessageBox.Show("Total of all employee basic pay is :" + total);
}
}
class Emp2
{
public string Name
{
get;
set;
}
public int EmpID
{
get;
set;
}
public int BasicPay
{
get;
set;
}
}
}

52 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

53 | P a g e
DES’s NMITD AWT Journal MC1944

V. Design a C# application to create a 3X2X2 int array and calculate the


total of all the elements.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Practical3_Q_3 : Form
{
public Practical3_Q_3()
{
InitializeComponent();
}
public int[,,] a = new int[,,]
{
{ { 1,2}, {3,4 } },
{ { 5,6}, {7,8 } },
{ { 9,10}, {11,12 } }
};
private void button1_Click(object sender, EventArgs e)
{
int total = 0;
for (int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
for(int k=0;k<2;k++)
{
total += a[i, j, k];
}
}
}
MessageBox.Show("Total of all element in array is: " + total);
}
}
}

54 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

55 | P a g e
DES’s NMITD AWT Journal MC1944

W. Design a C# application to create the following jagged int array and


display its elements.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string s = "";
private void button1_Click(object sender, EventArgs e)
{
int[][] jagged = new int[3][];
/*
jagged[0]=new int[3];
jagged[0][0]=1;
jagged[0][1]=2;
jagged[0][2]=3;

jagged[1]=new int[6];
jagged[1][0]=4;
jagged[1][1]=5;
jagged[1][2]=6;
jagged[1][3]=7;
jagged[1][4]=8;
jagged[1][5]=9;

jagged[2]=new int[4];
jagged[2][0]=10;
jagged[2][1]=11;
jagged[2][2]=12;
jagged[2][3]=13;
*/
jagged = new int[3][] { new int[3] { 1, 2, 3 }, new int[6] { 4, 5, 6, 7,
8, 9 }, new int[4] { 10, 11, 12, 13 } };

56 | P a g e
DES’s NMITD AWT Journal MC1944

for(int i=0;i<jagged.Length;i++)
{
s = "";
int[] intArray = jagged[i];
for(int a=0;a<intArray.Length;a++)
{
s += intArray[a] + " ";
}
MessageBox.Show("Inner Array " + (i + 1) + "'s values " + s);
}
Application.Exit();
}
}
}

Output:

57 | P a g e
DES’s NMITD AWT Journal MC1944

X. Design a C# application to create a 2-dimensional int array with


lowerbound {11,1} using Array class.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
int[] length = { 2, 2 };
int[] lowerbound = { 11, 1 };
string output = "";
Array FinalMarks = Array.CreateInstance(typeof(int), length,
lowerbound);
for(int i=lowerbound[0];i<lowerbound[0]+length[0];i++)
{
for(int j=lowerbound[1];j<lowerbound[1]+length[1];j++)
{
FinalMarks.SetValue(i + j * 10, i, j);
output += "Roll No " + i + " sub " + j + "--> " +
FinalMarks.GetValue(i, j)+" ";
}
output += Environment.NewLine;
}
MessageBox.Show(output);
}
}
}

58 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

59 | P a g e
DES’s NMITD AWT Journal MC1944

Y. Design a C# application to demonstrate the use of Copy() and


Clone(). a. Note: Use Array.Copy(source, destination, length)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class CopyClone : Form
{
public CopyClone()
{
InitializeComponent();
}

private void val_copy_Click(object sender, EventArgs e)


{
//Example of value type copy
int[] a = { 10, 20, 30, 40 };
int[] b = (int[])a.Clone();
int[] c = new int[3];
Array.Copy(a, c, 3);
//Changing value in original array
a[0] = 120;
foreach (var val in a)
{
original1.Text += val + Environment.NewLine;
}
foreach (var val in b)
{
clone1.Text += val + Environment.NewLine;
}
foreach (var val in c)
{
copy1.Text += val + Environment.NewLine;
}
}

private void userdef_copy_Click(object sender, EventArgs e)


{
//Example of refernce type copy
original2.Clear();
clone2.Clear();
copy2.Clear();
Books[] B = new Books[3];

60 | P a g e
DES’s NMITD AWT Journal MC1944

B[0] = new Books { BName = "Tata Mcgraw" };


B[1] = new Books { BName = "Wrox" };
B[2] = new Books { BName = "Pearson" };
Books[] BClone = (Books[])B.Clone();
Books[] BCopy = new Books[3];
Array.Copy(B, BCopy, 3);
B[0].BName = "o'Reilly";
foreach (var val in B)
{
original2.Text += val.BName + Environment.NewLine;
}
foreach (var val in BClone)
{
clone2.Text += val.BName + Environment.NewLine;
}
foreach (var val in BCopy)
{
copy2.Text += val.BName + Environment.NewLine;
}
}
}
class Books
{
public string BName
{
get;
set;
}
}
}

61 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

62 | P a g e
DES’s NMITD AWT Journal MC1944

Z. Design a C# application to sort Employee’s array based on their


Names. (Inherit from IComparable).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class SortExample : Form
{
public SortExample()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)


{
textBox2.Clear();
string[] str = textBox1.Text.Split('\n');
Array.Sort(str);
foreach(var val in str)
{
textBox2.Text += val + Environment.NewLine;
}
}

private void button1_Click(object sender, EventArgs e)


{
textBox2.Clear();
string[] strEmp = textBox1.Text.Split('\n');
Emp1[] E = new Emp1[strEmp.Length];
for(int i=0;i<strEmp.Length;i++)
{
E[i] = new Emp1 { EName = strEmp[i] };
}
Array.Sort(E);
foreach (var val in E)
{
textBox2.Text += val.EName + Environment.NewLine;
}
}
}
class Emp1 : IComparable<Emp1>
{
public string EName

63 | P a g e
DES’s NMITD AWT Journal MC1944

{
set;
get;
}
public int CompareTo(Emp1 obj)
{
int Result = this.EName.CompareTo(obj.EName);
MessageBox.Show(Result.ToString());
return Result;
}
}
}

Output:

64 | P a g e
DES’s NMITD AWT Journal MC1944

AA. C# application to overload ++ and + operator

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Eg1
{
public partial class AA : Form
{
public AA()
{
InitializeComponent();
}

private void label2_Click(object sender, EventArgs e)


{

private void button1_Click(object sender, EventArgs e)


{
Coord c1 = new Coord(Convert.ToInt32(textBox1.Text),
Convert.ToInt32(textBox2.Text));
Coord c2 = new Coord(Convert.ToInt32(textBox3.Text),
Convert.ToInt32(textBox4.Text));
Coord c3=new Coord();
c3 = c1 + c2;
c3.ShowXY3();
}

private void button2_Click(object sender, EventArgs e)


{
Coord c1 = new Coord(Convert.ToInt32(textBox1.Text),
Convert.ToInt32(textBox2.Text));
Coord c2 = new Coord();
c2 = ++c1;
c2.ShowXY();

Coord c3 = new Coord(Convert.ToInt32(textBox3.Text),


Convert.ToInt32(textBox4.Text));
Coord c4= new Coord();
c4 = ++c3;
c4.ShowXY1();
}
}

65 | P a g e
DES’s NMITD AWT Journal MC1944

class Coord
{
private int x;
private int y;
public Coord()
{

}
public Coord(int i,int j)
{
x = i;
y = j;
}
public void ShowXY()
{
MessageBox.Show("Number 1= " + x + " Number 2= " + y);
}
public void ShowXY1()
{
MessageBox.Show("Number 3= " + x + " Number 4= " + y);
}
public void ShowXY3()
{
MessageBox.Show("Number 1+Number 3= " + x + " Number
2+Number 4= " + y);
}
public static Coord operator ++(Coord c)
{
Coord temp = new Coord();
temp.x = ++c.x;
temp.y = ++c.y;
return temp;
}
public static Coord operator +(Coord c1,Coord c2)
{
Coord temp = new Coord();
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}
}
}

66 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

67 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO.2
A. C# application to simulate a Bank Account with exception handling

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac3
{
public partial class Bank : Form
{
Account a = new Account();
public Bank()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try
{
if (textBox1.Text.Equals("") || textBox2.Text.Equals(""))
throw new EmptyFields("Cannot be null");
string cname = textBox1.Text;

a.Check(textBox2.Text);
double amt = Convert.ToDouble(textBox2.Text);
a = new Account(cname, amt);
MessageBox.Show("Account Created");
listBox1.Items.Add(a.GetDetails());
}
catch (EmptyFields ef) {
ef.display();
MessageBox.Show(ef.Message);
}
catch (ArgumentException aex)
{
MessageBox.Show(aex.Message);
textBox2.Focus();
}
}
class Account {
private string CName {
get;
set;

68 | P a g e
DES’s NMITD AWT Journal MC1944

}
private double Balance {
get;
set;
}
public Account(String name, double bal) {
CName = name;
Balance = bal;
}
public Account() :this("",0.0) {
}

public void deposite(double amt) {


this.Balance += amt;
}
public void withdraw(double amt) {
if (this.Balance - amt < 1000)
throw new ArgumentException("Balance is too low... Should be
1000 after withdrawl.. Transaction cancelled");
Balance -= amt;
}
public string GetDetails() {
return "Name : " + CName + " Balance : " + Balance + " Date : " +
DateTime.Now + Environment.NewLine;
}
public void Check(String a) {
double r;
if (!double.TryParse(a, out r)) {
throw new ArgumentException("Amount is not in correct format");
}
}
}
class EmptyFields : Exception {
public EmptyFields(String msg) : base(msg) {

}
public void display() {
MessageBox.Show("Name and Amount can not be blank...");
}
}

private void button2_Click(object sender, EventArgs e)


{
listBox1.Items.Add(a.GetDetails());
}

private void button3_Click(object sender, EventArgs e)


{
try
{
a.Check(textBox2.Text);
a.deposite(Convert.ToDouble(textBox2.Text));

69 | P a g e
DES’s NMITD AWT Journal MC1944

MessageBox.Show("Amount Deposited");
listBox1.Items.Add(a.GetDetails());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void button4_Click(object sender, EventArgs e)


{
try
{
a.Check(textBox2.Text);
a.withdraw(Convert.ToDouble(textBox2.Text));
MessageBox.Show("Amount Withdraw");
listBox1.Items.Add(a.GetDetails());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

}
}
}

70 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

71 | P a g e
DES’s NMITD AWT Journal MC1944

72 | P a g e
DES’s NMITD AWT Journal MC1944

73 | P a g e
DES’s NMITD AWT Journal MC1944

B. C# application to calculate Simple Interest and Compound Interest


with Exception handling

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac3
{
public partial class Loan : Form
{
decimal p, n, r, si, t;
double ci;

public Loan()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
try {

p = Convert.ToDecimal(textBox1.Text);
n = Convert.ToDecimal(textBox2.Text);
r = Convert.ToDecimal(textBox3.Text);

if (p.Equals("") || n.Equals("") || r.Equals("")) {


throw new EmptyException("Enter principal,amount & no of years
& interest");
}
else if (p <= 0 || n <= 0 || r <= 0) {
throw new EmptyException("No of years and rate have to be
greater than 0");
}
else {
si = (p * n * r) / 100;
MessageBox.Show(si.ToString());

textBox5.Text = "Principal:- " + p + Environment.NewLine +


"No of Years:- " + n + Environment.NewLine + "Rate of Interest:-"
+ r + Environment.NewLine + "Simple Interest Gained:-" + si;
}
}
catch (EmptyException ex) {
MessageBox.Show(ex.Message.ToString());

74 | P a g e
DES’s NMITD AWT Journal MC1944

}
}

private void button2_Click(object sender, EventArgs e)


{
try
{

p = Convert.ToDecimal(textBox1.Text);
n = Convert.ToDecimal(textBox2.Text);
r = Convert.ToDecimal(textBox3.Text);
t = Convert.ToDecimal(textBox4.Text);

if (p.Equals("") || n.Equals("") || r.Equals(""))


{
throw new EmptyException("Enter principal,amount & no of years
& interest");
}
else if (p <= 0 || n <= 0 || r <= 0)
{
throw new EmptyException("No of years and rate have to be
greater than 0");
}
else
{
decimal rr = r / 100;
double res = Convert.ToDouble(1 + (rr / t));
double N = Convert.ToDouble(n);
double P = Convert.ToDouble(n);
double T = Convert.ToDouble(n);
double res1 = N * T;
ci = P * Math.Pow(res, res1);

textBox5.Text = "Principal:- " + p + Environment.NewLine +


"No of Years:- " + n + Environment.NewLine + "Rate of Interest:-"
+ r + Environment.NewLine + "Compunded Interest :-" + ci;
}
}
catch (EmptyException ex)
{
MessageBox.Show(ex.Message.ToString());

}
}

public class EmptyException : Exception {

public EmptyException(string message) :base(message) { }

}
}

75 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

76 | P a g e
DES’s NMITD AWT Journal MC1944

C. C# application to simulate a simple calculator

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac3
{
public partial class Cal : Form
{
Double resultValue = 0;
String operationPerformed = "";
bool isOperationPerformed = false;
public Cal()
{
InitializeComponent();
}

private void button_click(object sender, EventArgs e)


{
if ((textBox1.Text == "0") || (isOperationPerformed))
textBox1.Clear();

isOperationPerformed = false;
Button button = (Button)sender;

if (button.Text == ".")
{

if (!textBox1.Text.Contains("."))
{
textBox1.Text = textBox1.Text + button.Text;
}
}
else
{

textBox1.Text = textBox1.Text = textBox1.Text + button.Text;


}

private void operator_click(object sender, EventArgs e)


{
Button button = (Button)sender;

77 | P a g e
DES’s NMITD AWT Journal MC1944

if (resultValue != 0) {
button16.PerformClick();
operationPerformed = button.Text;
labelCurrentOperation.Text = resultValue + " " +
operationPerformed;
isOperationPerformed = true;
}
else
{
operationPerformed = button.Text;
resultValue = Double.Parse(textBox1.Text);
labelCurrentOperation.Text = resultValue + " " +
operationPerformed;
isOperationPerformed = true;
}

private void button5_Click(object sender, EventArgs e)


{
textBox1.Text = "0";
labelCurrentOperation.Text = " ";
}

private void button6_Click(object sender, EventArgs e)


{
textBox1.Text = "0";
resultValue = 0;
labelCurrentOperation.Text = " ";
}

private void button16_Click(object sender, EventArgs e)


{

try {

switch (operationPerformed)
{
case "+":
textBox1.Text = (resultValue +
Double.Parse(textBox1.Text)).ToString();
break;
case "-":
textBox1.Text = (resultValue -
Double.Parse(textBox1.Text)).ToString();
break;
case "*":
textBox1.Text = (resultValue *
Double.Parse(textBox1.Text)).ToString();
break;
case "/":

78 | P a g e
DES’s NMITD AWT Journal MC1944

textBox1.Text = (resultValue /
Double.Parse(textBox1.Text)).ToString();
break;
default: break;

}
resultValue = Double.Parse(textBox1.Text);
labelCurrentOperation.Text = "";

}
catch (Exception ae) {
MessageBox.Show(ae.Message);
}

}
}
}
Output :

79 | P a g e
DES’s NMITD AWT Journal MC1944

D. C# application to simulate a TODO app using ArrayList

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac1_1
{
public partial class Form1 : Form
{
ArrayList a1 = new ArrayList();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
a1.Add(textbox1.Text);
listBox1.Items.Add(textbox1.Text);
}

private void button2_Click(object sender, EventArgs e)


{
listBox1.Items.RemoveAt(a1.Count - 1);
a1.RemoveAt(a1.Count - 1);
listBox1.Refresh();
}
}
}

80 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

81 | P a g e
DES’s NMITD AWT Journal MC1944

E. C# application to maintain inventory of Laptops using List<>

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac1_1
{
public partial class Form1 : Form
{
List<string> laptops = new List<string>();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
laptops.Add(textbox1.Text);
listBox1.Items.Add(textbox1.Text);
}

private void button2_Click(object sender, EventArgs e)


{
listBox1.Items.Remove(textbox1.Text);
laptops.Remove(textbox1.Text);
listBox1.Refresh();
}

private void button3_Click(object sender, EventArgs e)


{
listBox1.Items.RemoveAt(laptops.Count - 1);
laptops.RemoveAt(laptops.Count - 1);
listBox1.Refresh();
}

}
}

82 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

83 | P a g e
DES’s NMITD AWT Journal MC1944

F. C# application to create a generic Swap function

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

static void Swap<T>(ref T lhs, ref T rhs)


{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}

private void button1_Click(object sender, EventArgs e)


{
int a, b;

a = Convert.ToInt16 (textBox1.Text);
b = Convert.ToInt16 (textBox2.Text);

//display values before swap:


MessageBox.Show ("Int values before calling swap:a = "+a+" b =
"+b );

//call swap
Swap<int>(ref a, ref b);

//display values after swap:


MessageBox.Show ("Int values after calling swap:a = " + a + " b = " +
b);
}
}
}

84 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

85 | P a g e
DES’s NMITD AWT Journal MC1944

G. C# application to implement generic Stack class

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prac1_1
{
public partial class Form1 : Form
{
Stack<Employee> stackEmployees = new Stack<Employee>();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
Employee emp = new Employee();
emp.Name = textbox1.Text;
emp.Salary = Convert.ToInt16(textBox2.Text);
stackEmployees.Push(emp);
listBox1.Items.Add($"Name: {textbox1.Text}, Salary:
{textBox2.Text}");
}

private void button2_Click(object sender, EventArgs e)


{
listBox1.Items.RemoveAt(stackEmployees.Count-1);
stackEmployees.Pop();
listBox1.Refresh();
}

public class Employee


{
public string Name { get; set; }
public int Salary { get; set; }
}
}
}

86 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

87 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO.3
A. File Information Application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace prac5
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string p = textBox1.Text;
DirectoryInfo theDir = new DirectoryInfo(p);
listBox1.Items.Clear();
listBox2.Items.Clear();

textBox2.Text = theDir.FullName;
string CurrentFolderPath = theDir.FullName;

if (theDir.Exists) {

foreach (DirectoryInfo nextFolder in theDir.GetDirectories())


listBox2.Items.Add(nextFolder.Name);

foreach (FileInfo files in theDir.GetFiles())


listBox1.Items.Add(files);
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
string selFile = listBox1.SelectedItem.ToString();
MessageBox.Show(selFile.ToString());

string CurrentFolderPath = textBox1.Text;

88 | P a g e
DES’s NMITD AWT Journal MC1944

string FilePath = Path.Combine(CurrentFolderPath,selFile);

FileInfo currFile = new FileInfo(FilePath);

textBox3.Text = currFile.FullName;

textBox4.Text = currFile.FullName.Length.ToString();
textBox5.Text = currFile.CreationTime.ToLongTimeString();
textBox7.Text = currFile.LastWriteTime.ToLongDateString();
textBox6.Text = currFile.LastAccessTime.ToLongDateString();

private void button3_Click(object sender, EventArgs e)


{
File.Move(textBox3.Text, textBox8.Text);
MessageBox.Show("File Moved");
}

private void button4_Click(object sender, EventArgs e)


{
File.Copy(textBox3.Text,textBox8.Text);
MessageBox.Show("File Copied");
}

private void button2_Click(object sender, EventArgs e)


{
DirectoryInfo theDrive = new DirectoryInfo(textBox1.Text);
textBox2.Text = theDrive.Parent.FullName;
}

private void button5_Click(object sender, EventArgs e)


{
File.Delete(textBox8.Text);
}
}
}

89 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

90 | P a g e
DES’s NMITD AWT Journal MC1944

91 | P a g e
DES’s NMITD AWT Journal MC1944

92 | P a g e
DES’s NMITD AWT Journal MC1944

93 | P a g e
DES’s NMITD AWT Journal MC1944

B.Read and Write Files using FILE class

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace prac5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
textBox2.Text += File.ReadAllText(textBox1.Text);

private void button2_Click(object sender, EventArgs e)


{
File.WriteAllText(textBox1.Text,textBox2.Text);
}
}
}

Output :

94 | P a g e
DES’s NMITD AWT Journal MC1944

95 | P a g e
DES’s NMITD AWT Journal MC1944

C.Read and Write Files using FileStream

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace prac5
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
String p = textBox1.Text;

FileStream fs = new FileStream(p,FileMode.Open,FileAccess.Read);

int b = fs.ReadByte();

while (b != -1) {
textBox2.Text += (char)b;
b = fs.ReadByte();
}
fs.Close();
}

private void button2_Click(object sender, EventArgs e)


{
String p = textBox1.Text;
FileStream fs = new FileStream(p,FileMode.OpenOrCreate |
FileMode.Append,FileAccess.Write);
byte nextByte;
string str = textBox2.Text;

for (int i = 0; i < str.Length; i++) {


nextByte = Convert.ToByte(str[i]);
fs.WriteByte(nextByte);
}
fs.Close();
}
}
}

96 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

97 | P a g e
DES’s NMITD AWT Journal MC1944

98 | P a g e
DES’s NMITD AWT Journal MC1944

D. Read and Write Files using StreamReader and StreamWriter

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace prac5
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
String p = textBox1.Text;
StreamReader sr = new StreamReader(p);
while (!sr.EndOfStream)
{
textBox2.Text += sr.ReadLine();
}
sr.Close();

private void button2_Click(object sender, EventArgs e)


{
String p = textBox1.Text;
StreamWriter sw = new StreamWriter(p, true);
sw.WriteLine(textBox2.Text);
sw.Close();
}
}
}

99 | P a g e
DES’s NMITD AWT Journal MC1944

Output :

100 | P a g e
DES’s NMITD AWT Journal MC1944

E. Notepad Application with MenuStrip, ToolStrip, FontDialog,


ColorDialog, OpenFileDialog, SaveFileDialog.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace prac5
{
public partial class NotepadApp : Form
{
public NotepadApp()
{
InitializeComponent();
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
Application.Exit();
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)


{
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK) {
string str = op.FileName;
textBox1.Text = File.ReadAllText(str);
}
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


{
SaveFileDialog sv = new SaveFileDialog();
if (sv.ShowDialog() == DialogResult.OK) {
string str = sv.FileName;
File.WriteAllText(textBox1.Text,str);
}
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
textBox1.Clear();
textBox1.Focus();
}

101 | P a g e
DES’s NMITD AWT Journal MC1944

private void copyToolStripMenuItem_Click(object sender, EventArgs e)


{
textBox1.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{
textBox1.Paste();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{
textBox1.Cut();
}

private void toolStripButton1_Click(object sender, EventArgs e)


{
textBox1.Font = new Font("Arial",12,FontStyle.Bold);

private void toolStripButton2_Click(object sender, EventArgs e)


{
textBox1.Font = new Font("Arial", 12, FontStyle.Italic);
}

private void toolStripButton3_Click(object sender, EventArgs e)


{
textBox1.Font = new Font("Arial", 12, FontStyle.Underline);
}

private void toolStripButton4_Click(object sender, EventArgs e)


{
if (fontDialog1.ShowDialog() == DialogResult.OK) {
textBox1.Font = fontDialog1.Font;
}
}

private void toolStripButton5_Click(object sender, EventArgs e)


{
if (colorDialog1.ShowDialog() !=
System.Windows.Forms.DialogResult.Cancel)
{
textBox1.ForeColor = colorDialog1.Color;
}
}
}
}

Output :
102 | P a g e
DES’s NMITD AWT Journal MC1944

103 | P a g e
DES’s NMITD AWT Journal MC1944

104 | P a g e
DES’s NMITD AWT Journal MC1944

105 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO.4
A. Bank Application Connected DB -> Change ListView View to Detail

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Eg1
{
public partial class DatabaseEg1 : Form
{
public DatabaseEg1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
listView1.Items.Clear();
listView1.Columns.Clear();
OleDbConnection con = new OleDbConnection();
con.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Owner\Documents\EmpDB.mdb";
con.Open();
string selstring = "select * from Table1";
OleDbCommand cmd = new OleDbCommand(selstring, con);
OleDbDataReader dr = cmd.ExecuteReader();
for(int i=0;i<dr.FieldCount;i++)
{
listView1.Columns.Add(dr.GetName(i));
}
ListViewItem lv1 = new ListViewItem();
while(dr.Read())
{
lv1 = new ListViewItem(dr[0].ToString());
lv1.SubItems.Add(dr[1].ToString());
lv1.SubItems.Add(dr[2].ToString());
lv1.SubItems.Add(dr[3].ToString());
listView1.Items.Add(lv1);
}
dr.Close();
con.Close();
}

106 | P a g e
DES’s NMITD AWT Journal MC1944

private void button2_Click(object sender, EventArgs e)


{
string str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Owner\Documents\EmpDB.mdb";
OleDbConnection con = new OleDbConnection(str);
con.Open();
string qry = "insert into Table1
values(@EmpId,@EmpName,@EmpDesin,@Location)";
OleDbCommand cmd = new OleDbCommand(qry, con);

OleDbParameter param = new OleDbParameter();


param.ParameterName = "@EmpId";
param.Value = Convert.ToInt16(textBox1.Text);
cmd.Parameters.Add(param);

param = new OleDbParameter();


param.ParameterName = "@EmpName";
param.Value = textBox2.Text;
cmd.Parameters.Add(param);

param = new OleDbParameter();


param.ParameterName = "@EmpDesin";
param.Value = textBox3.Text;
cmd.Parameters.Add(param);

param = new OleDbParameter();


param.ParameterName = "@Location";
param.Value = textBox4.Text;
cmd.Parameters.Add(param);

cmd.ExecuteScalar();
con.Close();

listView1.Items.Clear();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Focus();
button1_Click(sender,e);
}
}
}

Output :
107 | P a g e
DES’s NMITD AWT Journal MC1944

B. Bank Application Disconnected DB

108 | P a g e
DES’s NMITD AWT Journal MC1944

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace DBprac
{
public partial class Form3 : Form
{
DataSet ds;
OleDbDataAdapter da;
OleDbConnection con;
OleDbCommandBuilder bldr;

public Form3()
{
InitializeComponent();
}

private void Form3_Load(object sender, EventArgs e)


{
con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=F:\accessDB\EmpDB.mdb");
}
private void display()
{
da = new OleDbDataAdapter("Select * from EmpMaster", con);
ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds, "Emp");
bldr = new OleDbCommandBuilder(da);
dataGridView1.DataSource = ds.Tables["Emp"];
}

private void button1_Click(object sender, EventArgs e)


{
display();
}

private void button2_Click(object sender, EventArgs e)


{
DataRow drnew = ds.Tables["Emp"].NewRow();
drnew[0] = textBox1.Text;
drnew[1] = textBox2.Text;
drnew[2] = textBox3.Text;
drnew[3] = textBox4.Text;

109 | P a g e
DES’s NMITD AWT Journal MC1944

ds.Tables["Emp"].Rows.Add(drnew);
da.Update(ds, "Emp");
MessageBox.Show("Record added");
dataGridView1.DataSource = ds.Tables["Emp"];
}

private void button3_Click(object sender, EventArgs e)


{
DataRow dr = ds.Tables[0].Rows.Find(textBox1.Text);
dr["EmpName"] = textBox2.Text;
dr["EmpDesign"] = textBox3.Text;
dr["Location"] = textBox4.Text;
da.Update(ds, "Emp");
MessageBox.Show("updated..");
dataGridView1.DataSource = ds.Tables[0];

private void button4_Click(object sender, EventArgs e)


{
DataRow row =
ds.Tables["Emp"].Rows.Find(Convert.ToInt32(textBox1.Text));
row.Delete();
da.Update(ds, "Emp");
MessageBox.Show("Record Deleted");
dataGridView1.DataSource = ds.Tables["Emp"];
}

private void button5_Click(object sender, EventArgs e)


{

this.BindingContext[ds.Tables[0]].Position = 0;

private void button8_Click(object sender, EventArgs e)


{

this.BindingContext[ds.Tables[0]].Position = ds.Tables[0].Rows.Count -
1;

private void button6_Click(object sender, EventArgs e)


{

if (this.BindingContext[ds.Tables[0]].Position <
ds.Tables[0].Rows.Count - 1)
{
this.BindingContext[ds.Tables[0]].Position += 1;
}

110 | P a g e
DES’s NMITD AWT Journal MC1944

private void button7_Click(object sender, EventArgs e)


{
if (this.BindingContext[ds.Tables[0]].Position > 0)
{
this.BindingContext[ds.Tables[0]].Position -= 1;
}
}
}
}
Output :

C. Data Tools (GridView, ToolStrip, BindingNavigator)


Step 1: Drag and Drop BindingNavigator and GridView

111 | P a g e
DES’s NMITD AWT Journal MC1944

Step 2: For attaching BindingNavigator and GridView, Drag and drop Binding
Source. It will not seen on windows for but it will be outside the window form.
Step 3: Configure BindingSource
- Configure Data Source to database
- Configure Data Member to Table

Step 4: Attach BindingNavigator


BindingSource using BindingSource
property
attach GridView to BindingSource
using DataSource property

Output :

PRACTICAL NO. 5

112 | P a g e
DES’s NMITD AWT Journal MC1944

Design the above application to query


 Int Array
 Var Multidimensional Array
 Access DB
Output:

On Load Random button click

On Even No’s button click

113 | P a g e
DES’s NMITD AWT Journal MC1944

On Range No’s click

114 | P a g e
DES’s NMITD AWT Journal MC1944

On Load Access DB

On Find Employee

115 | P a g e
DES’s NMITD AWT Journal MC1944

On Load Array click

On search Array click

116 | P a g e
DES’s NMITD AWT Journal MC1944

ASP.NET

117 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO. 6
A. Page Events

Solution:

using System;

namespace asp_practicals.practical_1 {

public partial class title101: System.Web.UI.Page {

protected void Page_PreInit(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "PreInit";

protected void Page_Init(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "Init";

protected void Page_InitComplete(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "InitComplete";

protected override void OnPreLoad(EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "PreLoad";

protected void Page_Load(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "Load";

protected void Button1_Click(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "btnSubmit_Click";

protected void Page_LoadComplete(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "LoadComplete";

protected override void OnPreRender(EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "PreRender";

protected override void OnSaveStateComplete(EventArgs e) {

118 | P a g e
DES’s NMITD AWT Journal MC1944

lblName.Text = lblName.Text + "<br/>" + "SaveStateComplete";

protected void Page_UnLoad(object sender, EventArgs e) {

lblName.Text = lblName.Text + "<br/>" + "UnLoad";

Output:

119 | P a g e
DES’s NMITD AWT Journal MC1944

120 | P a g e
DES’s NMITD AWT Journal MC1944

B. PostBack and CrossPage Posting

Solution:

Title102.aspx

using System;

namespace asp_practicals.practical_1 {

public partial class title102: System.Web.UI.Page {

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

protected void Button1_Click(object sender, EventArgs e) {

Label1.Text = "Hello" + TextBox1.Text + "<br/>" + "Your date of birth is" +


Calendar1.SelectedDate.ToShortDateString();

title102_add_on.aspx

using System;

using System.Web.UI.WebControls;

namespace asp_practicals.practical_1 {

public partial class title102_add_on: System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

TextBox textbox2;

Calendar calender2;

textbox2 = (TextBox) PreviousPage.FindControl("TextBox1");

calender2 = (Calendar) PreviousPage.FindControl("Calendar1");

Label1.Text = "Hello" + textbox2.Text + "<br/>" + " Your date of birth is "


+ calender2.SelectedDate.ToShortDateString();

121 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

122 | P a g e
DES’s NMITD AWT Journal MC1944

C. Web Server Controls

Solution:

using System;

namespace asp_practicals.practical_1 {

public partial class title103: System.Web.UI.Page {

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

protected void Button1_Click(object sender, EventArgs e) {

Literal1.Text = "<h3><marquee>AWT Semester 4</marquee></h3>";

protected void Button2_Click(object sender, EventArgs e) {

if (FileUpload1.HasFile) {

FileUpload1.SaveAs(@ "D:\MCA\AWT\Practical\asp.net web practicals\asp


practicals\practical_1\images\" + FileUpload1.FileName);

Label4.Text = "File uploaded successfully";

else {

Label4.Text = "Please select file";

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)


{

if (RadioButton1.Checked) {

Label3.Text = "You are Male";

} else {

Label3.Text = "You are Male";

protected void RadioButton2_CheckedChanged(object sender, EventArgs e)


{

if (RadioButton2.Checked) {

Label3.Text = "You are Female";

} else {

123 | P a g e
DES’s NMITD AWT Journal MC1944

Label3.Text = "You are Male";

protected void Button3_Click(object sender, EventArgs e) {

Label3.Text = "Welcome " + TextBox1.Text + " Your image file " +


FileUpload1.FileName + " is uploaded ";

Image2.ImageUrl = @ "~\images\" + FileUpload1.FileName;

Image2.Visible = true;

Output:

124 | P a g e
DES’s NMITD AWT Journal MC1944

D. Validation Controls

Solution:

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


CodeBehind="title104.aspx.cs" Inherits="asp_practicals.practical_1.title104"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

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

function ValidateNo(){

if((parseInt(document.forms[0].TextBox6.value)%2)==0){

alert("Even Number");

else {

alert("Odd Number");

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

Enter your
name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" ErrorMessage="This is required
field" ForeColor="#990000">*</asp:RequiredFieldValidator>

<br />

<br />

125 | P a g e
DES’s NMITD AWT Journal MC1944

Enter
password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;

<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>

<br />

<br />

Enter confirm password:

<asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>

<br />

<br />

Enter age:

<asp:TextBox ID="TextBox9" runat="server"></asp:TextBox>

<br />

<br />

Enter your
email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb
sp;

<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox5"
ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-
+.']\w+)*@\w+([-.]\w+)*\.\w+
([-.]\w+)*"></asp:RegularExpressionValidator>

<br />

<br />

Enter Random No.:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:CustomValidator ID="CustomValidator1" runat="server"


ControlToValidate="TextBox6" ErrorMessage="CustomValidator"
ClientValidationFunction="ValidateNo"></asp:CustomValidator>

<br />

<br />

126 | P a g e
DES’s NMITD AWT Journal MC1944

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


Text="submit" />

<br />

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />

<br />

</div>

</form>

</body>

</html>

Output:

127 | P a g e
DES’s NMITD AWT Journal MC1944

128 | P a g e
DES’s NMITD AWT Journal MC1944

E. Design a e-Commerce WebSite using MasterPage, Theme and Skins.

Solution:

Site.master

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


CodeBehind="Site1.master.cs"
Inherits="asp_practicals.practical_1.title105.Site1" %>

<!DOCTYPE html>

<html>

<head runat="server">

<title></title>

<asp:ContentPlaceHolder ID="head"
runat="server"></asp:ContentPlaceHolder>

<style type="text/css">

.auto-style1 {

height: 51px;

</style>

</head>

<body>

<form id="form1" runat="server">

<table border="1">

<tr>

<td style="text-align: center" colspan="2" class="auto-style1">

<h1>Welcome to ABC Shopping World</h1>

</td>

</tr>

<tr>

<td style="width:40%; background-color: Aqua">

<asp:ContentPlaceHolder ID="ContentPlaceHolder1"
runat="server"></asp:ContentPlaceHolder>

</td>

<td style="width:60%">

129 | P a g e
DES’s NMITD AWT Journal MC1944

<asp:Image ID="Image1" Width="250px" runat="server"


ImageUrl="~/practical_1/images/shop.png" />

<asp:ContentPlaceHolder ID="ContentPlaceHolder2"
runat="server"></asp:ContentPlaceHolder>

</td>

</tr>

<tr>

<td style="width:40%; background-color: red">

<asp:Label ID="Label1" runat="server" Text="Copyright to DES's


NMITD"></asp:Label>

</td>

<td style="width:60%">

<asp:ContentPlaceHolder ID="ContentPlaceHolder3"
runat="server"></asp:ContentPlaceHolder>

</td>

</tr>

</table>

</form>

</body>

</html>

130 | P a g e
DES’s NMITD AWT Journal MC1944

Title105.aspx

<%@ Page Title="" Language="C#"


MasterPageFile="~/practical_1/title105/Site1.Master" AutoEventWireup="true"
CodeBehind="title105.aspx.cs"
Inherits="asp_practicals.practical_1.title105.title105" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head"


runat="server"></asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"


runat="server">

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2"


runat="server">

<p>

Enter your Name:

<asp:TextBox ID="TextBox1" runat="server"


EnableTheming="False"></asp:TextBox>

</p>

<p>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:Button ID="Button1" runat="server" Text="Submit"


OnClick="Button1_Click" />

</p>

</asp:Content>

<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder3"


runat="server">

<p>

<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</p>

</asp:Content>

131 | P a g e
DES’s NMITD AWT Journal MC1944

Title105.aspx.cs

using System;

namespace asp_practicals.practical_1.title105 {

public partial class title105: System.Web.UI.Page {

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

protected void Button1_Click(object sender, EventArgs e) {

Label2.Text = "Welcome: " + TextBox1.Text;

Output:

132 | P a g e
DES’s NMITD AWT Journal MC1944

133 | P a g e
DES’s NMITD AWT Journal MC1944

F. Use AJAX controls to change Banner AD’s after every second, make
use of Ad rotator Control.

Solution:

XMLFile1.xml

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

<Advertisements>

<Ad>

<ImageUrl>~/practical_1/images/google.jpg</ImageUrl>

<NavigateUrl>http://www.google.com</NavigateUrl>

<AlternateText>Visit Google.com</AlternateText>

<Impressions>80</Impressions>

<Keyword>Search</Keyword>

</Ad>

<Ad>

<ImageUrl>~/practical_1/images/yahoo.jpg</ImageUrl>

<NavigateUrl>http://www.yahoo.com</NavigateUrl>

<AlternateText>Visit Yahoo.com</AlternateText>

<Impressions>80</Impressions>

<Keyword>Search</Keyword>

</Ad>

<Ad>

<ImageUrl>~/practical_1/images/msn.jpg</ImageUrl>

<NavigateUrl>http://www.msn.com</NavigateUrl>

<AlternateText>Visit msn.com</AlternateText>

<Impressions>80</Impressions>

<Keyword>Search</Keyword>

</Ad>

</Advertisements>

134 | P a g e
DES’s NMITD AWT Journal MC1944

Title106.aspx

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


CodeBehind="title106.aspx.cs" Inherits="asp_practicals.practical_1.title6" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h1>AJAX controls to change Banner AD’s after every second</h1>

<br />

<asp:ScriptManager ID="ScriptManager1"
runat="server"></asp:ScriptManager>

<br />

<br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Timer runat="server" ID="Timer1" Interval="1000">

</asp:Timer>

<asp:AdRotator ID="AdRotator1" runat="server"


AdvertisementFile="XMLFile1.xml" />

<br />

</ContentTemplate>

</asp:UpdatePanel>

<br />

</div>

</form>

</body>

</html>

135 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

136 | P a g e
DES’s NMITD AWT Journal MC1944

137 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO. 7
A. Login and CreateUserWizard

Solution:

Title201.aspx

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


CodeBehind="title201.aspx.cs" Inherits="asp_practicals.practical_2.title201"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"


BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderStyle="Solid"
BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em"
OnCreatedUser="CreateUserWizard1_CreatedUser">

<ContinueButtonStyle BackColor="White" BorderColor="#CC9966"


BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
ForeColor="#990000" />

<CreateUserButtonStyle BackColor="White" BorderColor="#CC9966"


BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
ForeColor="#990000" />

<TitleTextStyle BackColor="#990000" Font-Bold="True"


ForeColor="White" />

<WizardSteps>

<asp:CreateUserWizardStep ID="CreateUserWizardStep1"
runat="server"></asp:CreateUserWizardStep>

<asp:CompleteWizardStep ID="CompleteWizardStep1"
runat="server"></asp:CompleteWizardStep>

</WizardSteps>

<HeaderStyle BackColor="#FFCC66" BorderColor="#FFFBD6"


BorderStyle="Solid" BorderWidth="2px" Font-Bold="True" Font-Size="0.9em"
ForeColor="#333333" HorizontalAlign="Center" />

138 | P a g e
DES’s NMITD AWT Journal MC1944

<NavigationButtonStyle BackColor="White" BorderColor="#CC9966"


BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
ForeColor="#990000" />

<SideBarButtonStyle ForeColor="White" />

<SideBarStyle BackColor="#990000" Font-Size="0.9em"


VerticalAlign="Top" />

</asp:CreateUserWizard>

<br />

</div>

</form>

</body>

</html>

Title201(login).aspx

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


CodeBehind="tilte201(login).aspx.cs"
Inherits="asp_practicals.practical_2.tilte201_login_" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Login ID="Login1" runat="server" BackColor="#FFFBD6"


BorderColor="#FFDFAD" BorderPadding="4" BorderStyle="Solid"
BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em"
ForeColor="#333333" OnLoggedIn="Login1_LoggedIn"
TextLayout="TextOnTop">

<InstructionTextStyle Font-Italic="True" ForeColor="Black" />

<LoginButtonStyle BackColor="White" BorderColor="#CC9966"


BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-
Size="0.8em" ForeColor="#990000" />

<TextBoxStyle Font-Size="0.8em" />

139 | P a g e
DES’s NMITD AWT Journal MC1944

<TitleTextStyle BackColor="#990000" Font-Bold="True" Font-


Size="0.9em" ForeColor="White" />

</asp:Login>

<br />

</div>

</form>

</body>

</html>

Title201.aspx.cs

using System;

namespace asp_practicals.practical_2 {

public partial class title201: System.Web.UI.Page {

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

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) {

Response.Redirect("~/practical_2/tilte201(login).aspx");

Title201(login).aspx.cs

using System;

namespace asp_practicals.practical_2 {

public partial class tilte201_login_: System.Web.UI.Page {

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

protected void Login1_LoggedIn(object sender, EventArgs e) {

Response.Redirect("~/practical_2/title201(Successfull).aspx");

140 | P a g e
DES’s NMITD AWT Journal MC1944

Title201(success).aspx

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


CodeBehind="title201(Successfull).aspx.cs"
Inherits="asp_practicals.practical_2.title201_Successfull_" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="lbl_msg" runat="server" Text="SuccessFull Login"


Font-Bold="True" Font-Size="Larger" ForeColor="#33CC33"></asp:Label>

</div>

</form>

</body>

</html>

Output:

141 | P a g e
DES’s NMITD AWT Journal MC1944

142 | P a g e
DES’s NMITD AWT Journal MC1944

B. GridView with AccessDataSource

Solution:

Title202.aspx

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


CodeBehind="title202.aspx.cs" Inherits="asp_practicals.practical_2.title202"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" runat="server" CellPadding="4"


ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="accessDB_1">

<AlternatingRowStyle BackColor="White" />

<Columns>

<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"


ReadOnly="True" SortExpression="ID">

<HeaderStyle HorizontalAlign="Center" />

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="c_name" HeaderText="c_name"


SortExpression="c_name">

<HeaderStyle HorizontalAlign="Center" />

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="pan_card" HeaderText="pan_card"


SortExpression="pan_card">

<HeaderStyle HorizontalAlign="Center" />

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

143 | P a g e
DES’s NMITD AWT Journal MC1944

<asp:BoundField DataField="age" HeaderText="age"


SortExpression="age">

<HeaderStyle HorizontalAlign="Center" />

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="acc_bal" HeaderText="acc_bal"


SortExpression="acc_bal">

<HeaderStyle HorizontalAlign="Center" />

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

</Columns>

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White"


/>

<HeaderStyle BackColor="#990000" Font-Bold="True"


ForeColor="White" />

<PagerStyle BackColor="#FFCC66" ForeColor="#333333"


HorizontalAlign="Center" />

<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"


ForeColor="Navy" />

<SortedAscendingCellStyle BackColor="#FDF5AC" />

<SortedAscendingHeaderStyle BackColor="#4D0000" />

<SortedDescendingCellStyle BackColor="#FCF6C0" />

<SortedDescendingHeaderStyle BackColor="#820000" />

</asp:GridView>

<br />

<asp:accessdatasource ID="accessDB_1" runat="server"


DataFile="~/Access_DB/Database1.mdb" SelectCommand="SELECT * FROM
[emp]"></asp:accessdatasource>

</div>

</form>

</body>

</html>

144 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

145 | P a g e
DES’s NMITD AWT Journal MC1944

C. GridView with SQLDataSource

Solution:

Title203.aspx

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


CodeBehind="title203.aspx.cs" Inherits="asp_practicals.practical_2.title203"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<style>

table, th, td {

border: 1px solid black;

margin:5px;

padding:5px;

</style>

</head>

<body>

<form id="form1" runat="server">

<h2>Account Info</h2>

<table style="width:50%;">

<tr>

<td>ACCOUNTS INFO:</td>

<td></td>

</tr>

<tr>

<td>Enter CustomerID:</td>

<td>

<asp:TextBox ID="txt_cut_id" runat="server"></asp:TextBox>

&nbsp;&nbsp;

146 | P a g e
DES’s NMITD AWT Journal MC1944

<asp:Button ID="btn_ok" runat="server" Text="OK"


OnClick="btn_ok_Click" />

</td>

</tr>

<tr>

<td>

VIEW

<asp:LinkButton ID="lnk_all_cust" OnClick="lnk_all_cust_Click"


runat="server">ALL Customers</asp:LinkButton>

</td>

<td>

<asp:GridView ID="GridView1" runat="server" CellPadding="4"


ForeColor="#333333" GridLines="None">

<AlternatingRowStyle BackColor="White" ForeColor="#284775" />

<EditRowStyle BackColor="#999999" />

<FooterStyle BackColor="#5D7B9D" Font-Bold="True"


ForeColor="White" />

<HeaderStyle BackColor="#5D7B9D" Font-Bold="True"


ForeColor="White" />

<PagerStyle BackColor="#284775" ForeColor="White"


HorizontalAlign="Center" />

<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True"


ForeColor="#333333" />

<SortedAscendingCellStyle BackColor="#E9E7E2" />

<SortedAscendingHeaderStyle BackColor="#506C8C" />

<SortedDescendingCellStyle BackColor="#FFFDF8" />

<SortedDescendingHeaderStyle BackColor="#6F8DAE" />

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="<%$ ConnectionStrings:SQLserverConnection %>"
ProviderName="<%$ ConnectionStrings:SQLserverConnection.ProviderName
%>"></asp:SqlDataSource>

</td>

</tr>

147 | P a g e
DES’s NMITD AWT Journal MC1944

<tr>

<td>BRANCH INFO:</td>

<td></td>

</tr>

<tr>

<td>BRANCH NAME:</td>

<td>

<asp:DropDownList ID="ddl_branchId" AutoPostBack="true"


runat="server" DataSourceID="SqlDataSource2" DataTextField="BranchId"
DataValueField="BranchId"
OnSelectedIndexChanged="ddl_name_SelectedIndexChanged"></asp:DropDow
nList>

<asp:SqlDataSource ID="SqlDataSource2" runat="server"


ConnectionString="<%$ ConnectionStrings:SQLserverConnection %>"
SelectCommand="SELECT [BranchId] FROM
[AccMaster]"></asp:SqlDataSource>

</td>

</tr>

</table>

</form>

</body>

</html>

Title203.aspx.cs

using System;

using System.Data.SqlClient;

using System.Configuration;

namespace asp_practicals.practical_2 {

public partial class title203: System.Web.UI.Page {

private static string connstr =


ConfigurationManager.ConnectionStrings["SQLserverConnection"].ConnectionStri
ng;

SqlConnection conn = new SqlConnection(connstr);

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

protected void lnk_all_cust_Click(object sender, EventArgs e) {

148 | P a g e
DES’s NMITD AWT Journal MC1944

SqlDataSource1.SelectCommand = "select * from [dbo].[AccMaster]";

SqlDataSource1.DataBind();

GridView1.DataSource = SqlDataSource1;

GridView1.DataBind();

protected void btn_ok_Click(object sender, EventArgs e) {

string qry = "select * from [dbo].[AccMaster] where AcNo=@AcNo";

conn.Open();

SqlCommand cmd = new SqlCommand(qry, conn);

cmd.Parameters.AddWithValue("@AcNo", txt_cut_id.Text);

GridView1.DataSource = cmd.ExecuteReader();

GridView1.DataBind();

conn.Close();

protected void ddl_name_SelectedIndexChanged(object sender, EventArgs e)


{

conn.Open();

string cmd_select = "select* from[dbo].[AccMaster] where


BranchId=@BranchId";

SqlCommand cmd = new SqlCommand(cmd_select, conn);

cmd.Parameters.AddWithValue("@BranchId", ddl_branchId.SelectedValue);

GridView1.DataSource = cmd.ExecuteReader();

GridView1.DataBind();

conn.Close();

149 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

D. GridView with ObjectDataSourceCode:

150 | P a g e
DES’s NMITD AWT Journal MC1944

Solution:

Title204.aspx

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


CodeBehind="title204.aspx.cs" Inherits="asp_practicals.practical_2.title204"
%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" runat="server" CellPadding="4"


ForeColor="#333333" GridLines="None" DataSourceID="ObjectDataSource1">

<AlternatingRowStyle BackColor="White" />

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White"


/>

<HeaderStyle BackColor="#990000" Font-Bold="True"


ForeColor="White" />

<PagerStyle BackColor="#FFCC66" ForeColor="#333333"


HorizontalAlign="Center" />

<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"


ForeColor="Navy" />

<SortedAscendingCellStyle BackColor="#FDF5AC" />

<SortedAscendingHeaderStyle BackColor="#4D0000" />

<SortedDescendingCellStyle BackColor="#FCF6C0" />

<SortedDescendingHeaderStyle BackColor="#820000" />

</asp:GridView>

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"


SelectMethod="GetCustomerDetail"
TypeName="asp_practicals.practical_2.helper"></asp:ObjectDataSource>

</div>

151 | P a g e
DES’s NMITD AWT Journal MC1944

</form>

</body>

</html>

Output:

152 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO. 8
A. View State Example

Solution:

Code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace WebApplication1 {

public partial class WebForm6: System.Web.UI.Page {

int count = 0;

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

TextBox1.Text = "0";

protected void Button1_Click(object sender, EventArgs e) {

count++;

TextBox1.Text = count.ToString();

protected void Button2_Click(object sender, EventArgs e) {

if (ViewState["clk"] != null) {

count = (int) ViewState["clk"] + 1;

TextBox1.Text = count.ToString();

ViewState["clk"] = count;

153 | P a g e
DES’s NMITD AWT Journal MC1944

Note: Set EnableViewState property to True in form source

Output:

Using View State

On Submit Button

154 | P a g e
DES’s NMITD AWT Journal MC1944

B. Cookies with Multiple Keys

Solution:

Cookie Form:

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class WebForm7: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


HttpCookie cookie1 = new HttpCookie("Info");
cookie1["Fname"] = TextBox1.Text;
cookie1["Lname"] = TextBox2.Text;

Response.Cookies.Add(cookie1);
Response.Write("Cookie Created");
}

protected void Button2_Click(object sender, EventArgs e) {


Response.Cookies["Info"].Value = null;
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(-1);
}
}
}
Cookie Read:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class CookieRead: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
HttpCookie ck1 = Request.Cookies["Info"];
if (ck1 != null) {
Label1.Text = ck1["Fname"];

155 | P a g e
DES’s NMITD AWT Journal MC1944

Label2.Text = ck1["Lname"];
}
}
}
}

Output:
Create Cookie

Show Cookie

Delete Cookie

C. Login Application CookiesCode:

156 | P a g e
DES’s NMITD AWT Journal MC1944

Solution:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

namespace WebApplication1 {

public partial class WebForm8: System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

if (Request.Cookies["username"] != null) {

TextBox1.Text = Request.Cookies["username"].Value;

if (Request.Cookies["password"] != null) {

TextBox1.Text = Request.Cookies["password"].Value;

if (Request.Cookies["username"] != null && Request.Cookies["password"] !


= null) {

CheckBox1.Checked = true;

protected void Button1_Click(object sender, EventArgs e) {

SqlConnection con = new SqlConnection(@ "Data Source=DESKTOP-


0NRI8FC;Initial Catalog=demo;Integrated Security=True");

157 | P a g e
DES’s NMITD AWT Journal MC1944

string query = "Select username,password from login where username='" +


TextBox1.Text + "' and password='" + TextBox2.Text + "'";

SqlCommand cmd = new SqlCommand(query, con);

SqlDataAdapter adapt = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

adapt.Fill(ds);

if (ds.Tables[0].Rows.Count > 0) {

if (CheckBox1.Checked == true) {

Response.Cookies["username"].Value = TextBox1.Text;

Response.Cookies["password"].Value = TextBox2.Text;

Response.Cookies["username"].Expires = DateTime.Now.AddDays(15);

Response.Cookies["password"].Expires = DateTime.Now.AddDays(15);

} else {

Response.Cookies["username"].Expires = DateTime.Now.AddDays(-1);

Response.Cookies["password"].Expires = DateTime.Now.AddDays(-1);

Response.Redirect("~/welcome.aspx");

} else {

Response.Write("Invalid User and Password");

Welcome Page Code:

using System;

using System.Collections.Generic;

using System.Linq;

158 | P a g e
DES’s NMITD AWT Journal MC1944

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace WebApplication1 {

public partial class welcome: System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

HttpCookie ck1 = Request.Cookies["username"];

if (ck1 != null) {

Label1.Text = ck1.Value;

Output:

D. Application to change Background Color based on selection. (Cookie)

159 | P a g e
DES’s NMITD AWT Journal MC1944

Solution:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace WebApplication1 {

public partial class WebForm9: System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

if (Request.Cookies["Bgcolor"] != null) {

DropDownList1.SelectedValue = Request.Cookies["Bgcolor"].Value;

BodyTag.Style["background-color"] = DropDownList1.SelectedValue;

protected void DropDownList1_SelectedIndexChanged(object sender,


EventArgs e) {

BodyTag.Style["background-color"] = DropDownList1.SelectedValue;

HttpCookie cookie = new HttpCookie("Bgcolor");

cookie.Value = DropDownList1.SelectedValue;

cookie.Expires = DateTime.Now.AddHours(-1);

Response.SetCookie(cookie);

160 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

161 | P a g e
DES’s NMITD AWT Journal MC1944

E. Application to change Background Color based on selection. (Session)

Solution:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace WebApplication1 {

public partial class WebForm9: System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

if (Session["Bgcolor"] != null) {

DropDownList1.SelectedValue = Session["Bgcolor"].ToString();

BodyTag.Style["background-color"] = DropDownList1.SelectedValue;

protected void DropDownList1_SelectedIndexChanged(object sender,


EventArgs e) {

BodyTag.Style["background-color"] = DropDownList1.SelectedValue;

Session["Bgcolor"] = DropDownList1.SelectedValue;

Note: Add this statement to web.config file “<system.web>


<sessionState mode="InProc" timeout="30"></sessionState>
</system.web>”

162 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

163 | P a g e
DES’s NMITD AWT Journal MC1944

F. Login Application with Session

Solution:

Session Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class SessionUser: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


Session["uname"] = TextBox1.Text;
Response.Redirect("~/Home.aspx");
}
}
}
Home Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class Home: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Session["uname"] != null && Session["uname"] != "") {
Label1.Text = Session["uname"].ToString();
}

}
}
}

164 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

165 | P a g e
DES’s NMITD AWT Journal MC1944

G. Out Of Process Session State

Solution:

Outofprocess.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="outofprocess.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Username"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"
TextMode="Password"></asp:TextBox>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Login" />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</form>
</body>
</html>
Outprocess.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

166 | P a g e
DES’s NMITD AWT Journal MC1944

using System.Web.UI.WebControls;
public partial class _Default: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {}
protected void Button1_Click(object sender, EventArgs e) {
Session["Name"] = TextBox1.Text;
Response.Redirect("~/WebForm1.aspx");
}
}
Webform1.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class webform1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "welcome" + Session["name"].ToString();
}
}

Output:

167 | P a g e
DES’s NMITD AWT Journal MC1944

168 | P a g e
DES’s NMITD AWT Journal MC1944

H. SQLServer Session State

Solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class SQLsessionuser: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


Session["uname"] = TextBox1.Text;
Session["uid"] = TextBox2.Text;
Response.Redirect("~/Home.aspx");
}
}
}
HomePage:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class Home: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Session["uname"] != null) {
Label1.Text = Session["uname"].ToString();
} else {
Label1.Text = "Anonymous User";
}

}
}
}
Note: Add this line to the web.config in a new <system.web> tag
“<sessionState mode="SQLServer" sqlConnectionString="Data
Source=DESKTOP-0NRI8FC;Integrated Security=SSPI"
timeout="20"></sessionState>”

169 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

Again the rerunning the program after the stopping the site

And Redirecting to the homepage again

170 | P a g e
DES’s NMITD AWT Journal MC1944

I. Cookieless Session

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class Cookieless: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


Session["data"] = TextBox1.Text;
Response.Redirect("~/Home.aspx");
}
}
}
Home Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class Home: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Session["data"] != null) {
Label1.Text = Session["data"].ToString();
} else {
Label1.Text = "Anonymous User";
}
}
}
}

171 | P a g e
DES’s NMITD AWT Journal MC1944

Output:
Cookie Page:

Home Page:

172 | P a g e
DES’s NMITD AWT Journal MC1944

J. Application State Program:

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class WebForm10: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Application["visits"] = (int) Application["visits"] + 1;
Label1.Text = "The No of Visits" + Application["visits"].ToString();
}
}
}
Globab.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace WebApplication1 {
public class Global: System.Web.HttpApplication {

protected void Application_Start(object sender, EventArgs e) {


Application["visits"] = 0;
}

protected void Session_Start(object sender, EventArgs e) {


Application.Lock();
Application["visits"] = (int) Application["visits"] + 1;
Application.UnLock();
}

protected void Application_BeginRequest(object sender, EventArgs e) {

protected void Application_AuthenticateRequest(object sender, EventArgs e) {

protected void Application_Error(object sender, EventArgs e) {

173 | P a g e
DES’s NMITD AWT Journal MC1944

protected void Session_End(object sender, EventArgs e) {

protected void Application_End(object sender, EventArgs e) {

}
}
}
Output:

174 | P a g e
DES’s NMITD AWT Journal MC1944

K. Output Cache

Solution:

Vary by Param

Web Page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class WebForm11: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Label1.Text = DateTime.Now.ToString();
}
}
Form Source:

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


CodeBehind="WebForm11.aspx.cs" Inherits="WebApplication1.WebForm11" %>
<%@ OutputCache Duration="30" VaryByParam="p" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>OutputCacheWithVaryByParam</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<p>The Page will be rendered from cache until the value of QueryString
named &quot;id&quot; is changed or Duration
is expired<br />
<a href="?p=1">One</a><br />
<a href="?p=2">Two</a><br />
<a href="?p=3">Three</a><br />
</p>
</div>
</form>
</body>
</html>

175 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

Vary By Control

Web Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class WebForm12: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Label2.Text = DateTime.Now.ToLongTimeString();
}

protected void DropDownList1_SelectedIndexChanged(object sender,


EventArgs e) {
Label1.Text = DropDownList1.SelectedValue.ToString();
}
}
}

176 | P a g e
DES’s NMITD AWT Journal MC1944

Form Source:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm12.aspx.cs" Inherits="WebApplication1.WebForm12" %>
<%@ OutputCache Duration="30" VaryByControl="DropDownList1"
VaryByParam="none"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Option One</asp:ListItem>
<asp:ListItem>Option Two</asp:ListItem>
<asp:ListItem>Option Three</asp:ListItem>
</asp:DropDownList>
<br />
<br />
The page will be rendered from cache basing on the selected item of
DropDown List.<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>

Output:

177 | P a g e
DES’s NMITD AWT Journal MC1944

Vary By Custom:

Web Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1 {
public partial class VaryByCustom: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


Label1.Text = DateTime.Now.ToLongTimeString();

}
}
}

178 | P a g e
DES’s NMITD AWT Journal MC1944

Output:
FireFox

Microsoft Edge

179 | P a g e
DES’s NMITD AWT Journal MC1944

L. Cache Object
Solution:

Cache a DataSet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace WebApplication1 {
public partial class DataCache: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button2_Click(object sender, EventArgs e) {


if (Cache["Data"] != null) {
Cache.Remove("Data");
Label1.Text = "DataSet removed from the cache";
} else {
Label1.Text = "There is nothing in the cache to remove";
}
}

protected void Button1_Click(object sender, EventArgs e) {


if (Cache["Data"] == null) {
SqlConnection con = new SqlConnection(@ "Data Source=DESKTOP-
0NRI8FC;Initial Catalog=demo;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("Select * from accounts", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

Cache["Data"] = ds;
Label1.Text = "Data Loaded from DB";
} else {
GridView1.DataSource = (DataSet) Cache["Data"];
GridView1.DataBind();
Label1.Text = "Data Loaded from Cache";
}
}
}
}

180 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

181 | P a g e
DES’s NMITD AWT Journal MC1944

Cache an ArrayList
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebApplication1 {
public partial class CacheArrayList: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
ArrayList datestamps;
if (Cache["datestamps"] == null) {
datestamps = new ArrayList();
datestamps.Add(DateTime.Now);
datestamps.Add(DateTime.Now.AddDays(1));
datestamps.Add(DateTime.Now.AddDays(2));
Cache.Add("datestamps", datestamps, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 0, 60), System.Web.Caching.CacheItemPriority.Default,
null);
} else {
datestamps = (ArrayList) Cache["datestamps"];
foreach(DateTime dt in datestamps) {
Response.Write(dt.ToString() + "<br/>");
}
}
}
}
}

Output:

182 | P a g e
DES’s NMITD AWT Journal MC1944

M. Shopping Cart Example

Solution:

Webform2.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/ecom.Master"


AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="AssiASP.WebForm2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head"
runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<h2>Welcome </h2>
<p>
&nbsp;
</p>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/Mycart.aspx">View Cart</asp:HyperLink>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="Id" DataSourceID="SqlDataSource1"
ForeColor="#333333"
GridLines="None"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Id" HeaderText="Id"
SortExpression="Id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="name1" HeaderText="name1"
SortExpression="name1" />
<asp:BoundField DataField="price" HeaderText="price"
SortExpression="price" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center"
/>
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333"
/>
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />

183 | P a g e
DES’s NMITD AWT Journal MC1944

<SortedDescendingHeaderStyle BackColor="#4870BE" />


</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [shopping]" ProviderName="<%$
ConnectionStrings:ConnectionString.ProviderName
%>"></asp:SqlDataSource>
</asp:Content>

Webform2.aspx.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
namespace AssiASP {
public partial class WebForm2: System.Web.UI.Page {
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
protected void Page_Load(object sender, EventArgs e) {}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs
e) {
ArrayList SelectedProductList;
if (Session["cart"] == null) {
//cart is empty
SelectedProductList = new ArrayList();
Cart cart = new Cart();
//retrive selected product id
cart.productid =
Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Value);
//retrieve product name and price
con = new
OleDbConnection(@ "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source = C: \Users\ pc - 1\ Documents\ Database7.accdb ");
con.Open(); cmd = new OleDbCommand("select * from shopping where
Id=" +
cart.productid, con); dr = cmd.ExecuteReader(); dr.Read();
cart.productname = dr["name1"].ToString();; cart.price =
Convert.ToInt32(dr["price"]);
// add cart to list
SelectedProductList.Add(cart); Session["cart"] = SelectedProductList;
}
else {

184 | P a g e
DES’s NMITD AWT Journal MC1944

Cart cart = new Cart();


cart.productid =

Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Value);

con = new
OleDbConnection(@ "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source = C: \Users\ pc - 1\ Documents\ Database7.accdb ");
con.Open(); cmd = new OleDbCommand("select * from shopping
where Id=" +
cart.productid, con); dr = cmd.ExecuteReader(); dr.Read();
cart.productname = dr["name1"].ToString();; cart.price =
Convert.ToInt32(dr["price"]); SelectedProductList = (ArrayList) Session["cart"];
SelectedProductList.Add(cart);
}
}
}
}

Cart.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AssiASP {
public class Cart {
public int productid;
public string productname;
public int price;
}
}

Mycart.aspx

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


CodeBehind="Mycart.aspx.cs"
Inherits="AssiASP.Mycart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>

185 | P a g e
DES’s NMITD AWT Journal MC1944

</html>

Mycart.aspx.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AssiASP {
public partial class Mycart: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Cart cartobj = null;
ArrayList productList = (ArrayList) Session["cart"];
if (productList != null) {
for (int i = 0; i < productList.Count; i++) {
cartobj = (Cart) productList[i];
Response.Write("<b/><b> Product ID </b> " + cartobj.productid);
Response.Write("<br/><b> Product Name </b> " +
cartobj.productname +
"<br/> <b>Price </b> " + cartobj.price);
}
} else Response.Write("Cart is empty");
}
}
}

Ecom.Master
<%@ Master Language="C#" AutoEventWireup="true"
CodeBehind="ecom.master.cs" Inherits="AssiASP.ecom" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>C1747</title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;

186 | P a g e
DES’s NMITD AWT Journal MC1944

}
li a {
font-size:30px;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
#header{
background-color: black;
color:white;
margin:0px;
font-family:cursive;
font-size:30px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="header">
<center>Shopping Cart</center>
</div>
<div>
<center>
<ul>
<li><a class="active" href="Home.aspx">Home</a></li>
<li><a href="addProduct.aspx">Add Products</a></li>
<li><a href="viewProduct.aspx">Display Products</a></li>
</ul>
</center>
</div>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

187 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

188 | P a g e
DES’s NMITD AWT Journal MC1944

Web
Services

189 | P a g e
DES’s NMITD AWT Journal MC1944

PRACTICAL NO.9
A. Create an XML Web Service to add two integers. Consume this service
through a Web Client.

Solution:-

Create empty web application add web service (CalcService.asmx)

CalcService.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace webservice2 {
/// <summary>
/// Summary description for CalcService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class CalcService: System.Web.Services.WebService {

[WebMethod]
public int Add(int a, int b) {
return a + b;
}

}
}

190 | P a g e
DES’s NMITD AWT Journal MC1944

Now for client side:

Create new web application

191 | P a g e
DES’s NMITD AWT Journal MC1944

Add service reference

Add browser link of CalcService.asmx

192 | P a g e
DES’s NMITD AWT Journal MC1944

Webform1.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Clientwebservice {
public partial class WebForm1: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}

protected void Button1_Click(object sender, EventArgs e) {


ServiceReference1.CalcServiceSoapClient client = new
ServiceReference1.CalcServiceSoapClient();

Label1.Text = (client.Add(Convert.ToInt16(TextBox1.Text),
Convert.ToInt16(TextBox2.Text))).ToString();
}
}
}

193 | P a g e
DES’s NMITD AWT Journal MC1944

194 | P a g e
DES’s NMITD AWT Journal MC1944

B. Create an XML Web Service with methods to calculate the area and
perimeter of a Rectangle. Consume this service through a Windows
client application.

Solution:-

Rectangle.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace AreaperimeterWebService {
/// <summary>
/// Summary description for rectangle
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class rectangle: System.Web.Services.WebService {

[WebMethod]
public int Area(int a, int b) {
return a * b;
}

[WebMethod]
public int Perimeter(int a, int b) {
return 2 * (a + b);
}
}
}

Create AreaperirectClient window application add reference of web service


rectangle.asmx

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

195 | P a g e
DES’s NMITD AWT Journal MC1944

namespace AreaperirectClient {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e) {


ServiceReference1.rectangleSoapClient client = new
ServiceReference1.rectangleSoapClient();
label3.Text = (client.Perimeter(Convert.ToInt16(textBox1.Text),
Convert.ToInt16(textBox2.Text))).ToString();
}

private void button1_Click(object sender, EventArgs e) {


ServiceReference1.rectangleSoapClient client = new
ServiceReference1.rectangleSoapClient();
label3.Text = (client.Area(Convert.ToInt16(textBox1.Text),
Convert.ToInt16(textBox2.Text))).ToString();

}
}
}

196 | P a g e
DES’s NMITD AWT Journal MC1944

197 | P a g e
DES’s NMITD AWT Journal MC1944

C. Create an XML Web Service that returns all the branch details from
BranchTB. Write a Windows application that uses this service to
display branch details in a datagridview control.

Solution:-

Webapp1: WebServiceC

Add web service WebService.asmx

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceC {
/// <summary>
/// Summary description for WebServicec
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebServicec: System.Web.Services.WebService {
[WebMethod]
public DataSet getBranchDetls() {
OleDbConnection con = new OleDbConnection(@
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:\MCA\sem4\AWT\BranchTB.mdb");
OleDbDataAdapter da = new OleDbDataAdapter("Select * from
BranchTB", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
return ds;
}

}
}

198 | P a g e
DES’s NMITD AWT Journal MC1944

Create Windows application: ClientC

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClienC {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}

private void dataGridView1_CellContentClick(object sender,


DataGridViewCellEventArgs e) { }

private void Form1_Load(object sender, EventArgs e) {


ServiceReference1.WebServicecSoapClient client = new
ServiceReference1.WebServicecSoapClient();
DataSet ds = new DataSet();
ds = client.getBranchDetls();
dataGridView1.DataSource = ds.Tables[0];
}
}
}

Output:

199 | P a g e
DES’s NMITD AWT Journal MC1944

Access Database:

200 | P a g e
DES’s NMITD AWT Journal MC1944

D. Create an XML Web Service that returns the selected branch’s


information from BranchTB. Write a Windows application that uses
this service to display branch details in a datagridview control. Also
add a web method to insert new branch information entered by the
user into the branch table.

Solution:-

Form Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StringPractical1 {
public partial class Form2: Form {
public Form2() {
InitializeComponent();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)


{
ServiceReference2.WebService1SoapClient client1 = new
ServiceReference2.WebService1SoapClient();
DataSet ds = new DataSet();
if (comboBox1.SelectedValue != null) {
ds =
client1.getBranchDtlswithBrId(Convert.ToInt32(comboBox1.SelectedValue.ToStri
ng()));
dataGridView1.DataSource = ds.Tables[0];
}
}

private void button2_Click(object sender, EventArgs e) {


ServiceReference2.WebService1SoapClient client1 = new
ServiceReference2.WebService1SoapClient();
DataSet ds = new DataSet();
ds = client1.insertBankDtls(Convert.ToInt32(textBox2.Text.ToString()),
textBox3.Text, textBox4.Text);
ds = client1.getBrancHDtls();
dataGridView1.DataSource = ds.Tables[0];

Form2_Load(sender, e);
//this.branchTableTableAdapter3.Fill
//(this.branchTbDataSet3.BranchTable);
//comboBox1_SelectedIndexChanged(sender,e);

201 | P a g e
DES’s NMITD AWT Journal MC1944

textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox2.Focus();
}

private void Form2_Load(object sender, EventArgs e) {


// TODO: This line of code loads data into the 'database3DataSet3.Table1'
table. You can move, or remove it, as needed.
this.table1TableAdapter.Fill(this.database3DataSet3.Table1);

ServiceReference2.WebService1SoapClient client1 = new


ServiceReference2.WebService1SoapClient();
DataSet ds = new DataSet();
ds = client1.getBrancHDtls();
dataGridView1.DataSource = ds.Tables[0];

private void button1_Click(object sender, EventArgs e) {


Form2_Load(sender, e);
}
}
}

Web Service Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.OleDb;
using System.Data;

namespace WebService {
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1: System.Web.Services.WebService {

[WebMethod]
public DataSet getBrancHDtls() {

202 | P a g e
DES’s NMITD AWT Journal MC1944

OleDbConnection con = new OleDbConnection(@


"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Xorro\Documents\Database3.mdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Table1",
con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
return ds;
}

[WebMethod]
public DataSet getBranchDtlswithBrId(int c) {
OleDbConnection con = new OleDbConnection(@
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Xorro\Documents\Database3.mdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Table1
where Br_Id=" + c, con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}

[WebMethod]
public DataSet insertBankDtls(int c, string s, string s1) {
OleDbConnection con = new OleDbConnection(@
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Xorro\Documents\Database3.mdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Insert into Table1 values('"
+ c + "','" + s + "','" + s1 + "')", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}

[WebMethod]
public DataSet getLoginDtls(string uname, string pwd) {
OleDbConnection con = new OleDbConnection(@
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\Xorro\Documents\Database3.mdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Table2
where Login_ID='" + uname + "' and Password='" + pwd + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}

203 | P a g e
DES’s NMITD AWT Journal MC1944

Output:

Show all Insert Record

Web Service in the browser

204 | P a g e
DES’s NMITD AWT Journal MC1944

E. Create an XML Web Service that calculates the sum of two double
variables. Call this method and continue the execution of client
application while the sum is being calculated. (Asynchronous call to
Web Service)

Solution:-

Form Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StringPractical1 {
public partial class Form4: Form {
public Form4() {
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) {


double A = Convert.ToDouble(textBox1.Text);
double B = Convert.ToDouble(textBox2.Text);

ServiceReference3.WebService2SoapClient cl = new
ServiceReference3.WebService2SoapClient();
IAsyncResult myIar;

myIar = cl.BeginAddDouble(A, B, null, null);


int x = 0;
while (myIar.IsCompleted == false) {
x += 1;
}

label3.Text = "Result from web service: " + cl.EndAddDouble(myIar) + "


Local count while waiting: " + x.ToString();

}
}
}

205 | P a g e
DES’s NMITD AWT Journal MC1944

Web Service Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService {
/// <summary>
/// Summary description for WebService2
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService2: System.Web.Services.WebService {

[WebMethod]

public double AddDouble(double A, double B) {


System.Threading.Thread.Sleep(2000);
return A + B;
}
}
}

Output:

206 | P a g e
DES’s NMITD AWT Journal MC1944

Web Service Running in the browser:

207 | P a g e
DES’s NMITD AWT Journal MC1944

F. Create an XML Web Service that checks for Login credentials entered
by user with values in LoginTB. Write a Windows client that uses this
web service to Login.

Solution:-

Web app: LoginserviceQ5.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.OleDb;

namespace LoginserviceQ5 {
/// <summary>
/// Summary description for logincheck
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class logincheck: System.Web.Services.WebService {

[WebMethod]
public DataSet getlogindtls(string uname, string pwd) {
OleDbConnection con = new OleDbConnection(@
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:\MCA\sem4\AWT\BranchTB.mdb");
OleDbDataAdapter da = new OleDbDataAdapter("select * from login where
Id='" + uname + "' and password='" + pwd + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}

Client window app:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

208 | P a g e
DES’s NMITD AWT Journal MC1944

using System.Threading.Tasks;
using System.Windows.Forms;

namespace loginchek {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) {


ServiceReference1.logincheckSoapClient cs = new
ServiceReference1.logincheckSoapClient();
DataSet ds = new DataSet();
ds = cs.getlogindtls(textBox1.Text, textBox2.Text);
if (ds.Tables[0].Rows.Count > 0) MessageBox.Show("Valid user");
else
MessageBox.Show("Invlid User");
}
}
}

Output:

209 | P a g e
DES’s NMITD AWT Journal MC1944

Access database:

210 | P a g e
DES’s NMITD AWT Journal MC1944

G. Create a WCF web service to provide calculator services. 

Solution:-

Service Code:

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1 {
// NOTE: You can use the "Rename" command on the "Refactor" menu to
change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1 {

/*[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
*/

[OperationContract]
int AddData(int a, int b);

[OperationContract]
int SubData(int a, int b);

[OperationContract]
int MulData(int a, int b);

[OperationContract]
int DivData(int a, int b);

// TODO: Add your service operations here


}

// Use a data contract as illustrated in the sample below to add composite


types to service operations.
[DataContract]
public class CompositeType {
bool boolValue = true;

211 | P a g e
DES’s NMITD AWT Journal MC1944

string stringValue = "Hello ";

[DataMember]
public bool BoolValue {
get {
return boolValue;
}
set {
boolValue = value;
}
}

[DataMember]
public string StringValue {
get {
return stringValue;
}
set {
stringValue = value;
}
}
}
}

Service1.svc.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1 {
// NOTE: You can use the "Rename" command on the "Refactor" menu to
change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please
select Service1.svc or Service1.svc.cs at the Solution Explorer and start
debugging.
public class Service1: IService1 {
/*public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}

public CompositeType GetDataUsingDataContract(CompositeType composite)


{
if (composite == null)
{

212 | P a g e
DES’s NMITD AWT Journal MC1944

throw new ArgumentNullException("composite");


}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
*/

public int AddData(int a, int b) {


return a + b;
}

public int SubData(int a, int b) {


return a - b;
}

public int MulData(int a, int b) {


return a * b;
}

public int DivData(int a, int b) {


return a / b;
}

}
}

Output:

Addition

Subtraction:

Multiply:

213 | P a g e
DES’s NMITD AWT Journal MC1944

Division:

WCF Test Client:

214 | P a g e
DES’s NMITD AWT Journal MC1944

I. Create a WCF web service to calculate age in no. of days. 

Solution:-

Web Page Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication3 {
public partial class CalculateDays: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {


int day, Month, Year, TotalDays;

//creating the object of WCF service client


ServiceReference1.Service1Client age = new
ServiceReference1.Service1Client();

//assigning the input values to the variables


day = int.Parse(TextBox1.Text);
Month = int.Parse(TextBox2.Text);
Year = int.Parse(TextBox3.Text);

//assigning the output value from service Response


TotalDays = age.CalculateDays(day, Month, Year);

//assigning the output value to the lable to show user


Label1.Text = ("You are Currently " + Convert.ToString(TotalDays) + " days
old");
Response.Write("<script>alert('You Are Currently':" + TotalDays.ToString()
+ "'Years Old');</script>");
}
}
}
Add this to your IService1.cs[OperationContract]
int CalculateDays(int day, int month, int year);
Add this to your Service1.svc.cs
public int CalculateDays(int day, int month, int year) {
DateTime dt = new DateTime(year, month, day);
int datetodays = DateTime.Now.Subtract(dt).Days;

215 | P a g e
DES’s NMITD AWT Journal MC1944

return datetodays;
}

Output:

216 | P a g e

You might also like