Thursday, September 16, 2010

ADO.NET : Record Insert and Display Using StoredProcedure

Windows Application Screenshot :

***************************



****************************

Screenshot Of StoredProcedure in SQL Server 2005
================================================

================================================
StoredProcedure : GetEmployee
================================================
USE [ANGEL]
GO
/****** Object: StoredProcedure [dbo].[GetEmployee] Script Date: 09/17/2010 08:52:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[GetEmployee]

AS SELECT EmpNo,EmpName, EmpSal,DeptNo FROM Employee
====================================================
StoredProcedure : InsertUser
====================================================

USE [ANGEL]
GO
/****** Object: StoredProcedure [dbo].[InsertUser] Script Date: 09/17/2010 08:54:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertUser] (
@Username varchar(50), @Password varchar(50)
)
AS INSERT INTO Users VALUES(@Username, @Password)

==================================================

Code :
==================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{

SqlConnection conn;
SqlCommand command;
SqlCommand command1;
SqlDataAdapter adapter;
DataSet ds;
public Form1()
{

InitializeComponent();
conn = new SqlConnection("Data Source=localhost; Initial Catalog=ANGEL; Integrated Security=SSPI");
conn.Open();

}

private void Form1_Load(object sender, EventArgs e)
{

command = new SqlCommand("GetEmployee", conn);
adapter = new SqlDataAdapter(command);
ds = new DataSet();
adapter.Fill(ds, "Employee");
dg_Data.DataSource = ds.Tables[0];


}

private void button1_Click(object sender, EventArgs e)
{
string username=Username.Text;
string password=Password.Text;

command1= new SqlCommand("InsertUser", conn);
command1.CommandType = CommandType.StoredProcedure;
command1.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;
command1.Parameters.Add("@Password", SqlDbType.VarChar).Value = password;

int rows = command1.ExecuteNonQuery();
conn.Close();
if (rows == 1)
{
MessageBox.Show("Record Inserted successfully ...");
}
else
{
MessageBox.Show("Problem in insert !!! Check coding ");
}
Username.Text = "";
Password.Text = "";
}
}
}

=====================================================================

Tuesday, September 7, 2010

IEnumerable and Ienumerator Interfaces Details:

1) IEnumerable interface members helps foreach loop to iterate over a collection.
2) The method like GetEnumerator() of IEnumerable interface has to be defined to iterate a collection.
3) There is 1 method of IEnumerable interface. Which is IEnumerator GetEnumerator (). (Return type is Ienumerator type)
4) It returns an IEnumerator object that can be used to iterate through the collection.
5) Its not required to implement IEnumerable interface though we are overriding the GetEnumerator(), because we are using Namespace System.Collections. So it’s not mandatory to right IEnumerable interface.
6) We should implement the IEnumerable to use foreach iteration.
7) There are 2 public methods of IEnumerator Interface.
8) MoveNext() advances the enumerator to the next element of the collection.
9) Reset() sets the enumerator to its initial position, which is before the first element in the collection.
10) MoveNext() returns bool. And the Syntax is bool MoveNext().
11) If it’s true then enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
12) After an enumerator is created or after the Reset method is called, an enumerator is positioned before the first element of the collection, and the first call to the MoveNext method moves the enumerator over the first element of the collection.
If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false until Reset is called.
13) An enumerator remains valid as long as the collection remains unchanged.
14) If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException.
15) IEnumerator.Current Property gets the current element in the collection. Its syntax is Object Current { get; }

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Example:

Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ienumeratordemo
{
class Employee
{
private string name;
private int empno;


public Employee(int empno, string name)
{
this.empno = empno;
this.name = name;
}

public int Empno
{
get { return empno; }
set { empno = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
}

EmployeeInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Ienumeratordemo
{
class EmployeeInfo //: IEnumerable
{

public Employee[] empArray = new Employee[3];


public EmployeeInfo()
{
empArray[0] = new Employee(1001, "Ajit");
empArray[1] = new Employee(1002, "Sunil");
empArray[2] = new Employee(1003, "Raj");

}


public IEnumerator GetEnumerator()
{
return empArray.GetEnumerator();
}
}
}


Program.cs

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

namespace Ienumeratordemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("IEnumerable / IEnumerator Demo\n");

EmployeeInfo empinfoObj = new EmployeeInfo();

// Hand over each Employee in the collection ?
foreach (Employee e in empinfoObj)
{
Console.WriteLine("{0} \t {1}",e.Empno, e.Name);
}


//manually iterate
IEnumerator i = empinfoObj.GetEnumerator();
i.MoveNext();

Employee myEmployee = (Employee)i.Current;
Console.WriteLine("{0} \t {1}", myEmployee.Empno, myEmployee.Name);
i.Reset();

Console.WriteLine(" *******************************************");

IEnumerator i1 = empinfoObj.GetEnumerator();
i1.MoveNext();


i1.MoveNext();




i1.MoveNext();

Employee myEmployee1 = (Employee)i1.Current;
Console.WriteLine("{0} \t {1}", myEmployee1.Empno, myEmployee1.Name);

Console.Read();


}
}
}

Output :


Object Sender & EventArgs Parameter in System.EventHandler Delegate

EventHandler Delegate : Represents the method that will handle an event that has no event data.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Syntax :

public delegate void EventHandler(Object sender,EventArgs e)

sender

Type: System.Object
The source of the event.

e
Type: System.EventArgs
An EventArgs that contains event data.

************************************************************

Check the Code below :

private void btnShowDel_Click(object sender, EventArgs e)
{
int x = 6;
int y = 7;

int z = x + y;
MessageBox.Show("" + z);
MessageBox.Show(e.ToString());
}

On this above code, btnShowDel_Click is the eventhandler. Which is match with the predefined delegate System.EventHandler.

See the following code :


this.btnShowDel.Click += new System.EventHandler(this.btnShowDel_Click);

This code tells that, btnShowDel is an object and Click is the event. And btnShowDel raises the event. The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:

* A delegate that identifies the method that provides the response to the event.
* A class that holds the event data.

The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate. The standard signature of an event handler delegate defines a method that does not return a value, whose first parameter is of type Object and refers to the instance that raises the event, and whose second parameter is derived from type EventArgs and holds the event data.If the event does not generate event data, the second parameter is simply an instance of EventArgs. Otherwise, the second parameter is a custom type derived from EventArgs and supplies any fields or properties needed to hold the event data.

EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must supply your own custom event data type and either create a delegate where the type of the second parameter is your custom type, or use the generic EventHandler delegate class and substitute your custom type for the generic type parameter.

To associate the event with the method that will handle the event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate.

The following code example demonstrates the declaration of an event handler delegate that does not use event data. The EventHandler class is the type of the event delegate, sender is the object that raises the event, and e is an event data object that contains no data. The second line of code in the example defines the event member in your class for an event that has no data.

************************************************************

public delegate void EventHandler(Object sender, EventArgs e);
public event EventHandler NoDataEventHandler;

**************************************************************

Wednesday, August 4, 2010

How to connect ADO.NET with Oracle 9i Database

Step – 1

Design a Windows application Form like the below screenshot.



# Write code to insert record into Employee table. (provided below)

# To know the connection string for oracle database, go to , Server Explorer->WriteClick on Data Connections ->Add Connection->Then provide the Global Database Name (SID), UserID and password as set at the time of installing Oracle .

Notes : User ID : Scott (Locked, So no changes)
Password: tiger (Locked, No changes)
Server : GDN (here 'GDN' in my Machine)

Only you have to provide the Global Database Name , at the time of installation.

See the below screenshot to create the connection using Server Explorer.









Then you will find the connection string which will be created automatically and set this connection string, with OracleConnection instance.

For details see the code details :

------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace ADOwithOra
{
public partial class Employee : Form
{
OracleConnection oracleConn;

public Employee()
{

InitializeComponent();
oracleConn = new OracleConnection();
oracleConn.ConnectionString = "Data Source=GDN;User ID=scott;Password=tiger;Unicode=True";
oracleConn.Open();
}

private void button1_Click(object sender, EventArgs e)
{

try
{

if (oracleConn.State == ConnectionState.Open)
{
oracleConn.Close();
}
oracleConn.Open();
//OracleCommand cmd = new OracleCommand("insert into Employee(EmpNo,EmpName,Sal) values(5,'Ravi',23000)", oracleConn); --->Hardcoding
OracleCommand cmd = new OracleCommand("insert into Employee values(" + textBox1.Text + ",'" + textBox2.Text + "'," + textBox3.Text + ")", oracleConn);
cmd.ExecuteNonQuery();
MessageBox.Show("Employee information added successfully...", "Employee Details", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
catch (Exception e2)
{
MessageBox.Show(e2.ToString());
}


}

private void btnReset_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
}
}
--------------------------------------------------
Result screenshot:



See the Oracle database screenshot:



Now we can do more works using Oracle 9i in ADO.NET.


All the best...

Friday, July 23, 2010

Boxing and Unboxing in C#

C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.


int i = 123;
object o = (object)i

The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;


Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

Boxing Conversion





In the above case, I have made an implicit boxing. At first time the i value is located in stack area as actual value. But when the i value is boxed, to object type. So, the reference will be resides on the stack memory area and the value pointing to that reference will be located on heap area.
Example:

class TestBoxing
{
static void Main()
{
int i = 797;
object o = i; // Implicit boxing

i = 456; // Change the contents of i

System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}







The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.

class TestUnboxing
{
static void Main()
{
int i = 797;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing Possible.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
}
}


This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;

to:

int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing Possible.

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
• Checking the object instance to make sure that it is a boxed value of the given value type.
• Copying the value from the instance into the value-type variable.
The following statements demonstrate both boxing and unboxing operations:
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing


Unboxing Conversion




In the above figure, i value 123 is stored in the stack, and when it is assigned to object type, the reference will be stored in stack only, but the actual value will be stored in heap. And when, it will be explicitly telecasted to int type, as per the above figure , j value will be stored in the stack.
Difference between Stack vs Heap memory
Stack
Stack memory stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task.
Once a function/method has completed its cycle the reference to the variable in the stack is removed.

Heap
Heap memory stores all instances or attributes, constructors and methods of a class/object.
Comparison
A Heap reference is stored in Stack memory until the life cycle of the object has completed. Inside the Heap reference all the contents of the object are stored whereas with a local variable only the variable contents are stored in the stack.
Example:
Stack
int x
ref 0x456783 (Heap reference)
int y
ref 0x498702 (Heap reference)
int z


Heap (0x456783)
name => Ali
age => 33
city => CTC
height => 5'8
sex => Male

Heap (0x498702)
name => Saroj
age => 29
city => BBSR
height => 6'0
sex => male

So, above all, I would like to say, for performance point of view, heap is works better then stack.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Monday, April 26, 2010

WebServices in ASP.NET




A Simple Example To run a WebServices :
=====================================================================================
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 Factorial : System.Web.Services.WebService
{
public Factorial()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public int FindFact(int x)
{
int a=1;
while (x != 0)
{
a = a * x;
x--;
}
return a;

}

}
=================================================================================

Client Program :


using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

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


}
protected void btnClick_Click(object sender, EventArgs e)
{
Factorial Fct = new Factorial();
int Res = Fct.FindFact(Convert.ToInt32(txtFact.Text));
txtShowFact.Text = Convert.ToString(Res);
}
}


===========================================================================

Output:


==============================================================================

Monday, April 5, 2010

Introduction to Delegate

A delegate is an object that can refer to a method. Delegate object contain references to methods that need to be invoked instead of containing actual method names.

Features of Delegate

q Methods can be passed as parameters to a delegate. In addition, a delegate can accept a block of code as a parameter. Such blocks are referred to as anonymous methods because they have no method name.

q A delegate can invoke multiple methods simultaneously. And this is known as multicasting.

q A delegate can encapsulate static methods.



Sunday, January 17, 2010

Abstract Class Program in Java

/*
Salary1.java
-------------------------------------------------------------------
WAP a Java Program to create one Abstract class i.e.
AbstractEmployee which contains Calculate() and Display() Methods.
Employee class inherits AbstractEmployee class which contains TA,DA,HRA,PF,
GS,GD and NetSalary data members.

In this case Display() is Non-Abstract and defind in abstrct class
as well as derived class. So, we have to use super keyward to call
in the subclass version of the Display(). Then super class Display()
will call first then sub class Display() will call.
--------------------------------------------------------------------
TA is 20% of Basic.
DA is 5% of Basic.
Income Tax is 15% of Basic

PF = 5000

GS = Basic+HRA+TA+DA

GD=IT+PF

Display the Employee Details.
-------------------------------------------------------------------
Question:-Can a method declared within abstract class ??
Yes, a non abstract method can be defined with an abstract class.

--------------------------------------------------------------------*/

