Академический Документы
Профессиональный Документы
Культура Документы
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 01
Practical-1
AIM: Learn Basics of Java language and its development libraries/ tools.
Objectives: Introduce programming languages. Introduce Java programming language. Show how to set up your system environment for Java development. Write, compile and run your first Java application "Hello World". Programming Languages By programming language, we mean a set of vocabulary, grammar and libraries that construct a language we can use to write computer programs. A programming language consists of the following: Vocabulary: set of meaningful keywords that have specific meaning in the programming language (also called reserved words). Syntax (grammar): set of rules that constraint the way in which programs are written. A program that does not follow these rules has one or more syntax errors. Software Development Kit (SDK) that contains the following: Libraries: also known as Application Programming Interface (API), these files are previously written classes and methods that contain some common functionality. Compiler: the program that translates files written in Java language (human language) into binary files (machine language) in order for the computer to be able to execute them. Interpreter: some programming languages does not compile the source code file into directly executable form (native code), but they instead compile it into partially compiled file that could be executed by a program called interpreter. Java Programming Language Java programming language is an interpreted programming language, that is, when the source code is compiled into binary file, it needs an interpreter called Java Virtual Machine (JVM) to run it. Java compiler is called j avac . exe, and interpreter is called j ava. exe. Figure 2.1 shows a Java technology overview.
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 02
Characteristics of java Characteristics of java are very easy to understand. Java has advanced object oriented capabilities are they are very powerful. Some of the characteristics are: Architecture-neutral Distributed Interpreted and compiled Multithreaded Network-ready and compatible Object-oriented Portable Robust Secure Viewing Writing, Compiling and Running Your First Java Application To write a Java program, open the command prompt by selecting run from start menu and entering the command cmd in the dialog box, the command prompt console appears, show in figure 2.7. Change to the directory you have selected as Java directory (for example c :\ Documents and Settings\ Student\ Desktop\ java) by using cd command.
To write a new Java program using the notepad, enter the command notepad filename. For instance, we will write a class named HelloWorld, so we will use the command notepad HelloWorld.java . Note that we use a .java extension for all Java source files, and we always use upper case characters in the beginning of a class name. After starting the notepad, it will Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 03
ask you whether you wish to create a new file with the name specified, confirm file creation. It is important to keep in mind that file name and class name must be the same, otherwise the compiler will generate an error message and the file will not compile.
In the notepad, write the following code (always keep in mind that Java is case-sensitive language, for example if you typed Class instead of class the compiler will report a syntax error) //HelloWorld. java /* This is my first java program. */ class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World!"); System.out.println("How r u 2day?"); } //end of main method }//end of class When you are done with code writing, save the file and exit notepad. Your source code file is now ready for compilation, to compile a Java source code file, use the command javac filename. In our example, javac HelloWorld.java. If everything is alright, the compiler will terminate without any messages and go back to command prompt as shown in figure 2.9. After compilation, if you run dir command, you will notice that the compiler generated a new file called HelloWorld.class, this is the binary file JVM will execute. To run you application, use the command java ClassName , for our program, we will use java HelloWorld, if everything is alright, you shall see the program output on the screen. Notice that some lines in the program begin with //, these are called comments, compiler does not read comments, so whatever your write in them it will not affect the functionality of your program, the notations /* and */ declare the beginning and ending of a block of comments, so we call them multi-line comments.
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 04
successful compilation
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 05
Practical-2
Aim: Generate an editor screen containing menus, dialog boxes etc using Java.
import static java.awt.event.InputEvent.CTRL_DOWN_MASK; import java.awt.*; import javax.swing.*; import javax.swing.KeyStroke; import java.awt.event.KeyEvent; import java.awt.Dimension; import java.io.*; import java.awt.event.*; import javax.swing.text.*; class Menug extends JFrame { ScrollPane scroll; JMenuBar mb; JMenu file,edit,format,view,help; JMenuItem n,o,s,sa,ps,p,e,u,cut,copy,paste; JMenuItem del,f,fn,r,gt,sal,tym,wr,fo,vh,an; JCheckBoxMenuItem sb; JTextArea tf; private boolean changed = false; String currentFile = "Untitled"; private JFileChooser dialog = new JFileChooser(System.getProperty("user.dir")); Menug() { scroll = new ScrollPane();
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 06
mb=new JMenuBar(); //menu file=new JMenu("File"); file.setMnemonic('F');//shortcut edit=new JMenu("Edit"); edit.setMnemonic('E');//shortcut format=new JMenu("Format"); format.setMnemonic('O');//shortcut view=new JMenu("View"); view.setMnemonic('V');//shortcut help=new JMenu("Help"); help.setMnemonic('H');//shortcut //menuitem n=new JMenuItem("New"); o=new JMenuItem("Open"); s=new JMenuItem("Save"); sa=new JMenuItem("Save as"); ps=new JMenuItem("Page Setup"); p=new JMenuItem("Print"); e=new JMenuItem("Exit"); u=new JMenuItem("Undo"); cut=new JMenuItem("Cut"); copy=new JMenuItem("Copy"); paste=new JMenuItem("Paste"); del=new JMenuItem("Delete"); f=new JMenuItem("Find"); fn=new JMenuItem("Find next"); r=new JMenuItem("Replace"); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 07
gt=new JMenuItem("Go to"); sal=new JMenuItem("Select all"); tym=new JMenuItem("Time/Date"); wr=new JMenuItem("Word wrap"); fo=new JMenuItem("Font"); sb=new JCheckBoxMenuItem("Status bar"); vh=new JMenuItem("Help topics"); an=new JMenuItem("About Notepad"); tf=new JTextArea(100,100); } void demo() { Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); int X=(int)d.getWidth(); int Y=(int)d.getHeight(); setLocation(X/250,Y/200); setSize(X,Y); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setJMenuBar(mb); //File mb.add(file); n.addActionListener(new NewFrame()); file.add(n); o.addActionListener(new ActionListener(){ Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 08
if(dialog.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) { readInFile(dialog.getSelectedFile().getAbsolutePath()); } sa.setEnabled(true); } }); file.add(o); s.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { if(!currentFile.equals("Untitled")) saveFile(currentFile); else saveFileAs(); } }); s.setEnabled(false); file.add(s); sa.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { saveFileAs(); } }); sa.setEnabled(false); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 09
file.add(sa); file.addSeparator(); file.add(ps); file.add(p); file.addSeparator(); e.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { saveOld(); System.exit(0); } }); file.add(e); //Edit mb.add(edit); edit.add(u); edit.addSeparator(); edit.add(cut); cut.setEnabled(false); edit.add(copy); copy.setEnabled(false); edit.add(paste); paste.setEnabled(false); edit.add(del); del.setEnabled(false); edit.addSeparator(); edit.add(f); edit.add(fn); edit.add(r); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 010
edit.add(gt); edit.addSeparator(); edit.add(sal); edit.add(tym); //Format mb.add(format); format.add(wr); format.add(fo); //View mb.add(view); view.add(sb); //Help mb.add(help); help.add(vh); help.add(an); //SHORTCUTS n.setAccelerator(KeyStroke.getKeyStroke('N', CTRL_DOWN_MASK)); o.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK)); s.setAccelerator(KeyStroke.getKeyStroke('S', CTRL_DOWN_MASK)); p.setAccelerator(KeyStroke.getKeyStroke('P', CTRL_DOWN_MASK)); u.setAccelerator(KeyStroke.getKeyStroke('Z', CTRL_DOWN_MASK)); cut.setAccelerator(KeyStroke.getKeyStroke('X', CTRL_DOWN_MASK)); copy.setAccelerator(KeyStroke.getKeyStroke('C', CTRL_DOWN_MASK)); paste.setAccelerator(KeyStroke.getKeyStroke('V', CTRL_DOWN_MASK)); f.setAccelerator(KeyStroke.getKeyStroke('F', CTRL_DOWN_MASK)); r.setAccelerator(KeyStroke.getKeyStroke('H', CTRL_DOWN_MASK)); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 011
gt.setAccelerator(KeyStroke.getKeyStroke('G', CTRL_DOWN_MASK)); sal.setAccelerator(KeyStroke.getKeyStroke('A', CTRL_DOWN_MASK)); tf.addKeyListener(k1); scroll.add(tf); add(scroll); setVisible(true); } //ActionMap m = tf.getActionMap(); //Action cut = m.get(DefaultEditorKit.cutAction); //Action copy = m.get(DefaultEditorKit.copyAction); //Action paste = m.get(DefaultEditorKit.pasteAction); class NewFrame implements ActionListener { public void actionPerformed(ActionEvent ae) { Menug nmg=new Menug(); nmg.demo(); } } private KeyListener k1 = new KeyAdapter() { public void keyPressed(KeyEvent e) { changed = true; s.setEnabled(true); sa.setEnabled(true); } }; private void saveOld() { if(changed) {
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 012
if(JOptionPane.showConfirmDialog(this, "Would you like to save "+ currentFile +" ?","Save",JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION) saveFile(currentFile); } } private void readInFile(String fileName) { try { FileReader r = new FileReader(fileName); tf.read(r,null); r.close(); currentFile = fileName; setTitle(currentFile); changed = false; } catch(IOException e) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(this,"Editor can't find the file called "+fileName); } } private void saveFile(String fileName) { try { FileWriter w = new FileWriter(fileName); tf.write(w); w.close(); currentFile = fileName; setTitle(currentFile); changed = false; s.setEnabled(false); }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 013
catch(IOException e) { } } private void saveFileAs() { if(dialog.showSaveDialog(null)==JFileChooser.APPROVE_OPTION) saveFile(dialog.getSelectedFile().getAbsolutePath()); } } class MenugGUI { public static void main(String [] args) { Menug n=new Menug(); n.demo(); } }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 014
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 015
Practical-3
Aim: Create an applet with a text field and three buttons. When you press each button, make
some different text appear in the text field. Add a check box to the applet created, capture the event and insert different text in the text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.*; public class AppletDemo1 extends Applet { JPanel p=new JPanel(); JTextField tf=new JTextField(20); JButton bt1=new JButton("Button1"); JButton bt2=new JButton("Button2"); JButton bt3=new JButton("Button3"); JCheckBox ch=new JCheckBox("DONE"); String s="hello"; public void init() { System.out.println("INIT-->"); } public void start() { setLayout(null); tf.setBounds(30,0,100,25); add(tf); bt1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 016
}); bt1.setBounds(30,30,100,25); add(bt1); bt2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { tf.setText("BUTTON2"); } }); bt2.setBounds(30,60,100,25); add(bt2); bt3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { tf.setText("BUTTON3"); } }); bt3.setBounds(30,90,100,25); add(bt3); ch.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { tf.setText("DONE"); } }); ch.setBounds(30,120,100,50); add(ch); setResizable(false); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 017
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 018
Practical-4
AIM: Create an applet with a button and a text field. Write a handleEvent( ) so that if the
button has the focus, characters typed into it will appear in the text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.*; public class AppletDemo2 extends Applet { JTextField tf=new JTextField(20); JButton bt=new JButton("Button"); public void init() { System.out.println("INIT-->"); } public void start() { setLayout(new GridBagLayout()); GridBagConstraints gc=new GridBagConstraints(); gc.insets=new Insets(10,0,0,0); gc.gridx=0; gc.gridy=0; add(tf,gc); bt.addFocusListener(new FocusListener(){ public void focusGained(FocusEvent fe) { tf.setText("Button"); } Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 019
}); gc.gridx=1; gc.gridy=0; add(bt,gc); System.out.println("START-->"); } public void stop() { System.out.println("STOP-->"); } public void destroy() { System.out.println("DESTROY-->"); } }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 020
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 021
Practical-5
AIM: Create your own java bean called VALVE that contains two properties: a Boolean called
on and an integer called level. Create a manifest file, use jar to package your bean then load it into the beanbox or into your own beans enabled program builder tool. package Beans; public class Valve { private boolean on=true; private int level=5; public boolean isOn(){ return on; } public void setOn(boolean on){ this.on = on; } public int getLevel(){ return level; } public void setLevel(int level){ this.level=level; } }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 022
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 023
Practical-6
AIM: Develop a servlet that gets invoked when a form on a Web page in HTML is submitted.
Create a cookie object and enter/display value for that Cookie. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MyServlet extends HttpServlet { ServletConfig con; public void init(ServletConfig con) throws ServletException{ this.con=con; } public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { HttpSession session = req.getSession(true); res.setContentType("text/html"); PrintWriter out = res.getWriter(); String id=req.getParameter("user"); String e=req.getParameter("email"); Cookie c = new Cookie(id,e); res.addCookie(c); out.println("<html><body>"); out.println("<h4>Cokie Added</h4>"); out.println("</html></body>"); } public void destroy(){} } /*Showcookies.java*/ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ShowCokies extends HttpServlet { ServletConfig con; public void init(ServletConfig con) throws ServletException{ this.con=con; }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 024
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { HttpSession session = req.getSession(true); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><body>"); out.println("<h1>Cokies:</h1>"); Cookie cget[] = req.getCookies(); for(int i=0;i<cget.length;i++){ out.print("<h3>Name:"+cget[i].getName()+"</h3>"); out.println("<h3>Value:"+cget[i].getValue()+"</h3>"); } out.println("</html></body>"); } public void destroy(){} }
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 025
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 026
Practical-7
AIM: Using JAVA develop a front end for a contact management program using a flat file
database. DB needs to be distributed or centralized. /*contect.java*/ /*Using JAVA develop a front end for a contact management program using a flat file database. DB needs to be distributed or centralized.*/ import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.sql.*; class contact extends JFrame { JPanel p,bp; JTextField namet,pht; JLabel name,addr,ph,im; JTextArea addrt; JButton save,del,search; JTable tab; JScrollPane sp; Connection conn2; ResultSet rs; public contact() { super("CONTACT MANAGEMENT"); p=new JPanel(); bp=new JPanel(); im=new ImageIcon("C:/Users/DELL/Pictures/tinepic/2811720967_3b8da95ce9.jpg")); name=new JLabel("NAME"); JLabel(new
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 027
addr=new JLabel("ADDRESS"); ph=new JLabel("PHONE_No."); namet=new JTextField(30); namet.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED,2)); pht=new JTextField(30); pht.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED,2)); addrt=new JTextArea(5,35); addrt.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED,2)); addrt.setWrapStyleWord(true); addrt.setLineWrap(true); save=new JButton("SAVE"); del=new JButton("DELETE"); search=new JButton("SEARCH"); tab=new JTable(); sp=new JScrollPane(tab);
} public void launch() { Toolkit tk = Toolkit.getDefaultToolkit(); Dimension d = tk.getScreenSize(); int X=(int)d.getWidth(); int Y=(int)d.getHeight(); setLocation(X/100,Y/100); setSize(X,Y); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBackground(Color.WHITE); String [] ColumnNames={"NAME","ADDRESS","PHONE_No"}; Object [][] data=new Object[30][3]; Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 028
tab.setModel(new javax.swing.table.DefaultTableModel(data,ColumnNames));
setLayout(new GridLayout(4,1)); add(im); p.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED,5)); p.setLayout(new GridBagLayout()); GridBagConstraints gc=new GridBagConstraints(); gc.insets=new Insets(10,0,0,0); gc.gridx=0; gc.gridy=0; p.add(name,gc); gc.gridx=1; gc.gridy=0; p.add(namet,gc); gc.gridx=0; gc.gridy=1; p.add(ph,gc); gc.gridx=1; gc.gridy=1; p.add(pht,gc); gc.gridx=0; gc.gridy=2; p.add(addr,gc); gc.gridx=1; gc.gridy=2; p.add(addrt,gc); add(p); add(sp); bp.setLayout(new FlowLayout()); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 029
save.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent me) { try{ save.setBackground(Color.GREEN); Management r=new Management(); Connection conn=r.createcon(); prepare(conn); } catch(Exception e){System.out.println(e);} } }); bp.add(save); bp.add(del); search.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent me) { search.setBackground(Color.GREEN); createtable(); } });
bp.add(search); add(bp); setVisible(true); } public void prepare(Connection conn) Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 030
{ try{ String s="Insert into contactmgmt(Phno,CName,Addr) values(?,?,?)"; PreparedStatement p=conn.prepareStatement(s); p.setString(1,pht.getText()); p.setString(2,namet.getText()); p.setString(3,addrt.getText()); p.executeUpdate(); conn.commit(); JOptionPane.showMessageDialog(null,"UPDATED"); }catch(Exception e){System.out.println(e);} } public static void main(String...s) { contact c=new contact(); c.launch(); } public void createtable() { try { conn2.setAutoCommit(false); Statement stmt=conn2.createStatement(); String s="Select * from contactmgmt"; rs=stmt.executeQuery(s); int i=0; while(rs.next()) { tab.setValueAt(rs.getString(1),i,0); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 031
} catch(Exception e) { System.out.println(e); } } }
/*Management.java*/ import java.sql.*; class Management { private ResultSet rs; private Connection conn; private Statement stmt; private Object m; public Connection createcon() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 032
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 033
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 034
Practical-8
AIM: Java Networking Java Sockets and RMI.
/*chartclient*/ import javax.swing.*; import java.awt.*; import java.net.*; import java.awt.event.*; import java.io.*; public class Chatclient extends javax.swing.JFrame implements Runnable { JPanel cp; JLabel pic; JLabel me,h; Font fnt; JTextArea ta; JTextField ct; JButton send; Socket s1; public Chatclient() { super("CHAT client"); cp=new JPanel(); pic=newJLabel(new ImageIcon("C:/Users/DELL/Pictures/tinepic/BRI100D.jpg")); me=new JLabel("ME"); fnt=new Font("Viner Hand ITC",Font.BOLD,25); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 035
ta=new JTextArea(10,30); ta.setBorder(javax.swing.BorderFactory.createLineBorder(Color.RED,3)); ct=new JTextField(30); send=new JButton("SEND"); h=new JLabel("CHATTING"); try { s1=new Socket("127.0.0.1",5433); }catch(Exception e){System.out.println(e);} } public void launch() { Toolkit tk = Toolkit.getDefaultToolkit(); Dimension dm = tk.getScreenSize(); int X=(int)dm.getWidth(); int Y=(int)dm.getHeight(); setLocation(X/4,Y/250); setSize(X-800,Y-300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setLayout(new GridBagLayout()); GridBagConstraints gc=new GridBagConstraints(); gc.insets=new Insets(10,0,0,0); h.setFont(fnt); h.setForeground(Color.GREEN); gc.gridx=0; gc.gridy=0; add(h,gc);
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 036
gc.gridx=0; gc.gridy=1; add(ta,gc); cp.add(me); cp.add(ct); send.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { try{ String sn=ct.getText(); OutputStream os=s1.getOutputStream(); DataOutputStream dos=new DataOutputStream(os); dos.writeUTF(sn); ta.append("\n"+"CLIENT:"+sn); }catch(Exception e){System.out.println(e);} ct.setText(""); } }); cp.add(send); gc.gridx=0; gc.gridy=2; add(cp,gc); //add(pic); setVisible(true); } public void run() { try{ while(true) Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 037
}catch(Exception e){System.out.println(e);} } public static void main(String args[]) { Chatclient c=new Chatclient(); Thread t=new Thread(c); t.start(); c.launch(); } }
/*chart server*/ import javax.swing.*; import java.awt.*; import java.net.*; import java.awt.event.*; import java.io.*; public class Chatserver extends javax.swing.JFrame implements Runnable { JPanel sp; JLabel pic; JLabel me,h; Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 038
Font fnt; JTextArea ta; JTextField st; JButton send; ServerSocket s; Socket s1; JScrollPane p; public Chatserver() { super("CHAT SERVER"); sp=new JPanel(); p=new JScrollPane(); pic=new ImageIcon("C:/Users/DELL/Pictures/tinepic/BRI100D.jpg")); me=new JLabel("ME"); fnt=new Font("Viner Hand ITC",Font.BOLD,25); ta=new JTextArea(10,30); ta.setBorder(javax.swing.BorderFactory.createLineBorder(Color.GREEN,3)); st=new JTextField(30); send=new JButton("SEND"); h=new JLabel("CHATTING"); try { s=new ServerSocket(5433); s1=s.accept(); }catch(Exception e){System.out.println(e);} } public void launch() { Toolkit tk = Toolkit.getDefaultToolkit(); Name Roll No. Submitted to:JLabel(new
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 039
Dimension dm = tk.getScreenSize(); int X=(int)dm.getWidth(); int Y=(int)dm.getHeight(); setLocation(X/4,Y/250); setSize(X-800,Y-300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); //add(pic); setLayout(new GridBagLayout()); GridBagConstraints gc=new GridBagConstraints(); gc.insets=new Insets(10,0,0,0); h.setFont(fnt); h.setForeground(Color.RED); gc.gridx=0; gc.gridy=0; add(h,gc); gc.gridx=0; gc.gridy=1; add(ta,gc); sp.add(me); sp.add(st); send.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { try{ String sn=st.getText(); OutputStream os=s1.getOutputStream(); DataOutputStream dos=new DataOutputStream(os); dos.writeUTF(sn); ta.append("\n"+"SERVER:"+sn); Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 040
OUTPUT:
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 041
Practical-9
AIM: Programming under development tool ASP.net.
Microsoft Visual Studio 2005 and ASP.NET 2.0 represent a major release for Microsoft. If you have previous experience with Visual Studio products, you will see the differences immediately when you attempt to create your first Web site. Even if you are new to Visual Studio 2005 and ASP.NET 2.0, you will be able to immediately take advantage of the productivity enhancements. Looking at the ASP.NET Page Structure When an ASP.NET Web page is created, it must have an .aspx extension. The typical Web page is composed of three sections: page directives, code, and page layout. These sections are defined as follows: Page Directives This section is used to set up the environment, specifying how the page should be processed. For example, this is where you can import namespaces and load assemblies. Code This section contains code to handle events from the page or its controls. Code can be placed in a <script> tag. By default, script blocks contain client-side code but they may be designated as being server-side code by including the runat="server" attribute in the <script> tag. As a side note, code can also be contained in attached files, called codebehind files. All page code is compiled prior to execution. In addition, all pages can be precompiled to an assembly if the assembly is the only file that needs to be deployed. Page Layout The page layout is the HTML of the page, which includes the HTML body and its markup. The body can contain client and server controls as well as simple text.
A simple Web page may look like the following. <!page directives--> <%@ Page Language="VB" %> <!--script--> <script runat="server"> Private Sub SayHi(ByVal sender As Object, ByVal args As EventArgs) Response.Write("Hello " + txtName.Value) End Sub </script> <!--layout--> <html> <head> Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 042
<title>Say Hi Page</title> </head> <body> <form id="form1" runat="server"> <input runat="server" id="txtName" type="text" /> <input runat="server" id="btnSayHi" type="button" value="Say Hi" onserverclick="SayHi" /> </form> </html> </body>
Notice the runat="server" attribute that is used. For the script block, this indicates that the code will run at the server. For the form and its controls, this indicates that ASP.NET will create server-side objects to match these HTML tags. A server-side object is capable of running serverside code and raising server-side events. Creating a Web Site We mentioned that there are four ways to create a Web site. This section demonstrates the creation of each of the Web site types: file, FTP, local HTTP, and remote HTTP. The basic steps for creating a new Web site in Visual Studio 2005 are as follows: 1. In Visual Studio 2005, use the menus to request the creation of a new Web site. 2. Select the Web site type, the default programming language, and the location. 3. Click OK. Enter additional information if prompted. You can create a Web Site application by opening Visual Studio 2005 and selecting File | New | Web Site. The New Web Site dialog box appears, as shown in Figure
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 043
Working With Web Server Controls In this lab, you work with the Web server controls that are defined in this chapter. _ Exercise 1: Adding Controls to the Web Page In this exercise, you add Web page controls to the Web page that was created in the previous lab. 1. Open Visual Studio 2005 and open the Web site called LifeCycleEvents 2. Open the Default.aspx Web page in Design view. 3. Drag a Label, TextBox, Button, CheckBox, and three RadioButtons onto the Web page. Change the Text properties of these controls to match, which shows how the Web page
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 044
4. Right-click the Web page and click View Code to open the code-behind page. Notice that no additional code was added to the code-behind page. 5. Press F5 to run the Web application. 6. Try clicking the Button, CheckBox, and RadioButton controls. Observe the behavior of these controls. Notice that the Button is the only control that performs a PostBack to the Web server. Also notice that the RadioButton controls are not mutually exclusive.
7. Double-click the Button control to add the Buttons Click event handler. Add the following code to populate the Label with any text that has been typed into the TextBox. Be sure to take the security warnings seriously and use the HtmlEncode method. The code should look like the following. //C# a. protected void Button1_Click(object sender, EventArgs e) { Label1.Text = Server.HtmlEncode(TextBox1.Text);} 8. .Double-click the CheckBox control to add the CheckedChanged event handler. Add code to replace its Text property with the current date and time if the Check-Box is selected. Your code should look like the following. 'VB a. Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged If Name Roll No. Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 045
(CheckBox1.Checked) Then CheckBox1.Text = DateTime.Now.ToString() End If End Sub //C# protected void CheckBox1_CheckedChanged(object sender, EventArgs e) b. { if (CheckBox1.Checked) { CheckBox1.Text = DateTime.Now.ToString (); }} 9. To make the RadioButton controls mutually exclusive, these controls must have the same GroupName property setting, as long as the setting is not empty. Assign MyGroup to the GroupName property of all three RadioButton controls. 10. Add a single event handler for the CheckedChanged event of the three RadioButtons. You can do so by selecting all three RadioButton controls, and then clicking the lightning bolt icon in the Properties window to see the events that are available. In the CheckedChanged event, type RadioChanged and press Enter. This adds an event hander to the code-behind page. In the event handler, add code to copy the text of the selected RadioButton into the TextBox control. The event handler should look like the following. 'VB Protected Sub RadioChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles RadioButton1.CheckedChanged, _ 1. RadioButton2.CheckedChanged, _ 2. RadioButton3.CheckedChanged Dim r As RadioButton = CType(sender, RadioButton) TextBox1.Text = r.Text End Sub //C# protected void RadioChanged(object sender, EventArgs e) { RadioButton r = (RadioButton)sender; TextBox1.Text = r.Text; } 11. Press F5 to run the Web application. The Web page is displayed. 12. Type something into the TextBox control and click the Button control. You should see the contents of the TextBox control in the Label control. 13. Click the CheckBox several times. Notice that nothing seems to happen. Make sure that the CheckBox is selected and then click the Button. Notice that the CheckBox controls Text property now contains the current date and time. The CheckBox does not have AutoPostBack set to true.
Name
Roll No.
Submitted to:-
Advance Technologies
PRACTICAL FILE
CSE-311
GOLPURA, BARWALA
PAGE NO 046
14. Type different text into the TextBox. Click RadioButton2. Notice that nothing happens because AutoPostBack is not enabled for the RadioButton controls. Click the Button. Notice that the TextBox is updated to RadioButton2 and the Label also contains RadioButton2. This behavior is predictable because the event that caused the PostBack always follows the events that did not cause the AutoPostBack. 15. Select the CheckBox and the RadioButtons and set the AutoPostBack to true. 16. Press F5 to run the Web application. The Web page is displayed. 17. Click the CheckBox. Notice that this control performs a PostBack, and the date and time are updated when the CheckBox is selected. 18. Click each of the RadioButton controls. Notice that these controls perform a Post-Back and the TextBox is updated to show the RadioButton that was clicked.
Name
Roll No.
Submitted to:-