Professional Documents
Culture Documents
Lab Book
Lab Book
Section-II: Android
Dr. Vikas N. Mahandule MAEER’s MIT Arts Commerce & Science College, Alandi (D.),
Pune
Mrs. Vidya S. Chandgude MAEER’s MIT Arts Commerce & Science College, Alandi (D.),
Pune
Reviewed By:
Dr. Ranjit Patil Principal, Dr. D. Y. Patil ACS College Pimpri, Pune
Not Done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5
You have to ensure appropriate hardware and software is made available to each
student.
The operating system and software requirements on server side and also client side
are as given below:
Operating System - Windows
jdk 1.7 onwards. Tomcat 7.0 onwards
Android
Dot Net Framework
Assignment Completion Sheet
2 Multithreading
3 Socket Programming
Total ( Out of 25 )
Total (Out of 5)
Instructor Signature:
Section-II: Android
1 Introduction to Android
Total (Out of 5)
‘OR’
2 VB.Net
3 C#.Net
4 ASP.Net
5 ADO.Net
Total ( Out of 25 )
Total (Out of 5)
Instructor Signature:
Section – I
Advanced Java
Assignment No. 1: Introduction to JDBC
Introduction:
It is technique used to connect java application either with DSN or Database. For JDBC
application java.sql.* package has to import.
Jdbc Process:
For connecting java program with either database or DSN JDBC Process is used. It consists of
following steps:
1. To import JDBC-API.
The name of jdbc-api is java.sql. It consists of following classes and interfaces which are
require for the JDBC application. The List is as follow:
Interfaces:
Connection
Statement
PreparedStatement
CollableStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
Classes:
DriverManager
Class
2. To load the driver.
Loading is a process used to bring the drivers from operating system to JVM. For loading
drivers following statement is used:
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
The forName() is a static method of class Class used to load given driver into the JVM, If
driver is not available then it throws ClassNotFoundException.
3. To establish the connection between java program and Database or DSN (Data
Source Name).
4. To create a Statement.
Statement st=cn.createStatement ();
Statement interface is used to execute database queries after making the connection with
database. It is used to execute static query. The Statement interface has following
methods:
boolean execute()
int executeUpdate()
ResultSet executeQuery()
ResultSet rs
ENo EName Salary
101 Advait 70,000
102 Ajay 60,000
103 Vikas 80,000
For reading data record wise from ResultSet interface next() method is used.
rs.next()
101 Advait 70,000
Index of first column in ResultSet interface is 1. For reading data, column wise from
ResultSet interface getXXX() method is used.
The getXXX() method is available in 3 forms:
getInt() : It reads numeric value.
getFloat() : It reads float value.
getString() : It reads all kinds of values.
JDBC Components:
1. DriverManager Class:
Method Description
public static void It is used to deregister the given driver (drop the
deregisterDriver(Driver driver) driver from the list) with DriverManager.
Syntax:
2. Connection Interface:
Method Description
public void commit() It saves the changes made since the previous
commit/rollback permanent.
public void rollback() Drops all changes made since the previous
commit/rollback.
public void close() closes the connection and Releases a JDBC resources
immediately.
Syntax:
3. Statement Interface:
a. Statement
b. PreparedStatement
c. CallableStatement
a. Statement Interface:
The Statement interface provides methods to execute queries with the database.
The statement interface is a factory of ResultSet i.e. it provides factory method to get the
object of ResultSet.
The important methods of Statement interface are as follows:
Method Description
public boolean execute(String sql) It is used to execute queries that may return multiple
results.
b. PreparedStatement:
Method Description
public void setInt(int paramIndex, Sets the integer value to the given parameter
int value) index.
public void setString(int Sets the String value to the given parameter
paramIndex, String value) index.
public void setFloat(int Sets the float value to the given parameter index.
paramIndex, float value)
public void setDouble(int Sets the double value to the given parameter
paramIndex, double value) index.
public int executeUpdate() Executes the query. It is used for create, drop,
insert, update, delete etc.
c. CallableStatement Interface:
Syntax:
CallableStatement stmt=cn.prepareCall("{call Disp(?,?)}");
It is used to execute
It is used to execute parameterized or dynamic It is used to call the stored
normal SQL queries. SQL queries. procedures.
It is preferred when a
particular SQL query It is preferred when a It is preferred when the
is to be executed only particular query is to be stored procedures are to be
once. executed multiple times. executed.
You cannot pass the You can pass the You can pass 3 types of
parameters to SQL parameters to SQL query at parameters using this
query using this run time using this interface. They are – IN,
interface. interface. OUT and IN OUT.
4. ResultSet Interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int, int) method as well as we can make this object as updatable.
There are three Types of ResultSet:
Type Description
For Example
Statement st = cn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Method Description
public boolean next() It is used to move the cursor to the one row next from the
current position.
public boolean previous() It is used to move the cursor to the one row previous from
the current position.
public boolean first() It is used to move the cursor to the first row in result set
object.
public boolean last() It is used to move the cursor to the last row in result set
object.
public boolean It is used to move the cursor to the specified row number in
absolute(int row) the ResultSet object.
public boolean It is used to move the cursor to the relative row number in
relative(int row) the ResultSet object, it may be positive or negative.
public int getInt(int It is used to return the data of specified column index of the
columnIndex) current row as int.
public int getInt(String It is used to return the data of specified column name of the
columnName) current row as int.
public String It is used to return the data of specified column index of the
getString(int current row as String.
columnIndex)
public String It is used to return the data of specified column name of the
getString(String current row as String.
columnName)
Examples:
1. Write a Menu Driven Java program for the following:
1. Create
2. Insert
3. Update
4. Delete
5. Display
6. Exit
Solution:
import java.sql.*;
import java.io.*;
class DBDemo
{
public static void main(String args[]) throws Exception
{
String sql,sn;
int r,p,k,ch;
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:DSN","","");
Statement st=cn.createStatement();
do
{
System.out.println("1. Create");
System.out.println("2. Insert");
System.out.println("3. Update");
System.out.println("4. Delete");
System.out.println("5. Display");
System.out.println("6. Exit");
System.out.println("Enter Your Choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
sql="create table stud (rno number, sname text, per number)";
st.execute(sql);
System.out.println("Table Is Created...!");
break;
case 2:
System.out.println("RNo Sname Per");
r=Integer.parseInt(br.readLine());
sn=br.readLine();
p=Integer.parseInt(br.readLine());
sql="insert into stud values("+ r + ",'"+ sn +"'," + p +")";
k=st.executeUpdate(sql);
if(k>0)
System.out.println("Record Is Added...!");
break;
case 3:
System.out.println("RNo And Per");
r=Integer.parseInt(br.readLine());
p=Integer.parseInt(br.readLine());
sql="update stud set per=" + p + " where rno=" + r;
k=st.executeUpdate(sql);
if(k>0)
System.out.println("Record Is Updated...!");
break;
case 4:
System.out.println("RNo");
r=Integer.parseInt(br.readLine());
sql="delete from stud where rno=" + r;
k=st.executeUpdate(sql);
if(k>0)
System.out.println("Record Is Deleted...!");
break;
case 5:
System.out.println("Records from Table are...");
ResultSet rs=st.executeQuery("select * from stud");
while(rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " +
rs.getString(3));
}
break;
case 6:
cn.close();
System.exit(0);
}
}
while(ch!=6);
}
}
2. Write a java program for the implementation of DDL Commands.( Use Swing)
Solution:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
class DDLDemo extends Frame implements ActionListener
{
Button b1,b2,b3;
TextField t1;
String sql;
Label l1;
Connection cn;
Statement st;
public DDLDemo()
{
setLayout(null);
l1=new Label("Type Your Query Here");
t1=new TextField();
b1=new Button("Create");
b2=new Button("Alter");
b3=new Button("Drop");
l1.setBounds(100,100,100,30);
t1.setBounds(220,100,300,30);
b1.setBounds(100,140,100,30);
b2.setBounds(220,140,100,30);
b3.setBounds(340,140,100,30);
add(l1);
add(t1);
add(b1);
add(b2);
add(b3);
setSize(500,500);
setVisible(true);
setTitle("DDL Commands");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:DSN","","");
st=cn.createStatement();
}
catch(Exception obj)
{
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
Button b=(Button)ae.getSource();
if(b==b1)
{
sql=t1.getText();
st.execute(sql);
JOptionPane.showMessageDialog(null," Table Is Created");
}
if(b==b2)
{
sql=t1.getText();
st.execute(sql);
JOptionPane.showMessageDialog(null, "Table Is Altered");
}
if(b==b3)
{
sql=t1.getText();
st.execute(sql);
JOptionPane.showMessageDialog(null, "Table Is Deleted");
}
}
catch(Exception obj)
{
}
}
public static void main(String args[]) throws Exception
{
new DDLDemo();
}
}
l1.setBounds(100,100,100,30);
t1.setBounds(220,100,100,30);
l2.setBounds(100,140,100,30);
t2.setBounds(220,140,100,30);
l3.setBounds(100,180,100,30);
t3.setBounds(220,180,100,30);
b1.setBounds(100,220,100,30);
b2.setBounds(220,220,100,30);
b3.setBounds(100,260,100,30);
b4.setBounds(220,260,100,30);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
add(b3);
add(b4);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:TYBBACA","","");
st=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs=st.executeQuery("select * from emp");
rs.next();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
}
catch(Exception obj)
{
}
}
public void actionPerformed (ActionEvent ae)
{
try
{
JButton b=(JButton)ae.getSource();
if(b==b1)
{
rs.first();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
}
if(b==b2)
{
rs.next();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
}
if(b==b3)
{
rs.previous();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
}
if(b==b4)
{
rs.last();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
}
}
catch(Exception obj)
{
}
}
public static void main(String args[])
{
new ScrImp();
}
}
5. Write a java program to accept the details of Teacher(TID, TName, Salary) and
store it into the database. (PreparedStatement Interface).
Solution:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class PDemo extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2;
String sql,tn;
int s,tid,k;
Connection cn;
PreparedStatement ps;
public PDemo()
{
setLayout(null);
l1=new JLabel("TID");
l2=new JLabel("TName");
l3=new JLabel("Salary");
t1=new JTextField();
t2=new JTextField();
t3=new JTextField();
b1=new JButton("Save");
b2=new JButton("Cancel");
l1.setBounds(100,100,100,30);
t1.setBounds(220,100,100,30);
l2.setBounds(100,140,100,30);
t2.setBounds(220,140,100,30);
l3.setBounds(100,180,100,30);
t3.setBounds(220,180,100,30);
b1.setBounds(100,220,100,30);
b2.setBounds(220,220,100,30);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
setSize(500,500);
setVisible(true);
setTitle("Teacher Info");
b1.addActionListener(this);
b2.addActionListener(this);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:DSN","","");
}
catch(Exception obj)
{
}
}
public void actionPerformed(ActionEvent ae)
{
JButton b=(JButton)ae.getSource();
if(b==b1)
{
tid=Integer.parseInt(t1.getText());
tn=t2.getText();
s=Integer.parseInt(t3.getText());
try
{
sql="insert into emp values(?,?,?)";
ps=cn.prepareStatement(sql);
ps.setInt(1,tid);
ps.setString(2,tn);
ps.setInt(3,s);
k=ps.executeUpdate();
if(k>0)
JOptionPane.showMessageDialog(null,"Record Is Added....!");
}
catch(Exception obj)
{
System.out.println(obj);
}
}
if(b==b2)
{
try
{
cn.close();
System.exit(0);
}
catch(Exception obj)
{
}
}
}
public static void main(String args[])
{
new PDemo();
}
}
Set A:
1. Write a java program to count number of records in a table.
2. Write a java program to display all the EName from Emp table. Assume Emp (ENo,
EName, Salary) table is already created.
3. Write a java program to create Student table with attributes Rno, Sname, Per.
4. Write a java program to delete salary column from Emp table. Assume Emp table
with attributes ENo, EName and salary is already created.
5. Write a java program to delete the details of given Teacher. Assume Teacher table
with attributes tno, tname, subject is already created.
Set B:
1. Write a java program to accept the details of Hospital (HId, HName, Address,
PH_No) and store it into the database. (Use Swing).
2. Write a java program to display the details of Doctor (DNO, DName, Specialization)
on JTable. Assume Doctor table is already created.
3. Write a java program to make the changes in data which is in ResultSet if you make
the changes in data in database.
4. Write a java program for the following:
Create a Table
Alter a Table
Drop a Table
5. Write a java program to accept the details of College (CID, CName, Address) and
display it on next frame. (Use Swing and PreparedStatement).
Set C:
1. Write a java program for the following:
a. Create a table.
b. Insert
c. Update
d. Search
e. Display
2. Write a java program to update the salary of given employee and display updated
details in JTable. (Use Swing). Assume Emp (ENo, EName, Sal) table is already
created.
3. Write a java program for the implementation of Scrollable ResultSet. Consider
Teacher (TID, TName, Subject) table is already created.
4. Write a java program for the following:
Accept the details of 5 Employees (ENo, EName, Salary), store it into the JTable by
clicking on Add Button. If user clicks on Save button then data from JTable must be
save into the database.
5. Write a java program to create at least 5 tables in a database. Add a column(field) in a
given table. Drop given table from the database.
Assignment Evaluation:
Signature of Instructor
Assignment No 2: MultiThreading:
A smallest unit of a program which is in executive mode is called thread. Multithreading
allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within a
process.
There are basically two types of a thread, Main thread and child thread. A thread which
contains main method is called main thread and all other threads are called child threads.
Execution as well as termination of a program is done from the main thread.
Method Description
String getName() Retrieves the name of running thread in the current context in
String format
void start() This method will start a new thread of execution by calling
run() method of Thread/runnable object.
void run() This method is the entry point of the thread. Execution of
thread starts from this method.
void sleep(int This method suspend the thread for mentioned time duration in
sleeptime) argument (sleeptime in ms)
void yield() By invoking this method the current thread pause its execution
temporarily and allow other threads to execute.
void setName(String This method changes the name of this thread to be equal to the
name) argument name
synchronized (Object)
{
}
x7=x8=100;
y7=y8=150;
x5=y5=x6=y6=125;
x=x2=y2=100;
x3=x4=150;
y4=y3=100;
y=100;
x1=100;
y1=100;
t1=new Thread(this,"Ass");
t1.start();
}
}
catch(Exception obj)
{
}
}
public void paint(Graphics g)
{
g.drawLine(x,y,x1,y1);
g.drawLine(x,y,x2,y2);
g.drawLine(x3,y3,x4,y4);
g.drawLine(x5,y5,x6,y6);
g.drawLine(x7,y7,x8,y8);
}
}
3. Write a java program to blink image.
Solution:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Blink extends JFrame implements ActionListener,Runnable
{
Thread t1;
JLabel l1;
JButton b1;
boolean b;
public Blink()
{
b=true;
setLayout(null);
ImageIcon img=new ImageIcon("Koala.jpg");
l1=new JLabel(img);
t1=new Thread(this,"DYP");
b1=new JButton("Blink");
l1.setBounds(100,100,100,100);
b1.setBounds(100,210,100,30);
add(l1);
add(b1);
setSize(400,400);
setVisible(true);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
t1.start();
}
public void run()
{
try
{
while(true)
{
t1.sleep(500);
if(b==true)
{
l1.setVisible(true);
b=false;
}
else
{
l1.setVisible(false);
b=true;
}
}
}
catch(Exception obj)
{
}
}
public static void main(String args[])
{
new Blink();
}
}
t1.setBounds(100,100,100,30);
b.setBounds(100,140,100,30);
add(t1);
add(b);
b.addActionListener(this);
setSize(400,400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
t.start();
}
public void run()
{
try
{
for(i=1;i<=100;i++)
{
t.sleep(200);
t1.setText(Integer.toString(i));
}
}
catch(Exception obj)
{
}
}
public static void main(String args[])
{
new NumText();
}
}
5. Write a program to calculate the sum and average of an array of 1000 integers
(generated randomly) using 10 threads. Each thread calculates the sum of 100
integers. Use these values to calculate average. [Use join method ].
Solution:
import java.util.*;
class Mythread implements Runnable
{
Thread t;
int i,no,sum;
int a[]=new int[1000];
String TN="";
Mythread(String s,int n)
{
TN=s;
Random rs = new Random();
t=new Thread(this,s);
no=n;
int j=0;
for(i=1;i<=1000;i++)
{
a[j]=rs.nextInt(1000);
j++;
}
t.start();
}
public void run()
{
for(i=0;i<100;i++)
{
sum=sum+a[no];
no++;
}
System.out.println("Name of thread is = "+TN);
System.out.println("Sum = "+sum);
System.out.println("Avg ="+sum/100);
}
}
public class ThreadDemo
{
public static void main(String[] arg) throws InterruptedException
{
int n=0;
String TName[]={"One","Two","Third","Fourth","Fifth","Six", "Seven",
"Eighth","Nineth", "Tenth" };
Mythread T[] = new Mythread[10];
for(int i=0;i<10;i++)
{
T[i]=new Mythread(TName[i],n);
n=n+100;
T[i].t.join();
}
}
}
Set B:
1. Program to define a thread for printing text on output screen for ‘n’ number of times.
Create 3 threads and run them. Pass the text ‘n’ parameters to the thread constructor.
Example:
i. First thread prints “Hello” 10 times.
ii. Second thread prints “Good Morning” 20 times
iii. Third thread prints “Sir/Mam” 30 times.
2. Write a java program in multithreading to create 3 balls and bounce them vertically.
3. Write a java program in multithreading to draw five lines vertically.
4. Write a java program to create 2 cars and move them randomly from left to right.
5. Write a java program to display the characters from a given string into the TextField.
Each character should be displayed after 1 second.
Set C:
2. Write a program to calculate the sum and average of an array of 1000 integers
(generated randomly) using 10 threads. Each thread calculates the sum of 100
integers. Use these values to calculate average. [Use join method ].
3. Write a program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the value is odd, the third
thread will print the value of cube of the number.
4. Write a java program for drawing simple house.
5. Write a java program for drawing star on the applet container.
Assignment Evaluation:
Signature of Instructor
3. Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE. Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server
2. Port number.
Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server; server reads the message and prints it. Here, two classes are
being used: Socket and ServerSocket. The Socket class is used to communicate client and server.
Through this class, we can read and write message. The ServerSocket class is used at server-side.
The accept () method of ServerSocket class blocks the console until the client is connected. After
the successful connection of client, it returns the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.
Important methods:
Method Description
1) public InputStream getInputStream() Returns the InputStream attached with this socket.
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description
1) public Socket accept() Returns the socket and establish a connection between
server and client.
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept () method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket (6666);
Socket s=ss.accept ();//establishes connection and waits for the client.
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to
pass the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.
Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives and
prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println ("message= "+str);
ss.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e){System.out.println(e);}
}
}
Communication
To communicate over a socket connection, streams are used to both input and output the data.
Communication
The getOutputStream () method is used to send the output through the socket.
Important Points
Server application makes a ServerSocket on a specific port which is 5000. This starts
our Server listening for client requests coming in for port 5000.
Then Server makes a new Socket to communicate with the client.
socket c = server.accept()
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method. Our Server keeps
receiving messages until the Client sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them. Then
first run the server application and then run the Client application.
For knowing IPAddress of a machine type ipconfig command on command prompt.
Client accepted
3. Then you can start typing messages in the Client window. Here is a sample input to the
Client
Hello
I made my first socket connection
Over
Which the Server simultaneously receives and shows,
Hello
I made my first socket connection
Over
Closing connection
Notice that sending “Over” closes the connection between the Client and the Server just like
said before.
Solved Examples:
1. Java program to display IPAddress of a Machine.
Solution:
import java.io.*;
import java.net.*;
class AssAddr
{
public static void main(String args[]) throws Exception
{
System.out.println("IPAddress Is " + InetAddress.getLocalHost());
}
}
2. Write a java program to display date of Server machine on client’s machine.
Solution:
Client.java
import java.io.*;
import java.net.*;
import java.util.*;
class Client
{
public static void main(String args[]) throws Exception
{
String str;
Socket c=new Socket(InetAddress.getLocalHost(),1234);
DataInputStream din=new DataInputStream(c.getInputStream());
DataOutputStream dout=new
DataOutputStream(c.getOutputStream());
dout.writeUTF("Date Plz");
str=din.readUTF();
System.out.println("Date Is " + str);
}
}
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
public static void main(String args[]) throws Exception
{
String str;
ServerSocket s=new ServerSocket(1234);
System.out.println("Wait....Server is Starting");
Socket c=s.accept();
DataInputStream din=new DataInputStream(c.getInputStream());
DataOutputStream dout=new DataOutputStream(c.getOutputStream());
Date d=new Date();
dout.writeUTF("Date Is : + d);
}
}
Set A:
1. Write a java program to display IP address of a machine.
2. Write a java program to accept a number in client application, send it to the server, server
will check whether it is Armstrong or not and sends result accordingly to the client.
3. Write a java program to send “Hi” message to the Server.
4. Write a java program to accept a user name in client application and greets to the user
according to the time on server machine.
5. Write a java program to accept a string in client application and display the vowels from
that string on server terminal.
Set B:
1. Write a java program for standalone chatting application.
2. Write a java program to accept a filename in client application and check whether it is
available on server machine or not, if it there then display its contents on client’s terminal
otherwise display the message “File Not Found”. (Write Client and Server application on
different terminals.)
3. Write a java program to accept a number in client application, send it to the server, server
will calculates its factors and display them on the client terminal. (Each factor should
display after 2 seconds). Write Client and Server application on different terminals.
Set C:
1. Write a java program for chatting application. (Use Swing for GUI). (Write Client and
Server application on different terminals).
2. Write a java program to send and receive the messages from multiple terminals.
3. Write a java program to share a file on server machine between multiple clients.
Assignment Evaluation:
Signature of Instructor
4. Servlet and JSP:
Servlet is a server-side Java program that executes on tomcat web server.
Servlet is a technology which is used to create a web application.
Servlet is an API that provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
Servlet is a web component that is deployed on the server to create a dynamic web page.
Servlet is server side scripting language so it does not have main() method.
Servlet application compiled by using javac compiler explicitly.
For developing Servlet application in java following API’s must be imported:
o javax.servlet.*;
o javax.servlet.http.*;
o java.io.*
There are two types Servlet:
GenericServlet
HttpServlet
The GenericServlet and HttpServlet are the classes belongs to packages javax.servlet.*
and javax.servlet.http.*.
Methods of Servlet
Method Description
public void init(ServletConfig config) Initializes the Servlet. It is the life cycle
method of Servlet and invoked by the web
container only once.
public void service(ServletRequest Provides response for the incoming request.
request, ServletResponse response) It is invoked at each request by the web
container.
public void destroy() Is invoked only once and indicates that
Servlet is being destroyed.
public ServletConfig Returns the object of ServletConfig.
getServletConfig()
public String getServletInfo() Returns information about Servlet such as
writer, copyright, version etc.
MY_WEBAPP
2. Write a client side request application and save it into your web application folder with
.html extension.
Note: In form tag the action parameter should be the Servlet “.class” file name.
<html>
<body>
<form method=post action="Demo">
Enter your Name<input type=text name="nm">
<input type=submit name=submit value=submit>
</form>
</body>
</html>
3. The WEB-INF folder is a web information folder which holds the information about
your web application such as the .class file and deployment descriptor i.e. web.xml
<web-app>
<servlet>
<servlet-name> My_WEBAPP </servlet-name>
<servlet-class>Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> My_WEBAPP </servlet-name>
<url-pattern>/Demo</url-pattern>
</servlet-mapping>
</web-app>
4. Now write the java program and save it in classes folder. Compile it and a “.class file”
will be generated.
Note: Classes folder must be represented in a small case letter.
The “.class file” very important here it is used in form tag of HTML file as well as in
web.xml for mapping
For Example: In the “.html” file we used “Demo” as class file name then we must create a
“Demo.java” servlet file.
Java Servlet Program to accept name from user and display on browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Demo extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType ("text/html");
// set the type of response given to client
PrintWriter out = response.getWriter ();
// For using println() to display output
String name = request.getParameter ("nm"); //accepting
input request from client (Note: nm is a variable from .html file)
out.print("Hello "+name);
out.close();
}
catch(Exception exp)
{
System.out.println (exp);
}
}
}
Save the above program in C:\Program Files\Apache Software
Foundation\Apache Tomcat 8.0.27\webapps\My_WEBAPP\WEB-INF\classes\. Compile
and a class file “Demo.class:” is generated.
Methods of ServletRequest
ServletRequest Methods Description
String getParameter(String name) Obtains the value of a parameter sent to the
servlet as part of a get or post request. The name
argument represents the parameter name.
Enumeration getParameterNames() Returns the names of all the parameters sent to the
servlet as part of a post request.
String[] getParameterValues(String For a parameter with multiple values, this method
name) Returns an array of strings containing the values
for a specified servlet parameter.
String getProtocol() Returns the name and version of the protocol the
request uses in the form
protocol/majorVersion.minorVersion, for
example, HTTP/1.
String getRemoteAddr() Returns the Internet Protocol (IP) address of the
client that sent the request.
String getRemoteHost() Returns the fully qualified name of the client that
sent the request.
int getServerPort() Returns the port number on which request was
received.
String getServerName() Returns the host name of the server that received
the request.
HttpServletRequest Methods
Cookie[] getCookies() Returns an array of Cookie objects stored on the
client by the server.
HttpSession getSession(boolean create) Returns an HttpSession object associated with the
client's current browsing session. This method can
create an HttpSession object (True argument)if
one does not already exist for the client.
String getServletPath() Returns the part of this request's URL that calls
the servlet.
String getMethod() Returns the name of the HTTP method with
which this request was made, for example, GET,
POST, or PUT.
String getQueryString() Returns the query string that is contained in the
request URL after the path.
String getPathInfo() Returns any extra path information associated
with the URL the client sent when it made this
request.
String getRemoteUser() Returns the login of the user making this request,
ifm the user has been authenticated, or null if the
user has not been authenticated.
ServletResponse Methods
OutputStream getOutputStream() Obtains a byte-based output stream for sending
binary data to the client.
PrintWriter getWriter() Obtains a character-based output stream for
sending text data (usually HTML formatted text)
to the client.
void setContentType(String type) Specifies the content type of the response to the
browser. The content type is also known as
MIME (Multipurpose Internet Mail Extension)
type of the data. For examples, "text/html",
"image/gif"etc.
String setContentLength(int len) Sets the length of the content body in the response
In HTTP servlets, this method sets the HTTP
Content-Length header.
HttpServletResponse Methods
void addCookie(Cookie cookie) Used to add a Cookie to the header of the
response to the client.
void sendError(int ec) Sends an error response to the client using the
specified status.
void sendError(int ec, String msg) Sends an error response to the client using the
specified status code and descriptive message.
void sendRedirect (String url) Sends a temporary redirect response to the client
using the specified redirect location URL.
void setHeader(String name, String Sets a response header with the given name and
value) value.
Solved Example:
1. Write a servlet application to display marksheet on to the browser.
Solution:
Index.html
<html>
<body>
<form method="Get" action="Mark">
<pre>
Seat No <input type="text" name="t1">
Stud Name <input type="text" name="t2">
Class <input type="text" name="t3">
Total Marks <input type="text" name="t4">
<input type="submit" value="Submit">
</pre>
</form>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>Ass15B</servlet-name>
<servlet-class>Mark</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ass15B</servlet-name>
<url-pattern>/Mark</url-pattern>
</servlet-mapping>
</web-app>
Mark.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Mark extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String sno=req.getParameter("t1");
String sn=req.getParameter("t2");
String cn=req.getParameter("t3");
int tm=Integer.parseInt(req.getParameter("t4"));
int p=tm/6;
String gd;
if(p>=70)
{
gd="Dist";
}
else if(p>=60 && p<70)
{
gd="First";
}
else if(p>=50 && p<60)
{
gd="Second";
}
else if(p>=40 && p<50)
{
gd="Pass";
}
else
gd="Fail";
JSP is Java Server Page, which is a dynamic web page and used to build dynamic websites.
To run JSP, we need web server which can be tomcat provided by apache.
JSP is dynamic file where as Html file is static. HTML cannot get data from database or
dynamic data.
JSP can be interactive and communicate with database and controllable by programmer.
It is saved by extension of .jsp. Each Java server page is compiled into a servlet before it can
be used. This is normally done when the first request to the JSP page is made.
There is no need to compile jsp page it gets compiled implicitly by JSP Engine.
For writing JSP application its delimiters are used: Starting Delimiter (<%) and ending
Delimiter(%>)
JSP Elements
A JSP contains three important types of elements:
1. JSP Directives:
Directives are message to the JSP container that enable the programmer to specify page
setting to include content from other resources & to specify custom tag libraries for use in
a JSP.
Syntax: <%@ name attribute1=”….”, attribute2=”…”…%>
For example:
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ] [ session="true|false" ]
[ buffer="none|8kb|sizekb" ] [ autoFlush="true|false" ]
[ isThreadSafe="true|false" ] [ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType [ ; charset=characterSet ]" | "text/html ; charset=ISO-8859-1"
]
[ isErrorPage="true|false" ]
[ pageEncoding="characterSet | ISO-8859-1" ]
%>
Program to display current Date.
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
b. Include Directive:
An include directive is used to include the contents of any resource it may be JSP file, HTML
file or text file.
If we want to use any file in JSP file then we can use include directive.
An include directive includes the original content of the included resource at page translation
time (the JSP page is translated only once so it will be better to include static resource).
Syntax:<%@ include file="resourceName" %>
Note: resourseName is any file which we want to use in current JSP file
Program to include welcome.html
<html>
<body>
<%@ include file="welcome.html" %>
Today is: <%= java.util.Calendar.getInstance ().getTime() %>
</body>
</html>
c. Taglib Directive:
The JSP taglib directive is used to define a tag library that defines many tags.
We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we
will use this tag so it will be better to learn it in custom tag.
Syntax: <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
For Example: In this example, we are using our tag named currentDate. To use this tag we
must specify the taglib directive so the container may get information about the tag.
Program to demonstrate taglib directive.
<html>
<body>
<%@ tagliburi="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
2. Scripting Elements:
In JSP, java code can be written inside the jsp page using the scriptlet tag.
The scripting elements provide the ability to insert java code inside the jsp.
There are three types of scripting elements:
a. Declaration Tag:
A declaration declares one or more variables or methods that you can use in Java code later
in the JSP file.
Syntax: <%! Java declaration statements %>
Example:
<%! private int count = 0; %>
<%! int i = 0; %>
b. Expressions Tag:
An expression element contains a java expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file.
Syntax: <%= expression %>
Example: Your name is <%= request.getParameter("name") %>
c. Scriptlet Tag:
A scriptlet contains a set of java statements which is executed.
A scriptlet can have java variable and method declarations, expressions, use implicit objects
and contain any other statement valid in java.
Syntax: <% statements %>
Write a JSP Script to display Hello message to the User.
<html>
<body>
<form method=”Get” action=”Name.jsp”>
User Name <input type=”text” name=”username”>
<input type=”submit” value=”Submit”>
<%
String name = request.getParameter("userName");
out.println(“Hello “ + name);%>
Solved Examples:
1. Write a JSP application to check whether given mail ID is valid or not.
Solution:
Index.html
<html>
<body>
<form method="Get" action="AssVal.jsp">
Enter EMail ID <input type="text" name="t1"> <br>
<input type="submit" value="Submit">
</form>
</body>
</html>
AssVal.jsp
<%
String em;
int i,l,scnt=0,dcnt=0;
char ch;
em=request.getParameter("t1");
l=em.length();
for(i=0;i<l;i++)
{
ch=em.charAt(i);
if(ch=='.')
{
dcnt++;
}
if(ch=='@')
{
scnt++;
}
}
if(dcnt==0)
{
out.println("Invalid....It does not contain Dot(.)");
}
else if(scnt>1 || scnt<1)
{
out.println("It does not have @ symbol or more than one @
symbol");
}
else
out.println("Valid Email Id " + em);
%>
2. Write a JSP Application to accept nick name and Name from a user, If visit count is even then
display name otherwise display nickname.
Solution:
Index.html
<html>
<body>
<form method="Get" action="NickName.jsp">
<pre>
Name <input type="text" name="t1">
Nick Name <input type="text" name="t2">
<input type="submit" value="Submit">
</pre>
</form>
</body>
</html>
NickName.jsp
<%! static int cnt;%>
<%
String nm,nk;
nm=request.getParameter("t1");
nk=request.getParameter("t2");
cnt++;
if(cnt%2==0)
out.println(nk);
else
out.println(nm);
%>
Set A
a) Design a servlet that provides information about a HTTP request from a client, such
as IP address and browser type. The servlet also provides information about the server
on which the servlet is running, such as the operating system type, and the names of
currently loaded servlets.
d) Write a JSP script to display all the prime number’s between 1 to n in Red Color.
e) Write a JSP application to accept the details of Emp (Eno, EName, Salary) and display
it in Tabular format on the browser.
Set B
a) Design an HTML page which passes customer number to a search servlet. The servlet
searches for the customer number in a database (customer table) and returns customer
details if found the number otherwise display error message.
b) Design an HTML page containing option buttons (Maths, Physics, Chemistry and
Biology) and buttons submit and reset. When the user clicks submit, the server
responds by adding a cookie containing the selected subject and sends a message back
to the client. Program should not allow duplicate cookies to be written.
c) Write a Servlet program to display the details of PATIENT (PatientNo, PatientName,
PatientAddress, Patientage, PatientDiease) in tabular form on browser.
d) Write a JSP application to accept a user name and greets to the user according to the
system Time.
Set C
a) Create a JSP page for an online multiple choice test. The questions are randomly
selected from a database and displayed on the screen. The choices are displayed
using radio buttons. When the user clicks on next, the next question is displayed.
When the user clicks on submit, display the total score on the screen.
b) Write a program to create an Online Book purchase. User must be login and then
purchase the book. Each page should have a page total. The last page should display a
total book and bill, which consists of a page total of whatever the purchase has been
done and print the total. (Use HttpSession)
c). Write a JSP application to accept the details of Teacher (TID, TName, Salary) and
display it in tabular format.
Assignment Evaluation:
Signature of Instructor
5 Spring and Hibernate
What is Spring?
Spring is an open source framework created to address the complexity of enterprise
application development. Spring is a very lightweight framework which provides well-defined
infrastructure support for developing Java application.
Why Spring?
Spring is considered to be a secure, low-cost and flexible framework. Spring improves coding
efficiency and reduces overall application development time because it is lightweight and
efficient at utilizing system resources. Spring removes tedious configuration work so that
developers can focus on writing program logic. Spring handles the infrastructure so
developers can focus on the application.
Spring Framework
The Spring Framework is one of the most popular Java-based application Frameworks. It is
an application framework and Inversion of Control (IoC) container for the Java platform. The
Spring Framework is a mature, powerful and highly flexible framework focused on building
Web applications in Java. The Spring Framework provides a comprehensive programming
and configuration model for modern Java-based enterprise applications - on any kind of
deployment platform.
Spring Module
JDBC Module: This module provides the JDBC abstraction layer and helps to avoid tedious
JDBC coding.
ORM Module: This module provides integration for object relational mapping APIs such as
JPA, Hibernate, JDO, etc.
JMS (Java Messaging Service) Module: This module contains features for producing and
consuming messages.
Model: A model contains the data of the application. A data can be a single object or a
collection of objects. The Model encapsulates the application data and in general they will
consist of POJO.
View: View is responsible for presenting data to the end user. A view represents the provided
information in a particular format. The View is responsible for rendering the model data and
in general it generates HTML output that the client's browser can interpret.
Controller: The controller is a logic that is responsible for processing and acting on user
requests. The Controller is responsible for processing user requests and building an
appropriate model and passes it to the view for rendering.
Annotation Description
@Controller : It represents the controller class
@RequestMapping: It can be used for the mapping of incoming requests.
@GetMapping : It is used to map HTTP Get requests.
@PostMapping : It is used to map HTTP Post requests.
@RequestParam : It reads the HTML form data.
@ModelAttribute : This annotation accesses elements present
pom.xml
It stands for Project Object Model. POM is a fundamental unit of work in Maven.
Project Object Model (POM) is a XML file that contains information about the project and
configuration details used by Maven to build the project. When executing a task, Maven
looks for the POM in the current directory. It reads the POM, gets the required configuration
and information, then executes the goal. Configurations specified in the POM are the
project dependencies, the plugins or goals that can be executed, the build project.
Download the Spring Tool Suits 4 for that follow the link https://spring.io/tools
Example
Step 1: Create Java Project: The first step is to lunch the workspace and then create a
simple spring starter project. Follow the option File → New → Spring Starter Project and
finally select Java Project wizard from the wizard list. Lunch workspace window as
shown in Fig.
Now name the project as SpringCore is created successfully.
Step 2: Add Required Libraries: As a second step let us add Spring Framework and
common logging API libraries in our project. To do this, right-click on the project name
springcore and then follow the following option available in the context menu − Build
Path - Configure Build Path to display the Java Build Path window.
Now use Add External JARs button available under the Libraries tab to add the following
core JARs from Spring Framework and Common Logging installation directories:
commons-logging-1.1.1
spring-aop-4.1.6.RELEASE
spring-aspects-4.1.6.RELEASE
spring-beans-4.1.6.RELEASE
spring-context-4.1.6.RELEASE
spring-context-support-4.1.6.RELEASE
spring-core-4.1.6.RELEASE
spring-expression-4.1.6.RELEASE
spring-instrument-4.1.6.RELEASE
spring-instrument-tomcat-4.1.6.RELEASE
spring-jdbc-4.1.6.RELEASE
spring-jms-4.1.6.RELEASE
spring-messaging-4.1.6.RELEASE
spring-orm-4.1.6.RELEASE
spring-oxm-4.1.6.RELEASE
spring-test-4.1.6.RELEASE
spring-tx-4.1.6.RELEASE
spring-web-4.1.6.RELEASE
spring-webmvc-4.1.6.RELEASE
spring-webmvc-portlet-4.1.6.RELEASE
spring-websocket-4.1.6.RELEASE
Step 3: Create Source Files: Now let us create actual source files under the SpringCore
project. First we need to create a package called springcore.
Example: To do this, right click on src in package explorer section and follow the option − New
Package. Next we will create HelloBean.java and Main.java files.
Here is the content of HelloBean.java file:
package springcore.example;
public class HelloBean
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void sayHello()
{
System.out.println("Hello" + this.name);
}
}
Content of the second file Main.java
//Main.java
package springcore.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main
{
private static ApplicationContext context;
public static void main(String[] args)
{
context = new ClassPathXmlApplicationContext("beans.xml");
HelloBean helloBean = (HelloBean) context.getBean("HelloBean");
helloBean.sayHello();
}
}
Step 4: Create Bean Configuration File: We need to create a Bean Configuration file which
is an XML file and acts as cement that glues the beans, i.e. the classes together. This file
needs to be created under the src directory (Src/main/resources) beans.xml.
Usually developers name this file as Beans.xml, but we are independent to choose any
name we like.
//beans.xml
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://ww
w.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.sprin
gframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scanbase-package="springcore.examples"/>
<bean id="HelloBean"class="springcore.example.HelloBean">
<propertyname="name"value="Spring Programe"/>
</bean>
//pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springcore_example</groupId>
<artifactId>SpringCoreExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
Step 5: Running the Program: Once we are done with creating the source and beans
configuration files, we are ready for this step, which is compiling and running the
program. To do this, keep Main.java file tab active and use either Run option. If
everything is fine with the application, this will print the following message in console.
Hibernate:
Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The javax.persistence package contains the JPA classes and interfaces.
The Hibernate architecture includes many objects such as persistent object, session factory,
transaction factory, connection factory, session, transaction etc.
Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction
API) and JNDI (Java Naming Directory Interface).
Elements of Hibernate Architecture
For creating the first hibernate application, we must know the elements of Hibernate
architecture. They are as follows:
SessionFactory
Session
The session object provides an interface between the application and data stored in the database.
It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and
Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface
provides methods to insert, update and delete the object. It also provides factory methods for
Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
TransactionFactory
Here, we are going to create the first hibernate application without IDE. For creating the first
hibernate application, we need to follow the following steps:
Employee.java
package com.javatpoint.mypackage;
public class Employee {
private int id;
private String firstName,lastName;
The mapping file name conventionally, should be class_name.hbm.xml. There are many
elements of the mapping file.
hibernate-mapping : It is the root element in the mapping file that contains all the
mapping elements.
class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent
class.
id : It is the subelement of class. It specifies the primary key attribute in the class.
generator : It is the sub-element of id. It is used to generate the primary key. There are
many generator classes such as assigned, increment, hilo, sequence, native etc. We will
learn all the generator classes later.
property : It is the sub-element of class that specifies the property name of the Persistent
class.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
The configuration file contains information about the database and mapping file. Conventionally,
its name should be hibernate.cfg.xml .
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</proper
ty>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
In this class, we are simply storing the employee object to the database.
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {
//Create typesafe ServiceRegistry object
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hiberna
te.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
5) Load the jar file
For successfully running the hibernate application, you should have the hibernate5.jar file.
Download the required jar files for hibernate
We may run this hibernate application by IDE (e.g. Eclipse, Myeclipse, Netbeans etc.) or without
IDE.
Here, we are going to create a simple example of hibernate application using eclipse IDE. For
creating the first hibernate application in Eclipse IDE, we need to follow the following steps:
Create the java project by File Menu - New - project - java project . Now specify the
project
name e.g. firsthb then next - finish .
To add the jar files Right click on your project - Build path - Add external archives.
Now select all the jar files as shown in the image given below then click open.
In this example, we are connecting the application with oracle database. So you must add the
ojdbc14.jar file.
Here, we are creating the same persistent class which we have created in the previous topic. To
create the persistent class, Right click on src - New - Class - specify the class with package
name (e.g. com.javatpoint.mypackage) - finish .
Employee.java
package com.javatpoint.mypackage;
public class Employee {
private int id;
private String firstName,lastName;
public int getId()
{
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
Here, we are creating the same mapping file as created in the previous topic. To create
the mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml)
- ok. It must be outside the package.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
The configuration file contains all the information’s for the database such as connection_url,
driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in
the database automatically. We will have in-depth learning about Dialect class in next topics. To
create the configuration file, right click on src - new - file. Now specify the configuration file
name e.g. hibernate.cfg.xml.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</proper
ty>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
In this class, we are simply storing the employee object to the database.
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main( String[] args )
{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hiberna
te.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Employee e1=new Employee();
e1.setId(1);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
7) Run the application
Before running the application, determine that directory structure is like this.
To run the hibernate application, right click on the StoreData class - Run As - Java
Application.
Set A
Set B
a) Design a Spring application for accepting student information like Student_id, Student_Name
and Student_Age.
b) Design an Employee login form application using spring form MVC validation.
Assignment Evaluation:
Signature of Instructor
Section II: Android
Assignment 1: Introduction to Android
Objectives
Reading
You should read the following topics before starting this exercise:
1. Installing Android Studio
2. Create "Hello World" application
3. Explore the project structure
4. The Gradle build system
5. Create a virtual device (emulator)
6. Run your app on an emulator
7. Android Architecture
1. Installing Android Studio
1) Install Java JDK: Get the latest version. The JDK may be downloaded here
https://www.oracle.com/java/technologies/downloads/#java8
2) Install Android Studio bundle. Use the latest stable version. Android Studio may be downloaded here:
https://developer.android.com/studio
3) Follow the prompts to complete the installation. I used the default settings.
4) Allow Android Studio access to the network.
5) Select your desired UI theme.
6) Android Studio will download additional components. This will take several minutes.
7) Select ―Configure/SDK Manager.
8) Deselect All. Scroll down and select ―Android 8.1 (API 27) Install the packages.
1
2. Create "Hello World" application
1. In the Welcome to Android Studio window, click Create New Project. (If you have a project already
opened, select File > New > New Project.)
2. In the Select a Project Template window, select Empty Activity and click Next.
4. Click Finish.
2
5. After some processing time, the Android Studio main window appears.
3
consistent across your app. Expand the values subfolder within the res folder. It includes these
subfolders:
o colors.xml: Shows the default colors for your chosen theme, and you can add your own colors
or change them based on your app's requirements.
o dimens.xml: Store the sizes of views and objects for different resolutions.
o strings.xml: Create resources for all your strings. This makes it easy to translate them to other
languages.
o styles.xml: All the styles for your app and theme go here. Styles help give your app a
consistent look for all UI elements.
4. The Gradle build system:
Android Studio uses Gradle as its build system. As you progress through these practicals, you will learn more
about gradle and what you need to build and run your apps.
1. Expand the Gradle Scripts folder. This folder contains all the files needed by the build system.
2. Look for the build.gradle(Module:app) file. When you are adding app-specific dependencies,
such as using additional libraries, they go into this file
5. Create a virtual device (emulator)
In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device or emulator
that simulates the configuration for a particular type of Android device. Using the AVD Manager, you define
the hardware characteristics of a device and its API level, and save it as a virtual device configuration. When
you start the Android emulator, it reads a specified configuration and creates an emulated device that behaves
exactly like a physical version of that device, but it resides on your computer. With virtual devices, you can
test your apps on different devices (tablets, phones) with different API levels to make sure it looks good and
works for most users. You do not need to depend on having a physical device available for app development.
In order to run an emulator on your computer, you have to create a configuration that describes the virtual
device.
o In Android Studio, select Tools > AVD Manager, or click the AVD Manager icon in the toolbar.
o Click the +Create Virtual Device…. (If you have created a virtual device before, the window
shows all of your existing devices and the button is at the bottom.) The Select Hardware screen
appears showing a list of preconfigured hardware devices. For each device, the table shows its
diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density (Density).
o Choose which version of the Android system to run on the virtual device. You can select the latest
system image. There are many more versions available than shown in the recommended tab.
o If a Download link is visible next to a system image version, it is not installed yet, and you need to
download it. If necessary, click the link to start the download, and click Finish when it's done.
o On System Image screen, choose a system image and click Next.
o Verify your configuration, and click Finish. (If the Your Android Devices AVD Manager window
stays open, you can go ahead and close it.)
6. Run your app on an emulator
1) In Android Studio, select Run > Run app or click the Run icon in the toolbar.
2) In the Select Deployment Target window, under Available Emulators, select Pixel API 27 and click
OK
3) You should see the Hello World app as shown in the following screenshot.
7. Android Architecture
Android architecture or Android software stack is categorized into five parts:
1. Linux kernel
4
2. Native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
1) Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible
for device drivers, power management, memory management, device management and resource access.
2) Native Libraries
On the top of Linux kernel, there are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media,
C runtime library (libc) etc. The WebKit library is responsible for browser support. SQLite is for database.
FreeType for font support, Media for playing and recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run
android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and
provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android framework
includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data)
and package managers. It provides a lot of classes and interfaces for android application development.
5) Applications
On the top of android framework, there are applications. All applications such as home, contact, settings,
games, browsers are using android framework that uses android runtime and libraries. Android runtime and
native libraries are using Linux kernel.
Objectives
• To study how to use Activities, Layouts and Intents in the application.
5
• To study different layout in an Android.
• To study how to link Activities and interaction between Intent.
Reading
You should read the following topics before starting this exercise:
• Android - UI Layouts
• Activity, Activity Lifecycle
• Linking Activities using Intent.
Ready Reference
1) Android - UI Layouts
A layout defines the structure for a user interface in our app, such as in an activity. All elements in the
layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something
the user can see and interact with. Whereas a View Group is an invisible container that defines the
layout structure for View and other ViewGroup objects.
The View objects are usually called
"widgets" and can be one of many
subclasses, such as Button or TextView.
The ViewGroup objects are usually called
"layouts" can be one of many types that
provide a different layout structure, such
as LinearLayout or ConstraintLayout .
There are number of Layouts provided by
Android which we will use in almost all the Android applications to provide different view, look and
feel and they are...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
LinearLayout:
android:layout_height="wrap_content"
android:text="This is a TextView"/>
<Button android:id="@+id/button"
android:layout_width="wrap_content"
Android LinearLayout is a view group that aligns
android:layout_height="wrap_content"
all children in a single direction either vertically
android:text="This is a Button"/>
or horizontally.
<EditText
android:id="@+id/edtPainText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a EditText"/>
<!-- More GUI components go here -->
</LinearLayout>
6
Android RelativeLayout enables you to specify android:paddingLeft="16dp"
how child views are positioned relative to each android:paddingRight="16dp" >
other. The position of each view can be specified <EditText
as relative to sibling elements or relative to the android:id="@+id/name"
parent. Using RelativeLayout, you can align two android:layout_width="match_parent"
elements by right border, or make one below android:layout_height="wrap_content"
another, centered in the screen, centered left, and android:hint="@string/reminder" />
so on. By default, all child views are drawn at the <Spinner android:id="@+id/dates"
top-left of the layout. android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
</RelativeLayout>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
TableLayout :
<TableRow android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="First Name"
Android TableLayout going to be arranged
android:layout_width="wrap_content"
groups of views into rows and columns. You will
android:layout_height="wrap_content"
use the <TableRow> element to build a row in the
android:layout_column="1"/>
table. Each row has zero or more cells; each cell
<EditText android:width="200px"
can hold one View object,
android:layout_width="wrap_content"
like ImageView, TextView or any other view.
android:layout_height="wrap_content"/>
For building a row in a table you will use
</TableRow>
the <TableRow> element. Table row objects are
<TableRow
the child views of a table layout. Total width of a
android:layout_width="fill_parent"
table is defined by its parent container. Column
android:layout_height="fill_parent">
can be both stretchable and shrinkable. If
<Button
shrinkable then the width of column can be
android:layout_width="wrap_content"
shrunk to fit the table into its parent object and if
android:layout_height="wrap_content"
stretchable then it can expand in width to fit any
android:text="Submit"
extra space available.
android:id="@+id/button"
android:layout_column="2"/>
</TableRow>
</TableLayout>
AbsoluteLayout: <AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
In Android, an Absolute Layout is a layout used android:layout_height="fill_parent">
to design the custom layouts. An Absolute Layout <Button android:layout_width="100dp"
7
lets you specify exact locations (x/y coordinates) android:layout_height="wrap_content"
of its children. Absolute layouts are less flexible android:text="OK"
and harder to maintain than other types of layouts android:layout_x="50px"
without absolute positioning android:layout_y="361px"/>
<Button android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px" android:layout_y="361px"/>
</AbsoluteLayout>
FrameLayout : ConstraintLayout :
Frame Layout is designed to block out an area on
the screen to display a single item. Generally, Android Constraint Layout is a ViewGroup (i.e. a view that
FrameLayout should be used to hold a single holds other views) which allows you to create large and
child view, because it can be difficult to organize complex layouts with a flat view hierarchy, and also allows
child views in a way that's scalable to different you to position and size widgets in a very flexible way. It was
screen sizes without the children overlapping created to help reduce the nesting of views and also improve
each other. You can, however, add multiple the performance of layout files.
children to a FrameLayout and control their
position within the FrameLayout by assigning
gravity to each child, using the
android:layout_gravity attribute.
ListView : GridView :
List of scrollable items can be displayed in In android GridView is a view group that display items in two
Android using ListView. It helps you to or more dimensional scrolling grid (rows and columns), the
displaying the data in the form of a scrollable list. grid items are not necessarily predetermined but they are
Users can then select any list item by clicking on automatically inserted to the layout using a ListAdapter. Users
it. ListView is default scrollable so you do not can then select any grid item by clicking on it. GridView is
need to use scroll View or anything else default scrollable so you don’t need to use ScrollView or
with ListView. A very common example of anything else with GridView. An example of GridView is your
ListView is phone contact book default Gallery
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
ScrollView :
android:layout_height="match_parent"
tools:context=".MainActivity">
In Android, a ScrollView is a view group that is
<ScrollView
used to make vertically scrollable views. A scroll
android:layout_width="match_parent"
view contains a single direct child only. In order
android:layout_height="match_parent"
to place multiple views in the scroll view, one
tools:layout_editor_absoluteX="0dp"
needs to make a view group(like LinearLayout)
tools:layout_editor_absoluteY="-127dp">
as a direct child and then you can define many
<TextView android:id="@+id/scrolltext"
views inside it. A ScrollView supports Vertical
android:layout_width="match_parent"
scrolling only, so in order to create a horizontally
android:layout_height="wrap_content"
scrollable view, HorizontalScrollView is used.
android:text="@string/scrolltext"
android:textColor="@color/green"/>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
8
Activity Lifecycle : Activities in the system are managed as an activity stack. When a new activity is
started, it is placed on the top of the stack and becomes the running activity - the previous activity always
remains below it in the stack, and will not come to the foreground again until the new activity exits.
Activity Lifecycle Public Methods , Description & Structure
1) onCreate ( ) : called when activity is first created.
This is where you should do all of your normal static
set up: create views, bind data to lists, ect.
2) onStart ( ) : called when activity is becoming visible
to the user.
3) onResume ( ): called when activity will start
interacting with the user.
Explicit Intent: Explicit Intents are used to connect the application internally.In Explicit we use the name of
component which will be affected by Intent. For Example: If we know class name then we can navigate the
app from One Activity to another activity using Intent. Explicit Intent work internally within an application
to perform navigation and data transfer.
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Implicit Intent: In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of another application.
The basic example of implicit Intent is to open any web page
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);
9
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example you have just
specified an action. Now when we will run this code then Android will automatically start your web browser
and it will open google home page.
Example :
Activity_main.xml MainActivity.java
<?xml version="1.0" encoding="utf-8"?> package com.example.factorial;
<androidx.constraintlayout.widget.ConstraintLayout import androidx.appcompat.app.AppCompatActivity;
xmlns:android="http://schemas.android.com/apk/res/android" import android.os.Bundle;
xmlns:app="http://schemas.android.com/apk/res-auto" import android.view.View;
xmlns:tools="http://schemas.android.com/tools" import android.widget.Button;
android:layout_width="match_parent" import android.widget.EditText;
android:layout_height="match_parent" import android.widget.TextView;
tools:context=".MainActivity"> public class MainActivity extends AppCompatActivity {
<TextView EditText edNum;
android:id="@+id/textView" Button btFind,btReset;
android:layout_width="404dp" TextView txtDisplay;
android:layout_height="36dp" @Override
android:layout_marginLeft="16dp" protected void onCreate(Bundle savedInstanceState) {
android:layout_marginTop="52dp" super.onCreate(savedInstanceState);
android:fontFamily="sans-serif-light" setContentView(R.layout.activity_main);
android:gravity="center" init();
android:text="The Facorial Demo" android:textSize="24sp" btFind.setOnClickListener(new View.OnClickListener() {
app:layout_constraintBottom_toTopOf="@+id/edNum" @Override
app:layout_constraintEnd_toEndOf="parent" public void onClick(View v) {
app:layout_constraintHorizontal_bias="1.0" int num = Integer.parseInt(edNum.getText().toString());
app:layout_constraintStart_toStartOf="parent" int f = 1;
app:layout_constraintTop_toTopOf="parent" /> for(int i = 1;i<=num;i++)
<EditText f = f * i;
android:id="@+id/edNum" txtDisplay.setText("Facorial : "+f);
android:layout_width="318dp" android:layout_height="76dp" }
android:layout_marginTop="24dp" android:ems="10" });
android:hint="Enter the Positive Number" }
android:inputType="textPersonName" public void init()
android:textColor="#C50F0F" android:textSize="24sp" {
app:layout_constraintEnd_toEndOf="parent" edNum = findViewById(R.id.edNum);
app:layout_constraintHorizontal_bias="0.494" btFind = findViewById(R.id.btFind);
app:layout_constraintStart_toStartOf="parent" btReset = findViewById(R.id.btReset);
app:layout_constraintTop_toBottomOf="@+id/textView" /> txtDisplay = findViewById(R.id.txtDisplay);
<Button }
android:id="@+id/btFind" }
android:layout_width="296dp" android:layout_height="95dp"
android:layout_marginBottom="348dp" android:text="Find"
android:textColor="#AD1111" android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edNum" />
<Button
android:id="@+id/btReset"
android:layout_width="287dp"
android:layout_height="104dp"
android:text="Reset"
android:textColor="#AD1111" android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btFind"
app:layout_constraintVertical_bias="0.151" />
<TextView
android:id="@+id/txtDisplay"
android:layout_width="269dp" android:layout_height="78dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btReset"
app:layout_constraintVertical_bias="0.245" />
</androidx.constraintlayout.widget.ConstraintLayout>
10
Lab Assignments:
Set A
1. Create a Simple Application Which Shows Life Cycle of Activity.
2. Create a Simple Application Which Send ―Hello‖ message from one activity to another with help of Button
(Use Intent).
3. Create a Simple Application, which read a positive number from the user and display its factorial value in
another activity.
4. Create a Simple Application, that performs Arithmetic Operations. (Use constraint layout)
Set B
1. Create an Android App, Which reads the Students Details (Name, Surname, Class, Gender, Hobbies, Marks)
and Display the all information in another activity in table format on click of Submit button.
2. Create an Android App with Login Screen. On successful login, gives message go to next Activity (Without
Using Database & use Table Layout).
11
Set C
1. Create a Simple calculator. (Use Linear Layout)
Assignment Evaluation
12
Assignment 3 : Android User Interface and Event Handling
Objectives
• Study how to create user interface in Android.
• Study how to perform event handling
Reading
You should read the following topics before starting this exercise:
• Android - UI Layouts
• Activity, Activity Lifecycle
Control Description Xml code Java Code
Android -
<ImageView ImageView img = findViewById(R.id.img);
ImageView Control android:id="@+id/img" //get the id of second image view
Android android:layout_width="fill_parent" img.setOnClickListener(new View.OnClickListener() {
ImageButton Control android:layout_height="wrap_content" @Override
In Android, ImageView class is android:src="@drawable/lion" /> public void onClick(View view) {
used to display an image file in <ImageButton Toast.makeText(getApplicationContext(),
application. android:id="@+id/img1" "Lion", Toast.LENGTH_LONG).show();
In Android, ImageButton is used to android:layout_width="wrap_content" //display the text on image click event
display a normal button with a android:layout_height="wrap_content" }
custom image in a button android:src="@drawable/home" });
android:background="#000"/>
13
Android - Switch (On/Off)
<Switch simpleSwitch = findViewById(R.id.simpleSwitch);
: android:id="@+id/simpleSwitch" submit = (Button) findViewById(R.id.submitButton);
In Android, Switch is a two-state android:layout_width="wrap_content submit.setOnClickListener(new View.OnClickListener() {
toggle, switch widget that can " @Override
select between two options. It is android:layout_height="wrap_content public void onClick(View view) {
used to display checked and " String ss;
unchecked state of android:checked="true" if (simpleSwitch.isChecked())
a button providing slider control to android:text="switch" ss = simpleSwitch.getTextOn().toString();
user. It is basically an android:layout_centerHorizontal="true else
off/on button which indicate the " ss = simpleSwitch.getTextOff().toString();
current state of Switch. It is android:textOn="On"
commonly used in selecting on/off android:textOff="Off" Toast.makeText(getApplicationContext(), "Switch :" + ss + "\n",
in Sound, Bluetooth, WiFi etc. android:textColor="#f00" Toast.LENGTH_LONG).show();
android:padding="20dp"
android:gravity="center"
android:textSize="25sp"
android:background="#000"/>
ToggleButton (On/Off) :
<ToggleButton tb = findViewById(R.id.tb);
In Android, ToggleButton is used
android:id="@+id/tb" submit = (Button) findViewById(R.id.submitButton);
to display checked and unchecked
android:layout_width="wrap_conten submit.setOnClickListener(new View.OnClickListener() {
state of
t" @Override
a button. ToggleButton basically
android:layout_height="wrap_conten public void onClick(View view) {
an off/on button with a light
t" String status = "ToggleButton : " + tb.getText();
indicator, which indicate the
android:checked="true" Toast.makeText(getApplicationContext(),
current state of toggle button. The
android:textOff="Off State" status, Toast.LENGTH_SHORT).show();
most simple example
android:textOn="On State" // display the current state of toggle button's
of ToggleButton is doing on/off in
android:textSize="25sp" } });
sound, Bluetooth, wifi, hotspot etc.
android:layout_centerHorizontal="tru
e"
android:textColor="#f00"
android:padding="40dp"/>
RadioButton &
<RadioGroup public void showMethod(View view){
RadioGroup android:layout_width="wrap_conten male = findViewById(R.id.male);
In Android, RadioButton are t" android:layout_height="wrap_conten female = findViewById(R.id.female);
mainly used together in t">
a RadioGroup. str = "Male : "+male.isChecked()+"\n Female :
<RadioButton "+female.isChecked();
In RadioGroup checking the one android:id="@+id/simpleRadioButton str = str+"\nYes : "+yes.isChecked()+"\n No : "+no.isChecked();
radio button out of several " textView.setText(str.toString());
radio button added in it will android:layout_width="wrap_conten
automatically unchecked all the Toast toast =
t" Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG);
others. android:layout_height="wrap_conten toast.setMargin(200,100);
It means at one time we can t" toast.show(); }
checked only one radio button from android:checked="true"
a group of radio buttons which android:textSize="25sp"
belong to same radio group. android:textStyle="bold|italic"
RadioButon is a two state button android:padding="20dp"
that can be checked or unchecked. android:layout_centerHorizontal="tru
If a radio button is unchecked then e"
a user can check it by simply android:text="Male"
clicking on it. Once a RadiaButton android:textColor="#f00"
is checked by user it can’t be android:background="#000"/>
unchecked by simply pressing on <RadioButton
the same button. android:id="@+id/female" android:la
It will automatically unchecked yout_width="wrap_content" android:la
when you press any yout_height="wrap_content"/>
other RadioButton within </RadioGroup>
same RadioGroup.
14
Android Toast : Android Toast can be used to display information for the short period of time. Toast class is
used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the
user interaction. Constants of toast :
public static final int LENGTH_LONG : displays view for the long duration of time.
public static final int LENGTH_SHORT : displays view for the short duration of time.
public static Toast makeText(Context context, CharSequence text, int duration) : makes the toast
containing text and duration.
public void show() : displays toast.
public void setMargin (float horizontalMargin, float verticalMargin): changes the horizontal and
vertical margin difference.
Example :
Toast toast=Toast.makeText(getApplicationContext(),"Hello Friends”, Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
RatingBar : RatingBar is used to get the rating from the app user. A user can simply touch, drag or click on
the stars to set the rating value. The value of rating always returns a floating point number which may be 1.0,
2.5, 4.5 etc.
1) The getRating() method of android RatingBar class returns the rating number.
RatingBar simpleRatingBar = (RatingBar) findViewById(R.id.simpleRatingBar); // initiate a rating bar
Float ratingNumber = simpleRatingBar.getRating(); // get rating number from a rating bar
2) numStars: numStars attribute is used to set the number of stars (or rating items) to be displayed in a
rating bar. By default a rating bar shows five stars but we can change it using numStars attribute.
numStars must have a integer number like 1,2 etc.
<RatingBar
android:id="@+id/simpleRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="7" />
Java code : simpleRatingBar.setNumStars(7); // set total number of stars
3) getNumStars(): is used to get the number of stars of a RatingBar.
int numberOfStars = simpleRatingBar.getNumStars(); // get total number of stars of rating bar
4) rating: Rating attribute set the default rating of a rating bar. It must be a floating point number.
<RatingBar
android:id="@+id/simpleRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:rating="3.5" />
Java code : simpleRatingBar.setRating((float) 3.5); // set default rating
Lab Assignments:
Set A
1. Create an Android Application that will change color of the College Name(Use TextView) on click
of Push Button and change the font size, font style of text view using xml.
15
2. Create an Android Application to accept two numbers(Use PainText) and create two buttons
(power and Average). Display the result on the next activity on Button click
3. Design Following Screens Using RadioButtons & CheckBoxes.Display the selected text using Toast.
Set B
1. Create an Android Application that Demonstrate RatingBar and Display the number of stars selected on
Toast and TextView
2. Create an Android Application to perform following string operation according to user selection
of radio button.
16
3. Write an Android Application to Change the Image
Displayed on the Screen
Set C
1. Construct image switcher using setFactory().
17
Signature of the instructor: ------------------------- Date:------------------------
Assignment Evaluation
Android - Alert Dialog: Alert Dialog in an android UI prompts a small window to make decision on mobile
screen. Sometimes before making a decision, it is required to give an alert to the user without moving to next
activity. For example you have seen this type of alert when you try to exit the App and App ask you to confirm
exiting.
AlertDialog.Builder is used to create an interface for Alert Dialog in Android for setting like alert title,
message, image, button, button onclick functionality etc.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
1) setTitle(CharSequence title) – This component is used to set the title of the alert
dialog. It is optional component.
alertDialogBuilder.setTitle("Confirm Exit..!!!"); // Setting Alert Dialog Title
2) setIcon(Drawable icon) – This component add icon before the title. You will need to
save image in drawable icon.
alertDialogBuilder.setIcon(R.drawable.question); // Icon Of Alert Dialog
3) setMessage(CharSequence message) – This component displays the required message
in the alert dialog.
alertDialogBuilder.setMessage("Are you sure,You want to exit");// Setting Alert Dialog
Message
4) setCancelable(boolean cancelable) – This component has boolean value i.e true/false.
If set to false it allows to cancel the dialog box by clicking on area outside the dialog
else it allows.
alertDialogBuilder.setCancelable(false);
5) setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) – This
component add positive button and further with this user confirm he wants the alert dialog question to
happen.
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish ();
} });
18
6) setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) – This
component add negative button and further with this user confirm he doesn’t want the alert dialog
question to happen.
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You clicked over No",Toast.LENGTH_SHORT).show();
} });
19
adb.show();
}
});
Custom Alert Dialog: The custom dialog uses DIALOG to create custom alert in android studio. Dialog
display a small window that is a popup which draws the user attention over the activity before they continue
moving forward. The following are the steps to create custom alert Dialog.
Step 1: Create a new project and name it CustomAlertDialogDemo.
Step 2: Open res -> layout -> activity_main.xml and create XML for button and textview. On button
click custom alert dialog will appear & textview is for asking user to click on button.
Step 3 : Now create a layout file name as custom.xml . In this file we are going to define the XML
for custom dialog appearance. For example a textbox , imageview and a button.
Step 4 : Now open app -> java -> package -> MainActivity.java and add the below code. In this code
onclick is added over the button click and Dialog is used to create the custom alert dialog.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context); // custom dialog
dialog.setContentView(R.layout.custom);
// if button is clicked, close the custom dialog
dialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
}
});
TimePicker: In Android, TimePicker is a widget used for selecting the time of the day in either
AM/PM mode or 24 hours mode. The displayed time consist of hours, minutes and clock format. If
we need to show this view as a Dialog then we have to use a TimePickerDialog class.
<TimePicker
android:id="@+id/simpleTimePicker“
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:timePickerMode="spinner"/> or clock
Some Methods of TimePicker:
1) setCurrentHour(Integer currentHour): This method is used to set the current hours in
a time picker.
20
2) setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour). In this method there is only one parameter of
integer type which is used to set the value for hours.
3) setCurrentMinute(Integer currentMinute): This method is used to set the current minutes
in a time picker.
4) getCurrentHour(): getCurrentHour() method was deprecated in API level 23. From api level
23 you have to use getHour(). This method returns an integer value.
5) getCurrentMinute():This method is used to get the current minutes from a time picker.
6) getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use getMinute(). This method returns an integer value.
7) setIs24HourView(Boolean is24HourView):This method is used to set the mode of the Time
picker either 24 hour mode or AM/PM mode. In this method we set a Boolean value either
true or false. True value indicate 24 hour mode and false value indicate AM/PM mode.
8) is24HourView():This method is used to check the current mode of the time picker. This
method returns true if its 24 hour mode or false if AM/PM mode is set.
21
Set B
1. Develop an Android application that create custom Alert Dialog containing Friends Name and
onClick of Friend Name Button greet accordingly.
2. Create an Android Application that Demonstrate DatePicker and DatePickerDailog.
Assignment Evaluation
22
Assignment 5 : Android Adapter and Menu
In Android, Adapter is a bridge between UI component and data source that helps us to fill data in
UI component. It holds the data and send the data to an Adapter view then view can takes the data
from the adapter view and shows the data on different views like
as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or
custom adapters. To fill data in a list or a grid we need to implement Adapter.
There are the some commonly used Adapter in Android used to fill the data in the UI components.
1) BaseAdapter – It is parent adapter for all other adapters
2) ArrayAdapter – It is used whenever we have a list of single items which is backed by an
array.
3) Custom ArrayAdapter – It is used whenever we need to display a custom list.
4) SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file
5) Custom SimpleAdapter – It is used whenever we need to display a customized list and
needed to access the child items of the list or grid
List View: It is widely used in android applications. A very common example of ListView is your
phone contact book, where you have a list of your contacts displayed in a ListView and if you click
on it then user information is displayed.
Adapter: To fill the data in a ListView we simply use adapters. List items are automatically inserted
to a list using an Adapter that pulls the content from a source such as an arraylist, array or database.
Listview is present inside Containers. From there you can drag and drop on virtual mobile screen to
create it. Alternatively you can also XML code to create it.
divider: This is a drawable or color to draw between different list items.
dividerHeight: This specify the height of the divider between list items. This could be in dp(density
pixel), sp(scale independent pixel) or px(pixel).
XML Code :
<ListView
android:id="@+id/simpleListView“
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
android:listSelector="#0f0"/>
Java code :
ListView simpleList;
String countryList[] = {"Rajesh", "Ramesh", "Suresh", "Satish", "Rakesh", "Dinesh"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView)findViewById(R.id.simpleListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, R.id.textView, countryList);
simpleList.setAdapter(arrayAdapter);
}
23
GridView : In android GridView is a view group that display items in two dimensional scrolling grid
(rows and columns), the grid items are not necessarily predetermined but they are automatically
inserted to the layout using a Adapter. Users can then select any grid item by clicking on it.
GridView is default scrollable. An example of GridView is your default Gallery, where you have
number of images displayed using grid. To fill the data in a GridView we simply use adapter and grid
items are automatically inserted to a GridView using an Adapter which pulls the content from a
source such as an arraylist, array or database
XML Code :
<GridView
android:id="@+id/simpleGridView" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:numColumns="3“
android:verticalSpacing="50dp“
android:horizontalSpacing="50dp“
android:columnWidth="80dp"
android:listSelector="#0f0"
/>
Spinner :
In Android, Spinner provides a quick way to select one value from a set of values. Android spinners
are nothing but the drop down-list seen in other programming languages. In a default state,
a spinner shows its currently selected value. It provides a easy way to select a value from a list of
values.
XML Code :
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content”
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
Java code :
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
spin.setOnItemSelectedListener(this);
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position],
Toast.LENGTH_LONG).show(); }
Menu in Android : In android, there are three types of Menus available to define a set of options
and actions in our android applications.
1) Android Options Menu : The options menu is the primary collection of menu items for an
activity. It's where you should place actions that have a overall impact on the app, such as
Search, Compose Email and Settings.
2) Android Context Menu : A context menu is a floating menu that appears when the user
performs a long-click on an element. It provides actions that affect the selected content or
context frame.
24
3) Android Popup Menu : A popup menu displays a list of items in a vertical list that is
anchored(sticked) to the view that invoked the menu. It's good for providing an overflow of
actions that relate to specific content or to provide options for a second part of a command.
How to create a Menu?
For all menu types, Android provides a standard XML format to define menu items. you should
define a menu and all its items in an XML menu resource. You can then inflate the menu resource i.e
load the XML files as a Menu object in your activity.
1) A new menu directory would be made under res directory.
2) Add menu_file.xml file in menu directory by right clicking on menu --> New --> Menu
resource file.
3) Give the name as menu_file.xml and click on Ok.
4) The menu_file.xml file contains the following tags:
a) <menu> : It defines a Menu, which is a container for menu items. A <menu> element
must be the root node for the file and can hold one or more <item> and <group>
elements.
b) <item>: It creates a MenuItem, which represents a single item in a menu. This element
may contain a nested <menu> element in order to create a submenu.
c) <group> :It is an optional, invisible container for <item> elements. It allows you to
categorize menu items so they share properties such as active state and visibility.
menu_file.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="item1“
android:icon="@drawable/item" >
<!-- "item" submenu -->
<menu>
<item
android:id="@+id/a"
android:title="subitem a"
android:icon="@drawable/subitem_a"/>
<item
android:id="@+id/b“
android:title="subitem b“
android:icon="@drawable/subitem_b" />
</menu>
</item>
</menu>
Making an Option Menu
◼ To make an option menu, we need to Override onCreateOptionsMenu() method as
follows:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file, menu);
return true;
25
}
MenuInflater inflater = getMenuInflater();
This gives a MenuInflater object that will be used to inflate(convert our XML file into Java
Object) the menu_file.xml file.
inflater.inflate(R.menu.menu_file, menu);
inflate() method is used to inflate the menu_file.xml file.
Handling Click Events
◼ When the user selects an item from the options menu, the system calls your
activity's onOptionsItemSelected() method.
◼ This method passes the MenuItem selected.
◼ You can identify the item by calling getItemId() method, which returns the unique ID for
the menu item (defined by the android:id attribute in the menu resource).
◼ You can match this ID against known menu items to perform the appropriate action.
@Override
switch (item.getItemId()) {
case R.id.i1:
case R.id.a:
case R.id.b:
◼ To make a floating context menu, you need to follow the following steps:
◼ Register the View to which the context menu should be associated by
calling registerForContextMenu() and pass it the View.
◼ If your activity uses a ListView or GridView and you want each item to provide the same
context menu, you can register yout all items for a context menu by passing the ListView or
GridView object to registerForContextMenu() method.
◼ Implement the onCreateContextMenu() method in your Activity.
26
◼ When the registered view receives a long-click event, the system calls
your onCreateContextMenu() method.
◼ This is where you define the menu items, usually by inflating a menu resource.
For example:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
inflater.inflate(R.menu.menu_file, menu);
MenuInflater allows you to inflate the menu_file.xml file from a menu resource. The method
parameters include the View that the user selected and aContextMenu. ContextMenuInfo object
provides additional information about the item selected. If your activity has several views such that
each provide a different context menu, you might use these parameters to determine which context
menu to inflate.
@Override
switch (item.getItemId())
{
case R.id.i1:
//Perform any action; return true;
case R.id.a:
//Perform any action; return true;
case R.id.b:
//Perform any action; return true;
default: return super.onContextItemSelected(item);
}
}
Making Popup Menu
◼ If you have define your menu_file.xml file in XML, here's how you can show the popup
menu:
◼ Make an object of PopupMenu, whose constuctor takes the current application Context and
the View to which the menu should be anchored.
◼ Use MenuInflater to inflate your menu resource into the Menu object returned
by PopupMenu.getMenu()
27
◼ Call PopupMenu.show()
For example,
<Button android:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Button"
android:onClick="pop" />
The activity can then show the popup menu like this:
public void pop(View v)
{ PopupMenu popup = new PopupMenu(this,v);
MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_file,popup.getMenu());
popup.show();
}
Listener
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final PopupMenu popup = new PopupMenu(getApplicationContext(),v);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_file,popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),"selected
"+item.getTitle(),Toast.LENGTH_LONG).show();
return true;
}
});
Set A
1. Create an Android Application that Demonstrate ListView and Onclick of List Display the
Toast.
28
2. Create an Android Application that Demonstrate GridView and Onclick of Item Display the Toast.
Set B
1. Create an Android Application that Demonstrate Custom ListView which shows the BookName and
Author Name
29
3. Create an Android Application that Demonstrate ContextMenu.
Set C
1. Create the following layout using spinner
Assignment Evaluation
30
Assignment 6: Thread and Services
Objective:
• To provide a way to improve application performance through parallelism.
• To ensure that the application remains active in the background so that the user can operate
multiple applications at the same time.
Worker threads
Worker threads are background threads. They are the threads that are created separately, other than
the UI thread. Since blocking the UI thread is restricted according to the rule, user should run the
child processes and tasks in worker threads.
Example
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
In the above example code, the download operation is handled by a second thread other than
the UI thread. But the program violates the second rule. The imageView from UI thread is
manipulating from this worker thread. In the above example code, the download operation is handled
by a second thread other than the UI thread. But the program violates the second rule. The imageView
from UI thread is manipulating from this worker thread.
According to the second rule, UI could not be accessed from outside the UI thread. Solution
for such a restriction is runOnUiThread(Runnable) method. The main or UI thread can be accessed
from other threads using runOnUiThread(Runnable) method. As a result, the specified runnable
action passed through this method will run on the UI thread. The action will execute immediately, if
the current thread is in the UI itself. Else the action will be posted to the event queue.
Example:
MainClassName.this.runOnUiThread(new Runnable() {
public void run() {
textViewObject.setText("Set this " + value from worker thread + "!");
}
});
31
Handlers & Runnable:
A handler is basically a message queue. You post a message to it, and it will eventually
process it by calling its run method and passing the message to it. Since these run calls will always
occur in the order of messages received on the same thread, it allows you to serialize events.
Uses of Handler:
Looper will take care of dispatching work on its message-loop thread. On the other hand
Handler will serve two roles:
Example:
public void onClick(View v) {
nstoploop = true;
new Thread(new Runnable() {
@Override
public void run() {
while (nstoploop){
try
{
Thread.sleep(500);
count++;
32
We can’t touch background thread to main thread directly so handler is going to collect all events
which are available in main thread in a queue and posses this queue to looper class.
In android Handler is mainly used to update the main thread from background thread or other than
main thread. There are two methods are in handler.
• Post() − it going to post message from background thread to main thread using looper.
• sendmessage() − if you want to organize what you have sent to ui (message from background
thread) or ui functions. you should use sendMessage().
AsynTask:
Methods of AsyncTask
• onPreExecute() –
Before doing background operation we should show something on screen like
progressbar or any animation to user. we can directly comminicate background operation
using on doInBackground().
• doInBackground(Params) –
In this method we have to do background operation on background thread. Operations
in this method should not touch on any mainthread activities or fragments.
• onProgressUpdate(Progress…) –
While doing background operation, if you want to update some information on UI, we
can use this method.
• onPostExecute(Result) –
In this method we can update ui of background operation result.
• TypeOfVarArgParams –
It contains information about what type of params used for execution.
• ProgressValue –
33
It contains information about progress units. While doing background operation we
can update information on ui using onProgressUpdate().
• ResultValue –
It contains information about result type.
Example:
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.btn1);
b2 = (Button)findViewById(R.id.btn2);
tv = (TextView)findViewById(R.id.textView);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stoploop = true;
async = new MyAsynctask();
async.execute(count);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stoploop = false;
}
});
}
private class MyAsynctask extends AsyncTask<Integer,Integer ,Integer>
{
private int ccount;
@Override
protected void onPreExecute() {
super.onPreExecute();
ccount=0;
34
}
@Override
protected Integer doInBackground(Integer... integers) {
ccount = integers[0];
while(stoploop){
try
{
Thread.sleep(1000);
ccount++;
publishProgress(ccount);
}
catch (InterruptedException e){
Log.i(TAG," "+e.getMessage());
}
}
return ccount;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tv.setText(""+values[0]);
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
tv.setText(""+integer);
count = integer;
}
}
}
Activity_main.xml
35
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.58"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.102" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Thread"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.116" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Thread"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn1"
36
app:layout_constraintVertical_bias="0.145" />
</androidx.constraintlayout.widget.ConstraintLayout>
Broadcast Receiver :
Broadcast in android is the system-wide events that can occur when the device starts, when a
message is received on the device or when incoming calls are received, or when a device goes to
airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast
Receivers allow us to register for the system and application events, and when that event happens,
then the register receivers get notified. There are mainly two types of Broadcast Receivers:
37
Intent Description Of Event
android.intent.action.DATE_CHANGED Indicates that the date has changed
Example:
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private EditText txtPhone;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtPhone = (EditText)findViewById(R.id.mblTxt);
btn = (Button)findViewById(R.id.btnCall);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callPhoneNumber();
}
});
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if(requestCode == 101)
{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
callPhoneNumber();
}
38
}
}
public void callPhoneNumber()
{
try
{
if(Build.VERSION.SDK_INT > 22)
{
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.CALL_PHONE}, 101);
return;
}
}
else {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + txtPhone.getText().toString()));
startActivity(callIntent);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
39
android:layout_marginTop="150dp"
android:text="Mobile No"
/>
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10">
</EditText>
<Button
android:id="@+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Call" />
</LinearLayout>
Services:
A service is a component that runs in the background to perform long-running operations
without needing to interact with the user and it works even if application is destroyed.
There can be two forms of a service.The lifecycle of service can follow two different paths: started
or bound.
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it runs
in the background indefinitely. It is stopped by stopService() method. The service can stop itself by
calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The
client can unbind the service by calling the unbindService() method.
40
Fundamentals of Android Services:
Methods Description
The Android service calls this method when a component(eg:
onStartCommand() activity) requests to start a service using startService(). Once the
service is started, it can be stopped explicitly using stopService()
or stopSelf() methods.
This method is mandatory to implement in android service and
is invoked whenever an application component calls the
onBind() bindService() method in order to bind itself with a service. User-
interface is also provided to communicate with the service
effectively by returning an IBinder object. If the binding of
service is not required then the method must return null.
onUnbind() The Android system invokes this method when all the clients get
disconnected from a particular service interface.
Once all clients are disconnected from the particular interface
onRebind() of service and there is a need to connect the service with new
clients, the system calls this method.
Whenever a service is created either using onStartCommand()
onCreate() or onBind(), the android system calls this method. This method
is necessary to perform a one-time-set-up.
onDestroy() When a service is no longer in use, the system invokes this
method just before the service destroys as a final clean up call.
41
Methods Description
Services must implement this method in order to clean up
resources like registered listeners, threads, receivers, etc.
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp"
android:textStyle="bold" />
<Button
42
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<Button
android:id="@+id/stopButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:text="@string/stopButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this, R.raw.ss);
43
player.setLooping( true );
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
// assigning ID of stopButton
// to the object stop
stop = (Button) findViewById( R.id.stopButton );
// process to be performed
44
// if start button is clicked
if(view == start){
// process to be performed
// if stop button is clicked
else if (view == stop){
}
}
}
Step 6: Modify the AndroidManifest.xml file
To implement the services successfully on any android device, it is necessary to mention the
created service in the AndroidManifest.xml file.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
45
The NotificationCompat.Builder Class
Method Description
Notification build() Combine all of the options that have been
set and return a new Notification object.
NotificationCompat.Builder Setting this flag will make it so the
setAutoCancel (boolean autoCancel) notification is automatically canceled
when the user clicks it in the panel.
NotificationCompat.Builder setContent Supply a custom RemoteViews to use
(RemoteViews views) instead of the standard one.
NotificationCompat.Builder Set the text (first row) of the notification,
setContentTitle (CharSequence title) in a standard notification.
Example:
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
46
A PendingIntent object helps you to perform an action on your applications behalf, often at a
later time, without caring of whether or not your application is running.
Example:
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Example:
SMS messages can be send using SmsManager Class or Built-in SMS application.
Using SmsManager class: Using the SmsManager class, you can send SMS messages from within
your application without the need to involve the built-in Messaging application.
Steps to send SMS
Create a new Android project and name it SMS. Replace the TextView with the following
statements in the main.xml file:
47
Example:
<Button android:id=‖@+id/btnSendSMS‖
android:layout_width=‖fill_parent‖
android:layout_height=‖wrap_content‖
android:text=‖Send SMS‖
android:onClick=‖onClick‖ />
48
ArrayList<PendingIntent>
deliveryIntents)
void sendTextMessage(String
destinationAddress, String Send a text based SMS.
scAddress, String text, PendingIntent
sentIntent, PendingIntent
deliveryIntent)
Example:
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Intent Object used to set a message for one or more phone number with putExtra( ) method and a
message can be send to multiple receivers separated by ‗:‘.
smsIntent.putExtra(―address‖,new String(―0123456789;3398765587‖));
OR
smsInent.putExtra(―address‖,‖5556 ; 5553 ; 5566‖);
Sending E-mail:
We can send Email by using Email/Gmail application available on Android. An Email account
is configured by using POP3 or IMAP.
Steps to send Email
Create Android project and name it as Emails
49
<Button android:id=”@+id/btnSendEmail”
android:layout_width=”fill_parent” android:layout_height=”wrap_content”
android:text=”Send Email”
android:onClick=”onClick” />
Add the following statements in MainActivity.java file:
public class MainActivity extends Activity {
Button btnSendEmail;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendEmail = (Button) findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String[] to = {―weimenglee@learn2develop.net‖,
―weimenglee@gmail.com‖};
String[] cc = {― ‖};
Lab Assignments:
50
SET A
1. Create an Android application to service in android that plays an audio in the background.
Audio will not be stopped even if you switch to another activity. To stop the audio, you need
to stop the service.
2. Create application to send and receive messages using SMSManager.
3. Create application to send email.
4. Create a Notification in Android and display the notification message on second activity .
SET B
1. Create application to design login form, validate it. Write and send email with appropriate
message.
2. Create an Android application to demonstrate Progress Dialog Box using AsyncTask
3. Create an Android application to demonstrate phone call in android using Implicit Intent.
SET C
1. Create an Android application to demonstrates how to use a service to download a file from the
Internet based on a button click from an activity. Once done, the service notifies the activity via a
broadcast receiver that the download is complete.
2. Create application to send email with attachment.
Assignment Evaluation
Complete
51
Assignment 7: SQLite Database Connection
Objective:
SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database. It is embedded
in android bydefault. So, there is no need to perform any database setup or administration task.
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in
with built in SQLite database implementation. SQLite supports all the relational database features.
In order to access this database, you don't need to establish any kind of connections for it like ODBC.
SQLiteOpenHelper
Constructors Description
SQLiteOpenHelper(Context context, String Create a helper object to create, open,
name, SQLiteDatabase.CursorFactory and/or manage a database
factory, int version)
SQLiteOpenHelper(Context context, String Create a helper object to create, open,
name, SQLiteDatabase.CursorFactory and/or manage a database.
factory, int version, DatabaseErrorHandler
errorHandler)
52
Public Methods Description
String getDatabaseName()
opened, as given to the constructor.
SQLiteDatabase getWritableDatabase()
for reading and writing.
time.
void onOpen(SQLiteDatabase db) Called when the database has been opened.
53
Sets the maximum number of milliseconds that
void setIdleConnectionTimeout(long
idleConnectionTimeoutMs)
Example:
public class DBHelper extends SQLiteOpenHelper{
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db){
SQLite Database:
The main package is android.database.sqlite that contains the classes to manage your own
databases:
Database – Creation
In order to create a database you just need to call this method openOrCreateDatabase with
your database name and mode as a parameter. Its syntax is given below:
Database – Insertion
We can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below
54
public void insert(String name, String desc) { ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name); contentValue.put(DatabaseHelper.DESC,
desc); database.insert(DatabaseHelper.TABLE_NAME, null, contentValue); }
Content Values creates an empty set of values using the given initial size.
Database – Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Example:
Cursor resultSet=mydb.rawQuery(―Select * from
Login‖,null); resultSet.moveToFirst();
String username= resultSet.getString(0);
String password= resultSet.getString(1);
Methods Description
int getColumnCount() Returns the total number of
columns of the table.
int getColumnIndex(String Returns the index number of a
columnName) column by specifying the name of
the column.
String getColumnName (int Returns the name of the column by
columnIndex) specifying the index of the
column.
String[ ] getColumnNames() Returns the array of all the column
names of the table.
int getCount() Returns the total number of rows
in the cursor.
int getPosition() Returns the current position of the
cursor in the table.
boolean isClosed() Returns true if the cursor is closed.
Lab Assignments
SET A
55
1. Create table Customer (id, name, address, phno). Create Android Application for performing the
following operation on the table. (using sqlite database)
i) Insert New Customer Details.
ii) Show All the Customer Details
3. Create simple application shown below. Create table Student(Sid ,Sname ,phno). Use
autoincrement for Sid and Perform following Operation.
a. Add Student and display its information.
b. Delete Student.
4. Create sample application with login module (Check username and password). On successful
login, pass username to next screen And on failing login, alert user using Toast (Hint :Use
Login(username, password) Table.
SET B
1. Create Table project (pno, p_name, ptype, duration) and employee (id, e_name, qulification,
joindate)
SET C
56
1. Create table Game(no,name,type, no_of_players). Create Application to perform the following
operations.
i) Insert Game Details.
ii) Update no_of_players to four where game is Badminton.
iii) Display all the records.
2. Create Table Employee(empno,emp_name,dept,salary,branch). Create Android Application to
perform following operations.
i) Display all Fields of employee table.
Assignment Evaluation
Assignment 8:
57
Location-Based Services and Google Map
Objectives:
• Study the location based services in android
Google Map: Google Maps is web based service developed by Google. It provides
many facilities such as Satellite view, Street view, real time traffic condition, and
navigations for travelling by foot, car, bicycle and public transportation. To use Google
Maps in your Android applications programmatically.
58
Use the link provided in the google_maps_api.xml file.
Copy the link provided in the google_maps_api.xml file and pastes it into your
browser. The link takes you to the Google API Console and supplies the required
information to the Google API Console via URL parameters.
Follow the instructions to create a new project on the Google API Console or select
an existing project.
Create an Android-restricted API key for your project.
Copy the resulting API key, go back to Android Studio, and paste the API key into
the <string> element in the google_maps_api.xml file.
Classes and Interface used for displaying Map are given below:
Interfaces:
59
Fragment findFragmentByTag(String Finds a fragment that was identified by the
tag) given
tag.
GoogleMap: This is the main class of the Google Maps Android API. You cannot
instantiate a GoogleMap object directly, rather, you must obtain one from the
getMapAsync() method on a MapFragment. This class provides methods to set type
of map, add markers, add polyline or move camera etc.
Constants Description
60
Lab Assignments
SET A
Write a program to perform Zoom In, Zoom Out operation and display Satellite view.
Write a program to perform Zoom In, Zoom Out operation and display Terrain view of current
location on Google Map.
Write a program to find the specific location of an Android device and display details of the
place like Address line, city with Geocoding.
SET B
SET C
Write a program to track an android device using mobile number and display the location on
Google Map.
Write a program to modify the above program to draw the path along a route on Google Map.
Assignment Evaluation
61
Section II: Dot Net
ASSIGNMENT -A: DOT NET FRAMEWORK
Basic:
The main objective of this framework is to develop an application that can run on
the windows platform.
1
Components of .NET Framework
6. .NET Assemblies
8. Window Services
2
It is an important part of a .NET framework that works like a virtual component of the
.NET Framework to executes the different languages program like C#, Visual Basic, etc.
A CLR also helps to convert a source code into the byte code, and this byte code is
known as CIL (Common Intermediate Language) or MSIL (Microsoft Intermediate
Language). After converting into a byte code, a CLR uses a JIT compiler at run time that
helps to convert a CIL or MSIL code into the machine or native code.
It specifies a standard that represent what type of data and value can be defined and
managed in computer memory at runtime. A CTS ensures that programming data defined
in various languages should beinteract with each other to share information. For example,
in C# we define data type as int, while in VB.NET we define integer as a data type.
The base class library has a rich collection of libraries features and functions that help to
implement many programming languages in the .NET Framework, such as C #, Visual
C++, and more. Furthermore, BCL divides into two parts:
1. User defined class library
o Assemblies - It is the collection of small parts of deployment an
application's part. It contains either the DLL (Dynamic Link Library) or exe
(Executable) file.
2. Predefined class library
o Namespace - It is the collection of predefined class and method that
present in .Net. In other languages such as, C we used header files, in java
we used package similarly we used "using system" in .NET, where using is
a keyword and system is a namespace.
CLS (Common language Specification)
It is a subset of common type system (CTS) that defines a set of rules and regulations
which should be followed by every language that comes under the .net framework. In
other words, a CLS language should be cross-language integration or interoperability. For
example, in C# and VB.NET language, the C# language terminate each statement with
semicolon, whereas in VB.NET it is not end with semicolon, and when these statements
execute in .NET Framework, it provides a common platform to interact and share
information with each other.
3
It provides the various system functionality in the .NET Framework, that includes
classes, interfaces and data types, etc. to create multiple functions and different types of
application such as desktop, web, mobile application, etc. In other words, it can be
defined as, it provides a base on which various applications, controls and components are
built in .NET Framework.
4
ASSIGNMENT -B: VB.Net
Overview of VB.NET
The VB.NET stands for Visual Basic .Network Enabled Technologies. It is a simple,
high-level, object-oriented programming language developed by Microsoft in 2002 to
replace Visual Basic 6.
VB.NET is an object-oriented programming language. This means that it supports the
features of object-oriented programming which include encapsulation, polymorphism,
abstraction and inheritance.
Windows Application
Console Application
Web Application
Comments
In VB .NET, you write a comment by writing an apostrophe ' or writing REM. This
means the rest of the line will not be taken into account by the compiler.
5
Hello World Program in VB.Net
Create a Hello_Program.vb file in MYConsoleApp project and write the following code:
Imports System 'System is a Namespace
Module Hello_Program
Sub Main()
Console.WriteLine("Hello, Welcome to the world of VB.NET")
Console.WriteLine("Press any key to continue...")
Console.ReadKey()
End Sub
End Module
Compile and run the above program by pressing the F5 key, we get the follwoing output.
Output:
6
Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
-9,223,372,036,854,775,808 through
Long 8 bytes
9,223,372,036,854,775,807(signed)
-3.4028235E+38 through -1.401298E-45 for
negative values;
Single 4 bytes
1.401298E-45 through 3.4028235E+38 for positive
values
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative values
Double 8 bytes
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
0 through +/-
79,228,162,514,264,337,593,543,950,335 (+/-
Decimal 16 bytes 7.9...E+28) with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28 places
to the right of the decimal
Char 2 bytes 0 through 65535 (unsigned)
Depends on
String 0 to approximately 2 billion Unicode characters
implementing platform
0:00:00 (midnight) on January 1, 0001 through
Date 8 bytes
11:59:59 PM on December 31, 9999
4 bytes on 32-bit
platform
Object Any type can be stored in a variable of type Object
8 bytes on 64-bit
platform
Example of Datatypes :
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim c As Char
Dim s As String
Dim bl As Boolean
b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
c = "U and me"
s = "Me"
Console.ReadKey()
End Sub
End Module
8
CDate(expression): converts the expression to a Date data type.
CDbl(expression): converts the expression to a Double data type.
CByte (expression): converts the expression to a byte data type.
CChar(expression): converts the expression to a Char data type.
CLng(expression): converts the expression to a Long data type.
CDec(expression): converts the expression to a Decimal data type.
CInt(expression): converts the expression to an Integer data type.
CObj(expression): converts the expression to an Object data type.
CStr(expression): converts the expression to a String data type.
CSByte(expression): converts the expression to a Byte data type.
CShort(expression): converts the expression to a Short data type.
Variable Declaration
In VB.NET, the declaration of a variable involves giving the variable a name and
defining the data type to which it belongs. We use the following syntax:
In the above example, 'x' is the variable name while Integer is the data type to which
variable x belongs.
Variable Initialization
Initializing a variable means assigning a value to the variable. The following example
demonstrates this:
Example-1 :
Dim x As Integer
x = 10
Example-2 :
9
Input Output Functions used in Console Application
Output Functions :
1) Write( ) :
Write() method displays the output but do not provide a new line character.
Example :
Console.Write("One")
Console.Write("Two")
Output : OneTwo
2) WriteLine( )
WriteLine() method displays the output and also provides a new line character it
the end of the string, This would set a new line for the next output.
Example :
Console.WriteLine("One")
Console.WriteLine("Two")
Output : One
Two
Console.ReadLine()
It read all the characters from user input. (and finish when press enter).
Note: It return a STRING so data type should be STRING.
Example 1:
Dim name As String
Console.WriteLine("Enter student name : ")
name = Console.ReadLine()
Console.WriteLine( name) o/p ------------ Sachin Saxena
or
Console.WriteLine("Student Name is = {0}", name)
o/p ------------ My Name is = Sachin Saxena
In this example, if you enter the string "Sachin Saxena" it read as it is. It means it
reads all characters until the end of line.
10
Example 2:
Dim sum As Integer
Console.WriteLine("Enter two numbers : ")
sum = CInt(Console.ReadLine()) + CInt(Console.ReadLine())
Console.WriteLine("Addition = {0}", sum)
Example 3:
Dim num1, num2, sum As Integer
Console.WriteLine("Enter two numbers : ")
num1 = Console.ReadLine()
num2 = Console.ReadLine()
sum = num1 + num2
Console.WriteLine("num1 = {0} num 2 = {1}", num1, num2)
Console.WriteLine("Addition = {0}", sum)
Console.Read()
It only accept single character from user input and return its ASCII Code.
Note: Data type should be integer because it returns an integer value as ASCII.
Example :
Dim value As Integer
value = Console.Read( )
Console.WriteLine("Value Read from console is : ", value)
Console.ReadKey()
It reads that which key is pressed by user and returns its name.
Example :
Dim key As ConsoleKeyInfo
key = Console.ReadKey()
Console.WriteLine("You Pressed : {0}", key.Key)
11
Operators
Operator is a symbol that is used to perform various operations on variables. VB.NET has
different types of Operators that help in performing logical and mathematical operations
on data values.
Arithmetic Operators :
You can use arithmetic operators to perform various mathematical operations in
VB.NET.
Assume variable A = 2 and variable B = 7, then –
Operator Description Example
^ Raises one operand to the power of another B^A will give 49
Example :
Module Module1
Sub Main()
Dim no1 As Integer = 11
Dim no2As Integer = 5
Dim no3 As Integer = 2
Dim res1 As Integer
Dim res2 As Single
res1 = no1 + res2
12
Console.WriteLine(" Result of 11 + 5 is {0} ", res1)
res1 = no1 – no2
Console.WriteLine(" Result of 11 - 5 is {0} ", res1)
res1 = no1 * no2
Console.WriteLine(" Result of 11 * 5 is {0} ", res1)
res2 = no1 / no2
Console.WriteLine(" Result of 11 / 5 is {0}", res2)
res1 = no1 \ no2
Console.WriteLine(" Result of 11 \ 5 is {0}", res1)
res1 = no1 Mod no2
Console.WriteLine(" Result of 11 MOD 5 is {0}", res1)
res1 = no2^ no2
Console.WriteLine(" Result of 5 ^ 5 is {0}", res1)
Console.ReadLine()
End Sub
End Module
Comparison Operators
13
than or equal to the value of right operand; if
yes, then condition becomes true.
Assignment Operators :
14
Logical Operators
Assume variable A holds Boolean value True and variable B holds Boolean value False,
then −
Example :
X=10, Y = 30
Control Structure
1. Decision Making Statements
2. Loops Statements
15
Decision Making Statements :
1. If statement :
It executes a set of code when a condition is true.
2. If...Then... Else statement :
It selects one of two sets of lines to execute.
3. If...Then...ElseIf statement (Nested If statement) :
It selects one of many sets of lines to execute.
4. Select Case statement :
It select one of many sets of lines to execute.
1) If Then Statement If Then statement is a control structure which executes a set of code only
when the given condition is True.
Syntax:
If [Condition] Then
[Statements]
In the above syntax when the Condition is true then the Statements after Then are executed.
Example:
Dim x As Integer
x=9
If (x Mod 2) = 0 Then
Console.WriteLine("x is an even number")
End If
2) If Then Else Statement If Then Else statement is a control structure which executes different
set of code statements when the given condition is true or false.
Syntax:
If [Condition] Then
[Statements]
Else
[Statements]
In the above syntax when the Condition is true, the Statements after Then are executed. If the
condition is false then the statements after the Else part is executed.
Example:
Dim x As Integer
x=9
If (x Mod 2) = 0 THEN
Console.WriteLine("x is an even number")
Else
16
Console.WriteLine("x is an odd number")
End If
3) Nested If Then Else Statement Nested If..Then..Else statement is used to check multiple
conditions using if then else statements nested inside one another.
Syntax :
If condition1 Then
Statement1
statement2
ElseIf condition2 Then
Statement3
Statement4
Else
Statement5
Statement6
End If
Example:
Dim x As Integer
x = Console.ReadLine()
If x > 0 Then
Console.WriteLine("It is positive.")
Elseif x<0
Console.WriteLine("It is negative.")
Else
Console.WriteLine("It is zeo.")
End If
Case Statement Select case statement is used when the expected results for a condition can be
known previously so that different set of operations can be done based on each condition.
Syntax:
Select Case Expression
Case Expression1
Statement1
Case Expression2
Statement2
Case Expressionn
Statementn
...
Case Else
Statement
End Select
17
In the above syntax, the value of the Expression is checked with Expression1..n to check if the
condition is true. If none of the conditions are matched the statements under the Case Else is
executed.
Example - 1:
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Example - 2:
Dim no As Integer
Console.WriteLine("Enter no. between 1-10")
no = Console.ReadLine()
Select Case no
Case 1, 3, 5, 7, 9
Console.WriteLine("Odd number")
Case 2, 4, 6, 8, 10
Console.WriteLine("Even number")
Case Else
Console.WriteLine("Invalid number-OutofRange")
End Select
1) For Next Loop Statement For Next Loop Statement executes a set of statements repeatedly
in a loop for the given initial, final value range with the specified step by step increment or
decrement value.
Syntax:
For counter = start To end [Step]
[Statement]
Next [counter]
18
In the above syntax the Counter is range of values specified using the Start, End parameters.
The Step specifies step increment or decrement value of the counter for which the statements are
executed.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
Dim j As Integer
j=0
For i = 1 To 10 Step 1
j=j+1
MsgBox("Value of j is::" & j)
Next i
End Sub
Description:
In the above For Next Loop example the counter value of i is set to be in the range of 1 to 10 and
is incremented by 1. The value of j is increased by 1 for 10 times as the loop is repeated.
For Each...Next For Each...Next repeats a group of statements for each element in a
collection. For-Each, requires a collection. This loop is used for accessing and
manipulating all elements in an array or a VB.Net collection.
Syntax :
For Each element [As datatype ] In group
statements
Next [ element ]
19
3) Do While Loop Statement Do While Loop Statement is used to execute a set of statements
only if the condition is satisfied. But the loop get executed once for a false condition once before
exiting the loop. This is also known as Entry Controlled loop.
Syntax:
Do While [Condition]
[Statements]
Loop
In the above syntax the Statements are executed till the Condition remains true.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,ByVal e As
System.EventArgs) Handles MyBase.Load
Dim a As Integer
a=1
Do While a < 100
a=a*2
MsgBox("Product is::" & a)
Loop
End Sub
Description:
In the above Do While Loop example the loop is continued after the value 64 to display 128
which is false according to the given condition and then the loop exits.
4) While Wend Statement While Wend Statement is a looping statement where a condition is
checked first, if it is true a set of statements are executed. The condition can also become false
atleast once while this statement is used.
Syntax:
While condition
[statements]
Wend
In the above syntax the Statements are executed when the Condition is true. The condition may
also become false while the statements are executed.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim n As Integer
n=1
While n <= 1
n=n+1
MsgBox("First incremented value is:" & n)
End While
End Sub
Description:
In the above example, the value of n is 2 in the loop, which is false according to the condition
but the loop is continued until the condition is checked. Thus the while wend statement can be
used.
20
5) While Statement Do Loop While Statement executes a set of statements and checks the
condition, this is repeated until the condition is true. .It is also known as an Exit Control loop
Syntax:
Do
[Statements]
Loop While [Condition]
In the above syntax the Statements are executed first then the Condition is checked to find if it
is true.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim cnt As Integer
Do
cnt = 10
MsgBox("Value of cnt is::" & cnt)
Loop While cnt <= 9
End Sub
Description:
In the above Do Loop While example, a messa
6) Do Loop Until Statement Do Loop Until Statement executes a set of statements until a
condition becomes false, this is an infinite loop might have to be terminated using Ctrl + Break .
Syntax:
Do
[Statements]
Loop Until [Condition]
In the above syntax the Statements are executed until the Condition becomes false.
Example:
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim X As String
Do
X = InputBox$("Correct Password Please")
Loop Until X = "Ranger"
End Sub
Description:
In the above Do Until Loop example, a input box is displayed until the correct password is typed.
21
Windows Applications
Form Control :
22
6 MaximizeBox By default, this property is True and you can set it to False to
hide the Maximize button on the title bar.
7 MinimumSize This specifies the minimum height and width of the window
you can minimize.
8 MaximumSize This specifies the maximum height and width of the window
you maximize.
9 Name This is the actual name of the form.
10 StartPosition This property determines the initial position of the form when
it's first displayed. It will have any of the following values −
CenterParent − The form is centered in the area of its
parent form.
CenterScreen − The form is centered on the monitor.
Manual − The location and size of the form will
determine its starting position.
WindowsDefaultBounds − The form is positioned at
the default location and size determined by Windows.
WindowsDefaultLocation − The form is positioned at
the Windows default location and has the dimensions
you've set at design time.
11 Text The text, which will appear at the title bar of the form.
12 TopMost This property is a True/False value that lets you specify
whether the form will remain on top of all other forms in your
application. Its default property is False.
13 Width This is the width of the form in pixel.
14 AcceptButton The button that's automatically activated when you press
Enter, no matter which control has the focus at the time.
Usually the OK button on a form is set as AcceptButton for a
form.
15 CancelButton The button that's automatically activated when you hit the Esc
key.
23
Usually, the Cancel button on a form is set as CancelButton
for a form.
16 AutoScroll This Boolean property indicates whether scroll bars will be
automatically attached to the form if it is resized to a point that
not all its controls are visible.
Form Events:
6 KeyDown Occurs when a key is pressed while the form has focus.
7 KeyPress Occurs when a key is pressed while the form has focus.
8 KeyUp Occurs when a key is released while the form has focus.
10 MouseDown Occurs when the mouse pointer is over the form and a mouse
button is pressed.
13 MouseMove Occurs when the mouse pointer is moved over the form.
24
14 MouseUp Occurs when the mouse pointer is over the form and a mouse
button is released.
End Sub
End Sub
Button:
Properties – Following properties are commonly used properties of the Button control −.
AutoSizeMode
1
Gets or sets the mode by which the Button automatically resizes itself
BackColor
2
Gets or sets the background color of the control.
ForeColor
3
Gets or sets the foreground color of the control.
4 Image
25
Gets or sets the image that is displayed on a button control.
Location
5 Gets or sets the coordinates of the upper-left corner of the control
relative to the upper-left corner of its container.
TabIndex
6
Gets or sets the tab order of the control within its container.
Text
7
Gets or sets the text associated with this control.
TextBox:
The TextBox Control allows you to enter text on your form during runtime.
Properties – Following properties are commonly used properties of the TextBox control
–
26
7 ReadOnly
Gets or sets a value indicating whether text in the text box is read-only.
8 ScrollBars
Gets or sets which scroll bars should appear in a multiline TextBox control.
This property has values −
None, Horizontal, Vertical, Both
9 TabIndex
Gets or sets the tab order of the control within its container.
10 TextAlign
Gets or sets how text is aligned in a TextBox control. This property has
values – Left, Right, Center
11 TextLength
Gets the length of text in the control.
12 WordWrap
Indicates whether a multiline text box control automatically wraps words to
the beginning of the next line when necessary.
The following are some of the commonly used methods of the TextBox control –
27
Undoes the last edit operation in the text box.
SelectionStart - for setting or getting the starting point for the TextBox
Control.
SelectionLength - for setting or getting the number of characters that have
been selected in the TextBox Control.
SelectedText - returns the TextBox Control that is currently selected.
The following are some of the commonly used events of the Text control –
txt2.Name = "txtNo2"
txt2.Left = 100
txt2.Top = 150
txt2.Visible = True
Me.Controls.Add(txt2)
28
Dim txtNo1 As New TextBox
Dim btn1 As New Button()
txtNo1.Left = 100
txtNo1.Top = 200
txtNo1.Visible = True
Me.Controls.Add(txtNo1)
End Sub
btn1.Parent = Me
btn1.Name = "btn1"
btn1.Top = 10
btn1.Text = "Btn1"
Me.Controls.Add(btn1)
End Sub
End Class
Label :
The Label Control allows you to enter text on your form during runtime.
Properties – Following properties are commonly used properties of the Label control –
Sr.No. Property & Description
1 Autosize
29
Gets or sets a value specifying if the control should be
automatically resized to display all its contents.
2 BorderStyle
Gets or sets the border style for the control.
3 FlatStyle
Gets or sets the flat style appearance of the Label control
4 Font
Gets or sets the font of the text displayed by the control.
5 FontHeight
Gets or sets the height of the font of the control.
6 ForeColor
Gets or sets the foreground color of the control.
7 PreferredHeight
Gets the preferred height of the control.
8 PreferredWidth
Gets the preferred width of the control.
10 Text
Gets or sets the text associated with this control.
11 TextAlign
Gets or sets the alignment of text in the label.
Anchoring Control:
The Anchor property lets you attach one or more edges of the control to
corresponding edges of the form.
The anchored edges of the control maintain the same distance from the
corresponding edges of the form.
Place a TextBox control on a new form, set its MultiLine property to True, and
then open the control’s Anchor property in the Properties window.
Docking Control:
Dock property, which determines how a control will dock on the form. The default
value of this property is None.
30
CheckBox :
The CheckBox control allows the user to set true/false or yes/no type options. The user
can select or deselect it. When a check box is selected it has the value True, and when it
is cleared, it holds the value False.
The following are some of the commonly used properties of the CheckBox control −
1 Appearance
Gets or sets a value determining the appearance of the check box.
2 CheckAlign
Gets or sets the horizontal and vertical alignment of the check
mark on the check box.
3 Checked
Gets or sets a value indicating whether the check box is selected.
4 CheckState
Gets or sets the state of a check box.
5 Text
Gets or sets the caption of a check box.
6 ThreeState
Gets or sets a value indicating whether or not a check box should
allow three check states rather than two.
The following are some of the commonly used events of the CheckBox control −
31
control is changed.
3 CheckStateChanged
Occurs when the value of the CheckState property of the
CheckBox control is changed.
End Sub
Example 2:
Add four check boxes on form. The check boxes will allow the users to choose the
programming languages. When the user clicks the Submit button, he/she gets an
appropriate message.
Solution:
If CheckBox1.Checked = True Then
str &= CheckBox1.Text
str &= " "
End If
RadioButton :
32
The RadioButton control is used to provide a set of mutually exclusive options.
The user can select one radio button in a group.
If you need to place more than one group of radio buttons in the same form, you should
place them in different container controls like a GroupBox control.
Properties :
The following are some of the commonly used properties of the RadioButton control –
ListBox:
The ListBox represents a Windows control to display a list of items to a user. A user can
select an item from the list. It allows the programmer to add items at design time by using
the properties window or at the runtime.
Properties:
The following are some of the commonly used properties of the ListBox control –
Sr. Property & Description
No.
1 AllowSelection : Gets a value indicating whether the ListBox currently enables
selection of list items.
2 HorizontalScrollBar :Gets or sets the value indicating whether a horizontal scrollbar
is displayed in the list box.
33
3 Items : Gets the items of the list box.
4 MultiColumn : Gets or sets a value indicating whether the list box supports multiple
columns.
5 ScrollAlwaysVisible :Gets or sets a value indicating whether the vertical scroll bar is
shown at all times.
6 SelectedIndex :Gets or sets the zero-based index of the currently selected item in a list
box.
7 SelectedIndices : Gets a collection that contains the zero-based indexes of all
currently selected items in the list box.
8 SelectedItem: Gets or sets the currently selected item in the list box.
9 SelectedItems :Gets a collection containing the currently selected items in the list box.
10 SelectionMode
Gets or sets the method in which items are selected in the list box. This property has
values −
None – No item can be selected
One – Only one item can be selected
MultiSimple – Multiple items can be selected
MultiExtended – Multiple items can be selected with the help of Shift Ctrl and
arrow key
11 Sorted
Gets or sets a value indicating whether the items in the list box are sorted
alphabetically.
12 Text
Gets or searches for the text of the currently selected item in the list box.
13 TopIndex
Gets or sets the index of the first visible item of a list box.
34
Insert( ) method : It is used to insert items at particular position in ListBox at Runtime
Syntax :
ListBoxName.Items.Insert(Index, “DataItme”)
Example :
lstCity.Items.Insert(2,“Amravati”)
Count( ) method :
It returns the total number of items in the ListBox
Syntax :
Variable name = ListBoxName.Items.Count
Example :
n = lstCity.Items.Count
35
The following are some of the commonly used events of the ListBox control –
ComboBox Control :
The ComboBox control is used to display a drop-down list of various items.
It is a combination of a text box in which the user enters an item and a drop-
down list from which the user selects an item.
Properties of the ComboBox Control :
Sr.No. Property & Description
1 DropDownStyle : It specifies the appearance and behavior of the ComboBox
Values : 1) Simple
2) DropDown
3) DropDownList
2 ItemHeight
Gets or sets the height of an item in the combo box.
3 Items
Gets an object representing the collection of the items contained in this
ComboBox.
4 MaxDropDownItems
Gets or sets the maximum number of items to be displayed in the drop-down part
of the combo box.
To apply this first set the property IntegralHeight = False
5 MaxLength
Gets or sets the maximum number of characters a user can enter in the editable
area of the combo box.
6 SelectedIndex
Gets or sets the index specifying the currently selected item.
7 SelectedItem
Gets or sets currently selected item in the ComboBox.
36
8 SelectedText
Gets or sets the text that is selected in the editable portion of a ComboBox.
9 Sorted
Gets or sets a value indicating whether the items in the combo box are sorted.
10 Text
Gets or sets the text associated with this control.
RichTextBox :
The RichTextBox control allows the user to display, enter, and edit text while also
providing more advanced formatting features than the conventional TextBox control.
Methods :
1] SaveFile : The SaveFile method saves the contents of the control to a disk file.
Syntax : RichTextBox1.SaveFile(path, filetype)
Example :
2] LoadFile : The LoadFile method loads a text or RTF file to the control.
Syntax : RichTextBox1.LoadFile(path, filetype)
Example :
Properties :
Following properties are used to read or change the alignment of one or more paragraphs:
SelectionIndent : Sets / Gets the left indentation of paragraph.
SelectionRightIndent : Sets / Gets the right indentation of paragraph.
SelectionHangingIndent : Indents all other lines of paragraph with respect to
SelectionIndent.
Example:
RichTextBox1.SelectionIndent = 20
RichTexBox1.SelectionHangingIndent = -25
RichTextBox1.RightIndent = 10
Formatting Text of RichTextBox :
Dim fd As New FontDialog
fd.ShowDialog()
TextBox1.Font = fd.Font
37
MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a
command button before he /she can continues. This format is as follows:
myMsg=MsgBox(Prompt, Style Value, Title)
The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer to the below
Table for types of command button displayed. The Title argument will display the title of the
message board.
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constants in place of integers for the second argument to make the programs
more readable.
For example:
myMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
and
myMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")
are the same.
myMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values
are determined by the type of buttons being clicked by the users. It has to be declared as Integer
data type in the procedure or in the general declaration section. Below table shows the values, the
corresponding named constant and buttons.
Value Named Constant Button Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
38
6 vbYes Yes button
7 vbNo No button
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub
You can add an icon besides the message. There are four types of icons available as shown in
Table
16 vbCritical
3 vbQuestion
48 vbExclamation
64 vbInformation
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test
Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
39
End Sub
myMessage is a variant data type but typically it is declared as string, which accept the message
input by the users.
The arguments are explained as follows:
Example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry
Form", "Enter your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
40
The InputBox will appear as shown in the figure below when you press the command button.
41
Predefined Dialog Box in VB.Net:
There are many built-in dialog boxes to be used in Windows forms for various tasks
like opening and saving files, printing a page, providing choices for colors, fonts,
page setup, etc., to the user of an application.
The ShowDialog method is used to display all the dialog box controls at run-time.
The ShowDialog method returns a value of the type of DialogResult enumeration.
The values of DialogResult enumeration are −
Abort − returns DialogResult. Abort value, when user clicks an Abort button.
Cancel − returns DialogResult. Cancel, when user clicks a Cancel button.
Ignore − returns DialogResult. Ignore, when user clicks an Ignore button.
No − returns DialogResult. No, when user clicks a No button.
None − returns nothing and the dialog box continues running.
OK − returns DialogResult. OK, when user clicks an OK button
Retry − returns DialogResult. Retry , when user clicks an Retry button
Yes − returns DialogResult. Yes, when user clicks an Yes button
1] ColorDialog : It represents a common dialog box that displays available colors along
with controls that enable the user to define custom colors.
Example :
Dim ColorDialog1 As New ColorDialog
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
If ColorDialog1.ShowDialog < > Windows.Forms.DialogResult.Cancel Then
Label1.ForeColor = ColorDialog1.Color
End If
End Sub
2] FontDialog : It prompts the user to choose a font from among those installed on the
local computer and lets the user select the font, font size, and color.
Example :
Dim FontDialog1 As New FontDialog
If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
3] OpenFileDialog :It prompts the user to open a file and allows the user to select a file
to open.
42
Example:
Dim OpenFileDialog1 As New OpenFileDialog
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
4] SaveFileDialog : It prompts the user to select a location for saving a file and allows
the user to specify the name of the file to save data.
Example :
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
5] PrintDialog : It lets the user to print documents by selecting a printer and choosing
which sections of the document to print from a Windows Forms application.
Example :
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
43
Assignment 1:
Set A
1. Write a Vb.net program to accept string and count the number of words and display the
count.
2. Write VB.Net program to covert decimal number into binary, hexadecimal, and octal
number.
3. Write a Vb.net program to print second highest value in an array.
Set B
Set C
1. Write a Vb.net program to check whether entered number is Spy Number or not Using
Console Application.
[Note : A positive integer is called a spy number if the sum and product of its digits are
equal.]
Assignment Evaluation
Signature of Instructor
44
Assignment 2
Set A
1. Write a Vb.net program to design the following form, accept the numbers through textbox
and add them into the ListBoxe1 by clicking on Add button. When user click on Prime
button then all the prime numbers from ListBox1 should get added into ListBox2.
Set B
1. Write VB.Net program to add three text boxes at runtime. Allow user to enter values and
then display Maximum and Minimum value using message box after click on command
button.
2. Write VB .Net program to take three text boxes and two buttons on the form. Enter different
strings in first and second textbox. On clicking the First command button, concatenation of
two strings should be displayed in third text box and on clicking second command button,
reverse of string should display in third text box.
3. Write VB.Net Program to Design following form to store numbers in single dimensional
array and to find Maximum no & sum of all numbers in array.
45
Set C
1. Write a Vb.net program to design the following form, allow the user to select radio buttons
from Gender and Age Panel. After Selection appropriate CheckBox from Right Panel
should be selected automatically. Display appropriate message into the MessageBox by
clicking on Ok button.
46
Assignment Evaluation
Signature of Instructor
47
Assignment 3
7. Write a Vb.net program to design screen to accept the details from the user. Clicking on
Submit button Net Salary should be calculated and displayed into the TextBox. Display
the MessageBox informing the Name and Net Salary of employee.
Assignment Evaluation
Signature of Instructor
48
ASSIGNMENT - C: C#.NET
Most of the syntaxes of the C# programming language are similar to the C and C++
programming languages.
we created a C# file called Program1.cs, and we used the following code to print "Hello World"
to the screen:
namespace HelloWorld
{
class Program1
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Example explained
Line 1: using System means that we can use classes from the System namespace.
Line 2: namespace is used to organize your code, and it is a container for classes and other
namespaces.
Line 3: The curly braces {} marks the beginning and the end of a block of code.
Line 4: class is a container for data and methods, which brings functionality to your program.
Every line of code that runs in C# must be inside a class. In our example, we named the class
Program1.
Line 6: The Main method. Any code inside its curly brackets {} will be executed. It is an entry
point method, Program execution is stared from main method.
49
Line 7: Console is a class of the System namespace, which has a WriteLine() method that is
used to output/print text. In our example it will output "Hello World!".
Note:
1.If you omit the using System line, you would have to write System.Console.WriteLine() to
print/output text.
Types of C# compiler:
1. Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by C# compiler (will not be executed).
Example
// This is a comment
Console.WriteLine("Hello World!");
2. C# Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by C# compiler.
Example
/* This is the multi line comment and
the output of this example is Hello World
on the screen. */
Console.WriteLine("Hello World!");
C# Variables
Variables are the identifier, used for the storing values.
Syntax:
datatype variableName = value;
Example:
string name = "Vikas";
Console.WriteLine(name);
Constants
Constant is a variable that can’t be change its value during the program once initialized.
Examlple : const doublePI = 3.142;
50
C# Data Types
Data Type tells us that which kind of value store into a variable and how many bytes allocated
for that variable.
Note: A floating point number can also be a scientific number with an "e" to indicate the power
of 10:
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
Output
35000
120000
C# Type Casting
Type Casting is the converting the value of variable into one data type to another data type.
51
Console.WriteLine(doubleNum); // Outputs 10
Example:
There are some built-in methods which converts data types explicitly, such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int)
and Convert.ToInt64 (long):
namespace MyApplication
{
class Program2
{
static void Main(string[] args)
{
Console.WriteLine("Enter your full name:");
string fullName = Console.ReadLine();
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
52
Console.WriteLine("Your Full Name is: " + fullName+” and Age is:”+age);
}
}
}
C# Operators
53
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Control Structure:
using System;
namespace MyApplication {
class Program3
{
static void Main(string[] args)
{
if (20>10)
{
Console.WriteLine("20 is greater than 10");
}
}
}
}
ii. if-else statement: if condition is true then statements within if block are executed
otherwise statements within else block are executed.
Syntax:
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
using System;
namespace MyApplication {
class Program4
54
{
static void Main(string[] args)
{
Console.Write("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
if (num>=0)
{
Console.WriteLine(num+" is +ve");
}
else
{
Console.WriteLine(num+" is -ve");
}
}
}
}
iii. Nested if statement:if with ladder or if within if are called nested if statement.
Syntax:
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
using System;
namespace MyApplication
{
class Program5
{
static void Main(string[] args)
{
double per;
Console.Write("Enter the Percentage : ");
per = Convert.ToDouble(Console.ReadLine());
if (per >=75 10)
{
55
Console.WriteLine("First class with Distinction.");
}
else if (per >=60 && per<75)
{
Console.WriteLine("First Class.");
}
else if (per >=50 && per<60)
{
Console.WriteLine("Second Class.");
}
else if (per >=40 && per<50)
{
Console.WriteLine("Pass Class.");
}
else {
Console.WriteLine("Fail.");
}
}
}
}
namespace MyApplication
{
class Program6
{
56
switch (monthNumber)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("you did not enter correct value for month name");
break;
}
}
}
57
}
namespace MyApplication
{
class Program7
{
static void Main(string[] args)
{
int num, sum=0;
if(num <0)
{
Console.Write("Please Enter Positive Number");
}
else
{
while(num >0)
{
sum =sum+num;
num = num - 1;
}
}
Console.WriteLine("The sum is "+sum);
Console.ReadKey();
}
}
}
58
ii. do-while loop: it is an exit control loop it executed at least once even though
condition is false.
Syntax:
do
{
// code block to be executed
} while (condition);
namespace MyApplication
{
class Program8
{
static void Main(string[] args)
{
int number, sum=0,lastDigit;
do
{
lastDigit=number%10;
sum = sum+ lastDigit;
number =number/10;
}while(number>0);
Console.ReadKey();
}
}
}
iii. for loop: When we know the number of iterations in advance then for loop is
used instead of while loop.
Syntax:
for (Initialization ; Condition ; Updation)
{
// code block to be executed
}
59
namespace MyApplication
{
class Program9
{
static void Main(string[] args)
{
int i, number, fact;
Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = 1; i <= number; i++)
{
fact = fact * i;
}
Console.WriteLine("\nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}
using System;
namespace MyApplication
{
class Program10
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}
}
}
}
Output
60
0
1
2
3
ii. continue statement: it is use for breaks one iteration in the loop, if a specified
condition occurs, and continues with the next iteration in the loop.
using System;
namespace MyApplication
{
class Program11
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
}
}
}
Output
0
1
2
3
5
6
7
8
9
Array
Array is use to storing the heterogeneous elements into single variable.
Array element is accessed using an index, it starts from 0 to size-1.
Syntax:
Datatype[] array_name=new Datatype[size];
61
namespace MyApplication
{
class Program12
{
static void Main(string[] args)
{
int[] numbers = new int[10];
Random rnd = new Random();
int min, max;
Output
56
95
23
75
63
45
19
7
32
83
The highest number in the array:95
The lowest number in the array:7
62
Method: It is a block of statements used to perform a specific task and it may return value to the
calling program.
Syntax to define method:
static return_type method_name([parameter_list])
{
//method statements
}
Note: [] indicates it is optional.
namespace MyApplication
{
class Program13
{
static bool IsEvenNumber(int num)
{
if (num % 2 == 0)
{
return true;
}
else
{
return false;
}
}
static void Main(string[] args)
{
int n;
Console.Write("Enter an integer : ");
n = Int32.Parse(Console.ReadLine());
if (IsEvenNumber(n))
{
Console.WriteLine("{0} is even", n);
}
else
{
Console.WriteLine("{0} is odd", n);
}
Console.ReadKey();
}
}
63
}
Output
Enter an integer: 37
37 is odd
String class:
In C#, string is keyword which is an alias for System.String class. That is why string and String
are equivalent. We are free to use any naming convention.
String methods
64
IndexOf(String) It is used to report the zero-based index of the first occurrence of the
specified string in this instance.
Insert(Int32, String) It is used to return a new string in which a specified string is inserted
at a specified index position.
Intern(String) It is used to retrieve the system's reference to the specified String.
IsInterned(String) It is used to retrieve a reference to a specified String.
IsNormalized() It is used to indicate that this string is in Unicode normalization form
C.
IsNullOrEmpty(String) It is used to indicate that the specified string is null or an Empty
string.
IsNullOrWhiteSpace(String) It is used to indicate whether a specified string is null, empty, or
consists only of white-space characters.
Join(String, String[]) It is used to concatenate all the elements of a string array, using the
specified separator between each element.
LastIndexOf(Char) It is used to report the zero-based index position of the last
occurrence of a specified character within String.
LastIndexOfAny(Char[]) It is used to report the zero-based index position of the last
occurrence in this instance of one or more characters specified in a
Unicode array.
Normalize() It is used to return a new string whose textual value is the same as
this string, but whose binary representation is in Unicode
normalization form C.
PadLeft(Int32) It is used to return a new string that right-aligns the characters in this
instance by padding them with spaces on the left.
PadRight(Int32) It is used to return a new string that left-aligns the characters in this
string by padding them with spaces on the right.
Remove(Int32) It is used to return a new string in which all the characters in the
current instance, beginning at a specified position and continuing
through the last position, have been deleted.
Replace(String, String) It is used to return a new string in which all occurrences of a
specified string in the current instance are replaced with another
specified string.
Split(Char[]) It is used to split a string into substrings that are based on the
characters in an array.
StartsWith(String) It is used to check whether the beginning of this string instance
matches the specified string.
Substring(Int32) It is used to retrieve a substring from this instance. The substring
starts at a specified character position and continues to the end of the
string.
ToCharArray() It is used to copy the characters in this instance to a Unicode
character array.
ToLower() It is used to convert String into lowercase.
ToLowerInvariant() It is used to return convert String into lowercase using the casing
rules of the invariant culture.
65
ToString() It is used to return instance of String.
ToUpper() It is used to convert String into uppercase.
Trim() It is used to remove all leading and trailing white-space characters
from the current String object.
TrimEnd(Char[]) It Is used to remove all trailing occurrences of a set of characters
specified in an array from the current String object.
TrimStart(Char[]) It is used to remove all leading occurrences of a set of characters
specified in an array from the current String object.
Example:
using System.Text;
namespace MyApplication
{
class Program13
{
static void Main(string[] args)
{
string firstname;
string lastname;
Console.WriteLine(firstname.Clone());
// Make String Clone
Console.WriteLine(firstname.CompareTo(lastname));
//Compare two string value and returns 0 for true and1 for false
Console.WriteLine(firstname.GetHashCode());
//Returns HashCode of String
Console.WriteLine(firstname.GetType());
//Returns type of string
66
Console.WriteLine(firstname.GetTypeCode());
//Returns type of string
Console.WriteLine(firstname.ToLower());
//Covert string into lower case
Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case
Console.WriteLine(firstname.IsNormalized());
//Check Whether string is in Unicode normalization
from C
Console.WriteLine(firstname.Length);
//Returns the Length of String
Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.
string[] split = firstname.Split(new char[] { 'e' }); //Split the string based on specified value
Console.WriteLine(split[0]);
Console.WriteLine(split[1]);
Console.WriteLine(split[2]);
Console.WriteLine(firstname.StartsWith("S"));
//Check wheter first character of string is same as specified value
Console.WriteLine(firstname.Substring(2,5));
//Returns substring
Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.
67
Console.WriteLine(firstname.Trim());
//It removes starting and ending white spaces fromstring.
}
}
}
Output
Steven Clark
1
True
False
False
1470518261
System.String
String
2
steven clark
STEVEN CLARK
HelloSteven Clark
True
4
12
Steve
Stivin Clark
St
v
n Clark
True
even
Steven Clark
Steven Clark
68
It is a template from which objects are created. It can have fields, methods, constructors
etc.
Example:
using System;
public class Student
{
public int id;
public String name;
public void insert(int i, String n)
{
id = i;
name = n;
}
public void display()
{
Console.WriteLine(id + " " + name);
}
}
class TestStudent{
public static void Main(string[] args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.insert(1001, "Abhijeet");
s2.insert(1002, "Reshma");
s1.display();
s2.display();
}
}
Output
1001 Abhijeet
1002 Reshma
Access Description
Specifier
Public It specifies that access is not restricted.
Protected It specifies that access is limited to the containing class or in derived
69
class.
Internal It specifies that access is limited to the current assembly.
protected It specifies that access is limited to the current assembly or types derived
internal from the containing class.
Private It specifies that access is limited to the containing type.
Constructors
In C#, constructor is a special method its name should be same as its class name.
which is invoked automatically at the time of object creation.
It is used to initialize the data members of new object generally.
It does not have any return type even though void.
using System;
public class Employee
{
public int id;
public String name;
public float salary;
1. public Employee()
2. {
id = 101;
name = “Rahul Bhosale”;
salary = 750000f;
3.
4. Console.WriteLine("Default Constructor Invoked");
5. }
70
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee(102, "Mahesh Raut", 460000f);
e1.display();
e2.display();
}
}
Output
101Rahul Bhosale 750000
102Mahesh Raut 460000
Inheritance
In C#, inheritance is a process in which object of one class acquires the properties of object of
another class.
Inheritance provides reusability of code and extends or modifies the attributes, behaviors which
is defined in other class.
The class whose members are inherited is called base class or parent class or super class and the
class which inherits the members of another class is called derived class or child class or sub
class.
Types of inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
71
BabyDog d1 = new BabyDog();
d1.eat();
d1.bark();
d1.weep();
}
}
Output
Eating...
Barking...
Weeping...
Abstract method: A method which is declared abstract and has no body is called
abstract method. It can be declared inside the abstract class only. Its implementation must be
provided by derived classes.
Example:
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
72
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
Output
drawing ractangle...
drawing circle..
Interface
An interface is a completely "abstract class", which can only contain abstract methods (with
empty bodies)
Example:
using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
73
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}
}
Output
drawing ractangle...
drawing circle...
Method Overloading
Method having same name but different prototyping or signature called as method overloading.
The advantage of method overloading is that it increases the readability of the program because
you don't need to use different names for same action.
Example
using System;
public class Calculate{
public static int sum(int a,int b){
return a + b;
}
public static int sum(int a, int b, int c)
{
return a + b + c;
}
}
public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Calculate.sum(10, 20));
Console.WriteLine(Calculate.sum(10, 20, 30));
}
}
Output
30
60
Method Overriding
If derived class defines same method as defined in its base class, it is known as method
overriding.
It is used to achieve runtime polymorphism.
74
To perform method overriding, you need to use virtual keyword with base class method
and override keyword with derived class method.
Example:
using System;
public class Animal{
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
}
}
Output
Eating bread...
Delegates
In C#, Delegate is a reference to the method. It works like function pointer in C and C++. But it
is objected-oriented, secured and type-safe than function pointer.
For static method, delegate encapsulates method only. But for instance method, it encapsulates
method and instance both.
The best use of delegate is to use as event.
Internally a delegate declaration defines a class which is the derived class of System.Delegate.
Example:
using System;
delegate int Calculator(int n);//declaring delegate
public class DelegateExample
{
static int num = 100;
public static int addition(int n)
{
num = num + n;
75
return num ;
}
public static int multiplication(int n)
{
num = num * n;
return num;
}
public static int getNumber()
{
return num;
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator(addition);//instantiating delegate
Calculator c2 = new Calculator(multiplication);
c1(20);//calling method using delegate
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
}
}
Output
After c1 delegate, Number is: 120
After c2 delegate, Number is: 360
76
Assignment 4
Set A:
1. Program to display the addition, subtraction, multiplication and division of two number.
5. Define a Student class (roll number, name, and percentage). Define a default
andparameterized constructor. Override the toString method. Keep a count objects
created. Create objects using parameterized constructor and display the object count after
each object is created. (Use static member and method).
6. Define a class Employee having members – id, name, department, salary. Define default
and parameterized constructors. Create a subclass called “Manager” with member bonus.
Define methods accept and display in both the classes. Create no. objects of the Manager
class and display the details of the manager having the maximum total salary (salary +
bonus)
Set B:
Set C:
1. Define a class “Employee” which has members id, name, date of birth. Define
another class “Manager” which has members department name and joining date
and extends Employee. Create n objects of the manager class.
2. Define an abstract class “Staff” with members name and address. Define two
subclasses of this class – “FullTimeStaff” (department, salary) and
“PartTimeStaff” (numberof_hours, rate_per_hour). Define appropriate
constructors. Create n objects which could be of either FullTimeStaff or
PartTimeStaff class by asking the user’s choice. Display details of all
“FullTimeStaff” objects and all “PartTimeStaff” objects.
Assignment Evaluation
Signature of Instructor
78
ASSIGNMENT -D: ASP.NET
ASP.NET is a web development platform, which provides a programming model, a
comprehensive software infrastructure and various services required to build up robust web
applications for PC as well as mobile devices. ASP.NET works on top of the HTTP protocol, and
uses the HTTP commands and policies to set a browser-to-server bilateral communication and
cooperation. ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled
codes, written using the extensible and reusable components or objects present in .Net
framework. These codes can use the entire hierarchy of classes in .Net framework.
ASP.NET application codes can be written in any of the following languages:
C#
Visual Basic.Net
Jscript
J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It
consists of a large number of controls such as text boxes, buttons, and labels for assembling,
configuring, and manipulating code to create HTML pages.
1. Language – A variety of languages exists for .net framework. They are VB.net and C#.
These can be used to develop web applications.
2. Library – The .NET Framework includes a set of standard class libraries. The most
common library used for web applications in .net is the Web library. The web library has
all the necessary components used to develop.Net web-based applications.
3. Common Language Runtime – The Common Language Infrastructure or CLI is a
platform. .Net programs are executed on this platform. The CLR is used for performing
key activities. Activities include Exception handling and Garbage collection.
When an ASP.Net page is called, it goes through a particular lifecycle. This is done before
the response is sent to the user. There are series of steps which are followed for the
processing of an ASP.Net page.
The various stages of the lifecycle of an ASP.Net web page are as:
1. Page Request– This is when the page is first requested from the server. When the page is
requested, the server checks if it is requested for the first time. If so, then it needs to
compile the page, parse the response and send it across to the user. If it is not the first
time the page is requested, the cache is checked to see if the page output exists. If so, that
response is sent to the user.
79
2. Page Start – During this time, 2 objects, known as the Request and Response object are
created. The Request object is used to hold all the information which was sent when the
page was requested. The Response object is used to hold the information which is sent
back to the user.
3. Page Initialization – During this time, all the controls on a web page is initialized. So if
you have any label, textbox or any other controls on the web form, they are all initialized.
4. Page Load – This is when the page is actually loaded with all the default values. So if a
textbox is supposed to have a default value, that value is loaded during the page load
time.
5. Validation – Sometimes there can be some validation set on the form. For example, there
can be a validation which says that a list box should have a certain set of values. If the
condition is false, then there should be an error in loading the page.
6. Postback event handling – This event is triggered if the same page is being loaded
again. This happens in response to an earlier event. Sometimes there can be a situation
that a user clicks on a submit button on the page. In this case, the same page is displayed
again. In such a case, the Postback event handler is called.
7. Page Rendering – This happens just before all the response information is sent to the
user. All the information on the form is saved, and the result is sent to the user as a
complete web page.
8. Unload – Once the page output is sent to the user, there is no need to keep the ASP.net
web form objects in memory. So the unloading process involves removing all unwanted
objects from memory.
To change the Web Forms Designer from one view to another, click on the Design or
source button.
To close a window, click on the close button on the upper right corner and to redisplay,
select it from the View menu.
To hide a window, click on its Auto Hide button. The window then changes into a tab.
To display again, click the Auto Hide button again.
To change the size of a window, just drag it.
Adding Folders and Files to your Website
When a new web form is created, Visual Studio automatically generates the starting HTML for
the form and displays it in Source view of the web forms designer. The Solution Explorer is used
to add any other files, folders or any existing item on the web site.
To add a standard folder, right-click on the project or folder under which you are going to
add the folder in the Solution Explorer and choose New Folder.
To add an ASP.NET folder, right-click on the project in the Solution Explorer and select
the folder from the list.
To add an existing item to the site, right-click on the project or folder under which you
are going to add the item in the Solution Explorer and select from the dialog box.
80
Projects and Solutions
A typical ASP.NET application consists of many items: the web content files (.aspx), source
files (.cs files), assemblies (.dll and .exe files), data source files (.mdb files), references,
icons, user controls and miscellaneous other files and folders. All these files that make up the
website are contained in a Solution.
When a new website is created, dotnet environment automatically creates the solution and
displays it in the solution explorer.
Solutions may contain one or more projects. A project contains content files, source files, and
other files like data sources and image files. Generally, the contents of a project are compiled
into an assembly as an executable file (.exe) or a dynamic link library (.dll) file.
Typically a project contains the following content files:
Selecting Start
Selecting Start Without Debugging from the Debug menu
pressing F5
Ctrl-F5
The program is built meaning, the .exe or the .dll files are generated by selecting a command
from the Build menu.
81
3. Response objects are created. The application objects such as HttpContext, HttpRequest and
HttpResponse are created and initialized.
4. An instance of the HttpApplication object is created and assigned to the request.
5. The request is processed by the HttpApplication class. Different events are raised by this class
for processing the request.
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
EVENT HANDLING
An event is an action or occurrence such as a mouse click, a key press, mouse movements, or
any system-generated notification. A process communicates through events. For example,
interrupts are system-generated events. When events occur, the application should be able to
respond to it and manage it.
Events in ASP.NET are raised at the client machine and handled at the server machine. For
example, a user clicks a button displayed in the browser. A Click event is raised. The browser
handles this client-side event by posting it to the server.
Event Arguments
ASP.NET event handlers generally take two parameters and return void. The first parameter
represents the object raising the event and the second parameter is event argument. The general
syntax of an event is:
private void EventName (object sender, EventArgs e);
82
Page and Control Events
Common page and control events are:
End Sub
83
Write a Program to bind data using template in data list
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim constr As String =
ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").Connection String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Load
Dim conpubs As SqlConnection Dim cmdselect As SqlCommand Dim dtrAuthor As
SqlDataReader
conpubs = New SqlConnection(constr)
cmdselect = New SqlCommand("Select * from Author", conpubs) conpubs.Open()
dtrAuthor = cmdselect.ExecuteReader() dtrlstAuthor.DataSource = dtrAuthor
dtrlstAuthor.DataBind() dtrAuthor.Close()
conpubs.Close()
End Sub
End Class
Assignment 5
1. Write a Program to convert temperature from Fahrenheit to Celsius or vice versa.
2. Write a Program to display the selected date in the calendar
3. Write a Program to display the Difference between the two dates in the calendar.
Assignment Evaluation
Signature of Instructor
84
ASSIGNMENT -E: ADO .NET
A data-access technology that enables applications to connect to data stores and manipulate data
contained in them in various ways.
An object oriented framework that allows you to interact with database systems
ADO.NET components
1) Dataset
2) Data Provider
DataSet is an in-memory representation of data. It is a disconnected, cached set of
records that are retrieved from a database.
When a connection is established with the database, the data adapter creates a dataset and
stores data in it. After the data is retrieved and stored in a dataset, the connection with the
database is closed. This is called the 'disconnected architecture'. The dataset works as a
virtual database containing tables, rows, and columns.
85
Connecting to a Database
The .Net Framework provides two types of Connection classes −
SqlConnection − designed for connecting to Microsoft SQL Server.
OleDbConnection − designed for connecting to a wide range of databases, like
Microsoft Access and Oracle.
Steps :
We have a table stored in Microsoft SQL Server, named Customers, in a database
named testDB.
Select TOOLS → Connect to Database
Select a server name and the database name in the Add Connection dialog box.
Click on the Test Connection button to check if the connection succeeded.
Add a DataGridView on the form.
Click on the Choose Data Source combo box. Click on the Add Project Data
Source link.
This opens the Data Source Configuration Wizard.
Select Database as the data source type
Choose DataSet as the database model.
Choose the connection already set up.
Save the connection string.
Choose the database object, Customers table in our example, and click the Finish
button.
When the application is run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window
2) Data Provider:
A data provider is used for connecting to a database, executing commands and retrieving data,
storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects –
1) Connection
This component is used to set up a connection with a data source.
2) Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify
data in a data source.
86
3)DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only
mode.
4) DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database
through a data adapter. It retrieves data from a database into a dataset and updates the database.
When changes are made to the dataset, the changes in the database are actually done by the data
adapter.
There are following different types of data providers included in ADO.Net
1) The .Net Framework data provider for SQL Server - provides access to Microsoft SQL
Server.
2) The .Net Framework data provider for OLE DB - provides access to data sources exposed by
using OLE DB.
3) The .Net Framework data provider for ODBC - provides access to data sources exposed by
ODBC.
4) The .Net Framework data provider for Oracle - provides access to Oracle data source.
5) The Entity Client provider - enables accessing data through Entity Data Model (EDM)
applications.
CONNECTIONS:
ADO.NET provids both Sqlconnection and OLEDB connection classes for use with
datasource.
1) Sql Connection :-
To declare and instantiate Sql connection,u can use foll.stmt
Dim con AS Sqlconnection
con = New SqlConnection("server=YASH;database=test;integrated security=true")
2) OleDbConnection
Dim con As OleDbConnection
Dim con As OleDbConnection
87
con = New OleDbconnection ("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=yourdatabasename.mdb” )
Command
We use command object to tell database about operation we need to perform.
The typical command on database will be :-
1) Select
2) Insert
3) Delete
4) Update
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\user\Documents\Database5.accdb")
cn.Open()
MsgBox("oledb connection is successfully established")
End Sub
End Class
Data Adapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the
communication between the Dataset and the Datasource. We can use the DataAdapter in
combination with the DataSet Object. That is these two objects combine to enable both
data access and data manipulation capabilities.
88
The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the
Data Source. The Insert , Update and Delete SQL operations , we are using the
continuation of the Select command perform by the DataAdapter. That is the
DataAdapter uses the Select statements to fill a DataSet and use the other three SQL
commands (Insert, Update, delete) to transmit changes back to the Database
Types of DataAdapter
1) SqlDataAdapter
2) OleDbDataAdapter
Types of DataAdapter
1) SqlDataAdapter :-
Dim ad as SqlDataAdapter
ad=new SqlDataAdapter (cmd)
2) OleDbDataAdapter :-
Dim ad as OleDbDataAdapter
ad=new OleDbDataAdapter (cmd)
Example
Imports System.Data.OleDb
Public Class Form1
Dim cn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim ad As New OleDbDataAdapter
Dim dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database5DataSet.doctor' table. You can
move, or remove it, as needed.
Me.DoctorTableAdapter.Fill(Me.Database5DataSet.doctor)
89
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\user\Documents\Database5.accdb")
cn.Open()
MsgBox("oledb connection is successfully established")
cmd = New OleDbCommand("select * from doctor", cn)
ad = New OleDbDataAdapter(cmd)
ad.Fill(dt)
DataGridView1.DataSource = dt
End Sub
End Class
Dataset
The DataSet contains the copy of the data we requested through the SQL statement. We
can use Dataset in combination with SqlDataAdapter class . The SqlDataAdapter object
allows us to populate Data Tables in a DataSet.
Example
Imports System.Data.OleDb
Public Class Form1
Dim cn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim ad As New OleDbDataAdapter
Dim ds As New DataSet()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.DoctorTableAdapter.Fill(Me.Database5DataSet.doctor)
cn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Users\user\Documents\Database5.accdb")
90
cn.Open()
MsgBox("oledb connection is successfully established")
adp = New OleDbDataAdapter(cmd)
adp = New OleDbDataAdapter("select * from doctor", cn)
ad.Fill(ds, "doctor")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "doctor"
End Sub
End Class
Data Reader
To retrieve data using a DataReader, create an instance of the Command object, and then
create a DataReader bycalling Command.ExecuteReader to retrieve rows from a data
source.
DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of
query results from the Data Source, which do not update the data. The DataReader cannot
be created directly from code, they created only by calling the Execute Reader method of
a Command Object.
DataReader = Command.ExecuteReader()
DataTable
DataTable represents relational data into tabular form. ADO.NET provides a DataTable
class to create and use data table independently. It can also be used with DataSet also.
Initially, when we create DataTable, it does not have table schema. We can create table
schema by adding columns and constraints to the table. After defining table schema, we
can add rows to the table.
We must include System.Data namespace before creating DataTable.
Example
Imports System.Data. DataTable
Public Class Form1
Dim table As New DataTable("table")
91
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
table.Columns.Add("ID", Type.GetType("System.Int32"))
table.Columns.Add("FIRST NAME", Type.GetType("System.Int32"))
table.Columns.Add("LAST NAME", Type.GetType("System.Int32"))
table.Columns.Add("SUM", Type.GetType("System.Int32"))
DataGridView1.DataSource = table
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = table
End Sub
Data Validation
Data validation is the process of ensuring, at least as far as is possible, that the data given
to a program by a user or from a file is of the correct type, and in the correct format.
Although the programmer will obviously take every precaution to ensure the correct
operation of the program, and will attempt to eliminate bugs that could cause a problem
through a rigorous process of testing, they have no real control over mistakes made by the
user during data entry. Nor can they guarantee that any data files used by the program
will be free of errors and in the correct format.
92
Write a program to access data source through ADO.NET.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
string s1 = Session["rollno"].ToString();
string s2 = Session["sem"].ToString();
string s3 = Session["branch"].ToString();
string d1 = dr.GetValue(0).ToString();
string d2 = dr.GetValue(1).ToString();
string d3 = dr.GetValue(2).ToString();
string d4 = dr.GetValue(3).ToString();
string d5 = dr.GetValue(4).ToString();
string d6 = dr.GetValue(5).ToString();
string d7 = dr.GetValue(6).ToString();
string d8 = dr.GetValue(7).ToString();
93
TextBox1.Text = d1;
TextBox2.Text = d2;
TextBox3.Text = d3;
Label16.Text = d4;
Label17.Text = d5;
Label18.Text = d6;
Label19.Text = d7;
Label20.Text = d8;
dr.Dispose();
}
cmd1.CommandText = "select * from SEM_BRANCH_SUB where sem='"+s2+"' and
branch='"+s3+"' ";
OleDbDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
string d9 = dr1.GetValue(2).ToString();
string d10 = dr1.GetValue(3).ToString();
Label10.Text = d9;
Label11.Text = d10;
Label12.Text = d11;
Label13.Text = d12;
Label14.Text = d13;
}
}
Database programs with ASP.NET and ADO.NET Create a Login Module which adds Username
and Password in the database. Username in the database should be a primary key.
CODE:
LoginModule.aspx
using System;
using System.Collections.Generic;
using System.Linq;
94
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LoginModule : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
SqlDataSource1.InsertParameters["Username"].DefaultValue = txtUserName.Text;
SqlDataSource1.InsertParameters["Password"].DefaultValue = txtPassword.Text;
SqlDataSource1.Insert();
lblResult.Text = "User Added";
}
}
Assignment: 6
1. Create a web application to insert 3 records inside the SQL database table having
following fields( DeptId, DeptName, EmpName, Salary). Update the salary for any one
employee and increment it to 15% of the present salary. Perform delete operation on 1
row of the database table.
2. Create the table with the given fields. FIELD NAME DATA TYPE (EmpNo number
EmpName varchar EmpSal number EmpJob varchar EmpDeptNo number)For the given
table design a web page to display the employee information from table to grid control.
3. Create the table with the given fields. FIELD NAME DATA TYPE SRollno int SName
string SAddress string SFees int For the given table design a web page to display the
employee information from table to grid control.
4. Write a program to connect to the master database in SQL Server, in the Page_Load
event. When the connection is established, the message “Connection has been
established” should be displayed in a label in the form.
95
Assignment Evaluation
Signature of Instructor
96
Section III: RIT
T.Y.B.B.A.(C.A.) Sem-VI (CBCS 2019 Pattern)
Subject Code: CA-601
Subject: Recent Trends in IT Practical Assignments