Answer :


abstract class AbstractEmployee
{
int SlNo;
String Name;
float Basic;

AbstractEmployee(int SlNo, String Name,float Basic)
{

this.SlNo=SlNo;
this.Name=Name;
this.Basic=Basic;
}

abstract void Calculate();

abstract void test();

void Display()
{
System.out.println("APTECH");
System.out.println("NIIT");
System.out.println("SQL STAR");

}
}


class Employee extends AbstractEmployee
{
float ta,da,hra,pf,it,gs,gd,net;


Employee(int SlNo,String Name,float Basic)
{
super(SlNo,Name,Basic);
}

void Calculate()
{
ta=Basic * .20f;
da=Basic * .05f;
it=Basic * .15f;
hra=1000;
pf=5000;
gs=Basic+hra+ta+da;
gd=it+pf;
net=gs-gd;
}

void Display()
{

super.Display();

System.out.println(" SlNo of the Employee is " +SlNo);
System.out.println(" Name of the Employee is"+ Name);
System.out.println(" Basic Salary = "+ Basic);
System.out.println(" TA = " + ta);
System.out.println(" DA = " + da);
System.out.println(" HRA = " + hra);
System.out.println(" IT =" + it);
System.out.println("\n PF = " + pf);
System.out.println("\n GS = " + gs);
System.out.println("\n Net Salary = " + net);

}

void test()
{
System.out.println("Hello");
}

}


class Salary1
{
public static void main(String args[])
{
Employee e1=new Employee(1,"Saroj",25000);
e1. Calculate();
e1.Display();
e1.test();
}
}

Frame Program in Java

import java.awt.*;

import java.awt.event.*;

public class GUIFrame extends Frame
{

private Label l1,l2;

TextField t1,t2,t3;

Button badd;

public GUIFrame()
{

super("GUI Application");

setLayout(new FlowLayout());

l1 = new Label("Enter First Number:");

l2 = new Label("Enter Second Number:");

t1 = new TextField(20);

t2 = new TextField(20);

t3 = new TextField(20);

badd = new Button("Add");

add(l1);

add(t1);

add(l2);

add(t2);

add(t3);

add(badd);


badd.addActionListener(new ListenEvent(this)); /*Registration of the button with the event Listener Interface */

setSize(400,300);

setVisible(true);


}


public static void main(String args[])
{
GUIFrame g = new GUIFrame();
}


}


class ListenEvent implements ActionListener
{


GUIFrame g1;

ListenEvent(GUIFrame g1)
{
this.g1 = g1;
}

public void actionPerformed(ActionEvent e)
{
int n1,n2;

n1 = Integer.parseInt(g1.t1.getText());

n2 = Integer.parseInt(g1.t2.getText());

g1.t3.setText(String.valueOf(n1+n2));

}
}

Exception Program in Java

/* Pass 2 parameters from command Line. First parameter should be an integer , second is also an integer.Try to make the situation, that if user does not pass any parameter, then, there should be a message like "invalid parameter due to ArrayIndexOutOfBoundException".Second parameter for an array Size.If Array Size is -ve then, NegativeArraySizeException will be thrown and there should be a message
"ArraySize should not be -ve". Serach an element which is the args[0] position element from an user created Array. If that element not found from Array then a message should be displayed "Element not Found " else "Element Found";
**************************************************************************************/


import java.io.*; //Predefined package for input at run time


class Exceptionsize
{



public void test(String args[]) throws IOException, ArrayIndexOutOfBoundsException
{


try
{
int x,y, len = 0;

x=Integer.parseInt(args[0]);

y=Integer.parseInt(args[1]);

System.out.println(" User Entered from command Line...");

System.out.println("*************************************");

System.out.print(x + " " +y);

int total = x + y;

System.out.println(" Sum of 2 parameters passed from Command Line is : " + total );

System.out.println("***********************************");

len = args.length;

if(len<2)
{
throw new ArrayIndexOutOfBoundsException();
}


int size, i;

size = Integer.parseInt(args[1]);

int Arr[];


Arr = new int[size];

System.out.println("*********************************");

if(size < 0)
{
throw new NegativeArraySizeException();
}



else
{
System.out.println("Array Size is not -ve ");
}

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(in);


//BufferedReader br = new BufferedReader(new InputStreamReadern(System.in));

for(i = 0;i {
Arr[i] =Integer.parseInt(br.readLine());
}

System.out.println("*************************************");

System.out.println("Display Array Element...");

for(i=0;i {
System.out.print(" " + Arr[i]);
}

System.out.println();

System.out.println("Search that element which is the first parameter from command Line ");

System.out.println("*************************************");

boolean temp = false;

try
{

for(i = 0;i < size; i++)
{

if(Arr[i] == Integer.parseInt(args[0]))
{

System.out.println("***********");
System.out.print("Element Found");

temp = true;

break;
}

}

if(temp==false)
{

System.out.println("******************");
System.out.println(" Element not found ");

System.out.println("************");
}


}

catch(Exception e)
{


}
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Pls enter correct number of Argumets !!! ");
}

catch(NegativeArraySizeException e)
{
System.out.println("Array size should not be Negative ! Pls take positive number for Array size");
}

}





public static void main(String args[])
{
Exceptionsize obj=new Exceptionsize();


try
{
obj.test(args);
}

catch(Exception e)
{

}


finally
{

System.out.println("I am in finally block");
}

}

}

Event Handling Program in Java Using Frame

/*Design a Frame to calculate Electricity Bill for Consumers, where Current Month Reading(CMR) unit consumed has been provided with Last Month Reading(LMR) unit consumed.
So, calculate net unit consumed and Net Bill.
User Inputs : Consumer Number , Consumer Name, Address ,Current Month Reading(CMR) , Last Month Reading(LMR), Consumer Code .
What to find :-----
->Net Unit Consumed :(NUC)
->Rate per unit(RPU):
if Type Of Connections (TOC) :
Type Of Connections are as follows : - ******************************************************
# Agriculture - A
# Domestic - D
# Commercial - C
# Industrial - I
# Invalid - Default
_____________________________________________________________________________________________________*/
import java.awt.*;
import java.awt.event.*;

public class ElectricityBill extends Frame implements ActionListener
{
Label LblConsNo,LblConsName,LblConsAddress;
Label LblLMR,LblCMR,LblConsCode,LblConsNUC,LblRPU,LblNetBill,LblTOC;
TextField txtConsNo,txtConsName,txtConsAddress;
private TextField txtLMR, txtCMR,txtConsCode,txtConsNUC,txtRPU,txtNetBill,txtTOC;
Button BtnCalculate,BtnCancel;
public ElectricityBill()
{
super("-:Electricity Bill Calculation:-");
setLayout(new FlowLayout());
LblConsNo = new Label(" Enter Consumer Number: ");
LblConsName = new Label(" Enter Consumer Name: ");
LblConsAddress = new Label(" Enter Consumer Address: ");
LblLMR = new Label(" Enter Last Month Reading:");
LblCMR = new Label(" Enter Current Month Reading:");
LblConsCode = new Label(" Enter Consumer Code:[ A / D / C / I ]");
LblConsNUC = new Label(" Net Unit Consumed:");
LblRPU = new Label(" Rate Per Unit:");
LblNetBill = new Label(" Net Bill:");
LblTOC = new Label(" Type Of Connection:" );
txtConsNo = new TextField(20);
txtConsName = new TextField(20);
txtConsAddress = new TextField(20);
txtLMR = new TextField(20);
txtCMR = new TextField(20);
txtConsCode = new TextField(20);
txtConsNUC = new TextField(20);
txtRPU = new TextField(20);
txtNetBill = new TextField(20);
txtTOC = new TextField(20);
BtnCalculate = new Button("Calculate");
BtnCancel = new Button("Cancel");
add(LblConsNo);
add(txtConsNo);
add(LblConsName);
add(txtConsName);
add(LblConsAddress);
add(txtConsAddress);
add(LblLMR);
add(txtLMR);
add(LblCMR);
add(txtCMR);
add(LblConsCode);
add(txtConsCode);
add(LblConsNUC);
add(txtConsNUC);
add(LblRPU);
add(txtRPU);
add(LblNetBill);
add(txtNetBill);
add(LblTOC);
add(txtTOC);
add(BtnCalculate);
add(BtnCancel);
BtnCalculate.addActionListener(this);/*Registration of the Calculate Button with the event Listener Interface */
BtnCancel.addActionListener(this);
//addWindowListener(this);
setSize(400,500);
setVisible(true);
}
public static void main(String args[]) { ElectricityBill eb = new ElectricityBill(); }

public void actionPerformed(ActionEvent e)
{
int ConsNo;
String ConsName;
String ConsAddress;
int LMR,CMR;
char Code;
float RPU,NUC,NetBill;
String TOC;
if(e.getSource()==BtnCancel) { System.exit(0);
}
if(e.getSource()==BtnCalculate) { ConsNo = Integer.parseInt(txtConsNo.getText());
ConsName = txtConsName.getText();
ConsAddress = txtConsAddress.getText();
LMR = Integer.parseInt(txtLMR.getText());
CMR = Integer.parseInt(txtCMR.getText());
Code = txtConsCode.getText().charAt(0);
switch(Code) { case 'A':
RPU = 1.75f;
txtRPU.setText(String.valueOf(RPU));
NUC = CMR - LMR;
txtConsNUC.setText(String.valueOf(NUC));
NetBill = RPU*NUC;
txtNetBill.setText(String.valueOf(NetBill));
txtTOC.setText("Agriculture");
break; case 'D':
RPU = 3.75f;
txtRPU.setText(String.valueOf(RPU));
NUC = CMR - LMR;
txtConsNUC.setText(String.valueOf(NUC));
NetBill = RPU * NUC;
txtNetBill.setText(String.valueOf(NetBill));
txtTOC.setText("Domestic");
break;
case 'C': RPU = 5.90f;
txtRPU.setText(String.valueOf(RPU));
NUC = CMR - LMR;
txtConsNUC.setText(String.valueOf(NUC));
NetBill = RPU*NUC;
txtNetBill.setText(String.valueOf(NetBill));
txtTOC.setText("Commercial");
break; case 'I':
RPU = 10.75f;
txtRPU.setText(String.valueOf(RPU));
NUC = CMR - LMR;
txtConsNUC.setText(String.valueOf(NUC));
NetBill = RPU*NUC;
txtNetBill.setText(String.valueOf(NetBill));
txtTOC.setText("Inductrial");
break;
default:
RPU=0;
txtRPU.setText(String.valueOf(RPU));
NUC = CMR - LMR;
txtConsNUC.setText(String.valueOf(NUC));
NetBill= RPU * NUC;
txtNetBill.setText(String.valueOf(NetBill));
txtTOC.setText("Invalid Type Connection");
}
}
}
/*public void windowClosing(WindowEvent we) {
System.exit(0); }
public void windowActivated(WindowEvent we) {
}
public void windowClosed(WindowEvent we)
{
}
public void windowDeactivated(WindowEvent we)
{
}
public void windowDeiconified(WindowEvent we)
{
}
public void windowIconified(WindowEvent we)
{ }
public void windowOpened(WindowEvent we)
{ }*/

}