SHRIMATI INDIRA GANDHI COLLEGE

Size: px
Start display at page:

Download "SHRIMATI INDIRA GANDHI COLLEGE"

Transcription

1 SHRIMATI INDIRA GANDHI COLLEGE (Nationally Accredited at A Grade (3rd Cycle) By NAAC) Tiruchirappalli 2. INSTRUCTION MATERIAL DEPARTMENT OF COMPUTER APPLICATION 1

2 CONTENT S.NO SUBJECT CODE PAGE.NO 1 DT MATERIAL LAB (FOR III SEMESTER) P16MCA18P 3 2 PROGRAMMING IN ASP RCCS10CA SOFTWARE ENGINEERING MBECA1:1/ COMPUTER GRAPHICS AND MULTIMEDIA RCCS10CA MYSQL PRACTICAL RCCS10CA5P PHP RCCS10CA

3 SEM III - P16MCA18P DISTRIBUTED TECHNOLOGIES LAB Syllabus 1. RMI Invocation of server side methods. 2. Servlets Returning Information received from the client. 3. JSP use of scriptlet. 4. JSP use of java beans. 5. EJB Session Bean. 6. EJB Entity Bean. 7. ASP.NET Server & Client side controls. 8. ASP.NET and ADO.NET use of disconnected data object. 9. ASP.NET: Databind Controls. 10. DOM usage on the server side. 11. AJAX: Dynamic client server interaction example. 1. RMI INVOCATION OF SERVER SIDE METHODS Aim : To Develop an RMI (Remote Method Invocation) to invoke server side methods. Algorithm: Step 1: Define the Remote Interface Step 2: Define the class and implement the Remote Interface methods in this class Step 3: Define the Server side class Step 4: Define the Client side class Step 5: Compile all the four source (java) files Step 6: Generate the stub skeleton class by command Step 7: Start the RMI Remote Registry Step8: Run the server side class Step 9: Run the client side class (at another JVM) Program: Calculator.java import java.rmi.remote; import java.rmi.remoteexception; 3

4 public interface Calculator extends Remote { public long add(long a,long b)throws RemoteException; } CalculatorClient.java import java.rmi.naming; public class CalculatorClient { public static void main(string[] args) { try { Calculator c=(calculator)naming.lookup("prgms"); System.out.println("Addition:"+c.add(10,15)); } catch(exception e) { System.out.println(e); } } } CalculatorImpl.java import java.rmi.remoteexception; import java.rmi.server.unicastremoteobject; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { protected CalculatorImpl()throws RemoteException { super(); } public long add(long a,long b)throws RemoteException { return a+b; } } 4

5 CalculatorServer.java import java.rmi.naming; public class CalculatorServer { CalculatorServer() { Try { Calculator c=new CalculatorImpl(); Naming.rebind("prgms",c); } catch(exception e) { e.printstacktrace(); } } public static void main(string[] args) { new CalculatorServer(); } } Output: 5

6 6

7 Result: Calculator program using RMI has been implemented successfully. SERVLETS - RETURNING INFORMATION RECEIVED FROM THE CLIENT Aim: To develop a servlet for returning information from the clienr. Algorithm: Step 1: Start the Netbeans Step 2: Choose File New Project Java Web Web Application Next Finish Step 3: In Index.jsp, create HTML form tags by clicking window menu Palette HTML Forms Step 4: Choose Form Action Servlet Ok Step 5: Drag Text Input and give name for the text box as Uname Step 6: Drag Button and press Go Ok. Step 7: To create the servlet window, right click on web application new servlet Step 8: In servlet Window, give appropriate html tags to print result from the client.jsp file. Step 9: Save and Debug the project Step 10: Run the Project. 7

8 Program: index.jsp <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> <form action="servlet"> <input type="text" name="uname" /> <input type="submit" value="go" /> </form> </body> </html> servlet.java import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import = "servlet", urlpatterns = {"/servlet"}) public class servlet extends HttpServlet { protected void processrequest(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); try { String name=request.getparameter("uname"); out.println("<html>"); out.println("<head>"); out.println("<title> servlet servlet1</title>"); out.println("<head>"); out.println("<body>"); out.println("<h2>my NAME IS:"+ name +"</h2>"); 8

9 out.println("</body>"); out.println("<html>"); } finally { out.close(); } } Output: Result: Thus the Servlet has successfully received the information from the client. 9

10 2. JSP USE OF SCRIPTLET Aim: To develop a JSP program using Scriplet Algorithm: Step 1: Start the Program Step 2: Open Netbeans Step 3: Choose File New Project Java Web Web Application Next Finish Step 4: In Index.jsp, create HTML form tags by clicking window menu Palette HTML Forms Step 5: Choose Form Action Servlet Ok Step 6: Drag Text Input and give name for the text box as Uname Step 7: Drag Button and press Go Ok. Step 8: Open another.jsp file and name it as welcome.jsp Step 9: Receive a value from index.jsp file in welcome.jsp fle Step 10: Save and Debug both the files Step 11: Run the project Program: INDEX.JSP <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> <form action="welcome.jsp"> <br/><br/> <input type="text" name="uname" /><br/> <input type="submit" value="go" /><br/> </form> </body> </html> WELCOME.JSP <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> 10

11 <% String name=request.getparameter("uname"); out.print("welcome "+name); %> </body> </html> Output: Result: Thus a JSP program for the use of scriplet has been successfully created. 11

12 4.JSP USE OF JAVA BEANS Aim: To develop a Javabean for returning information received from the client Algorithm: Step 1: Start the Program Step 2: Open Netbeans Step 3: Choose File New Project Java Web Web Application Next Finish Step 4: In Index.jsp, create HTML form tags by clicking window menu Palette HTML Forms Step 5: Choose name of the Java bean program. Step 6: Drag Text Input and give name for the text box as user Step 7: Drag another Text Input and give name for the text box as pass & drag a Submit Button Ok Step 8: To create a validation bean file, right click on the web application new java class Step 9: Using validation bean file, give setuser,getuser,setpass and getpass application Step 10: Using the validate function, check whether the submitted Username and password are equal to the given user name and password. Step 11: If both are equal then print valid else Invalid Step 12: To create Receive.jsp file, right click on web application new.jsp Step 13: In Receive.jsp file JSP forms, give usebeanid, setproperty and getproperty Step 14: Save and Debug the Project Step 15: Run the Project Program: index.jsp <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> <form action="receive.jsp"> Enter user name<input type="text" name="user" /><br/> 12

13 Enter user password<input type="password" name="pass" /><br/> <input type="submit" value="submit" /> </form> </body> </html> receive.jsp <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> <jsp:usebean id="snr" class="pack.validatebean"/><br/> enter user name<jsp:setproperty name ="snr" property="user"/><br/> enter user password<jsp:setproperty name="snr" property="pass"/><br/> you entered user name as <jsp:getproperty name="snr"property="user"/><br/> you entered user password as <jsp:getproperty name="snr"property="pass"/><br/> <%=snr.validate("name","java")%>user<br/> </body> </html> validatebean.java package pack; public class ValidateBean { String user; String pass; public ValidateBean(){} public void setuser(string user) { this.user=user; } public String getuser() { return user; } public void setpass(string pass) 13

14 { this.pass=pass; } public String getpass() { return pass; } public String Validate(String s1,string s2) { if(s1.equals(user)&& s2.equals(pass)) return "VALID"; else return "INVALID"; } } 14

15 15

16 Result: Thus the java bean Program has been successfully created. 16

17 5.EJB SESSION BEAN Aim: To create EJB stateless program to calculate employee bonus. Algorithm: Step 1: Start the program Step 2: Create a client page using jsp for entering employee name, employee department and basic pay Step 3: Create a server page using servlet to retrieve or read the content. Step 4: Create a session bean with one business logic method for calculating employee bonus Step 5: In servlet, create an object for session bean class and invoke the business logic method using object (or)session bean. Step 6: Display employee details and bonus amount Step 7: Stop the Execution Program: EJB SESSION BEAN index.jsp <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>jsp Page</title> </head> <body> <center>employee Bonus Calculation <form name="form1" action="bonus" method="post"> <h1>bonus Calculation using EJB session Bean</h1> </center> <center>enter Employee Name:<input type="text" name="ename" value="/> </br></br> Enter Employee Basic Pay:<input type="text" name="bp" value=" " /></br></br> dept<select name="edept" size="3"> <option value="finance">financier.dept</option> <option value="cashier">cashier.dept</option> <option value="production">production.dept</option> </select></br></br> <input type="submit" value="submit" /> <input type="reset" value="reset" /> </form> </body> 17

18 </html> bonus.java import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.ejb.*; import = "bonus", urlpatterns = {"/bonus"}) public class bonus extends HttpServlet { private String mysession b1; protected void processrequest(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype("text/html;charset=utf-8"); PrintWriter out = response.getwriter(); try { double bp; String empname=request.getparameter("ename"); bp=double.parsedouble(request.getparameter("bp")); String empdept=request.getparameter("dept"); out.println("<html>"); out.println("<head>"); out.println("<title>servlet Bonus</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> Bonus Calculation</h1>"); out.println("<h2>employee Name"+empname+"</h2>"); out.println("<h2>employee Dept"+empdept+"</h2>"); out.println("<h2>employee Basic pay"+bp+"</h2>"); out.println("<h2>employee Bonus Amount" +b1.bonus(bp)+"</h2>"); out.println("</body>"); out.println("</html>"); 18

19 } } finally { out.close(); } mysessionbean.java package ejb; import javax.ejb.stateless; public class mysession { public double bonus(double bp) { double rate; if(bp<10000) { rate=0.02; } else if(bp>10000 && bp<=30000) { rate=0.03; } else { rate=0.04; } return(bp*rate); } } Output: 19

20 20

21 21

22 Result: Thus the bonus calculation using bean program is successfully completed and the output is verified. 22

23 6.ASP.NET SERVER & CLIENT SIDE CONTROLS Aim: To Create a established in Security Features in a Simple website with five pages. Algorithm: Step1: Start the Program. Step2: Create new website with five pages namely LoginPage, NewUserPage, ChangePassword page, ForgotPassword page and DisplayPage. Step3: In LoginPage, drag Login Control and set necessary properties for NewUser, Forgot Password, Change Password and Destination pageurl property. Step4: In NewUser page, drag create user Wizard control and set necessary properties. Step5: In ChangePassword Page, drag ChangePassword Wizard and set necessary properties. Step6: In forgot Password page, drag password recovery Wizard and set necessary properties. Step7: In Display page, design a welcome page and drag login name control and Hyper Link Control. Step 8: Create another page for Logout. Step9: Run the program in a Browser. Program: SOURCE CODE: LOGIN.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " 23

24 <html xmlns=" <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div><br /> <br /> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Names="Century Schoolbook" Font-Size="X-Large" Text="WEB USING LOGIN SECURITY CONTROLS"></asp:Label> <br /> <br /> <br /> <asp:login ID="Login1" runat="server" BackColor="#EFF3FB" BorderColor="#B5C7DE" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" CreateUserText="Create User ID" CreateUserUrl="~/login create.aspx" DestinationPageUrl="~/Message.aspx" Font-Names="Courier New" Font-Size="Large" ForeColor="#333333" HelpPageText="Forgott pwd" HelpPageUrl="~/forgotpwd.aspx" PasswordRecoveryText="Change your pwd" PasswordRecoveryUrl="~/change password.aspx"> <TextBoxStyle Font-Size="0.8em" /> <LoginButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" /> <InstructionTextStyle Font-Italic="True" ForeColor="Black" /> <TitleTextStyle BackColor="#507CD1" Font-Bold="True" Font-Size="0.9em" ForeColor="White" /> </asp:login> <br /> </div> </form></body></html> Login create.aspx Page Language="C#" AutoEventWireup="true" CodeFile="login create.aspx.cs" Inherits="login_create" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> 24

25 </head> <body> <form id="form1" runat="server"> <div> <br /> <asp:createuserwizard ID="CreateUserWizard1" runat="server" BackColor="#EFF3FB" BorderColor="#B5C7DE" BorderStyle="Solid" BorderWidth="1px" ContinueDestinationPageUrl="~/Login.aspx" Font-Names="Courier New" Font-Size="Large"> <MailDefinition BodyFileName="~/log.txt"> </MailDefinition> <SideBarStyle BackColor="#507CD1" Font-Size="0.9em" VerticalAlign="Top" /> <SideBarButtonStyle BackColor="#507CD1" Font-Names="Verdana ForeColor="White" /> <ContinueButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284E98" /> <NavigationButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284E98" /> <HeaderStyle BackColor="#284E98" BorderColor="#EFF3FB" BorderStyle="Solid" BorderWidth="2px" Font-Bold="True" Font-Size="0.9em" ForeColor="White" HorizontalAlign="Center" /> <CreateUserButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" ForeColor="#284E98" /> <TitleTextStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <StepStyle Font-Size="0.8em" /> <WizardSteps> <asp:createuserwizardstep runat="server" /> <asp:completewizardstep runat="server" /> </WizardSteps> </asp:createuserwizard> <br /> <br /> <br /> </div> </form></body></html> Change password.aspx Page Language="C#" AutoEventWireup="true" CodeFile="change password.aspx.cs" Inherits="change_password" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> </head> <body> 25

26 <form id="form1" runat="server"> <div> <br /> <br /> <br /> <asp:changepassword ID="ChangePassword1" runat="server" BackColor="#EFF3FB" BorderColor="#B5C7DE" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" ContinueDestinationPageUrl="~/Login.aspx" Font-Names="Courier New" Font-Size="Large"> <CancelButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" /> <PasswordHintStyle Font-Italic="True" ForeColor="#507CD1" /> <ContinueButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" /> <ChangePasswordButtonStyle BackColor="White"BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" /> <MailDefinition BodyFileName="~/log.txt"> </MailDefinition> <TitleTextStyle BackColor="#507CD1" Font-Bold="True" Font-Size="0.9em" ForeColor="White" /> <TextBoxStyle Font-Size="0.8em" /> <InstructionTextStyle Font-Italic="True" ForeColor="Black" /> </asp:changepassword> <br /> <br /> </div> </form></body></html> Forgottpassword.aspx Page Language="C#" AutoEventWireup="true" CodeFile="forgotpwd.aspx.cs" Inherits="forgotpwd" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> </head><body> <form id="form1" runat="server"> <div><br /> <br /> <asp:passwordrecovery ID="PasswordRecovery1" runat="server" BackColor="#EFF3FB" BorderColor="#B5C7DE" BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font- Names="Courier New" Font-Size="Large"> 26

27 <MailDefinition BodyFileName="~/log.txt"> </MailDefinition> <InstructionTextStyle Font-Italic="True" ForeColor="Black" /> <SuccessTextStyle Font-Bold="True" ForeColor="#507CD1" /> <TextBoxStyle Font-Size="0.8em" /> <TitleTextStyle BackColor="#507CD1" Font-Bold="True" Font-Size="0.9em" ForeColor="White" /> <SubmitButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" /> </asp:passwordrecovery> <br /> <br /> <br /> <br /> </div> </form></body></html> Message.aspx Page Language="C#" AutoEventWireup="true" CodeFile="Message.aspx.cs" Inherits="Message" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <br /> <br /> <br /> <asp:image ID="Image1" runat="server" Height="126px" ImageUrl="~/lotus.jpg" Width="197px" /> <br /> <br /> <br /> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Names="Bookman Old Style" Font-Size="X-Large" ForeColor="#FF0066" Text="WELCOME TO WEB SECURITY CONTROL"></asp:Label> <br /> <asp:hyperlink ID="HyperLink1" runat="server" Font-Bold="True" Font-Size="Large" NavigateUrl="~/Login.aspx">HOME</asp:HyperLink> <br /> <br /> <br /> 27

28 <br /> </div> </form></body></html> Web configure <?xml version="1.0"?> <!-- Note: As an alternative to hand editing this file you can use the web admin tool to configure settings for your application. Use the Website->Asp.Net Configuration option in Visual Studio. A full list of settings and comments can be found in machine.config.comments usually located in \Windows\Microsoft.Net\Framework\v2.x\Config --> <configuration> <configsections> <sectiongroup name="system.web.extensions" type="system.web.configuration.systemwebextensionssectiongroup, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectiongroup name="scripting" type="system.web.configuration.scriptingsectiongroup, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptresourcehandler" type="system.web.configuration.scriptingscriptresourcehandlersection, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirepermission="false" allowdefinition="machinetoapplication"/> <sectiongroup name="webservices" type="system.web.configuration.scriptingwebservicessectiongroup, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="jsonserialization" type="system.web.configuration.scriptingjsonserializationsection, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirepermission="false" allowdefinition="everywhere" /> <section name="profileservice" type="system.web.configuration.scriptingprofileservicesection, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirepermission="false" allowdefinition="machinetoapplication" /> <section name="authenticationservice" type="system.web.configuration.scriptingauthenticationservicesection, 28

29 System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirepermission="false" allowdefinition="machinetoapplication" /> <section name="roleservice" type="system.web.configuration.scriptingroleservicesection, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirepermission="false" allowdefinition="machinetoapplication" /> </sectiongroup> </sectiongroup> </sectiongroup> </configsections> <system.net> <mailsettings> <smtp deliverymethod="pickupdirectoryfromiis" </smtp> </mailsettings> </system.net> <appsettings/> <connectionstrings/> <system.web> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <compilation debug="false"> <assemblies> <add assembly="system.core, Version= , Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="system.web.extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="system.data.datasetextensions, Version= , Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="system.xml.linq, Version= , Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <!-- 29

30 The <authentication> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --> <authentication mode="forms" /> <!-- The <customerrors> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace. <customerrors mode="remoteonly" defaultredirect="genericerrorpage.htm"> <error statuscode="403" redirect="noaccess.htm" /> <error statuscode="404" redirect="filenotfound.htm" /> </customerrors> --> <pages> <controls> <add tagprefix="asp" namespace="system.web.ui" assembly="system.web.extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagprefix="asp" namespace="system.web.ui.webcontrols" assembly="system.web.extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <httphandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="system.web.script.services.scripthandlerfactory, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_appservice.axd" validate="false" type="system.web.script.services.scripthandlerfactory, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="get,head" path="scriptresource.axd" type="system.web.handlers.scriptresourcehandler, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> </httphandlers> <httpmodules> 30

31 <add name="scriptmodule" type="system.web.handlers.scriptmodule, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpmodules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warninglevel="4" type="microsoft.csharp.csharpcodeprovider, System, Version= , Culture=neutral, PublicKeyToken=b77a5c561934e089"> <provideroption name="compilerversion" value="v3.5"/> <provideroption name="warnaserror" value="false"/> </compiler> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warninglevel="4" type="microsoft.visualbasic.vbcodeprovider, System, Version= , Culture=neutral, PublicKeyToken=b77a5c561934e089"> <provideroption name="compilerversion" value="v3.5"/> <provideroption name="optioninfer" value="true"/> <provideroption name="warnaserror" value="false"/> </compiler> </compilers> </system.codedom> <!-- The system.webserver section is required for running ASP.NET AJAX under Internet Information Services 7.0. It is not necessary for previous version of IIS. --> <system.webserver> <validation validateintegratedmodeconfiguration="false"/> <modules> <remove name="scriptmodule" /> <add name="scriptmodule" precondition="managedhandler" type="system.web.handlers.scriptmodule, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="webservicehandlerfactory-integrated"/> <remove name="scripthandlerfactory" /> <remove name="scripthandlerfactoryappservices" /> 31

32 <remove name="scriptresource" /> <add name="scripthandlerfactory" verb="*" path="*.asmx" precondition="integratedmode" type="system.web.script.services.scripthandlerfactory, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="scripthandlerfactoryappservices" verb="*" path="*_appservice.axd" precondition="integratedmode" type="system.web.script.services.scripthandlerfactory, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="scriptresource" precondition="integratedmode" verb="get,head" path="scriptresource.axd" type="system.web.handlers.scriptresourcehandler, System.Web.Extensions, Version= , Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </handlers> </system.webserver> <runtime> <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentassembly> <assemblyidentity name="system.web.extensions" publickeytoken="31bf3856ad364e35"/> <bindingredirect oldversion=" " newversion=" "/> </dependentassembly> <dependentassembly> <assemblyidentity name="system.web.extensions.design" publickeytoken="31bf3856ad364e35"/> <bindingredirect oldversion=" " newversion=" "/> </dependentassembly> </assemblybinding> </runtime> </configuration> Log.txt user name=" ", password="" OUTPUT 32

33 33

34 34

35 35

36 36

37 37

38 38

39 Result: Thus the program has been Successfully Completed and the Output is verified. 39

40 7.ASP.NET AND ADO.NET USE OF DISCONNECTED DATA OBJECT Aim : To create a project to Insert, Update and Delete few records using Disconnected Data access. Algorithm : Step 1: Start the Program. Step 2: Create a new website using Microsoft visual studio Step 3: In menu bar select the website add SqlDatabase. Step 4: In a SqlDatabase create table and necessary fields and save the table. Step 5: In design page, design a form for updating table in the SqlDatabase. Step 6: Drag the gridviewcontrol and implement click event for display. Step 7: Create click event method for Insert, Update and Delete button to Insert, update and delete a row. Step 8: By clicking display button we can view records that are already in the database. Step 9: By clicking update button record can be updated in to database. ` Step 10: By clicking delete button the details can be removed from the database. Program: DISCONNECTED DATA BASE USING ASP.NET Source Code: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> <style type="text/css"> #form1 { height: 47px; } 40

41 </style> </head> <body> <form id="form1" runat="server"> <div> <asp:gridview ID="GridView1" runat="server" Style="z-index: 100; left: 112px; position: absolute; top: 120px"> </asp:gridview> <asp:label ID="Label2" runat="server" Font-Bold="True" Style="z-index: 102; left: 224px; position: absolute; top: 384px" Text="STNAME"></asp:Label> <asp:label ID="Label3" runat="server" Font-Bold="True" Style="z-index: 103; left: 224px; position: absolute; top: 416px" Text="PERCENTAGE"></asp:Label> <asp:textbox ID="TextBox1" runat="server" Style="z-index: 104; left: 344px; position: absolute; top: 344px"></asp:TextBox> <asp:textbox ID="TextBox2" runat="server" Style="z-index: 105; left: 344px; position: absolute; top: 384px"></asp:TextBox> <asp:textbox ID="TextBox3" runat="server" Style="z-index: 106; left: 352px; position: absolute; top: 424px"></asp:TextBox> <asp:button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click" Style="z-index: 107; left: 507px; position: absolute; top: 330px" Text="INSERT" /> <asp:button ID="Button2" runat="server" Font-Bold="True" OnClick="Button2_Click" Style="z-index: 108; left: 209px; position: absolute; top: 471px; height: 27px; width: 63px;" Text="VIEW" /> <asp:button ID="Button3" runat="server" Font-Bold="True" OnClick="Button3_Click" Style="z-index: 109; left: 323px; position: absolute; top: 474px" Text="CLEAR" /> <asp:button ID="Button4" runat="server" Font-Bold="True" OnClick="Button4_Click" Style="z-index: 110; left: 504px; position: absolute; top: 378px" Text="UPDATE" /> <asp:button ID="Button5" runat="server" Font-Bold="True" OnClick="Button5_Click" Style="z-index: 112; left: 511px; position: absolute; top: 430px" Text="DELETE" /> </div> <asp:label ID="Label1" runat="server" Font-Bold="True" Style="z-index: 101; left: 224px; position: absolute; top: 344px" Text="STNO"></asp:Label> <asp:label ID="Label4" runat="server" Font-Bold="True" Font-Names="Bookman Old Style" Font-Size="Large" Text="DISCONNECTED DATA BASE USING ASP.NET"></asp:Label> </form> </body> </html> 41

42 View Code: using System; using System.Data; using System.Configuration; 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; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection con; SqlCommand cmd; SqlDataAdapter da; DataSet ds; protected void Page_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename= DataDirectory \\Database.mdf;Integrated Security=True;User Instance=True"); } protected void Button1_Click(object sender, EventArgs e) { con.open(); cmd=new SqlCommand("insert into student values ("+Convert.ToInt32 (TextBox1.Text)+", '"+TextBox2.Text+"',"+Convert.ToInt32(TextBox3.Text)+")",con); cmd.executenonquery(); Response.Write("record inserted"); con.close(); } protected void Button2_Click(object sender, EventArgs e) { con.open(); da = new SqlDataAdapter("select * from student", con); ds = new DataSet(); da.fill(ds, "student"); 42

43 } GridView1.DataSource = ds; GridView1.DataBind(); con.close(); protected void Button3_Click(object sender, EventArgs e) { TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; } protected void Button5_Click(object sender, EventArgs e) { con.open(); cmd = new SqlCommand("delete from student where stno=" + Convert.ToInt32(TextBox1.Text) + "", con); cmd.executenonquery(); Response.Write("record delete"); da = new SqlDataAdapter("select * from student", con); ds = new DataSet(); da.fill(ds, "student"); GridView1.DataSource = ds; GridView1.DataBind(); con.close(); } protected void Button4_Click(object sender, EventArgs e) { con.open(); cmd = new SqlCommand("update student set stname='" + TextBox2.Text + "',percentage=" + Convert.ToInt32(TextBox3.Text) + " where stno=" + Convert.ToInt32(TextBox1.Text) + "", con); cmd.executenonquery(); Response.Write("record update"); da = new SqlDataAdapter("select * from student", con); ds = new DataSet(); da.fill(ds, "student"); 43

44 } } GridView1.DataSource = ds; GridView1.DataBind(); con.close(); 44

45 45

46 46

47 47

48 48

49 Result : Thus the program has been successfully completed and the output is verified. 49

50 8.ASP.NET: DATABIND CONTROLS Aim: To create a project to view the records using Grid view,details view and Form view controls. Algorithm: Step 1: Start the Program. Step 2: Create a new website using Microsoft visual studio Step 3: Choose the design page and drag the Grid view control. Step 4: Select the Grid view control choose the new data source. Step 5: In datasourcewindow,selectsqldatasource and choose existing database files. Step 6: Choose the design page and drag the Detailsview control Step 7: Repeat steps 4 and 5. Step 8: Next drag Formview control in a Design page. Step 9: Repeat step 4 and 5 to choose SqlDataSource. Step 10: Run the program in a browser. Step 11: Stop the program. Program: Data Bind using ASP.Net <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <br /> <br /> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Names="Bookman Old Style" Font-Size="Medium" Text="DATA BIND CONTROL"></asp:Label> <br /> <br /> 50

51 <asp:label ID="Label2" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="X-Large" Text="Grid View"></asp:Label> <br /> <br /> <asp:gridview ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="#CCFFCC" BorderStyle="Dashed" DataKeyNames="ID" DataSourceID="SqlDataSource1" EnableSortingAndPagingCallbacks="True" Font-Bold="True" Font-Size="Large" ForeColor="Black" HorizontalAlign="Center" PageSize="3" ShowFooter="True"> <PagerSettings Mode="NextPreviousFirstLast" /> <Columns> <asp:boundfield DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" /> <asp:boundfield DataField="ENO" HeaderText="ENO" SortExpression="ENO" /> <asp:boundfield DataField="ENAME" HeaderText="ENAME" SortExpression="ENAME" /> <asp:boundfield DataField="DESIGNATION" HeaderText="DESIGNATION" SortExpression="DESIGNATION" /> <asp:boundfield DataField="SALARY" HeaderText="SALARY" SortExpression="SALARY" /> </Columns> </asp:gridview> <asp:sqldatasource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:db3ConnectionString %>" ProviderName="<%$ ConnectionStrings:db3ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [db3]"></asp:sqldatasource> <br /> <br /> <br /> <asp:label ID="Label3" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="X-Large" Text="Details View"></asp:Label> <br /> <br /> <asp:detailsview ID="DetailsView1" runat="server" AllowPaging="True" AutoGenerateRows="False" BackColor="White" BackImageUrl="~/index44.png" BorderColor="Black" BorderStyle="Double" CaptionAlign="Top" CellSpacing="1" DataKeyNames="ID" DataSourceID="SqlDataSource1" Font-Bold="True" Font-Names="Arial" ForeColor="#003300" Height="50px" HorizontalAlign="Center" Width="125px"> <CommandRowStyle BorderColor="#3399FF" /> <Fields> <asp:boundfield DataField="ID" HeaderText="ID" InsertVisible="False" 51

52 ReadOnly="True" SortExpression="ID" /> <asp:boundfield DataField="ENO" HeaderText="ENO" SortExpression="ENO" /> <asp:boundfield DataField="ENAME" HeaderText="ENAME" SortExpression="ENAME" /> <asp:boundfield DataField="DESIGNATION" HeaderText="DESIGNATION" SortExpression="DESIGNATION" /> <asp:boundfield DataField="SALARY" HeaderText="SALARY" SortExpression="SALARY" /> </Fields> <EditRowStyle BorderColor="#33CCFF" /> </asp:detailsview> <br /> <br /> <asp:label ID="Label4" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="X-Large" Text="Data List"></asp:Label> <br /> <br /> <asp:datalist ID="DataList1" runat="server" CaptionAlign="Top" DataKeyField="ID" DataSourceID="SqlDataSource1" GridLines="Both" HorizontalAlign="Center" RepeatColumns="5" RepeatDirection="Horizontal" Width="660px"> <ItemStyle BackColor="White" /> <ItemTemplate> ID: <asp:label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /> <br /> ENO: <asp:label ID="ENOLabel" runat="server" Text='<%# Eval("ENO") %>' /> <br /> ENAME: <asp:label ID="ENAMELabel" runat="server" Text='<%# Eval("ENAME") %>' /> <br /> DESIGNATION: <asp:label ID="DESIGNATIONLabel" runat="server" Text='<%# Eval("DESIGNATION") %>' /> <br /> SALARY: <asp:label ID="SALARYLabel" runat="server" Text='<%# Eval("SALARY") %>' /> <br /> <br /> </ItemTemplate> </asp:datalist> <br /> <br /> <asp:label ID="Label5" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="X-Large" Text="Form View"></asp:Label> 52

53 <asp:formview ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="ID" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Size="Large" HorizontalAlign="Center"> <EditItemTemplate> ID: <asp:label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' /> <br /> ENO: <asp:textbox ID="ENOTextBox" runat="server" Text='<%# Bind("ENO") %>' /><br / ENAME: <asp:textbox ID="ENAMETextBox" runat="server" Text='<%# Bind("ENAME") %>' /> <br /> DESIGNATION: <asp:textbox ID="DESIGNATIONTextBox" runat="server" Text='<%# Bind("DESIGNATION") %>' /> <br /> SALARY: <asp:textbox ID="SALARYTextBox" runat="server" Text='<%# Bind("SALARY") %>' /> <br /> <asp:linkbutton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" /> <asp:linkbutton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </EditItemTemplate> <InsertItemTemplate> ENO: <asp:textbox ID="ENOTextBox" runat="server" Text='<%# Bind("ENO") %>' /> <br /> ENAME: <asp:textbox ID="ENAMETextBox" runat="server" Text='<%# Bind("ENAME") %>' /> <br /> DESIGNATION: <asp:textbox ID="DESIGNATIONTextBox" runat="server" Text='<%# Bind("DESIGNATION") %>' /> <br /> SALARY: <asp:textbox ID="SALARYTextBox" runat="server" Text='<%# Bind("SALARY") %>' /> <br /> <asp:linkbutton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" /> <asp:linkbutton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </InsertItemTemplate> <ItemTemplate> ID: <asp:label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /> <br /> 53

54 ENO: <asp:label ID="ENOLabel" runat="server" Text='<%# Bind("ENO") %>' /> <br /> ENAME: <asp:label ID="ENAMELabel" runat="server" Text='<%# Bind("ENAME") %>' /> <br /> DESIGNATION:<asp:Label ID="DESIGNATIONLabel" runat="server" Text='<%# Bind("DESIGNATION") %>' /> <br /> SALARY: <asp:label ID="SALARYLabel" runat="server" Text='<%# Bind("SALARY") %>' /> <br /> </ItemTemplate> <EditRowStyle BackColor="#FFCC99" /> </asp:formview> <br /> <br /> <br /> <br /> <br /> <br /> </div> </form> </body> </html> Output: 54

55 55

56 56

57 Result: Thus the program has been successfully completed and the output is verified. 57

58 9.DOM USAGE ON THE SERVER SIDE Aim: To develop a program to understand the usage of Document Object Model Algorithm: Step 1: Start the html program embedded with Java Script Step 2: Create a paragraph id to display the content Step 3: Call the function named myfunction on button s Onclick Method Step 4: Open the script tag Step 5: Define the function myfunction Step 6: Give a new content in this function using document.write Step 7: Close the script tag Step 8: Stop the execution Program: <html> <body> <p id="demo">click the button to replace this document with new content</p> <button onclick="myfunction()">tryit</button> <script> function myfunction() { document.open("text/html","replace"); document.write("<h2>learning about the javascript dom is interesting!</h2>"); document.close(); } </script> </body> Output: </html> 58

59 Result: Thus the DOM usage program has been run successfully. 59

60 10.AJAX: DYNAMIC CLIENT SERVER INTERACTION EXAMPLE Aim: To create an Ajax Program for dynamic client server interaction Algorithm: Step 1: Start the program Step 2: Create an object to use in the Ajax program and check the type of browser, choose the script language Step 3: In the body section, using html tags, create a button to call the sayhello function Step 4: Divide the screen using div tag to get the message Step 5: Using sayhello function, call the server side.php file Step 6: Update the result using the update page function Step 7: Stop the process Program: ajax.html <html> <head> <title>simple Ajax Example </title> <script language="javascript"> function postrequest(strurl) { var xmlhttp; if(window.xmlhttprequest) { var xmlhttp=new XMLHttpRequest(); } else if(window.activexobject) { var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open('post',strurl, true); xmlhttp.setrequestheader('content-type','application/x-www-form-urlencoded'); xmlhttp.onreadystatechange=function( ) { if(xmlhttp.readystate==4) { 60

61 updatepage(xmlhttp.responsetext); } } xmlhttp.send(strurl); } function updatepage(str) { document.getelementbyid("result").innerhtml="<font color='blue' size='5'>" + str + "</font>";; } function SayHello( ) { var url="simple.html"; postrequest(url); } </script> </head> <body> <h1 align="center"><font color="#000080">simple Ajax Example</font></h1> <p align="center"><font color="#000080">press "Say Hello Button"</font></p> <form name="f1"> <p align="center"><font color="#000080"> <input value="sayhello" type="button" onclick='javascript:sayhello( )' name="showdate"></font></p> <div id="result" align="center">fetched message will appear here</div> </form> <div id=result></div> </body> </html> Simple.html <html> <head> <title>my Title</title> </head> <body> <h2>hello World</h2> </body> 61

62 </html> OUTPUT ********* Result: Thus the Ajax program for dynamic client server interaction has been created successfully. 62

63 11.CRYSTAL REPORT Aim : To develop a project generate the crystal report form an existing database. Algorithm : Step 1: Start the Program. Step 2: Create a webpage by using Microsoft visual studio Step 3: In menu bar, select the website andadd a new crystal report. Step 4: In report window select the database expert from database fields. Step 5: Create a new connection and invoke a database from Microsoft Access Step 6: In a design page of a crystal reports drag those fields from the database. Step 7: In a formula field create a formula and add it intothe crystal reports. Step 8: Next insert a chart and add to display. Step 9: Choose the design page and drag the crystal report viewer control. Step 10: Select the crystal report viewer and choose new datasource. Step 11: In data source window select crystal report file Step 12:Run the program in a browser. Step 13: Stop the program. Program: SOURCE CODE: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="crystaldecisions.web, Version= , Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="crystaldecisions.web" tagprefix="cr" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> 63

64 <br /> <br /> CRYSTAL REPORT<br /> <br /> <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" Height="1039px" ReportSourceID="CrystalReportSource1" Width="901px" /> <CR:CrystalReportSource ID="CrystalReportSource1" runat="server"> <Report FileName="CrystalReport.rpt"> </Report> </CR:CrystalReportSource> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </div> </form> </body> </html> Output: 64

65 DESIGN PAGE 65

66 66

67 67

68 68

69 OUTPUT 69

70 Result : Thus the program has been successfully completed and the output is verified. 70

71 12.ADROTATOR CONTROL Aim : To create a webpage by making use of Adrotator control. Algorithm : Step 1: Start the Program. Step 2: Create a new website by using Microsoft visual studio Step 3: Choose the design page and drag the adrotator control. Step 4: Create a new xml file and write xml code for Advertisement. Step 5: Select the Adrotator Control create new DataSource. Step 6: InDataSource window select xml DataSource choose xml code file. Step 7: Write a Source code Response.AddHeader( refresh, 3 ) in page_load(); Step 9: Run the program in a browser. Step 10: Stop the program. Program: XMLFILE.xml <?xml version="1.0" encoding="utf-8"?> <Advertisements xmlns=" <Ad xmlns=""> <ImageUrl>file:///D:\Manisha Msc\adrotatoroutput\ery.jpg</ImageUrl> <AlternateText>Red Rose</AlternateText> <Impressions>20</Impressions> </Ad> <Ad xmlns=""> <ImageUrl>file:///D:\Manisha Msc\adrotatoroutput\index.jpg</ImageUrl> <AlternateText>Yellow Baby</AlternateText> <Impressions>20</Impressions> </Ad> <Ad xmlns=""> <ImageUrl>file:///D:\Manisha Msc\adrotatoroutput\lkjpg.jpg</ImageUrl> <AlternateText>Cute ABaby</AlternateText> <Impressions>20</Impressions> </Ad> </Advertisements> SOURCE CODING <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> 71

72 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:adrotator ID="AdRotator1" runat="server" DataSourceID="XmlDataSource1" /> <asp:xmldatasource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile.xml"></asp:XmlDataSource> </div> </form> </body> </html> VIEW CODING 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; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.AddHeader("Refresh", "3"); } } 72

73 Design Page: Output: 73

74 Result: Thus the program has been Successfully Completed and the Output is verified. 74

75 13. MULTIVIEW CONTROL Aim : To Create a Webpage involving Multiview control. Algorithm : Step 1: Start the Program. Step 2: Create a new Website in asp.net by using Microsoft visual Studio Step 3 : Choose the Design Page, drag the Multiview control. Step 4 : Select the property window, set ActiveViewIndex as 0. Step 5 : Drag the view control into the multiview create a Design In a view by using Standard Control. Step 6 : Drag the button into View 1 and set command name as NextView. Step 7 : Repeat the Step5 and Drag a button for PrevView and NextView Purpose. Step 8 : Repeat the Step5 to step7 for your design and create an Event Multiview1_ActiveViewChanged for multiview. Step 9 : Run the Program in a Browser. Step 10 : Stop the Program. Program: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:multiview ID="MultiView1" runat="server" ActiveViewIndex="0"> <br /> <asp:view ID="View1" runat="server"> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="FLOWER"></asp:Label> 75

76 <asp:textbox ID="TextBox1" runat="server"></asp:textbox><br /> </asp:view> <br /> <asp:button id="button1" runat="server" CommandName="NextView" Text="NEXT" /> <br /> <br /> <asp:view ID="View2" runat="server"> <br /> <asp:label ID="Label2" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="FRUIT"></asp:Label> <asp:textbox ID="TextBox2" runat="server"></asp:textbox><br /> <br /> <asp:label ID="Label3" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="VEGTABLE"></asp:Label> <asp:textbox ID="TextBox3" runat="server"></asp:textbox><br /> <br /> asp:button ID="Button2" runat="server" CommandName="PrevView" Text="PREVIOUS" /> <asp:button ID="Button3" runat="server" CommandName="NextView" Text="NEXT" /></asp:view> <asp:view ID="View3" runat="server"> <asp:label ID="Label4" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="FLOWER"></asp:Label> asp:label ID="Label7" runat="server" Text="Label"></asp:Label> 76

77 <asp:imagebutton ID="ImageButton1" runat="server" Height="50px" ImageUrl="~/Water lilies.jpg" Width="50px" /><br /> <br /> <asp:label ID="Label5" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" txt="fruit"></asp:label> <asp:label ID="Label8" runat="server" Text="Label"></asp:Label> <asp:imagebutton ID="ImageButton2" runat="server" Height="50px" ImageUrl="~/f1.jpg" OnClick="ImageButton2_Click" Width="50px" /><br /> <asp:label ID="Label6" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="VEGTABLE"></asp:Label> <asp:label ID="Label9" runat="server" Text="Label"></asp:Label> ;<asp:imagebutton ID="ImageButton3" runat="server" Height="50px" ImageUrl="~/v1.jpg" Width="50px" /><br /> </asp:view> </asp:multiview></div> </form> </body> </html> View code using System; using System.Data; using System.Configuration; 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; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { 77

78 } } protected void ImageButton2_Click(object sender, ImageClickEventArgs e) { Label7.Text = TextBox1.Text; Label8.Text = TextBox2.Text; Label9.Text = TextBox3.Text; } Output: 78

79 79

80 Result : Thus the Program has been Successfully Completed and the Output is verified. 80

81 14. WIZARD CONTROL Aim : To Create a Webpage involving Wizard Control. Algorithm : Step 1 : Start the Program. Step 2 : Create a new website in asp.net using Microsoft Visual Studio Step 3 : Choose the Design Page, Drag the Wizard Control. Step 4 : Select the properties window, choose wizard collection Add multiple wizard stepsand set properties. Step 5 : Create a Design for each wizardsteps and implement event Method for finish button. Step 6 : Run the Program in a Browser. Step 7 : Stop the Program. Program: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <br /> <strong><em><span style="font-size: 16pt"> WIZARD CONTROL<br /> </span></em></strong> <br /> </div> <asp:wizard ID="Wizard1" runat="server" ActiveStepIndex="2" Height="1px" OnFinishButtonClick="Wizard1_FinishButtonClick" Width="405px"> 81

82 <WizardSteps> <asp:wizardstep runat="server" Title="rate "> <asp:label ID="Label5" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="Larger" Font-Underline="True" ForeColor="#004000" Text="SIGC JEWELLARY"></asp:Label> <br /> <asp:label ID="Label1" runat="server" BorderColor="Black" BorderStyle="None" Font-Bold="True" Font-Italic="True" Font-Size="Large" Font-Underline="True" ForeColor="Black" Height="5px" Text="GOLD "></asp:label> <br /> <asp:image ID="Image1" runat="server" Height="50px" ImageUrl="~/29TVM_CHUNGATH1_ g.jpg" Width="50px" /> <asp:label ID="Label3" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="True" ForeColor="Magenta" Text="STARTING RATE RS:10,000"></asp:Label> <br /> <asp:label ID="Label2" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="True" ForeColor="Black" Text="SILVER"></asp:Label> <asp:image ID="Image2" runat="server" Height="50px" ImageUrl="~/silverjewellery-250x250.jpg" Width="50px" /> <asp:label ID="Label4" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="True" ForeColor="Fuchsia" Text="STARTING RATE RS:600"></asp:Label> </asp:wizardstep> <asp:wizardstep runat="server" Title="discount for gold"> 82

83 <asp:label ID="Label6" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="True" ForeColor="#C00000" Text="SIGC JEWELL DISCOUNT REPORT"></asp:Label> <asp:label ID="Label7" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="True" ForeColor="DarkViolet" Text="FOR GOLD:10%"></asp:Label> <asp:image ID="Image3" runat="server" Height="50px" ImageUrl="~/B6KneASCIAE0Mwf.png" Width="50px" /> <br /> <asp:label ID="Label8" runat="server" Font-Bold="True" Font-Italic="True" Font- Underline="True" ForeColor="Black" Text="ENTER THE GOLD RATE:" Font- Size="Large"></asp:Label> <asp:textbox ID="TextBox1" runat="server"></asp:textbo <br /> <br /> <asp:button ID="Button1" runat="server" BorderColor="Black" Font-Bold="True" Font-Italic="True" Font-Size="Large" Font-Underline="True" ForeColor="Black" Text="DISCOUNT RATE" OnClick="Button1_Click" /> <br /> <asp:label ID="Label11" runat="server" Font-Bold="True" Font- Italic="True" Font-Size="Large" ForeColor="Red" Text="SEE THE DISCOUNT RATE:"></asp:Label> <asp:textbox ID="TextBox3" runat="server"></asp:textbox> <br /> </asp:wizardstep> <asp:wizardstep runat="server" Title="discount for silver"> 83

84 <asp:label ID="Label12" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="Large" Font-Underline="True" ForeColor="Red" Text="SIGC JEWELL DISCOUNT REPORT"></asp:Label> <br /> <br /> <asp:label ID="Label9" runat="server" Font-Bold="True" Font-Italic="True" Font- Size="Large" Font-Underline="False" ForeColor="DarkViolet" Text="FOR SILVER:5%"></asp:Label> <br /> <br /> <asp:image ID="Image4" runat="server" Height="50px" ImageUrl="~/silverjewellery-wallpapers6.jpg" Width="50px" /> <br /> <asp:label ID="Label10" runat="server" Font-Bold="True" Font-Italic="True" Font-Underline="True" ForeColor="Black" Text="ENTER THE SILVER RATE:" Font- Size="Large"></asp:Label> <br /> <br /> & <asp:textbox ID="TextBox2" runat="server"></asp:textbox> <br /> <br /> <br /> <asp:button ID="Button2" runat="server" BorderColor="Black" Font-Bold="True" Font-Italic="True" Font-Size="Large" Font-Underline="True" ForeColor="Black" OnClick="Button2_Click" Text="DISCOUNT RATE" /> <br /> <br /> <br /> 84

85 <asp:label ID="Label13" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="Large" Font-Underline="True" ForeColor="Red" Text="SEE THE DISCOUNT RATE:"></asp:Label> &nbsp <asp:textbox ID="TextBox4" runat="server"></asp:textbox> <br /> <br /> </asp:wizardstep> </WizardSteps> </asp:wizard> </form> </body> </html> VIEW CODE: using System; using System.Data; using System.Configuration; 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; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { } protected void TextBox1_TextChanged(object sender, EventArgs e) { 85

86 } protected void Button1_Click(object sender, EventArgs e) { double p; p = Convert.ToDouble(TextBox1.Text); double per = 100; double a = p*(10/per); TextBox3.Text = "" + a; } protected void Button2_Click(object sender, EventArgs e) { double s; s = Convert.ToDouble(TextBox2.Text); double per = 100; double b = s* (5 / per); TextBox4.Text = "" + b; } } Output: 86

87 87

88 Result : Thus the program has been Successfully Completed and the Output is Verified. 88

89 15. IMAGEMAP CONTROL Aim: To Create a WebPage by using Image Control with involving the Hotspots. Algorithm: Step1: Start the program. Step2: Create a new website using Microsoft visual Studio Step3: Create a new webform and drag aimagemap control using property. Step4: In Imagemapcontrol,select the properties window setimageurl,width,height and hotspot. Step5: In hotspot mode property add multiple hotspot and setnecessary properties for that hotspot. Step6: Run the program in a browser. Step7: Stop the program. Program: Default.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:imagemap ID="ImageMap1" runat="server" Height="500px" ImageUrl="~/ai-3dplant-7.jpg" Style="z-index: 100; left: 304px; position: absolute; top: 0px" Width="500px"> <asp:circlehotspot AlternateText="betroom" HotSpotMode="Navigate" NavigateUrl="~/images (15).jpg" Radius="50" X="175" Y="180" /> <asp:circlehotspot AlternateText="bathromm" HotSpotMode="Navigate" NavigateUrl="~/download (10).jpg" Radius="50" X="175" Y="480" /> 89

90 <asp:circlehotspot AlternateText="living" HotSpotMode="Navigate" NavigateUrl="~/Default4.aspx" Radius="50" X="290" Y="460" /> <asp:circlehotspot AlternateText="dining" HotSpotMode="Navigate" NavigateUrl="~/Default5.aspx" Radius="50" X="320" Y="180" /> </asp:imagemap> </div> </form> </body> </html> Default2.aspx Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:image ID="Image1" runat="server" Height="232px" ImageUrl="~/images (15).jpg" Style="z-index: 100; left: 368px; position: absolute; top: 120px" Width="280px" /> <asp:button ID="Button1" runat="server" PostBackUrl="~/Default.aspx" Style="z-index: 102; left: 472px; position: absolute; top: 408px" Text="bedroom" /> </div> </form> </body> </html> Default5.aspx 90

91 Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:image ID="Image1" runat="server" ImageUrl="~/images (19).jpg" Style="z-index: 100; left: 392px; position: absolute; top: 72px" /> <asp:button ID="Button1" runat="server" Style="z-index: 102; left: 520px; position: absolute; top: 312px" Text="dining" PostBackUrl="~/Default.aspx" /> </div> </form> </body> </html> Output: 91

92 92

93 Result: Thus the program has been successfully completed and the output is verified. 93

94 16. MASTERPAGE CREATION Aim: To create a website by making use of Masterpage. Algorithm: Step1: Start the program. Step2: Create a new website by using Microsoft visual studio Step3: In Menubar, select the website and add new MasterPage. Step4: In Source Page, create three division tags and for header the content place holder and footer. Step5: Design a header and footer by using html controls. Step6: In website add content place the new design page will appear. Step7: In that page, create a design only in content place holder using various controls. Step8: Repeat Step6 and create different webpages as needed. Step9: Run the program in a browser. Step10: Stop the program. Program: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>untitled Page</title> <asp:contentplaceholder id="head" runat="server"> 94

95 </asp:contentplaceholder> </head> <body> <form id="form1" runat="server"> <asp:image ID="Image1" runat="server" Height="126px" ImageUrl="~/Srimati+Indira+Gandhi+College+Logo_.jpg" Width="110px" /> <br /> <br /> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large" Text="SHRIMATI INDIRA GANDHI COLLEGE "></asp:label> <br /> <br /> (Nationally Accredited at "A" Grade (3rd Cycle) by NAAC)<div> <asp:contentplaceholder id="contentplaceholder1" runat="server"> <p> </p> </asp:contentplaceholder> </div> <br /> <br /> <asp:image ID="Image2" runat="server" Height="112px" ImageUrl="~/Shrimati_Indira_Gandhi_College_Chatram_Bud_Stand_Tiruchirappalli_Tamil_Na du_1.jpg" Width="120px" /> <br /> <br /> <br /> 95

96 </form> </body> </html> DEFAULT.2 Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:content> <asp:content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <p> <br /> </p> <p> <asp:hyperlink ID="HyperLink1" runat="server" NavigateUrl="~/Default3.aspx">UG</asp:HyperLink> </p> <p> <asp:hyperlink ID="HyperLink2" runat="server" NavigateUrl="~/Default4.aspx">PG</asp:HyperLink> </p> <p> <asp:hyperlink ID="HyperLink3" runat="server" NavigateUrl="~/Default5.aspx">Celebrations</asp:HyperLink> </p> </asp:content> DEFAULT.3 96

97 Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <style type="text/css">.style1 { list-style-type: square; } </style> </asp:content> <asp:content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <p> <br /> <asp:image ID="Image1" runat="server" Height="117px" ImageUrl="~/p18o9fm06a4rb2kq1fu321o1mlf5.jpg" Width="123px" /> This courses available in UG </p> <p> <asp:hyperlink ID="HyperLink2" runat="server">laboratory classes</asp:hyperlink>. </p> <ul class="style1"> <li> BCA</li> <li>b.sc(mathematics)</li> <li>b.com</li> </ul> <p> <asp:hyperlink ID="HyperLink3" runat="server" NavigateUrl="~/Default2.aspx">HOME</asp:HyperLink> </p> </asp:content> DEFAULT.4 <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> 97

98 </asp:content> <asp:content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <p> <br /> <asp:image ID="Image2" runat="server" Height="114px" ImageUrl="~/p18o9fm06a1d4mgasuhmmle1r24.jpg" Width="116px" /> The courses are available in PG.</p> <p> <asp:hyperlink ID="HyperLink2" runat="server">mca Lab and libraries are very useful for all the students</asp:hyperlink> </p> <ul> <li>mca</li> <li>m.sc(cs)</li> <li>m.sc(it)</li> </ul> <p> <asp:hyperlink ID="HyperLink3" runat="server" NavigateUrl="~/Default2.aspx">HOME</asp:HyperLink> </p> </asp:content> DEFAULT.5 Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:content> <asp:content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <p> <br /> <asp:image ID="Image3" runat="server" Height="84px" ImageUrl="~/images-03.jpg" Width="101px" /> 98

99 </p> <p> IG Fest, Inter collagiate function, Hostel Day, College day, Association Day</p> <p> <asp:hyperlink ID="HyperLink1" runat="server">every year the college will be conduct cultural festivals</asp:hyperlink> </p> <p> <asp:hyperlink ID="HyperLink2" runat="server" NavigateUrl="~/Default2.aspx">HOME</asp:HyperLink> </p> </asp:content> 99

100 100

101 101

102 Result: Thus the program has been successfully completed and the Output is verified. 102

103 17. MOBILE FORM CREATION Aim: To use State Management concept in a MobileWeb Application. Algorithm: Step1: Start the Program. Step2: Create a new website using Microsoft Visual Studio Step3: In MenuBar, select the website and add new MobileForm. Step4: Design a page for login by using Standard Control. Step5: Run the Program in a Microsoft Mobile Explorer 3.0 Step6: Stop the Program. Program: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %> <html xmlns=" > <body> <mobile:form id="form1" runat="server"> <mobile:label ID="Label5" Runat="server">MOBILE WEB APPLICATION</mobile:Label> <br /><br /><br /><mobile:label ID="Label1" Runat="server">USERNAME</mobile:Label><br /><br /><mobile:textbox ID="TextBox1" Runat="server"> </mobile:textbox><br /><mobile:label ID="Label2" Runat="server">PASSWORD</mobile:Label><br /><br /><mobile:textbox ID="TextBox2" Runat="server"> </mobile:textbox><br /><mobile:label ID="Label3" Runat="server">Label</mobile:Label><br /><br /><mobile:command ID="Command1" Runat="server" OnClick="Command1_Click">LOGIN</mobile:Command><br /><br /> <br /><mobile:link ID="Link1" Runat="server">NAVIGATE</mobile:Link><br /><br /><br /><br /><br /><br /><br /><br /></mobile:form> </body> </html> 103

104 VIEW CODING using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class Default2 : System.Web.UI.MobileControls.MobilePage { protected void Page_Load(object sender, EventArgs e) { } } protected void Command1_Click(object sender, EventArgs e) { if ((TextBox1.Text.ToLower() == "kani") && (TextBox2.Text.ToLower() == "admin")) { Session["username"] = TextBox1.Text; this.redirecttomobilepage("default3.aspx"); } else { Label3.Visible = true; Label3.Text = "{error:invalid.entry}"; TextBox1.Text = ""; TextBox2.Text = ""; } } 104

105 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Mobile; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class Default3 : System.Web.UI.MobileControls.MobilePage { protected void Page_Load(object sender, EventArgs e) { Label1.Text = "WELCOME" + Session["username"].ToString(); } } Output: 105

106 106

107 Result: Thus the program has been Successfully Completed and the Output is verified. 107

108 18. WEBSERVICE USING SQL SERVER Aim: To Develop a webservice that has an asp.net client. Algorithm: Program: Step1: Start the Program. Step2: Create a new website by using Microsoft Visual Studio Step3: In Design page, create a design for client model using standard control. Step4: In Menubar, select the website and add new Webservice class. Step5: In WebService add new WebMethod. Step6: Again, select the website and add web reference. Step7: In default.aspx.cs file, create an object for Web service class and invoke method inwebservice. Step8: Run the Program in a Browser. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div style="color: black; font-style: italic"> <br /> 108

109 <br /> <br /> <strong><span style="font-size: 16pt; text-decoration: underline">webservices USING SQL SERVER</span></strong><br /> <br /> </div> <asp:gridview ID="GridView1" runat="server" Height="220px" Width="243px"> </asp:gridview> </form> </body> </html> WEBSERVICES CODE: using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Data.SqlClient; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = " [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService { public WebService () { } //Uncomment the following line if using designed components //InitializeComponent(); 109

110 [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public DataSet registry() { SqlConnection con; SqlDataAdapter da; DataSet ds; con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename= DataDirectory \\Database.mdf;Integrated Security=True;User Instance=True"); da = new SqlDataAdapter("select * from mscit", con); ds = new DataSet(); da.fill(ds, "mscit"); return ds; } } VIEW CODE: using System; using System.Data; using System.Configuration; 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; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { localhost.webservice a = new localhost.webservice(); GridView1.DataSource = a.registry(); GridView1.DataBind(); } 110

111 } DESIGN PAGE: 111

112 112

113 OUTPUT: 113

114 Result: Thus the Program has been Successfully Completed and the Output Verified. 114

115 PROGRAMMING IN ASP(RCCS10CA4) CORE COURSE VII- PROGRAMMING IN ASP Unit I Introduction to ASP Active Server Pages Model ASP File the process of serving an Active Server Page Using Scripting Languages Setting the Primary Scripting Language Including other files Understanding objects. Unit II Understanding components Working with users working with HTML forms retrieving form data using text boxes and text areas. Unit III Cookies working with cookies applications of cookies addressing the drawbacks of using cookies using cookies in ASP applications. Working with connections and data sources creating connections with OLEdb and ODBC connecting to Microsoft SQL server connecting to a Microsoft access database. Unit IV About the connection object executing a SQL statement with the connection object understanding session and connection pooling working with record sets retrieving a record set record set cursor and locking types understanding ADO cursors paging through a record set. Unit V Working with the command object creating stored procedures executing stored procedures with the connection object executing stored procedures with the command object retrieving parameter information. Text Books : 1. Practical ASP Ivan Bayross, BPB Publications, Special Edition Using Active Server Pages ScotJohnson, Prentice Hall of India Private Limited

116 ASP UNIT-1 ASP stands for Active Server Pages ASP is a server-side scripting environment. It can be used to create and run dynamic, interactive, high performance web server applications. ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information Services IIS comes as a free component with Windows 2000 ASP File CONTAINS: An ASP file is just the same as an HTML file An ASP file can contain text, HTML, XML, and scripts Scripts in an ASP file are executed on the server An ASP file has the file extension ".asp" Script: A script is a series of sentences placed one below the other in the form of a paragraph. The syntax will be written in the syntax of the scripting language. ASP Compatibility To run IIS you must have Windows NT 4.0 or later To run PWS you must have Windows 95 or later ASP Differ from HTML ASP can do When a browser requests an HTML file, the server returns the file When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML Dynamically edit, change, or add any content of a Web page Respond to user queries or data submitted from HTML forms Access any data or databases and return the results to a browser Customize a Web page to make it more useful for individual users Provide security - since ASP code cannot be viewed from the browser Clever ASP programming can minimize the network traffic 116

117 IIS - Internet Information Server IIS is a set of Internet-based services for servers created by Microsoft for use with Microsoft Windows. IIS comes with Windows 2000, XP, Vista, and Windows 7. It is also available for Windows NT. IIS is easy to install and ideal for developing and testing web applications. PWS - Personal Web Server PWS is for older Windows system like Windows 95, 98, and NT. PWS is easy to install and can be used for developing and testing web applications including ASP. The built in functions in ASP. Five built- in objects in ASP: 1. Application 2. Request 3. Response 4. Server 5. Session Applications object in ASP: Application object: Store and retrieve information that can be shared among all users of an application. Methods: Lock,Unlock Events: ApplicationOnEnd, ApplicationOnStart Benefits of ASP The benefits of ASP ASP runs as a service of the Web server, and is optimized for multiple threads and multiple users. You can create ASP pages using whatever language you want. ASPs can also take advantage of COM and DCOM objects with minimum effort. Server-side scripts cannot be readily copied because only the result of the script is returned to the browser; users cannot view the script commands that created the page they are viewing. ASP S object model 1. Request Object 117

118 2. Response Object 3. Server Object 4. Session Object 5. Application Objects Setting the Primary Scripting Language The ASP primary scripting language is the language used to process commands inside the <% and %> delimiters. By default, the primary scripting language is VBScript an ASP file can also contain server scripts, surrounded by the delimiters <% and %>. Asp Syntax ASP technology is not a scripting language. Asp provides an environment that processes the scripts are incorporated into HTML pages Delimiters HTML tags are differentiated from text by delimiters. A delimiter is a character or sequence of character that marks the beginning or end of a unit. The delimiters are (<) and (>). The response. write command is used to write output to a browser. <!DOCTYPE html> <html> <body> <% response.write("hello World!") %> </body> </html> The example above writes "Hello World!" into the body of the document. Using VBScript in ASP You can use several scripting languages in ASP. However, the default scripting language is VBScript: <!DOCTYPE html> <html> <body> <% response.write("hello World!") %> 118

119 </body> </html> Using JavaScript in ASP To set JavaScript as the default scripting language for a particular page you must insert a language specification at the top of the page: <%@ language="javascript"%> <!DOCTYPE html> <html> <body> <% Response.Write("Hello World!") %> </body> </html> Single Expressions Any expression valid for the primary scripting language can be used within asp delimiters Example <%=Now%> The above example returns the value of the vbscript function Now to the browser Statements A statement in Vbscript (other script) is a syntactically complete unit that express one kind of action, declarartion or definition Including other files,virtual Keyword and File Keyword Including other files Server-side include directives give you a way to insert the content of another file into a file before the Web server processes it. ASP implements only the #include directive of this mechanism. To insert a file into an.asp file Syntax <!-- #include virtual file ="filename" --> The virtual and file keywords indicate the type of path you are using to include the file, and filename is the path and file name of the file you want to include. Included files do not require a special file name extension; however, it is considered good programming practice to give included files an.inc extension to distinguish them from other types of files. Using the Virtual Keyword 119

120 Use the virtual keyword to indicate a path beginning with a virtual directory. For example, if a file named Footer.inc resides in a virtual directory named /Myapp, the following line would insert the contents of Footer.inc into the file containing the line: <!-- #include virtual ="/myapp/footer.inc" --> Using the File Keyword Use the file keyword to indicate a relative path. A relative path begins with the directory that contains the including file. For example, if you have a file in the directory Myapp, and the file Header1.inc is in Myapp\Headers, the following line would insert Header1.inc in your file: <!-- #include file ="headers\header1.inc" --> Note that the path to the included file, Headers\header1.inc, is relative to the including file; if the script containing this #include statement is not in the directory /Myapp, the statement would not work. You can also use the file keyword with the syntax (..\) to include a file from a parent, or higherlevel, directory if the Enable Parent Paths option is selected in the Internet Information Services snap-in. Asp Architecture or Asp model 120

121 Understanding objects Active Server Pages include several built in objects and installable ActiveX components. The built-in asp objects provide control over the sessions and web server applications. These objects and components can be used to extend the power of asp scripts Built in objects in asp Active Server Pages consist of five built in objects. Application 121

122 Request Response Server Session An object is typically has methods, properties and collections An object s methods determine the things that one can do with the object. An object s properties can be read or set to specify the state of the object An object s collections constitute different sets of key and value pairs related to the object The Application Object The Application object is used to store and retrieve information that can be shared among all users of an application Ex Use this object to pass information between users of the website Syntax Application.method Methods Lock UnLock Description Locks the application object so that only one user at a time can modify the values. Unlocks the application object allowing other users to modify application level variables. Lock The Lock method prevents other users from modifying the variables in the Application object (used to ensure that only one client at a time can modify the Application variables). Syntax Application.Lock Example <% Application.Lock Application("visits")=Application("visits")+1 %> 122

123 This page has been visited <%=Application("visits")%> times! UnLock The Unlock method enables other users to modify the variables stored in the Application object (after it has been locked using the Lock method). Syntax Application.Unlock Example <% Application.Lock Application("visits")=Application("visits")+1 Application.Unlock %> This page has been visited <%=Application("visits")%> times! Events Events Application_OnEnd Description Occurs when all user sessions are over, and the application ends Application_OnStart Occurs before the first new session is created (when the Application object is first referenced) 123

124 Application_OnStart The Application_OnStart event occurs before the first new session is created (when the Application object is first referenced). Syntax <script language="vbscript" runat="server"> Sub Application_OnStart... End Sub </script> Application_OnEnd Event The Application_OnEnd event occurs when the application ends (when the web server stops). Syntax <script language="vbscript" runat="server"> Sub Application_OnEnd... End Sub </script> The Request Object The request object can be used to access all information sent in arequest from a browser to the server.the Request object makes available all the values that client browser passes to the server during an HTTP request. Syntax Request.collection property method (variable) 124

125 Collections Description ClientCertificate Contains all the field values stored in the client certificate Cookies Form QueryString Contains all the cookie values sent in a HTTP request Contains all the form (input) values from a form that uses the post method Contains all the variable values in a HTTP query string ServerVariables Contains all the server variable values ClientCertificate The clientcertificate collection retrieves the certification fields from the request issued by the web browser Cookies The Cookies collection is used to set or get cookie values. If the cookie does not exist, it will be created, and take the value that is specified. A cookie is often used to identify a user. Syntax Request.Cookies(cookie)[(key).attribute] Parameters Cookie-specifies the cookie whose value should be retrieved Key-Optional used to retrieve subkey values from cookie dictionaries Attribute-specifies information about the cookie itself. Example The "Response.Cookies" command is used to create a cookie or to set a cookie value: <% Response.Cookies("firstname")="Alex" %> The "Request.Cookies" command is used to get a cookie value. <% fname=request.cookies("firstname") response.write("firstname=" & fname) %> Output: 125

126 Firstname=Alex Form The Form collection is used to retrieve the values of form elements from a form that uses the POST method. Syntax Request.Form(parameter)[(index).Count] Parameter element Description Required. The name of the form element from which the collection is to retrieve values index Optional. Specifies one of multiple values for a parameter. From 1 to Request.Form(parameter).Count. Example 1 <% for i=1 to Request.Form("color").Count Response.Write(Request.Form("color")(i) & "<br>") next %> Output: Blue Green Example 2 submit.html <form action="submit.asp" method="post"> <p>first name: <input name="firstname"></p> <p>last name: <input name="lastname"></p> <p>your favorite color: <select name="color"> <option>blue</option> <option>green</option> <option>red</option> <option>yellow</option> <option>pink</option> </select> </p> 126

127 <p><input type="submit"></p> </form> The following request might be sent: firstname=john&lastname=dove&color=red submit.asp Hi, <%=Request.Form("firstname")%>. Your favorite color is <%=Request.Form("color")%>. Output: Hi, John. Your favorite color is Red. QueryString The QueryString collection is used to retrieve the variable values in the HTTP query string. The HTTP query string is specified by the values following the question mark (?), like this: <a href= "test.asp?txt=this is a query string test">link with a query string</a> Syntax Request.QueryString(variable)[(index).Count] Parameter variable index Description Required. The name of the variable in the HTTP query string to retrieve Optional. Specifies one of multiple values for a variable. From 1 to Request.QueryString(variable).Count 127

128 Example 1 The following request is sent: and names.asp contains the following script: <% for i=1 to Request.QueryString("n").Count Response.Write(Request.QueryString("n")(i) & "<br>") next %> The file names.asp would display the following: John Susan Example 2 The following string might be sent: this results in the following QUERY_STRING value: name=john&age=30 Now we can use the information in a script: Hi, <%=Request.QueryString("name")%>. Your age is <%= Request.QueryString("age")%>. Output: Hi, John. Your age is 30. ServerVariables The ServerVariables collection is used to retrieve the server variable values. Syntax Request.ServerVariables (server_variable) 128

129 Parameter Description server_variable Required. The name of the server variable to retrieve Server Variables Variable Description AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE HTTP_<HeaderName> HTTPS LOGON_USER PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT URL server uses to validate users Length of the content as sent by the client Returns the data type of the content Returns the value stored in the header HeaderName Returns ON if the request came in through secure channel or OFF if the request came in through a nonsecure channel Returns the Windows account that the user is logged into Returns extra path information as given by the client A translated version of PATH_INFO that takes the path and performs any necessary virtualto-physical mapping Returns the query information stored in the string following the question mark (?) in the HTTP request Returns the IP address of the remote host making the request Returns the IP address of the remote host making the request Returns an unmapped user-name string sent in by the user Returns the method used to make the request Returns a virtual path to the script being executed Returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs Returns the port number to which the request was sent Returns the base portion of the URL 129

130 130

131 Example 1 You can loop through all of the server variables like this: <% for each x in Request.ServerVariables response.write(x & "<br>") next %> Example 2 <html> <body> <p> <b>you are browsing this site with:</b> <%Response.Write(Request.ServerVariables("http_user_agent"))%> </p> <p> <b>your IP address is:</b> <%Response.Write(Request.ServerVariables("remote_addr"))%> </p> <p> <b>the method used to call the page:</b> <%Response.Write(Request.ServerVariables("request_method"))%> </p> <p> <b>the server's domain name:</b> <%Response.Write(Request.ServerVariables("server_name"))%> </p> <p> <b>the server's port:</b> <%Response.Write(Request.ServerVariables("server_port"))%> </p> </body> </html> The Response Object The Response object is used to send the output back to the client (browser). It includes all the 131

132 HTTP variables, cookies that will be stored on the client browser and other info about the content being ContentType sent. Syntax The ContentType property sets the HTTP content type for the response object. Response.collection property method Syntax Cookies A collection used to specify the values of cookies which will be sent back to the client browser. Collections Properties Buffer ContentType Expires ExpiresAbsolute Status Description Description Indicates whether page output is buffered Specifies the HTTP content type for the response Specifies the length of time before a page cached on a browser expires. Specifies the date and time on which a page cached on a browser expires The value of the status line returned by the server Buffer The Buffer property specifies whether to buffer the output or not. When the output is buffered, the server will hold back the response to the browser until all of the server scripts have been processed, or until the script calls the Flush or End method. Syntax response.buffer[=flag] Parameter flag Description A boolean value that specifies whether to buffer the page output or not. 132

133 response.contenttype[=contenttype] Parameter Description contenttype A string describing the content type. Example If an ASP page has no ContentType property set, the default content-type header would be: content-type:text/html <%response.contenttype="text/html"%> <%response.contenttype="image/gif"%> <%response.contenttype="image/jpeg"%> <%response.contenttype="text/plain"%> Expires The Expires property sets how long (in minutes) a page will be cached on a browser before it expires. If a user returns to the same page before it expires, the cached version is displayed. Syntax response.expires[=number] Parameter Description number ExpiresAbsolute The time in minutes before the page expires The ExpiresAbsolute property sets a date and time when a cached page on a browser will expire. If a user returns to the same page before this date/time, the cached version is displayed. Syntax response.expiresabsolute[=[date][time]] Parameter date time Description Specifies the date on which the page will expire. If this parameter is not specified, the page will expire at the specified time on the day that the script is run. Specifies the time at which the page will expire. 133

134 If this parameter is not specified, the page will expire at midnight of the specified day. Example The following code indicates that the page will expire at 4:00 PM on October 11, 2012: <%response.expiresabsolute=#october 11, :00:00#%> Status The Status property specifies the value of the status line returned by the server. Syntax response.status=statusdescription Parameter Description statusdescription A three-digit number and a description of that code, like 404 Not Found. Example <% response.status="401 Unauthorized"%> Methods AddHeader AppendToLog BinaryWrite Clear End Flush Redirect Write Description Sets the HTML header name to value A string which is added to the end of the web server log entry for this page Writes down the given information to the current HTTP output without any character set conversion. Erases any existing HTML buffered output Stops the processing of the script in the current page and sends the already created content to the client. Sends the buffered output immediately to the client. Redirects the browser to another page (URL) e.g. Response.Redirect " Writes the specified string to the web page e.g. Response.Write "Hello World!". 134

135 AddHeader The AddHeader method adds a new HTTP header and a value to the HTTP response. Syntax response.addheader name,value Parameter name value Description Required. The name of the new header variable (cannot contain underscores) Required. The initial value of the new header variable Example <%Response.AddHeader "WARNING","Error message text"%> AppendToLog The AppendToLog method adds a string to the end of server log entry for this request. You can call this method multiple times in a script. Each time it is called it will append the specified string to the log entry. Syntax response.appendtolog string Parameter string Description Required. The text to append to the log file (cannot contain any comma characters) Example <%Response.AppendToLog "My log message"%> BinaryWrite The BinaryWrite method writes data directly to the output without any character conversion. Syntax response.binarywrite data Parameter Description data Required. The binary information to be sent Example If you have an object that generates an array of bytes, you can use BinaryWrite to send the bytes 135

136 to an application: <% Set objbinarygen=server.createobject("mycomponents.binarygenerator") pic=objbinarygen.makepicture response.binarywrite pic %> Clear The Clear method clears any buffered HTML output. Syntax response.clear End The End method stops processing a script, and returns the current result. Syntax Response.End Flush The Flush method sends buffered HTML output immediately. Syntax Response.Flush Redirect The Redirect method redirects the user to a different URL. Syntax Response.Redirect URL Parameter URL Description Required. The URL that the user (browser) is redirected to Examples <% Response.Redirect " %> Write The Write method writes a specified string to the output. Syntax Response.Write variant Parameter Description 136

137 variant Required. The data to write Example 1 <% Response.Write "Hello World" %> Output: Hello World Example 2 <% name="john" Response.Write(name) %> Output: John The Server Object The server object anables to use the various utility functions on the server. Syntax Server.property method Properties ScriptTimeout Description An integer which specifies time in seconds until which the script can run after that the server aborts the script and displays an error message. ScriptTimeout The ScriptTimeout property sets or returns the maximum number of seconds a script can run before it is terminated. Syntax Server.ScriptTimeout[=NumSeconds] Parameter Description 137

138 NumSeconds The maximum number of seconds a script can run before the server terminates it. Default is 90 seconds Example 1 Set the script timeout: <% Server.ScriptTimeout=200 Methods Description %> CreateObject MapPath HTMLEncode URLEncode Creates an instance of the object ( a component, application or a scripting object ). Maps a specified path to a physical path Applies HTML encoding to a specified string Applies URL encoding rules to a specified string 138

139 CreateObject The CreateObject method creates an instance of an object. Syntax Server.CreateObject(progID) Part progid Description Required. The type of object to create Example 1 This example creates an instance of the server component MSWC.AdRotator: <% Set adrot=server.createobject("mswc.adrotator") %> HTMLEncode The HTMLEncode method applies HTML encoding to a specified string. Syntax Server.HTMLEncode(string) Parameter Description string Required. The string to encode Example The following script: <% response.write(server.htmlencode("the image tag: <img>")) %> Output: The image tag: <img> Web browser output: The image tag: <img> 139

140 MapPath The MapPath method maps a specified path to a physical path. Syntax Server.MapPath(path) Parameter path Description Required. A relative or virtual path to map to a physical path. If this parameter starts with / or \, it returns a path as if this parameter is a full virtual path. If this parameter doesn't start with / or \, it returns a path relative to the directory of the.asp file being processed Example For the example below, the file "test.asp" is located in C:\Inetpub\Wwwroot\Script. The file "test.asp" (located in C:\Inetpub\Wwwroot\Script) contains the following code: <% response.write(server.mappath("test.asp") & "<br>") response.write(server.mappath("script/test.asp") & "<br>") response.write(server.mappath("/script/test.asp") & "<br>") response.write(server.mappath("\script") & "<br>") response.write(server.mappath("/") & "<br>") response.write(server.mappath("\") & "<br>") %> Output: c:\inetpub\wwwroot\script\test.asp c:\inetpub\wwwroot\script\script\test.asp c:\inetpub\wwwroot\script\test.asp c:\inetpub\wwwroot\script c:\inetpub\wwwroot c:\inetpub\wwwroot URLEncode The URLEncode method applies URL encoding rules to a specified string. Syntax Server.URLEncode(string) 140

141 Parameter Description string Required. The string to encode Example <% response.write(server.urlencode(" %> Output: http%3a%2f%2fwww%2ew3schools%2ecom Session Object A Session object stores information about, or change settings for a user session. Syntax Session. property method 141

142 Properties SessionId TimeOut SessionID Description Returns a unique id for each user. The unique id is generated by the server Sets or returns the timeout period (in minutes) for the Session object in this application The SessionID property returns a unique id for each user. The unique id is generated by the server. Syntax Session.SessionID Example <% Response.Write(Session.SessionID) %> Output: Timeout The Timeout property sets or returns the timeout period for the Session object for this application, in minutes. If the user does not refresh or request a page within the timeout period, the session will end. Syntax Session.Timeout[=nMinutes] Parameter nminutes Description The number of minutes a session can remain idle before the server terminates it. Default is 20 minutes Example <% response.write("<p>") response.write("default Timeout is: " & Session.Timeout) response.write("</p>") Session.Timeout=30 142

143 response.write("<p>") response.write("timeout is now: " & Session.Timeout) response.write("</p>") %> Output: Default Timeout is: 20 Timeout is now: 30 Methods Abandon Description Destroys a user session Abandon The Abandon method destroys a user session. Syntax Session.Abandon Example File1.asp: <% Session("name")="Hege" Session.Abandon Response.Write(Session("name")) %> Output: Hege Events Session_OnEnd Session_Onstart Description Occurs when a session ends Occurs when a session starts 143

144 UNIT-2 Components: Components can be used in asp applications to handle common web development tasks Purpose of Msgbox Function The MsgBox function displays a message box, waits for the user to click a button, and returns a value that indicates which button the user clicked. InputBox Function The Input Box function displays a dialog box, where the user can write some input and/or click on a button. If the user clicks the OK button or presses ENTER on the keyboard, the Input Box function will return the text in the text box. If the user clicks on the Cancel button, the function will return an empty string (""). AdRotator server control ASP AdRotator Component The ASP AdRotator component creates an AdRotator object that displays a different image each time a user enters or refreshes a page. A text file includes information about the images. Syntax <% Set adrotator=server.createobject("mswc.adrotator") adrotator.getadvertisement("textfile.txt") %> ASP AdRotator Example "ads.txt" WIDTH 4 REDIRECT banners.asp * w3s.gif Free Tutorials from W3Schools 50 xmlspy.gif XML Editor from Altova 50 The lines below the asterisk in the text file above specifies the name of the images (ads) to be displayed, the hyperlink addresses, the alternate text (for the images), and the display rates (in percent). 144

145 The first line in the text file above specifies what to happen when a visitor clicks on one of the images. The redirection page (banners.asp) will receive a querystring with the URL to redirect to. 145

146 "banners.asp" <html> <body> <% Set ad=server.createobject("mswc.adrotator") <%=ad.getadvertisement("ads.txt")%> %> </body> </html> ASP AdRotator Methods Method Description Example GetAdvertisement Returns HTML that displays the advertisement in the page <% set adrot=server.createobject("mswc.adrotator") Response.Write(adrot.GetAdvertisement("ads.txt")) %> ASP AdRotator Properties Property Description Example Border Clickable TargetFrame Specifies the size of the borders around the advertisement Specifies whether the advertisement is a hyperlink Name of the frame to display the advertisement <% set adrot=server.createobject("mswc.adrotator") adrot.border="2" Response.Write(adrot.GetAdvertisement("ads.txt")) %> <% set adrot=server.createobject("mswc.adrotator") adrot.clickable=false Response.Write(adrot.GetAdvertisement("ads.txt")) %> <% set adrot=server.createobject("mswc.adrotator") adrot.targetframe="target='_blank'" Response.Write(adrot.GetAdvertisement("ads.txt")) %> Use of ASP Browser Capabilities Component: The ASP Browser Capabilities component creates a BrowserType object that determines the type, capabilities and version number of a visitor's browser. 146

147 When a browser connects to a server, a User Agent header is also sent to the server. This header contains information about the browser. The BrowserType object compares the information in the header with information in a file on the server called "Browscap.ini". If there is a match between the browser type and version number in the header and the information in the "Browscap.ini" file, the BrowserType object can be used to list the properties of the matching browser. If there is no match for the browser type and version number in the Browscap.ini file, it will set every property to "UNKNOWN". Syntax <% Set MyBrow=Server.CreateObject("MSWC.BrowserType") %> Example <!DOCTYPE html> <html> <body> <% Set MyBrow=Server.CreateObject("MSWC.BrowserType") %> <table border="0" width="100%"> <tr> <th>client OS</th><th><%=MyBrow.platform%></th> </tr><tr> <td >Web Browser</td><td ><%=MyBrow.browser%></td> </tr><tr> <td>browser version</td><td><%=mybrow.version%></td> </tr><tr> <td>frame support?</td><td><%=mybrow.frames%></td> </tr><tr> <td>table support?</td><td><%=mybrow.tables%></td> </tr><tr> <td>sound support?</td><td><%=mybrow.backgroundsounds%></td> </tr><tr> <td>cookies support?</td><td><%=mybrow.cookies%></td> </tr><tr> <td>vbscript support?</td><td><%=mybrow.vbscript%></td> </tr><tr> 147

148 <td>javascript support?</td><td><%=mybrow.javascript%></td> </tr></table> </body> </html> Output: Client OS Web Browser Browser version 5.0 Frame support? Table support? Sound support? Cookies support? VBScript support? JavaScript support? WinNT IE True True True True True True Text Stream Component: The TextStream object is used to access the contents of a text file. The following code creates a text file (c:\test.txt) and then writes some text to the file (the variable f is an instance of the TextStream object): <% dim fs,f set fs=server.createobject("scripting.filesystemobject") set f=fs.createtextfile("c:\test.txt",true) f.writeline("hello World!") f.close set f=nothing set fs=nothing %> To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object. The TextStream object's properties and methods are described below: Properties Property AtEndOfLine Description Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file, and false if not 148

149 AtEndOfStream Column Line Methods Method Close Read ReadAll ReadLine Skip SkipLine Write WriteLine WriteBlankLines Returns true if the file pointer is at the end of a TextStream file, and false if not Returns the column number of the current character position in an input stream Returns the current line number in a TextStream file Description Closes an open TextStream file Reads a specified number of characters from a TextStream file and returns the result Reads an entire TextStream file and returns the result Reads one line from a TextStream file and returns the result Skips a specified number of characters when reading a TextStream file Skips the next line when reading a TextStream file Writes a specified text to a TextStream file Writes a specified text and a new-line character to a TextStream file Writes a specified number of new-line character to a TextStream file The Content Linking Component Using this several html pages can be linked so that they can be navigated easily The Counters Component This can be used to keep track of the number of visitors to the website. The ActiveX Data Objects ADO enables the retrieval and storage of data in databases The Collaboration Data Objects The CDO enables the sending and retrieval of from within asp pages The Content Rotator Component It is used to rotate through HTML content on a page The Page counter Component This is exactly like the counter component used to track the number of visitors and to add a hit to a particular web page The permission Checker Component This can be used to display links to web pages only to those users who have permission to see Overview about WORKING WITH USER InputBox Function The Input Box function displays a dialog box, where the user can write some input and/or click on a button. If the user clicks the OK button or presses ENTER on the keyboard, the Input Box function will return the text in the text box. If the user clicks on the Cancel button, the function will return an empty string (""). 149

150 Syntax InputBox(prompt,[title],[default][xpos][ypos]) Parameter prompt title default xpos ypos Description Is the dialog box prompt Optional. The title of the dialog box. Default is the application name Optional. A default text in the text box Is the horizontal position,in number to twis,from the left side of the screen Is the vertical position,in number to twis,from the top side of the screen * A twip is a measurement unit that is visually the same on all display systems. 1 twip is 1/1440 of an inch. Example 1 <%@ Language="vbscript"%> <script language="vbscript"> sub window_onload() InputBox "Please enter your name for Authentication","The Input Box is used to obtain your name","enter your name" End sub </script> <html> <head><title>using the InputBox function</title> </head> <body bgcolor="fffff"> <h1> User Authantication in progress</h1> </body> </html> OUTPUT 150

151 Msgbox Function The MsgBox function displays a message box, waits for the user to click a button, and returns a value that indicates which button the user clicked. Syntax MsgBox<MsgBoxPrompt>,<ButtonStyle>,<Title> Parameter prompt buttons title Description Is the prompt of the message box Is a number value Optional. The title of the message box. Default is the application name Icon Id Number Icon Type 16 Critical Message Icon 32 Warning Query Icon 48 Warning Message Icon 64 Information Message Message box codes for buttons and icon display Button Id Number Button/s Displayed 0 OK 1 OK and Cancel 2 Abort,Retry and Ignore 151

152 3 Yes,No and Cancel 4 Yes and No 6 Retry and Cancel 256 Second button is default 512 Third button is default 4097 The message box always appears on top of all other windows until the user responds to the message box Example <%@ Language="vbscript"%> <script language="vbscript"> sub window_onload() MsgBox "The information you are about to see is confidential!",16,"confidential Information" End sub </script> <html> <head><title>using the MsgBox function</title> </head> <body bgcolor="fffff"> <h1> Confidential information goes here</h1> </body> </html> OUTPUT Using HTML Forms Before you can process the information, you need to create an HTML form that will send information to 152

153 your ASP page. There are two methods for sending data to an ASP form: POST and GET. These two types of sending information are defined in your HTML Form element's Method attribute. Form.html Code: <form method="get" action="tizagget.asp"> Name <input type="text" name="name"/> Age <input type="text" name="age"/> <input type="submit" /> </form> Form.html Display (not functional): Name Age Submit HTML forms are used to pass data to a server. An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form: <form>. input elements. </form> HTML Forms - The Input Element The most important form element is the <input> element. The <input> element is used to select user information. An <input> element can vary in many ways, depending on the type attribute. An <input> element can be of type text field, checkbox, password, radio button, submit button, and more. The most common input types are described below. Using ActiveX Controls ActiveX control can be used to obtain input from users when the application requires more control over various attributes of the data entry fields. 153

154 Functionalities of HTML Forms Creating a website is processing information captured by HTML forms Retrieving Form Data Whenever a user submits an HTML form to a website all the form fields and their values are placed in the form collection of the request object Example result.html <html> <head><title>simple form</title> </head> <body> <form method="post" action=" <p>please enter your UserName: <br> <input type="text" name="username"> <p>please enter some comments: <br><textarea name="comments" cols=40 rows=5></textarea> <p><input type="submit" value="save"> </form> </body> </ html> result.asp <% dim username1,comments1 username1=request.form("username") comments1=request.form("comments") %> <html> <head><title>result</title></head> <body> Your UserName is<%=username1%> <p>your Comments are<%=comments1%> </body> </html> OUTPUT 154

155 Using TextBoxes and TextAreas Using Textarea Field <textarea rows="4" cols="50"> </textarea> The <textarea> tag is supported in all major browsers. 155

156 Definition and Usage The <textarea> tag defines a multi-line text input control. Using Radio Buttons <input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices: <form> <input type="radio" name="sex" value="male">male<br> <input type="radio" name="sex" value="female">female </form> Female Male Using Checkboxes <input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of choices. <form> <input type="checkbox" name="vehicle" value="bike">i have a bike<br> <input type="checkbox" name="vehicle" value="car">i have a car </form> I have a bike I have a car Using Select Lists A select list to display a limited menu of options. Create a drop-down list with four options: <select> <option value="volvo">volvo</option> <option value="saab">saab</option> <option value="mercedes">mercedes</option> <option value="audi">audi</option> </select> The <select> tag is supported in all major browsers. Definition and Usage The <select> element is used to create a drop-down list. 156

157 The <option> tags inside the <select> element define the available options in the list 157

158 Cookie? UNIT- 3 A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values. Purpose of cookies Cookies were created to overcome the problem of identifying visitors. Cookies were designed to hold information about a user including an identifying number. Applications of cookies. There are numerous practical applications that require the use of cookie Personal information-user s name, geographic location(country, account number) Personal preferences-preferred background color/bitmap, background music Information about an online transaction-items in shopping cart, time spent shopping, shopping cart expiration time/date Working with cookies and its drawbacks HTTP is a text-based, stateless request/response protocol. The client, typically a Web browser, sends a request, and the server, typically referred to as a Web or HTTP server, returns a response. Both the request and response include some headers as well as some additional data. Cookies are an extension to the HTTP protocol whereby a Web server requests that the client, traditionally a Web browser, store a small amount of information on the machine on which the client is running. Each time the client sends another request to the server, it checks its jar of cookies, and sends the applicable cookies along with the request. Addressing the drawbacks of using cookies Cookies can be lost Never depend on cookies to store valuable and irreplaceable information. Cookies files can be corrupted, deleted or overwritten when a new version of a web browser is installed When using cookies be prepared for a user a lose the cookie i.e. file used to store cookie data Cookies can be changed by users Cookies can be used to store non-confidential information. If confidential information need to be stored for future reference store in it server side database and assign identification code and password to user Cookies can be copied Cookies are not universally unique even if a universally a unique cookie is created for each HTTP transaction Cookies can be stolen Cookie information can be copied with or without the consent are knowledge of the owner of the cookie file 158

159 Uses of cookies in asp applications These applications manipulate using the Response and Request objects of asp How to Create a Cookie: The "Response. Cookies" command is used to create cookies. In the example below, we will create a cookie named "firstname" and assign the value "Alex" to it: <% Response.Cookies("firstname")="Alex" %> It is also possible to assign properties to a cookie, like setting a date when the cookie should expire: <% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2012# %> How to Retrieve a Cookie Value: The "Request.Cookies" command is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "firstname" and display it on a page: <% fname=request.cookies("firstname") response.write("firstname=" & fname) %> Output: Firstname=Alex A Cookie with Keys If a cookie contains a collection of multiple values, we say that the cookie has Keys. In the example below, we will create a cookie collection named "user". The "user" cookie has Keys that contains information about a user: <% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %> 159

160 Read all Cookies <% Response.Cookies("firstname")="Alex" Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith" Response.Cookies("user")("country")="Norway" Response.Cookies("user")("age")="25" %> The Cookies Collection Property Description Access Write Domain Tells the browser only to send the cookie to the specified domain. only Expires Tells the browser to delete the cookie at the specified date. If no date is specified, the cookie expires when the browser is closed. HasKeys Determines whether the cookie has any keys. Path Secure Tells the browser only to send the cookie to the specified path. If set to True then the cookie will only be sent to the server when using a secure connection. This defaults to False. Working with Connections and Data sources: The mostly commonly used data sources are Write only Read only Write only Write only 1. ADO-The ActiveX Data Objects provide an application-level interface to data providers such as MS Access or MS SQL ADO is directly used within asp to communicate with such databases 2. OLEDB-Object Linking Embedded Database. It is a system level interface to data providers such as MS Access or MS SQL It is never used directly within asp instead ADO is used as a higher-level interface to OLEDB 3. ODBC-Open Database Connectivity used as the standard for communicating with databases. It is compatible with all databases. Microsoft has also developed an OLEDB provider for ODBC to use with databases that do not have their own OLEDB providers The ADO contains all the objects used within asp 160

161 Connection Object This object represents all the features of a connection to the datasources A connection can be opened with the connection object before communicating with the data source Recordset Object This represents the rows of data returned from the data source Ex select query Command Object This represents a command that can be executed against a data source It is used to execute SQL stored procedure Creating connections with OLEDB and ODBC To access a database within asp ADO has to be used. The ADO contains the actual collection of objects that are used within script to create a connection to a database and read records from a database table The ADO does not communicate directly with the data source using an intermediary interface called OLEDB There are two ways that an OLEDB provider may provide access to a database 1. Either indirectly through ODBC driver or 2.Directly native OLEDB provider The traditional method for communicating with a database was through ODBC interface. Microsoft is gradually replacing ODBC with OLEDB The problem with ODBC was developed with narrow purpose of working with databases But OLEDB was designed to work with s much wider range of data sources The OLEDB provider for ODBC drivers maps the OLEDB methods and interfaces to the ODBC API There are currently two methods for using ADO to create a connection to a database 161

162 1. To create a connection using the OLEDB provider for ODBC driver this will work with any database that has an ODBC driver 2. To create a connection using a native OLEDB provider Connect Microsoft Access Database: Creating a Microsoft Access Connection Using OLEDB The preferred method for creating a connection an access database is by using a native OLEDB.There are 2 native OLEDB providers for MS-Access MICROSOFT.JET.OLEDB.3.5 and MICROSOFT.JET.OLEDB.4.0 Method 1 <% Set con=server.createobject("adodb.connection") con.open Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:/webdata/northwind.mdb %> Provider-Name of the OLEDB provider DATA Source-To provide a path of the access database To create a new Data link follows these steps 1. Right click on the desktop and choose new and select Microsoft data link 2. Double click the new data link. This will launch the data link applet 3. Next choose the data provided by choosing the Microsoft Jet OLEDB provider from the tabbed labeled provider, click next 4. From the connection tab enter the path to the access database 5. Click ok to save the new data link Method 2 <% Set con=server.createobject("adodb.connection") con.open File Name=c:/webdata/northwind.mdb %> Creating a Microsoft Access Connection Using ODBC To ODBC connection there are 3 choices i.e. 1. Store the information in the windows registry 2. A file or 3. In the connection string itself Create a System DSN for Microsoft Access 162

163 Store the information in the windows registry a System DSN must created Steps for creating System DSN 1. Open the ODBC icon in your Control Panel. 2. Choose the System DSN tab. 3. Click on Add in the System DSN tab. 4. Select the Microsoft Access Driver. Click Finish. 5. In the next screen, click Select to locate the database. 6. Give the database a Data Source Name (DSN). 7. Click OK. Method 1 <% Set con=server.createobject("adodb.connection") con.open DSN=AccessDSN;UID=admin;PWD=secret %> Create a File DSN for Microsoft Access The procedure for creating a File DSN is similar to the procedure for creating a System DSN Steps for creating File DSN 1. Open the ODBC icon in your Control Panel. 2. Choose the File DSN tab. 3. Click on Add in the File DSN tab. 4. Select the Microsoft Access Driver. Click Finish. 5. In the next screen, click Select to locate the database. 6. Give the database a Data Source Name (DSN). 7. Click OK. Method 2 <% Set con=server.createobject("adodb.connection") con.open FILEDSN=AccessDSN %> Create a DSN-less connection for Microsoft Access To create a DSN-less connection there are couple of parameters more to be added the Driver and DBQ parameter Method 2 163

164 <% Set con=server.createobject("adodb.connection") con.open "DRIVER={Microsoft Access Driver (*.mdb)};dbq= c:/webdata/northwind.mdb %> Driver-To specify the MS Access database file Connect Microsoft SQL Server To communicate with a database such as Microsoft SQL server an ADO connection object is opened with a connection string. The connection string contains such information as the location of the data source There are 2 methods of providing this information. All the information can be provided in the connection string itself can refer to an external file that contains the information Creating a SQL Server with OLEDB The preferred method for creating a connection an access database is by using a native OLEDB. Method 1 <% Set con=server.createobject("adodb.connection") con.open Provider=SQLOLEDB.4.0;DATA SOURCE=c:/webdata/northwind.mdb; UID=sa;PWD=secret;DATABASE=pubs %> Provider-Name of the OLEDB provider DATA Source-To provide a path of the access database UID-Indicates the SQL server login with the connection PWD-Indicates the SQL login password To create a new Data link follows these steps 1. Right click on the desktop and choose new and select Microsoft data link 2. Double click the new data link. This will launch the data link applet 3. Next choose the data provided by choosing the Microsoft OLEDB provider for SQL server tabbed labeled provider, click next 4. From the connection tab enter the path to the SQL database 5. Click ok to save the new data link Method 2 164

165 <% Set con=server.createobject("adodb.connection") con.open File Name=c:/webdata/northwind.mdb;UID=sa;PWD=secret;DATABASE=pubs %> Connecting to SQL Server with ODBC The traditional method for communicating to a SQL server is ODBC. The connection uses OLEDB provide for ODBC drivers To ODBC connection there are 3 choices i.e. 4. Store the information in the windows registry 5. A text file or 6. Within the connection string itself Create a System DSN for Microsoft SQL Server Steps for creating System DSN 1. Open the ODBC icon in your Control Panel. 2. Choose the System DSN tab. 3. Click on Add in the System DSN tab. 4. Select the Microsoft Access Driver. Click Finish. 5. In the next screen, click Select to locate the database. 6. Give the database a Data Source Name (DSN). 7. Click OK. Method 1 <% Set con=server.createobject("adodb.connection") con.open DSN=AccessDSN;UID=admin;PWD=secret;DATABASE=pubs %> Create a File DSN for Microsoft SQL Server The procedure for creating a File DSN is similar to the procedure for creating a System DSN Steps for creating File DSN 8. Open the ODBC icon in your Control Panel. 9. Choose the File DSN tab. 10. Click on Add in the File DSN tab. 11. Select the Microsoft Access Driver. Click Finish. 165

166 12. In the next screen, click Select to locate the database. 13. Give the database a Data Source Name (DSN). 14. Click OK. Method 2 <% Set con=server.createobject("adodb.connection") con.open FILEDSN=AccessDSN %> Create a DSN-less connection for Microsoft Access To create a DSN-less connection there are couple of parameters more to be added the Driver and DBQ parameter Method 2 <% Set con=server.createobject("adodb.connection") con.open "DRIVER={Microsoft Access Driver (*.mdb)};dbq= c:/webdata/northwind.mdb %> Driver-To specify the MS Access database file 166

167 PROGRAMMING IN ASP Unit IV Database: A database is an organized collection of data. A database is a collection of information that is organized so that it can easily be accessed, managed, and updated. Databases can be classified according to types of content: Text, numeric, and images. update data in a database table After the tables have been created and the data added, changing or updating data in the tables becomes one of the day-to-day processes in maintaining a database. SQL Server provides the following ways to change data in an existing table. The UPDATE statement is used to update existing records in a table. Syntax: UPDATE table_name SET column1=value1,column2=value2 WHERE some_column=some_value; Example: UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste'; Uses of Recordset object: The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database. ProgID Set rs=server.createobject ("ADODB.RecordSet") ADO ADO is a Microsoft technology. ADO stands for ActiveX Data Objects. ADO is a Microsoft Active-X component. ADO is automatically installed with Microsoft IIS. 167

168 ADO is a programming interface to access data in a database. connection object: The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. If you want to access a database multiple times, you should establish a connection using the Connection object. You can also make a connection to a database by passing a connection string via a Command or Recordset object. ProgID Set con=server.createobject("adodb.connection") Execute a SQL statement with the connection object: ADO Command Object Command Object The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records. If the query is used to retrieve data, the data will be returned as a RecordSet object. This means that the retrieved data can be manipulated by properties, collections, methods, and events of the Recordset object. The major feature of the Command object is the ability to use stored queries and procedures with parameters. ProgID Set cmd=server.createobject("adodb.command") Methods Method Cancel CreateParameter Execute Cancels an execution of a method Creates a new Parameter object Description Executes the query, SQL statement or procedure in the CommandText property Connection Object The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. 168

169 If you want to access a database multiple times, you should establish a connection using the Connection object. You can also make a connection to a database by passing a connection string via a Command or Recordset object. However, this type of connection is only good for one specific, single query. ProgID Set con=server.createobject("adodb.connection") Methods Method BeginTrans Cancel Close CommitTrans Execute Open OpenSchema RollbackTrans Begins a new transaction Cancels an execution Closes a connection Description Saves any changes and ends the current transaction Executes a query, statement, procedure or provider specific text Opens a connection Returns schema information from the provider about the data source Cancels any changes in the current transaction and ends the transaction Example: Create an ADO SQL Recordset We can also get access to the data in the "Customers" table using SQL: <% Set conn=server.createobject("adodb.connection") conn.provider="microsoft.jet.oledb.4.0" conn.open "c:/webdata/northwind.mdb" Set rs=server.createobject("adodb.recordset") rs.open "Select * from Customers", conn %> RecordSet ADO Recordset To be able to read database data, the data must first be loaded into a recordset. 169

170 Create an ADO Table Recordset After an ADO Database Connection has been created, as demonstrated in the previous chapter, it is possible to create an ADO Recordset. Suppose we have a database named "Northwind", we can get access to the "Customers" table inside the database with the following lines: <% Set conn=server.createobject("adodb.connection") conn.provider="microsoft.jet.oledb.4.0" conn.open "c:/webdata/northwind.mdb" Set rs=server.createobject("adodb.recordset") rs.open "Customers", conn %> Recordset Object The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database. ProgID Set rs=server.createobject("adodb.recordset") When you first open a Recordset, the current record pointer will point to the first record and the BOF and EOF properties are False. If there are no records, the BOF and EOF property are True. Recordset objects can support two types of updating: Immediate updating - all changes are written immediately to the database once you call the Update method. Batch updating - the provider will cache multiple changes and then send them to the database with the UpdateBatch method. In ADO there are 4 different cursor types defined: Dynamic cursor - Allows you to see additions, changes, and deletions by other users. Keyset cursor - Like a dynamic cursor, except that you cannot see additions by other users, and it prevents access to records that other users have deleted. Data changes by other users will still be visible. Static cursor - Provides a static copy of a recordset for you to use to find data or generate reports. Additions, changes, or deletions by other users will not be visible. This is the only type of cursor allowed when you open a client-side Recordset object. Forward-only cursor - Allows you to only scroll forward through the Recordset. Additions, changes, or deletions by other users will not be visible. 170

171 The cursor type can be set by the CursorType property or by the CursorType parameter in the Open method. This example demonstrates how to use the GetRows method. Output: <!DOCTYPE html> <html> <body> <% set conn=server.createobject("adodb.connection") conn.provider="microsoft.jet.oledb.4.0" conn.open(server.mappath("/db/northwind.mdb")) set rs = Server.CreateObject("ADODB.recordset") rs.open "Select * from Customers", conn 'The first number indicates how many records to copy 'The second number indicates what recordnumber to start on p=rs.getrows(2,0) response.write("<p>this example returns the value of the first column in the first two records:</p>") response.write(p(0,0)) response.write("<br>") response.write(p(0,1)) response.write("<p>this example returns the value of the first three columns in the first record:</p>") response.write(p(0,0)) response.write("<br>") response.write(p(1,0)) response.write("<br>") response.write(p(2,0)) rs.close conn.close %> </body> </html> This example returns the value of the first column in the first two records: ALFKI BERGS This example returns the value of the first three columns in the first record: 171

172 ADO cursors ALFKI Alfreds Futterkiste Maria Anders 1. Write a note on understanding ADO cursors. The CursorLocation and the CursorType properties of the ADO Recordset object determine what we are allowed to do with our underlying cursor of data. These properties help to determine things like whether we can move through the data one time or many times, whether or not we can get a count of the records up-front and even whether or not we can bind our data to a grid. The location and the cursor type also affect how well the application will perform and how well you will be able to scale this application. Scalability is a term used to describe how well an application can take on new users without losing performance. For example if I have an application and I add 2000 more users and the application still is as fast as it was with 20 users, this is a very scalable application. In ADO there are 4 different cursor types defined: Dynamic cursor - Allows you to see additions, changes, and deletions by other users. Keyset cursor - Like a dynamic cursor, except that you cannot see additions by other users, and it prevents access to records that other users have deleted. Data changes by other users will still be visible. Static cursor - Provides a static copy of a recordset for you to use to find data or generate reports. Additions, changes, or deletions by other users will not be visible. This is the only type of cursor allowed when you open a client-side Recordset object. Forward-only cursor - Allows you to only scroll forward through the Recordset. Additions, changes, or deletions by other users will not be visible. The cursor type can be set by the CursorType property or by the CursorType parameter in the Open method. Let s take a look at creating an ADO recordset with some very simple ADO code and see how the CursorLocation and CursorType properties come into play. Dim cn As ADODB.Connection Dim rs As ADODB.Recordset Set cn = New ADODB.Connection Set rs = New ADODB.Recordset 172

173 cn.open "Provider=SQLOLEDB;Data Source=server;" & _ "User Id=user1;Password=MyPassword;" & _ "initial catalog=pubs;" rs.open "select au_fname from authors", cn In this code we have done the bare minimum to create a recordset. We declared our ADO connection and recordset objects, instantiated them by setting them = to a new connection or recordset object and then opened our connection and recordset. Notice that we did not set any properties for the recordset object in this code except those that are absolutely necessary. If we attempt to MovePrevious in this recordset we will receive Error 3219 The operation is not allowed in this context. This is one of the most common issues that new users of ADO see. By default, when I create a recordset and I do not explicitely set the cursortype property, we get a cursortype of adopenforwardonly. This means that I can only move through my records one at a time in a forward only manner. Therefore MovePrevious gives an error. So what we see is if we do not explicitly set the cursor type property we get a default value of adopenforwardonly and can only make one pass through the records in a forward direction. Default values are there to help in ADO so you do not have to set every value, but if you are uncertain what the default values are, you can run into errors. Let s take a look at the default values on the CursorType and CursorLocation a bit more closely. Default CURSOR values CursorLocation = aduseserver CursorType = adopenforwardonly LockType = adopenreadonly When we create a recordset and do not specifically state the cursorlocation, cursortype or the locktype we then receive the default values for these properties. The defaults are aduseserver for the cursorlocation. adopenforwardonly for the default cursortype which allows us to move through our records in a forward-only manner. And although we are not going to discuss this specifically in this webcast, it is worth noting that the locktype on the ADO recordset object is set to adopenreadonly by default. So if I tried to 173

174 update our basic recordset, we would get an error. For more information on the LockType property please see MSDN. So by default we get back a recordset that is server-side, Forward-only and Read-only. A Recordset with these properties is a very special recordset that is commonly known as a FireHose Recordset or Firehose Cursor. CursorType Property Values - Can be set on or before the Open method. rs.open "select au_fname from authors", cn, adopenstatic (Or) Rs.CursorType = adopenstatic Rs.ActiveConnection = cn rs.open "select au_fname from authors" To create another cursor type, we set the CursorType property on the ADO recordset object. 174

175 PROGRAMMING IN ASP Unit V ADO Command Object: Stored Procedure: The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, and retrieving, deleting or updating records. If the query is used to retrieve data, the data will be returned as a RecordSet object. The major feature of the Command object is the ability to use stored queries and procedures with parameters. A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure. ADO Connection Object: The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. If you want to access a database multiple times, you should establish a connection using the Connection object. You can also make a connection to a database by passing a connection string via a Command or Recordset object. However, this type of connection is only good for one specific, single query. stored procedure.: Dynamically Create ASP Form from SQL Stored Procedure. It was designed mainly to allow developers to create parameter-based queries in the form of SQL Stored Procedures and turn them directly. SQL: SQL (Structured Query Language) is a standard interactive and programming language for getting information from and updating a database. Although SQL is both an ANSI (American National Standards Institute) and an ISO standard, many database products support SQL with proprietary extensions to the standard language. 175

176 Queries take the form of a command language that lets you select, insert, update, find out the location of data, and so forth. There is also a programming interface. ADO Command Object: Command Object The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, and retrieving, deleting or updating records. If the query is used to retrieve data, the data will be returned as a RecordSet object. This means that the retrieved data can be manipulated by properties, collections, methods, and events of the Recordset object. The major feature of the Command object is the ability to use stored queries and procedures with parameters. ProgID Set objcommand=server.createobject("adodb.command") Figure 1 shows the relationship between a DataAdapter and a Command object. Figure 1: The relationship between data Adapter and command Similar to the Connection class each data provider has its own Command class. Table 1 describes command classes for.net data providers. Table 1: Data provider command classes DATA PROVIDER COMMAND CLASS OleDb OleDbCommand Sql SqlCommand ODBC OdbcCommand 176

177 You call the ExecuteReader method of a Command object that executes the query and returns data in a DataReader object (see figure 2). Figure 2: Creating a data reader from a command object The Command Builder The SQL SELECT command is a fairly easy one to construct. Even if you don't know how to construct a SQL SELECT command, the Query builder in visual studio helps you. But notice there are three other commands in figure 1 to construct: InsertCommand, UpdateCommand, and DeleteCommand. These commands can get quite complicated in.net because they require complex parameter objects and often involve large lists of columns ADO.NET provides a nice utility know as the CommandBuilder that automatically builds these commands for you. Figure 1 describes the relationship between CommandBuilder and DataAdapter. CommandBuilder is constructed with DataAdapter and immediately generates the remaining Command objects upon construction. Figure 3: The relationship between Data Adapter and command Builder objects. The Data Adapter Object The DataAdapter object serves as a conduit between the data source and the Dataset. The DataAdapter knows about the DataSet and it knows how to populate it. The Adapter also knows about the connection to the data source. Figure 4 is a model that shows the simple relationship between the DataAdapter and the data source. Figure 4: The relationship between DataAdapter and DataSet 177

178 As you can see from Figure 4, the Fill method of a DataAdapter fills data from a DataAdapter to the DataSet, and the UPDATE method makes DataSet changes to the final data source. There is a DataAdapter available for each data provider. Table 3-3 describes data adapter classes for.net data providers. Table 1: Data provider Data Adapter classes DATA PROVIDER COMMAND CLASS OleDb OleDbCommand Sql SqlCommand ODBC OdbcCommand stored procedure. A stored procedure is a subroutine available to applications that access a relational database system. A stored procedure (sometimes called a proc, sproc, StoPro, StoredProc, StoreProc, sp or SP) is actually stored in the database data dictionary. Typical use for stored procedures include data validation (integrated into the database) or access control mechanisms. Furthermore, stored procedures can consolidate and centralize logic that was originally implemented in applications. Extensive or complex processing that requires execution of several SQL statements is moved into stored procedures, and all applications call the procedures. One can use nested stored procedures by executing one stored procedure from within another. Stored procedures are similar to user-defined functions (UDFs). The major difference is that UDFs can be used like any other expression within SQL statements, whereas stored procedures must be invoked using the CALL statement. [1] CALL procedure(...) or EXECUTE procedure(...) Stored procedures may return result sets, i.e. the results of a SELECT statement. Such result sets can be processed using cursors, by other stored procedures, by associating a result set locator, or by applications. Stored procedures may also contain declared variables for processing data and cursors that allow it to loop through multiple rows in a table. Stored procedure flow control statements typically include IF, WHILE, LOOP, REPEAT, and CASE statements, and more. Stored procedures can receive variables, return results or modify variables and return them, depending on how and where the variable is declared. Comparison with dynamic SQL Overhead Because stored procedure statements are stored directly in the database, they may remove all or part of the compilation overhead that is typically required in situations where software applications send inline (dynamic) SQL queries to a database. (However, most 178

179 database systems implement "statement caches" and other mechanisms to avoid repetitive compilation of dynamic SQL statements.) In addition, while they avoid some overhead, pre-compiled SQL statements add to the complexity of creating an optimal execution plan because not all arguments of the SQL statement are supplied at compile time. Depending on the specific database implementation and configuration, mixed performance results will be seen from stored procedures versus generic queries or user defined functions. Avoidance of network traffic A major advantage with stored procedures is that they can run directly within the database engine. In a production system, this typically means that the procedures run entirely on a specialized database server, which has direct access to the data being accessed. The benefit here is that network communication costs can be avoided completely. This becomes particularly important for complex series of SQL statements. Encapsulation of business logic Stored procedures allow programmers to embed business logic as an API in the database, which can simplify data management and reduce the need to encode the logic elsewhere in client programs. This can result in a lesser likelihood of data corruption by faulty client programs. The database system can ensure data integrity and consistency with the help of stored procedures. Delegation of access-rights In many systems, stored procedures can be granted access rights to the database that users who execute those procedures do not directly have. Some protection from SQL injection attacks Stored procedures can be used to protect against injection attacks. Stored procedure parameters will be treated as data even if an attacker inserts SQL commands. Also, some DBMSs will check the parameter's type. A stored procedure that in turn generates dynamic SQL using the input is however still vulnerable to SQL injections unless proper precautions are taken. Comparison with functions A function is a subprogram written to perform certain computations A scalar function returns only a single value (or NULL), whereas a table function returns a (relational) table comprising zero or more rows, each row with one or more columns. Functions must return a value (using the RETURN keyword), but for stored procedures this is not compulsory. Stored procedures can use RETURN keyword but without any value being passed. Functions could be used in SELECT statements, provided they don t do any data manipulation. However, procedures cannot be included in SELECT statements. A stored procedure can return multiple values using the OUT parameter or return no value at all. A stored procedure saves the query compilation time. A stored procedure is a database object. A stored procedure is a material object. Disadvantages Stored procedure languages are quite often vendor-specific. Switching to another vendor's database most likely requires rewriting any existing stored procedures. Stored procedure languages from different vendors have different levels of sophistication. 179

180 o For example, Oracle's PL/SQL has more language features and built-in features (via packages such as DBMS_ and UTL_ and others) than Microsoft's T- [citation needed] SQL. Tool support for writing and debugging stored procedures is often not as good as for other programming languages, but this differs between vendors and languages. o For example, both PL/SQL and T-SQL have dedicated IDEs and debuggers. PL/PgSQL can be debugged from various IDEs. Changes to stored procedures are more difficult to keep track of within a version control system than other code. Changes must be reproduced as scripts to be stored in the project history to be included, and differences in procedures can be more difficult to merge and track correctly. Executing stored procedure with command object. Call stored procedures, in a.net Environment, i.e Visual Studio.We use.net 2.0 and Visual Studio 2005 for all the examples.fs Creating Stored Procedures Writing stored procedures has never been easy as Microsoft has almost integrated SQL Server with Visual Studio In the past most of the developers has wondered can t we have a good editor for creating stored procedures. One of the main advantage of creating procedures in Visual Studio is it cre ates the basic stub for you and furthermore, it has inbuilt syntax checking which makes the job easier for us. In order to create a stored procedure from Visual Studio, first you need to create a data connection from the Server Explorer and follow the below steps. Step 1: Open Visual Studio Step 2: Create a VB.NET / C# Windows / Web Application Project. Step 3: Open the Server Explorer by Selecting View -> Server Explorer. Step 4: Create a Data Connection to your server you can do this by Right Clicking on the Data Connection Tree and Selecting Add New Connection. Step 5: It will Prompt for the Provider Type you can select.net SQL Server Provider as it gives more performance. Step 6: After giving all the credentials once the connection is active expand the database that you are having. Step 7: Expand the Stored Procedure Tree. Step 8: To Create a New Procedure Right Click and Select Add New Procedure. Step 9: The IDE will give you a Stub where you can replace the Name of the Procedure and 180

181 Arguments. Those who are familiar with Visual Studio IDE would love to create procedures here rather then doing it in Query Analyzer or in SQL Enterprise Manager, though it doesn t provide any fancy auto complete drop downs it s still the best I believe to create stored procedures. TIP: The Maximum number of parameters in a stored procedure is Calling Stored Procedure Hope everyone have used SQLCommand / OLEDB Command objects in.net. Here we can call stored procedures in two different forms, one without using parameter objects which is not recommended for conventional development environments, the other one is the familiar model of using Parameters. In the first method you can call the procedure using Exec command followed by the procedure name and the list of parameters, which doesn t need any parameters. Example: Dim SQLCon As New SqlClient.SqlConnection SQLCon.ConnectionString = "Data Source=Server;User ID=User;Password=Password;" SQLCon.Open() Calling Stored Procedures with Exec command SQLCmd.CommandText = "Exec SelectRecords 'Test', 'Test', 'Test'" SQLCmd.Connection = SQLCon 'Active Connection The second most conventional method of calling stored procedures is to use the parameter objects and get the return values using them. In this method we need to set the SQLCommandType to StoredProcedure remember you need to set this explicitly as the the default type for SQLCommand is SQLQuery. Here is an example to call a simple stored procedure. Example - I (A Stored Procedure Returns Single Value) In order to get XML Results from the Stored Procedure you need to first ensure that your stored procedure is returning a valid XML. This can be achieved using FOR XML [AUTO RAW EXPLICIT] clause in the select statements. You can format XML using EXPLICIT Keyword, you need to alter your Query accordingly 'Set up Connection object and Connection String for a SQL Client Dim SQLCon As New SqlClient.SqlConnection SQLCon.ConnectionString = "Data Source=Server;User ID=User;Password=Password;" SQLCon.Open() SQLCmd.CommandText = "SelectRecords" ' Stored Procedure to Call SQLCmd.CommandType = CommandType.StoredProcedure 'Setup Command Type SQLCmd.Connection = SQLCon 'Active Connection The procedure can be called by adding Parameters in at least two different methods, the simplest 181

182 way to add parameters and respective values is using SQLCmd.Parameters.AddWithValue("S_Mobile", "Test") SQLCmd.Parameters.AddWithValue("S_Mesg", "Test") SQLCmd.Parameters.AddWithValue("LastMsgID", "") In this above method, you doesn t necessarily know the actually data type that you had in your procedure and all parameters are validated according to the type declared in your procedure but only thing is all the validations will occur in SQL and not in your client code. Example - II (Stored Procedure to get Table Result Set) In order to get the result sets from the stored procedure, the best way is to use a DataReader to get the results. In this example we are getting the results from the Stored Procedure and filling the same in a DataTable. Here we need to additionally declare a SQLDataReader and DataTable Dim SQLDBDataReader As SqlClient.SqlDataReader Dim SQLDataTable As New DataTable SQLCmd.CommandText = "GetAuthors" SQLCmd.CommandType = CommandType.StoredProcedure SQLCmd.Connection = SQLCon SQLCmd.Parameters.Add(New SqlClient.SqlParameter("AuthorName", SqlDbType.VarChar, 100, ParameterDirection.Input, False, 30, 0, "", DataRowVersion.Current, "Y%")) SQLDBDataReader = SQLCmd.ExecuteReader() SQLDataTable.Columns.Add("AuthorName", GetType(Int32), "") SQLDataTable.Columns.Add("AuthorLocation", GetType(String), "") Dim FieldValues(1) As Object 'A Temporary Variable to retrieve all columns in a row and fill them in Object array While (SQLDBDataReader.Read) SQLDBDataReader.GetValues(FieldValues) SQLDataTable.Rows.Add(FieldValues) End While Example - III (Calling Simple Stored Procedure to get XML Result Set) In order to get XML Results from the Stored Procedure you need to first ensure that your stored procedure is returning a valid XML. This can be achieved using FOR XML [AUTO RAW EXPLICIT] clause in the select statements. You can format XML using EXPLICIT Keyword, you need to alter your Query accordingly. CREATE PROCEDURE GetRecordsXML (@AuthorName varchar(100)) AS Select Author_ID, Author_Name, Author_Location Where Author_Name from Authors FOR XML AUTO RETURN 182

183 When you use the above procedure you can get XML Results with TableName as Element and Fields as Attributes Dim SQLXMLReader As Xml.XmlReader SQLCmd.CommandText = "GetAuthorsXML" SQLCmd.CommandType = CommandType.StoredProcedure SQLCmd.Connection = SQLCon SQLCmd.Parameters.Add(New SqlClient.SqlParameter("AuthorName", SqlDbType.VarChar, 100, ParameterDirection.Input, False, 30, 0, "", DataRowVersion.Current, "Y%")) SQLDBDataReader = SQLCmd.ExecuteReader() SQLXMLReader = SQLCmd.ExecuteXmlReader() While (SQLXMLReader.Read) MsgBox(SQLXMLReader.ReadOuterXml) End While 183

184 Sem V Major Based Elective I (MBECA1:1/10) Software Engineering Unit I Introduction to Software Engineering: Definitions-Size Factors Quality and Productivity Factors. Planning a Software Project: Planning the Development Process Planning an Organizational Structure. Unit II Software Cost Estimation: Software cost Factors Software Cost Estimation Techniques Staffing-Level Estimation Estimating Software Estimation Costs. Unit III Software Requirements Definition: The Software Requirements specification Formal Specification Techniques. Software Design: Fundamental Design Concepts Modules and Modularization Criteria. Unit IV Design Notations Design Techniques. Implementation Issues: Structured Coding Techniques Coding Style Standards and Guidelines Documentation Guidelines. Unit V Verification and Validation Techniques: Quality Assurance Walkthroughs and Inspections Unit Testing and Debugging System Testing. Software Maintenance: Enhancing Maintainability during Development Managerial Aspects of Software Maintenance Configuration Management. Textbook: 1. Software Engineering Concepts Richard Fairley, 1997, Tata Mcgraw Hill. Reference Books: 1. Software Engineering for Internet Applications Eve Anderson, Philip Greenspun, Andrew Grumet, 2006, PHI. 2. Fundamentals of Software Engineering Rajib Mall, 2nd Edition, PHI 3. Software Engineering Stephen Schach, 7th edition, TMH. 184

185 UNIT:1 Software Engineering is the subdiscipline of Computer Science that attempts to apply engineering principles to the creation, operation, modification and maintenance of the software components of various systems. As with much of Computer Science, the subject of Software Engineering is at an very early stage in its development. It is much more of an art than a science, and at present has little in common which classical engineering. The water fall model There are two essential steps common to the development of computer programs: analysis and coding. Both involve creative work that directly contributes to the usefulness of the end product. In order to manage and control all of the intellectual freedom associated with software development, one must introduce several other overhead steps, including system requirements definition, software requirements definition, program design, and testing. These steps supplement the analysis and coding steps. Waterfall model phases Requirements analysis and definition System and software design Implementation and unit testing Integration and system testing Operation and maintenance The drawback of the waterfall model is the difficulty of accommodating change after the process is underway Waterfall model problems 185

186 Inflexible partitioning of the project into distinct stages This makes it difficult to respond to changing customer requirements Therefore, this model is only appropriate when the requirements are well-understood Pros: Cons: Easiest to understand Does not model the real world Easiest to instrument Too much documentation Enforced discipline Document and deliverable driven Suggested Changes Then and Now Point 1. Program design comes first. Program designer looks at storage, timing, data. Very high level First glimpse. First concepts During analysis: program designer must then impose storage, timing, and operational constraints to determine consequences. Begin design process with program designers, not analysts and programmers Design, define, and allocate data processing modes even if wrong. (allocate functions, database design, interfacing, processing modes, i/o processing, operating procedures. Even if wrong!!) Build an overview document to gain a basic understanding of system for all stakeholders. Point 2: Document the Design Development efforts required huge amounts of documentation manuals for everything User manuals; operation manuals, program maintenance manuals, staff user manuals, test manuals Most of us would like to ignore documentation. Each designer MUST communicate with various stakeholders: interface designers, managers, customers, testers, developers,.. 186

187 Point 3: Do it twice. History argues that the delivered version is really version #2Version 1, major problems and alternatives are addressed the big cookies such as communications, interfacing, data modeling, platforms, operational constraints, other constraints. Plan to throw first version away sometimes Version 2, is a refinement of version 1 where the major requirements are implemented. Version 1 often austere; Version 2 addressed shortcomings! Point 4: Then: Plan, Control, and Monitor Testing. Largest consumer of project resources (manpower, computing time, ) is the test phase. Phase of greatest risk in terms of cost and schedule. Occurs last, when alternatives are least available, and expenses are at a maximum. Typically that phase that is shortchanged the most To do: 1. Employ a non-vested team of test specialists not responsible for original design. 2. Employ visual inspections to spot obvious errors (code reviews, other technical reviews and interfaces) 3. Test every logic path 4. Employ final checkout on target computer.. Point 5 Old: Involve the Customer Old advice: involve customer in requirements definition, preliminary software review, preliminary program design (critical design review briefings ) Now: Involving the customer and all stakeholders is critical to overall project success. Demonstrate increments; solicit feedback; embrace change; cyclic and iterative and evolving software. Address risk early.. The Conventional Software Management Performance Finding and fixing a software problem after delivery costs 100 times more than finding and fixing the problem in early design phases. a. You can compress software development schedules 25% of nominal, but no more. b. For every $1 you spend on development, you will spend $2 on maintenance. c. Software development and maintenance costs are primarily a function of the number of source lines of code. d. Variations among people account for the biggest differences in software productivity. e. The overall ratio of software to hardware costs is still growing. In 1955 it was 15:85; in 1985, 85:15. f. Only about 15% of software development effort is devoted to programming. 187

188 g. Walkthroughs catch 60% of the errors. h. 80% of the contribution comes from 20% of contributors The basic parameters of the software cost models Most software cost models can be abstracted into a function of five basic parameters: a. Size of the end product which is typically quantified in terms of the number of source instructions or the function points required to develop the required functionality b. Process used to produce the end product and to avoid non-value adding activities like rework, communication overhead. c. Personnel particularly their experience with the computer science issues and the applications domain issues of the project. d. Environment which is made up of the tools and techniques available to support efficient software development and to automate process. e. Quality of the product, including its performance, reliability, and adaptability. The relationship among these parameters and the estimated cost can be written as follows;: Effort=(Personnel)(Environment)(quality)(size Process ) The figure following shows three generations of basic technology advancement in topls, components and process. Thre requited levels of quality and personnel are assumed to be constant. The ordinate of the graph refers to software unit costs like SLOC,Function Point, and component realized by an organization. The three generations of software development are defined as folows: Conventional: 1960s and 1970s craftmanship. Organization used custom tools, custom process, and virtually all custom components built in primitive languages. Transition: 1980s and 1990s, software engineering. Organizations used morerepeatable process and off-the-shelf tools and mostly >70% custom components buits in higer level languages. Some of the components <30% were available as commercial products, including the operating system, database management system, networking and graphical user interface. Modern Pracices: 2000 and late, software production. In this mostly 70% offthe-shelf components perhaps as few as 30% of the components need to be custom built. With advances in software technology and integrated production environments, thse components-based systems can be produced very rapidly. 188

189 The predominant cost estimation process Three generations of software economics: A good estimate has the following attributes: It is conceived and supported by the project manager, architecture team, development team, and test team accountable for performing the work. It is accepted by all stakeholders as ambitious but realizable. 189

190 It is based on a well defined software cost model with a credible basis. It is based on a database of relevant project experience that includes similar processes, technologies, environments, quality requirements, and people. It is defined in enough detail so that its key risk areas are understood and the probability of success is objectively assessed. To improve the software economics Five basic parameters of the software cost model: 1. Reducing the size or complexity of what needs to be developed 2. Improving the development process 3. Using more-skilled personnel and better teams 4. Using better environments 5. Trading off or backing off on quality thresholds 1. Reducing Software Product Size The most significant way to improve affordability and return on investment is usually to produce a product that achieves the design goals with the minimum amount of human-generated source material. Reuse, object-oriented technology, automatic code production, and higher order programming languages are all focused on achieving a given system with fewer lines of human-specified source directives. UFP -Universal Function Points The basic units of the function points are external user inputs, external outputs, internal logic data groups, external data interfaces, and external inquiries. SLOC metrics Are useful estimators for software after a candidate solution is formulated and an implementation language is known 190

191 Reducing Software Product Size: Object Oriented A ruthless focus on the development of a system that provides a well understood collection of essential minimal characteristics. The existence of a culture that is centered on results, encourages communication, but yet is not afraid to fail. The effective use of object-oriented modeling The existence of a strong architectural vision The application of a well-managed and incremental development life cycle Reducing Software Product Size Reuse Most truly reusable components of value are transitioned to commercial products supported by organizations with the following characteristics: They have an economic motivation for continued support They take ownership of improving product quality, adding new features, and transitioning to new technologies They have a sufficiently broad customer base to be profitable. Reducing Software Product Size Commercial Components 191

192 APPROACH ADVANTAGES DISADVANTAGES Commercial components Predictable license costs Broadly used, mature technology Available now Dedicated support organization Hardware/software independence Rich in functionality Frequent upgrades Up-front license fees Recurring maintenance fees Dependency on vendor Run-time efficiency sacrifices Functionality constraints Integration not always trivial No control over upgrades and maintenance Unnecessary features that consume extra resources Often inadequate reliability and stability Multiple-vendor incompatibility Custom development Complete change freedom Smaller, often simpler implementations Often better performance Control of development and enhancement Expensive, unpredictable development Unpredictable availability date Undefined maintenance model Often immature and fragile Single-platform dependency Drain on expert resources 2. Improving Software Processes Process is an overloaded term. There are three distinct process perspectives. f. Meta process: An Organization s policies, procedures and practices for pursuing a software-intensive line of business g. Macro Process: a project s policies, procedures, and practices for producing a complete software product within certain cost, schedule, and quality constraints. h. Micro process: a project team s policies, procedures, and practices for achieving an artifact of the software process. 192

193 Three levels of processes and their attributes Attributes Metaprocess Macroprocess Microprocess Subject Line of business Project Iteration Objectives Line-of-business profitability Competitiveness Project profitability Risk management Project budget, schedule, quality Resource management Risk resolution Milestone budget, schedule, quality Audience Acquisition authorities, customers Organizational management Software project managers Software engineers Subproject managers Software engineers Metrics Project predictability Revenue, market share On budget, on schedule Major milestone success Project scrap and rework On budget, on schedule Major milestone progress Release/iteration scrap and rework Concerns Bureaucracy vs. standardization Quality vs. financial performance Content vs. schedule Time scales 6 to 12 months 1 to many years 1 to 6 months 3. Improving Team Effectiveness Some rules of team management include the following: a. A well managed project can succeed with a nominal engineering team. b. A mismanaged project will almost never succeed, even with an expert team of engineers. c. A well architected system can be built by a nominal team of software builders. d. A poorly architected system will flounder even with an expert team of builders. In examining how to staff a software project, Boehm offered the following five staffing principles: 193

194 The principle of top talent: Use better and fewer people. The principle of job matching: Fit the task to the skills an motivation of the people available. The principle of career progression: An organization does best in the long run by helping its people to self-actualize. The principle of team balance: Select people who will complement and harmonize with one another. The principle of phase-out: Keeping a misfit on the team doesn t benefit anyone. The following are some attributes of successful software project managers that deserve much more attention (Important Project Manager Skills): o Hiring skills. Few decisions are as important as hiring decisions. Placing the right person in the right job seems obvious but is surprisingly hard to achieve. o Customer-interface skill. Avoiding adversarial relationships among stake-holders is a prerequisite for success. o Decision-making skill. The jillion books written about management have failed to provide a clear definition of this attribute. We all know a good leader when we run into one, and decision-making skill seems obvious despite its intangible definition. o Team-building skill. Teamwork requires that a manager establish trust, motivate progress, exploit eccentric prima donnas, transition average people into top performers, eliminate misfits, and consolidate diverse opinions into a team direction. o Selling skill. Successful project managers must sell all stakeholders (including themselves) on decisions and priorities, sell candidates on job positions, sell changes to the status quo in the face of resistance, and sell achievements against objectives. In practice, selling requires continuous negotiation, compromise, and empathy 4. Achieving Required Quality Key practices that improve overall software quality: Focusing on driving requirements and critical use cases early in the life cycle, focusing on requirements completeness and traceability late in the life cycle, and focusing throughout the life cycle on a balance between requirements evolution, design evolution, and plan evolution Using metrics and indicators to measure the progress and quality of an architecture as it evolves from a high-level prototype into a fully compliant product Providing integrated life-cycle environments that support early and continuous configuration control, change management, rigorous design methods, document automation, and regression test automation Using visual modeling and higher level language that support architectural control, abstraction, reliable programming, reuse, and self-documentation 194

195 Early and continuous insight into performance issues through demonstration-based evaluations The Principles of Conventional Software Engineering 1. Make quality #1. Quality must be quantified and mechanism put into place to motivate its achievement. 2. High-quality software is possible. Techniques that have been demonstrated to increase quality include involving the customer, prototyping, simplifying design, conducting inspections, and hiring the best people. 3. Give products to customers early. No matter how hard you try to learn users needs during the requirements phase, the most effective way to determine real needs is to give users a product and let them play with it. 4. Determine the problem before writing the requirements. When faced with what they believe is a problem, most engineers rush to offer a solution. Before you try to solve a problem, be sure to explore all the alternatives and don t be blinded by the obvious solution. 5. Evaluate design alternatives. After the requirements are agreed upon, you must examine a variety of architectures and algorithms. You certainly do not want to use an architecture simply because it was used in the requirements specification. 6. Use an appropriate process model. Each project must select a process that makes the most sense for that project on the basis of corporate culture, willingness to take risks, application area, volatility of requirements, and the extent to which requirements are well understood. 7. Use different languages for different phases. Our industry s eternal thirst for simple solutions to complex problems has driven many to declare that the best development method is one that uses the same notation through-out the life cycle. Why should software engineers use Ada for requirements, design, and code unless Ada were optimal for all these phases? 8. Minimize intellectual distance. To minimize intellectual distance, the software s structure should be as close as possible to the real-world structure. 9. Put techniques before tools. An undisciplined software engineer with a tool becomes a dangerous, undisciplined software engineer. 10. Get it right before you make it faster. It is far easier to make a working program run than it is to make a fast program work. Don t worry about optimization during initial coding. 11. Inspect code. Inspecting the detailed design and code is a much better way to find errors than testing. 12. Good management is more important than good technology. The best technology will not compensate for poor management, and a good manager can 195

196 produce great results even with meager resources. Good management motivates people to do their best, but there are no universal right styles of management. 13. People are the key to success. Highly skilled people with appropriate experience, talent, and training are key. The right people with insufficient tools, languages, and process will succeed. The wrong people with appropriate tools, languages, and process will probably fail. 14. Follow with care. Just because everybody is doing something does not make it right for you. It may be right, but you must carefully assess its applicability to your environment. Object orientation, measurement, reuse, process improvement, CASE, prototyping-all these might increase quality, decrease cost, and increase user satisfaction. The potential of such techniques is often oversold, and benefits are by no means guaranteed or universal. 15. Take responsibility. When a bridge collapses we ask, what did the engineers do wrong? Even when software fails, we rarely ask this. The fact is that in any engineering discipline, the best methods can be used to produce awful designs, and the most antiquated methods to produce elegant design. 16. Understand the customer s priorities. It is possible the customer would tolerate 90% of the functionality delivered late if they could have 10% of it on time. 17. The more they see, the more they need. The more functionality (or performance) you provide a user, the more functionality (or performance) the user wants. 18. Plan to throw one away.one of the most important critical success factors is whether or not a product is entirely new. Such brand-new applications, architectures, interfaces, or algorithms rarely work the first time. 19. Design for change. The architectures, components, and specification techniques you use must accommodate change. 20. Design without documentation is not design. I have often heard software engineers say, I have finished the design. All that is left is the documentation. 21. Use tools, but be realistic. Software tools make their users more efficient. 22. Avoid tricks. Many programmers love to create programs with tricks- constructs that perform a function correctly, but in an obscure way. Show the world how smart you are by avoiding tricky code. 23. Encapsulate. Information-hiding is a simple, proven concept that results in software that is easier to test and much easier to maintain. 24. Use coupling and cohesion. Coupling and cohesion are the best ways to measure software s inherent maintainability and adaptability. 25. Use the McCabe complexity measure. Although there are many metrics available to report the inherent complexity of software, none is as intuitive and easy to use as Tom McCabe s. 196

197 26. Don t test your own software. Software developers should never be the primary testers of their own software. 27. Analyze causes for errors. It is far more cost-effective to reduce the effect of an error by preventing it than it is to find and fix it. One way to do this is to analyze the causes of errors as they are detected. 28. Realize that software s entropy increases. Any software system that undergoes continuous change will grow in complexity and become more and more disorganized. 29. People and time are not interchangeable. Measuring a project solely by personmonths makes little sense. 30. Expert excellence. Your employees will do much better if you have high expectations for them. The Principles of Modern Software Management Top ten principles: 1. Base the process on an architecture-first approach: The architecturally significant design decisions, and the life cycle plans before the resources are committed for full scale development. 2. Establish an iterative life-cycle process: Today s sophisticated software systems, it is not possible to define the entire problem, design the entire solution, build the software, the test the end product in sequence. An iterative process that refines the problem understanding, an effective solution, and an effective plan over several iterations encourages a balanced treatment to all objectives. 3. Component based development: A component is a cohesive set of preexisting lines of code, either in source or executable format, with a defined interface and behavior. 4. Change management environment: The dynamic of iterative development, including concurrent workflows by different teams working on shared artifacts, necessitates objectively controlled baselines. 5. Round trip engineering: it is the environment support necessary to automate and synchronize engineering information in different formats. Change freedom a necessity in an iterative process, and establishing an integrated environment is crucial. 6. Model based notation: A model based approach supports the evolution of semantically rich graphical and textual design notations 7. Objective quality control: It is the best assessment mechanisms are well defined measures derived directly from the evolving engineering 197

198 8. Demonstration based approach: transitioning the current state of the product artifacts into an executable demonstration of relevant scenarios stimulates earlier convergence on integration 9. Evolving levels of detail: the evolution of project increments and generations must be commensurate with the current level of understanding f the requirements and architecture. 10. Configurable process: No single process is suitable for all software developments. A pragmatic process framework must be configurable to a broad spectrum of applications. Waterfall Process Requirements first Custom development Change avoidance Ad hoc tools Iterative Process Architecture first Component based development Change management Round-trip engineering 198

199 UNIT-II 1. The Life cycle phases The following are the two stages of the life-cycle: The engineering stage driven by smaller teams doing design and synthesis activities The production stage driven by larger teams doing construction, test, and deployment activities LIFE-CYCLE ASPECT ENGINEERING EMPHASIS STAGE PRODUCTION EMPHASIS STAGE Risk reduction Schedule, technical feasibility Cost Products Architecture baseline Product release baselines Activities Analysis, design, planning Implementation, testing Assessment Demonstration, inspection, analysis Testing Economics Resolving diseconomies of scale Exploiting economics of scale Management Planning Operations The engineering stage is decomposed into two distinct phases, inception and elaboration, and the production stage into construction and transition. These four phases of the life-cycle process are loosely mapped to the conceptual framework of the spiral model. The size of the spiral model corresponds to the inertia of the project with respect to the breadth and depth of the artifacts that have been developed. 199

200 In most conventional life cycles, the phases are named after the primary activity within each phase: requirements analysis, design, coding, unit test, integration test, and system test. Conventional software development efforts emphasized a mostly sequential process, in which one activity was required to be complete before the next was begun. Within an iterative process, each phase includes all the activities, in varying proportions. Inception Phase: Overriding goal of the inception phase is to achieve concurrence among stakeholders on the life-cycle objectives Essential activities : Elaboration Phase: Formulating the scope of the project (capturing the requirements and operational concept in an information repository) Synthesizing the architecture (design trade-offs, problem space ambiguities, and available solution-space assets are evaluated) Planning and preparing a business case (alternatives for risk management, iteration planes, and cost/schedule/profitability trade-offs are evaluated) It is easy to argue that the elaboration phase is the most critical of the four phases. At the end of this phase, the engineering is considered complete and the project faces its reckoning. During the elaboration phase, an executable architecture prototype is built in one or more iterations, depending on the scope, size, risk and novelty of the project. Essential activities : Elaborating the vision (establishing a high-fidelity understanding of the critical use cases that drive architectural or planning decisions) Elaborating the process and infrastructure (establishing the construction process, the tools and process automation support) Elaborating the architecture and selecting components (lessons learned from these activities may result in redesign of the architecture) Construction Phase: During the construction phase : All remaining components and application features are integrated into the application 200

201 All features are thoroughly tested Essential activities : Transition Phase: Resource management, control, and process optimization Complete component development and testing against evaluation criteria Assessment of the product releases against acceptance criteria of the vision The transition phase is entered when baseline is mature enough to be deployed in the enduser domain. This phase could include beta testing, conversion of operational databases, and training of users and maintainers. Essential activities : Synchronization and integration of concurrent construction into consistent deployment baselines Deployment-specific engineering (commercial packaging and production, field personnel training) Assessment of deployment baselines against the complete vision and acceptance criteria in the requirements set Evaluation Criteria: Is the user satisfied? Are actual resource expenditures versus planned expenditures acceptable? Each of the four phases consists of one or more iterations in which some technical capability is produced in demonstrable form and assessed against a set of the criteria. The transition from one phase to the nest maps more to a significant business decision than to the completion of specific software activity. A set represents a complete aspect of the system, an artifact represents cohesive information that typically is developed and reviewed as a single entity. Life cycle software artifacts are organized into five distinct sets that are roughly partitioned by the underlying language of the set: management, requirements, design, implementation, and deployment. 201

202 Management set: The Management set captures the artifacts associated with process planning and execution. Management artifacts are evaluated, assessed and measured through a combination of the following: a. Relevant stakeholder reviews b. Analysis of changes between the current version of the artifact and previous versions c. Major milestone demonstrations of the balance among all artifacts and in particular, the accuracy of the business case and vision artifacts. The Engineering Sets: The engineering sets consist of the requirements set, the design setk the implementation set, and the deployment set. Management artifacts: The management set includes several artifacts Work Breakdown Structure vehicle for budgeting and collecting costs. The software project manager must have insight into project costs 202

203 and how they are expended. If the WBS is structured improperly, it can drive the evolving design in the wrong direction. Business Case provides all the information necessary to determine whether the project is worth investing in. It details the expected revenue, expected cost, technical and management plans. Release Specifications Typical release specification outline : Two important forms of requirements: Vision statement - which captures the contract between the development group and the buyer. Evaluation criteria defined as management-oriented requirements, which may be represented by use cases, use case realizations or structured text representations. Software Development Plan the defining document for the project s process. It must comply with the contract, comply with the organization standards, evolve along with the design and requirements. Deployment depending on the project, it could include several document subsets for transitioning the product into operational status. It could also include computer system operations manuals, software installation manuals, plans and procedures for cutover etc. Environment A robust development environment must support automation of the development process. It should include : requirements management visual modeling 203

204 document automation automated regression testing Engineering Artifacts: In general review, there are three engineering artifacts Vision document supports the contract between the funding authority and the development organization. It is written from the user s perspective, focusing on the essential features of the system. It should contain at least two appendixes the first appendix should describe the operational concept using use cases, the second should describe the change risks inherent in the vision statement. Architecture Description it is extracted from the design model and includes views of the design, implementation, and deployment sets sufficient to understand how the operational concept of the requirements set will be achieved. Typical architecture description outline : 204

205 Software User Manual it should include installation procedures, usage procedures and guidance, operational constraints, and a user interface description. It should be written by members of the test team, who are more likely to understand the user s perspective than the development team. It also provides a necessary basis for test plans and test cases, and for construction of automated test suites. Architecture in the management perspective view From a management perspective, there are three different aspects of an architecture : An architecture (the intangible design concept) is the design of software system, as opposed to design of a component. An architecture baseline (the tangible artifacts) is a slice of information across the engineering artifact sets sufficient to satisfy all stakeholders that the vision can be achieved within the parameters of the business case (cost, profit, time, people). An architecture description (a human-readable representation of an architecture) is an organizes subsets of information extracted from the design set model. The importance of software architecture can be summarized as follows: Achieving a stable software architecture represents a significant project milestone at which the critical make/buy decisions should have been resolved. Architecture representations provide a basis for balancing the trade-offs between the problem space and the solution space. The architecture and process encapsulate many of the important communications among individuals, teams, organizations, and stakeholders. Poor architectures and immature processes are often given as reasons for project failures. A mature process, an understanding of the primary requirements, and a demonstrable architecture are important prerequisites for predictable planning. Architecture development and process definition are the intellectual steps that map the problem to a solution without violating the constraints. Architecture in the technical perspective view An architecture framework is defined in terms of views that are abstractions of the UML models in the design set. The design model includes the full breadth and depth of information. An architecture view is an abstraction of the design model, it contains only the architecturally significant information. 205

206 Most real world systems require four views: design, process, component, and deployment. The purposes of these views are as follows: Design: describes architecturally significant structures and functions of the design model. Process: describes concurrency and control thread relationships among the design components, and deployment views. Component: describes the structure of the implementation set. Deployment: describes the structure of the deployment set. The use case view describes how the system s critical use cases are realized by elements of the design model. It is modeled statically using case diagrams, and dynamically using any of the UML behavioral diagrams. The design view addresses the basic structure and the functionality of the solution. The process view addresses the run-time collaboration issues involved in executing the architecture on a distributed deployment model, including the logical software network topology, interprocess communicationand state management. The component view describes the architecturally significant elements of the implementation set and addresses the software source code realization of the system from perspective of the project's integrators and developers. 206

207 The deployment view addresses the executable realization of the system, including the allocation of logical processes in the distribution view to physical resources of the deployment network. Generally an architecture baseline should include the following: Requirements: critical use cases, system level quality objectives, and priority relationship among features and qualities Design: names, attributes, structures, behaviors, groupings and relationships of significant classes and components Implementation: source component inventory and bill of materials (number, name, purpose, cost) of all primitive components Deployment: executable components sufficient to demonstrate the critical use cases and the risk associated with achieving the system qualities Work flow and software process workflows The term workflow is used to mean a thread of cohesive and mostly sequential activities. Workflows are mapped to product artifacts. There are seven top level workflows: 1. Management workflow: Controlling the process and ensuring with conditions for all stakeholders 2. Environment workflow: automating the process and evolving the maintenance environment 3. Requirements workflow: analyzing the problem space and evolving the requirements artifacts. 4. Design workflow: modeling the solution and evolving the architecture and esign artifacts 5. Implementation workflow: programming the components and evolving the implementation and deployment artifacts 6. Assessment workflow: assessing the trends in process and product quality 7. Deployment workflow: transitioning the end products to the user Four basic key principles of the modern process frame work: 1. Architecture-first approach: implementing and testing the architecture must precede full-scale development and testing and must precede the downstream focus on completeness and quality of the product features. 2. Iterative life-cycle process: the activities and artifacts of any given workflow may require more than one pass to achieve adequate results. 207

208 3. Roundtrip engineering: Raising the environment activities to a first-class workflow is critical; the environment is the tangible embodiment of the project s process and notations for producing the artifacts. 4. Demonstration-based approach: Implementation and assessment activities are initiated nearly in the life-cycle, reflecting the emphasis on constructing executable subsets of the involving architecture. The iteration workflows of the software process Iteration consists of sequential set of activities in various proportions, depending on where the iteration is located in the development cycle. Each iteration is defined in terms of a se t of allocated usage scenarios. The components needed to implement all selected scenarios are developed and integrated with the results of previous iterations. An individual iteration s workflow illustrated in the following sequence: Management: Iteration planning to determine the content of the release and develop the detailed plan for the iteration, assignment of work packages, or tasks, to the development team. Environment: evolving the software change order database to reflect all new baselines and changes to existing baselines for all product, test and environment components Requirements: analyzing the baseline plan, the baseline architecture, and the baseline requirements set artifacts to fully elaborate the use cases to the demonstrated at the end of the iteration and their evaluation criteria. Design: Evolving the baseline architecture ad the baseline design set artifacts to elaborate fully the design model and test model components necessary to demonstrate against the evolution criteria allocated to this iteration. 208

209 Implementation: developing any new components, and enhancing or modifying any existing components, to demonstrate the evolution criteria allocated to this iteration Assessment: evaluating the results of the iteration, including compliance with the allocated evaluation criteria and the quality of the current baselines; indentifying any rework required and determining whether it should be performed before deployment of this release or allocated to the next release. Deployment: transitioning the released either to an external organization or to internal closure by conducting a post mortem so that lessons learned can be captured and reflected in the next iteration. The following is an example of a simple development life cycle, illustrates the difference between iterations and increments. This example also illustrates a typical build sequence from the perspective of an abstract layered architecture. Iteration emphasis across the life cycle It is important to have visible milestones in the life cycle, where various stakeholders meet to discuss progress and planes. The purpose of this events is to: Synchronize stakeholder expectations and achieve concurrence on the requirements, the design, and the plan. Synchronize related artifacts into a consistent and balanced state. Synchronize related artifacts into a consistent and balanced state Identify the important risks, issues, and out-of-tolerance conditions. Perform a global assessment for the whole life-cycle. 209

210 Three types of joint management reviews are conducted throughout the process: 1. Major milestones provide visibility to system wide issues, synchronize the management and engineering perspectives and verify that the aims of the phase have been achieved. 2. Minor milestones iteration-focused events, conducted to review the content of iteration in detail and to authorize continued work. 3. Status assessments periodic events provide management with frequent and regular insight into the progress being made. MAJOR MILESTONES: The four major milestones occur at the transition points between life-cycle phases. They can be used in many different process models, including the conventional waterfall model. In an iterative model, the major milestones are used to achieve concurrence among all stakeholders on the current state of the project. Different stakeholders have very different concerns: Customers: schedule and budget estimates, feasibility, risk assessment, requirements understanding, progress, product line compatibility Users: consistency with requirements and usage scenarios, potential for accommodating growth, quality attributes. Architectures and systems engineers: product line compatibility, requirements changes, tradeoff analyses, completeness and consistency, balance among risk, quality, and usability. 210

211 Developers: sufficiency of requirements detail and usuage scenario descriptions, frameworks for component selection of development, resolution of development risk, sufficiency of the development environment Maintainers: sufficiency of product and documentation artifacts, understandability, interoperability with existing systems, sufficiency of maintenance environment. Others: possibly many other perspectives by stakeholders such as regulatory agencies, independent verification and validation contractors, venture capital investors, subcontractors, associate contractors, and sales and marketing teams. The milestones may be conducted as one continuous meeting of all concerned parties or incrementally through mostly on-line review of the various artifacts. There are considerable differences in the levels of ceremony for these events depending on several factors. The essence of each major milestone is to ensure that the requirements understanding, the lifecycle plans, and the product s form, function, and quality are evolving in balanced levels of detail and to ensure consistency among the various artifacts. The following table summarizes the balance of information across the major milestones. 211

212 MINOR MILESTONES: All iterations are not created equal. An iteration can take on very different forms and priorities, depending on where the project is in the life cycle. Early iterations focus on analysis 212

213 and design with substantial elements of discovery, experimentation, and risk assessment. Later iterations focus much more on completeness, consistency, usability, and change management. Iteration readiness review: this informal milestone is conducted at the start of each iteration to review the detailed iteration plan the evolution criteria that have been allocated to this iteration. Iteration Assessment review: this informal milestone is conducted at the end of each iteration to assess the degree of which the iteration achieved its objectives and satisfied its evaluation criteria, to review iteration achieved its objectives and satisfied its evaluation criteria, to review iteration results, to review qualification test results, to determine the amount of rework to be done, and to review the impact of the iteration results on the plan for subsequent iterations. PERIODIC STATUS ASSESSMENTS: Periodic stats assessments are management reviews conducted at regular intervals to address progress and quality indicators, ensure continuous attention to project dynamics, and maintain open communications among all stakeholders. Status assessments provide the following: A mechanism for openly addressing, communicating, and resolving management issues, technical issues, and project risks Objective data directly from on-going activities and evolving product configurations A mechanism for disseminating process, progress quality trends, practices and experience information to and from all stakeholders in an open forum. The default content of periodic status assessments should include the topics indentified in the following table. 213

214 214

215 215

216 UNIT III & UNIT- IV A WBS is simply a hierarchy of elements that decomposes the project plan into the discrete work tasks. A WBS provides the following information structure: A delineation of all significant work A clear task decomposition for assignment of responsibilities A framework for scheduling, budgeting, and expenditure tracking. The development of a work breakdown structure is dependent on the project management style, organizational culture, customer preference, financial constraints and several other hard-to-define parameters. I. Conventional WBS Issues: Conventional WBS frequently suffer from three fundamental flaws: 1. Conventional WBS are prematurely structured around the product design: The figure following shows the typical conventional WBS that has been structured primarily around subsystems of its product architecture, the further decomposed into the components of each subsystem. Once this structure is ingrained in the WBS and then allocated to responsible managers with budgets, schedules and expected deliverables, a concrete planning foundation has been set that is difficult and expensive to change. (SCAN FIG1) 2. Conventional WBS are prematurely decomposed, planned, and budgeted in wither too much or too little detail: Large software projects tend to be over planned and small projects tend to be under planned. The WBS shown in the above figure is overly simplistic for most large scale systems, where size or more levels of WBS elements are commonplace. 3. Conventional WBS are project-specific, and cross-project comparisons are usually difficult or impossible: 216

217 Most organizations allow individual projects to define their own project-specific structure tailored to the project manager s style, the customer s demands, or other project-specific preferences. It is extremely difficult to compare plans, financial data, schedule data, organizational efficiencies, cost trends, productivity tends, or quality tends across multiple projects. Some of the following simple questions, which are critical to any organizational process improvement program, cannot be answered by most project teams that use conventional WBS. o What is the ratio of productive activities to overhead activities? o What is the percentage of effort expanded in rework activities? o What is the percentage of cost expended in software capital equipment o What is the ration of productive testing versus integration? o What is the cost of release? II. Evolutionary Work Breakdown Structures: An evolutionary WBS should organize the planning elements around the process framework rather than the product framework. The basic recommendation for the WBS is to organize the hierarchy as follows: First level WBS elements are the workflows(management, environment, requirement, design, implementation, assessment, and deployment) Second level elements are defined for each phase of the life cycle(inceptions, elaboration, construction and transition) Third level elements are defined for the focus of activities that produce the artifacts of each phase. A default WBS consistent with the process framework (phases, workflows, and artifacts) is shown in the following figure The structure shown is intended to be merely a starting point. It needs to be tailored to the specifics of a project in many ways. Scale: Larger projects will have more levels and substructures. 217

218 Organizational structure: projects that include subcontractors or span multiple organizational entities may introduce constraints that necessitate different WBS allocations. Degree of custom development: depending on the character of the project there can be very different emphases in the requirements, design, and implementation workflows. A business process re-engineering project based primarily on existing components would have much more depth in the requirements elements and a fairly shallow design and implementation element. Business context: contractual projects require much more elaborate management and assessment elements. Projects developing commercial products for delivery to a board customer base may require much more elaborate substructures for the deployment element. Precedent experience: very few projects start with a clean state. Most of them are developed as new generations of a legacy system or in the context of existing organizational standards. It is important to accommodate these constraints to ensure that new projects exploit the existing experience base and benchmarks of project performance. Planning guidelines Software projects span a board range of application domains. It is valuable but risky to make specific planning recommendations independent of project context. Project independent planning advice is also risky. There is the risk that the guidelines may be adopted blindly without being adapted to specific project circumstances. There is also the risk of misinterpretation. Two simple planning guidelines should be considered when a project plan is being initiated or assessed. The first guideline prescribes a default allocation of costs among the first-level WBS elements. The second guideline prescribes the allocation of effort and schedule across the life cycle phases. Given an initial estimate of total project cost and these two tables, developing a staffing profile, and allocation of staff resources to reams, a top-level project schedule, and an initial WBS with task budgets and schedules is relatively straightforward. 218

219 FIRST-LEVEL WBS ELEMENT DEFAULT BUDGET Management 10% Environment 10% Requirements 10% Design 15% Implementation 25% Assessment 25% Deployment 5% Total 100% The first guideline prescribes a default allocation of costs among the first-level WBS elements The above table provides default allocations for budgeted costs of each first-level WBS element. While these values are certain to vary across projects, this allocation provides a good benchmark for assessing the plan by understanding the rationale for deviations from these guidelines. An important point here is that this is cost allocation, not effort allocation. To avoid misinterpretation two explanations are necessary 1. The cost of different labor categories is inherent in these numbers 2. The cost of hardware and software assets that support the process automation and development teams is also included in the environment element. DOMAIN INCEPTION ELABORATION CONSTRUCTION TRANSITION Effort 5% 20% 65% 10% Schedule 10% 30% 50% 10% 219

220 The second guideline prescribes the allocation of effort and schedule across the life-cycle phases The above table provides guidelines for allocating effort and schedule across the life cycle phases. Although these values can also vary widely depending on the specific constraints of an application, they provide an average expectation across a spectrum of application domains. The cost and schedule estimating process Project plans need to be derived from two perspectives. The first is a forward-looking top-down approach. It starts with as understanding of the general requirements and constraints, derives a macro level budgets and intermediate milestones. Forward-looking: 1. The software project manager develops a characterization of the overall size, process, environment, people, and quality required for the project 2. A macro-level estimate of the total effort and schedule is developed using a software cost estimation model 3. The software project manager partitions the estimate for the effort into a top-level WBS, also partitions the schedule into major milestone dates and partitions the effort into a staffing profile 4. At this point, subproject managers are given the responsibility for decomposing each of the WBS elements into lower levels using their top-level allocation, staffing profile, and major milestone dates as constraints. The second perspective is a backward-looking, bottom-up approach. We start with the end in mind, analyze the micro-level budgets and schedules, the sum all these elements into the higher level budgets and intermediate milestones. Backward-looking: 1. The lowest level WBS elements are elaborated into detailed tasks, for which budgets and schedules are estimated by the responsible WBS element manager. 2. Estimates are combined and integrated into higher level budgets and milestones. 3. Comparisons are made with the top-down budgets and schedule milestones. Gross differences are assessed and adjustments are made in order to converge on agreement between the top-down and the bottom-up estimates. 220

221 These two planning approaches should be used together, in balance, throughout the life cycle of the project. During the engineering stage, the top-down perspective will dominate. During the production stage, these should be enough precedent experience and planning fidelity that the bottom up planning perspective will dominate. By then, the top-down approach should be well tuned to the project specific parameters, so is should be used more as a global assessment technique. The following figure shows this life cycle planning balance. The types of project organizations have Line of Business Organizations: Maps roles and responsibilities to a default line-of-business organization. This structure can be tailored to specific circumstances. The main features of the default organization are as follows: Responsibility for process definition and maintenance is specific toa cohensive line of business where process commonality makes sense. For example the process of developing avionics software is different from the process used to develop office applications. Responsibility for process automation, is an organizational role and its equal in importance to the process definition role. Organizational role may be fulfilled by a single individual or several different teams, depending on the scale of the organization. 221

222 Software Engineering Process Authority: The Software Engineering Process Authority (SEPA) facilitates the exchange of information and process guidance both to and from project practitioners. The SEBA must help initiate and periodically assess project process. The SEBA is necessary role in any organization. The SEBA could be a single individual, the general manager, or even a team of representatives. The SEBA must truly be an authority, competent and powerful. Project Review Authority: The project review authority (PRA) is the single individual responsible for ensuring that a software project complies with all organizational and business unit software policies, practices, and standards. The PRA reviews both the project s conformance to contractual obligations and the project s organizational policy obligations. The customer monitors contract requirements, contract milestones, contract deliverable, monthly management reviews, progress, quality, cost, schedule and risk. The PRA reviews customer commitments as well as adherence to organizational policies, organizational deliverables, and financial performance and other risks and accomplishments. Software Engineering Environment Authority: The Software Engineering Environment Authority (SEEA) is responsible for automating the organizations process, maintaining the organizations standard environment, training project to use environment, and maintain organization-wide reusable assets. The SEEA rule is necessary to achieve significant return on investment for a common process. 222

223 Infrastructure: An organization infrastructure provides human resource support, project-independent research and development, and other capital software engineering assets. The typical components of the organizational infrastructure are as follows Project Administration: Time accounting system; contracts, pricing, terms and condition; corporate information system integration. Engineering Skill Centers: Custom tools repository and maintenance, ind3ependent research and development. bid and proposal support, Professional Development: Internal training boot camp, personnel recruiting, personnel skills database maintenance, literature and assets library, technical publications. Project Organizations and how it handle their teams? A default project organization and maps project-level roles and responsibilities. The structure can be tailored to the size and circumstances of the specific project organization. The main features of the default organization are as follows. The project management team is an active participant, responsible for producing as well as managing. The architecture team is responsible for real artifacts and for the integration of components, not just for staff function. The development team owns the component construction and maintenance activities. Quality is everyone job, integrated into all activities and check points. Each team take responsibility for a different quality perspective. 223

224 Software Management Team: Most project are over constrained. Schedules, cost, functionality and quality expectations are highly inter related and require continuous negotiation among multiple stake holders who have different goals. The software management team carries the burden of delivering with condition to all stake holders. The software management team takes ownership of all aspects of quality. Software Architecture Team: The software architecture team is responsible for the architecture. This responsibility encompasses the engineering necessary to specify a complete bill of materials for the software and the engineering necessary to make significant make/ buy trade-offs so that all custom components are elaborated to the extent that construction/assembly costs are highly predictable. In most projects, the inception and elaboration phases will be dominated by two distinct teams: the software management team and the software architecture team. To succeed, the architecture must include a fairly broad level of expertise, including the following: Domain experience to produce an acceptable design view ( architecturally significant element s of the design model) and use case view (architecturally significant element s of the use case model). Software technology experience to produce an acceptable process view(concurrency and control thread relationships among the design, component, and deployment models), component view (structure of the implementation set), and deployment view(structure of the deployment set). 224

225 Software development team: The software development team is the most application specific group. In general, the software development team comprise several sub teams dedicated to groups of components that require a common skill set. The typical skill set include the following: Commercial component: Specialists with detail knowledge of commercial components central to a system s architecture Database: specialists with experience in the organization, storage, and retrieval of data Graphical user interfaces: specialists with experience in the display organization, data presentation, and user interaction. Operating systems and networking: specialist with experience in the execution of multiple software objects on a network of hardware resources. Domain applications: specialists with experience in the algorithms, application processing. 225

226 The software development team is responsible for the quality of individual components, including all component development, testing, and maintenance. Components tests should be built as self-documented. Software Assessment Team: There are two reasons for using an independent team for software assessment. It has to do with ensuring an independent quality perspective. A more important reason for using an independent test team is to exploit the concurrency of activities. A modern process should employ use-case-oriented or capability based testing (which may span many components). Organized as a sequence of builds and mechanized via two artifacts. Release specification (the plan and evaluation criteria for a release) Release description( the results of a release) The evaluation of organizations The project organization represents the architecture of the team and needs to evolve consistent with the project plan captured in the work breakdown structure. The following figure illustrates how the team s centre of gravity shifts over the life cycle, with about 50% of the staff assigned to one set of activities in each phase A different set of activities is emphasized in each phase, as follows: Inception team: an organization focused on planning, with enough support from the other teams to ensure that the plans represent a consensus of all perspectives. 226

227 Elaboration team: an architecture focused organization in which the driving forces of the project reside in the software architecture team and are supported by the software development software assessment teams has necessary to achieve a stable architecture baseline Construction team: a fairly balanced organization in which most of the activity resides in the software development and software assessment teams Transition team: a customer focus organization in which usage feedback drives the deployment activities. The automation tools available for building blocks in software process Many tools are available to automate the software development process. Most of the core software development tools map closely to one of the process workflows, as illustrated in the following figure. Each of the process workflows has a distinct for automation support. Management: there are many opportunities for automating the project planning and control activities of the management work flows. Software cost estimating tools and WBS tools are usual for generating the planning artifacts. Environment: configuration management and version control are essential in a modern interactive development process Requirements: conventional approaches decomposed system requirements into subsystems requirements, subsystem requirements into component requirement and component requirements into unit requirements. In a modern project the system requirements are captured in the vision statement. Lower levels of 227

228 requirements are driven the process organized by iteration rather than by lower level component. Design: the primary support required for the design work flow is visual modeling, which is used for capturing design models, presenting them in human readable format, and translating them into source code. An architecture first and demonstration based process is enabled by existing architecture components and middle ware. Implementation: the implementation work flow relies primarily on a programming environment but must also include substantial integration with the change management tools, visual modeling tools, and test automation tools to support productive iteration. Assessment and deployment: the assessment workflows require all the tools just discussed as well as additional capabilities to support test automation and test management. Defect tracking is another important that supports assessment. The metrics for managing a modern process Many different metrics may be of value in managing a modern process. There are seven core metrics that should be used on all software projects. Three are management indicators and four are quality indicators. Management indicators: 1. Work and progress 2. Budgeted cost and expenditure 3. Staffing team dynamics Quality indicators: 1. Change traffic and stability 2. Breakage and modularity 3. Rework and adaptability 4. Mean time between failure and maturity METRIC PURPOSE PERSPECTIVES Work and progress Iteration planning, plan SLOC, function points, object vs. actuals, management points, scenarios, test cases, SCOs indicator 228

229 Budget cost and expenditures Financial insight, plan vs. Cost per month, full-time staff per actuals, management month, percentage of budget indicator expended Staffing and team Resource plan vs. actuals, People per month added, people per dynamics hiring rate, attrition rate month leaving Change traffic and stability Breakage modularity Rework adoptability Iteration management indicator of schedule convergence small scales projects Vs large scale projects planning, Software changes and Convergence, software Reworked SLOC per change, by scrap, quality indicator type, by release/component/subsystem and Convergence, software Average hours per change, by type, rework, quality indicator by release/component/subsystem The lists elaborate some of the key differences in discriminators of success. None of these process components is unimportant although some of them are more important than others. Design is key in both domains. Good design of a commercial product is a key differentiator in the market place and is the foundation for efficient new product releases. Management is paramount in large projects where the consequences of planning errors, resource allocation errors, inconsistent stake holder expectation, and other out of banlaned factors we can have catastrophic consequences for the overall team dynamics Deployment plays a far greater role for a small commercial product because there is a broad user base of diverse individuals and environments Rank Large Complex Project Small Commercial Project 1 Management Design 2 Design Implementation 229

230 3 Requirements Deployment 4 Assessment Requirements 5 Environment Assessments 6 Implementation Management 7 Deployment Environment 230

231 UNIT -V Risk: An uncertain event or condition that, if it occurs, has a positive or negative effect on a project s objectives. The chance of exposure to the adverse consequences of future event. People may different terms but a key elements of a risk follow It relates to the future: The future is inherently uncertain. It involves cause and effect: a good definition of a specific risk identifies a situation such as inexperience staff and a particular type of outcome, such as lower productivity. The different categories of risk: Project risk is those that could prevent the achievement of the objectives given to the project managers and the project team. Risk has been categorized in other ways. Kalle Lyytinen and his colleagues for instance, have proposed a socio technical model of risk, a diagrammatic representation. The box labeled actors refers to all the people involved in the development of the application in question. The typical risk in this area is that high staff turnover leads to information of value to the project being lost. For eg. If a software developer build a software component and then leaves before it has been fully tested, the team member taking over that component might find that their lack of familiarity with the software makes diagnosis and correction of faults difficult. The box labeled technology encompasses both the technology used to implement the application and that embedded in the delivered product. Risk here could relate to the appropriateness of the technologies and to possible fault within them, especially if the novel. 231

232 Actors Structure Technology Tasks The box labeled structure describes the management structure and system. For eg. The implementation we need the user to carry out come take, but a responsibility for managing the user contribution to the project might not have been clearly allocated. The box labeled task in the same diagram related to the work to be carried out. Each box is linked to all the remaining boxes. 1. Dealing the risk: Planning for risk includes these steps: 1. Risk identification 2. Risk analysis and prioritization 3. Risk planning 4. Risk monitoring The two main approaches to the identification of risks are the use of the check list and brainstorming. Checklists: Checklists are simply list of the risk that has been found to occur regularly in software development project. Two check list-that of Lyytinen and his colleagues and the ISPL/Euro method model-have already been mentioned, but other exists including a specialized list of software development risk by Barry Boehm- a modified version which is appearing in the following table. 232

233 Risk Risk reduction techniques Personnel shortfalls Staffing with top talent; job matching; teambuilding; training and career development; early scheduling of key personnel Unrealistic time and cost estimates Developing the wrong software functions Developing the wrong user interface Multiple estimation techniques; design to cost; incremental development; recording and analysis of past projects; standardization of methods Improved software evaluation; formal specification methods; user surveys; prototyping; early user manuals Prototyping; task analysis; user involvement Personnel shortfalls Staffing with top talent; job matching; teambuilding; training and career development; early scheduling of key personnel Unrealistic time and cost estimates Multiple estimation techniques; design to cost; incremental development; recording and analysis of past projects; standardization of methods Developing the wrong software functions Developing the wrong user interface Improved software evaluation; formal specification methods; user surveys; prototyping; early user manuals Prototyping; task analysis; user involvement Brainstorming: Representatives of the main stakeholders can e bought together, ideally, once some kind of preliminary plan has been drafted then identifies using their individual knowledge of different parts of the project, the particular problem that might occur. Brainstorming can also been used to identify the possible solution to the problems that emerge. One useful outcome of such an approach is that we collaborative approaches may generate the sense of owner ship in the project. 233

234 The process that is beneficial explicitly asked stakeholders about their anxieties and then explores way of reducing those concerns. Casual mapping: The idea here is to get the major stakeholders together and to brainstorm collectively the things that could go wrong. The causes of the problems identified are traced back using the mapping technique which identifies the project factors ( or concept variables ) that people see as being important and the causal links between them. These links can be positive or negative. Where possible, for each factor, positive and negative aspects are identified e.g. stable unstable requirements. 234

235 Once a causal map has been drawn up identifying possible negative outcomes and their causes, the map can be modified to introduce policies or interventions which should reduce or mitigate the effects of the negative outcomes. Often a risk reduction activity can actually introduce new risks. The use of consultants to offset the effects of skill shortages is an example of this. Causal mapping can help identify such adverse side-effects. Risk assessment: The common problem with risk identification, particularly for the more anxious, is that a list of risk is potentially endless. Some way is therefore needed of distinguishing the more damaging and likely risks. This can be done by estimating the risk exposure for each risk using the formula: Risk exposure (RE) = (potential damage) x (probability of occurrence) If there were 100 people chipping in $5,000 each, there would be enough for the 1 in 100 chance of the flooding. If there were 2 floods then the system collapses! Risk planning: Risks can be dealt with by: Risk acceptance the cost of avoiding the risk may be greater than the actual cost of the damage that might be inflicted Risk avoidance avoid the environment in which the risk occurs e.g. buying an OTS application would avoid a lot of the risks associated with software development e.g. poor estimates of effort. Risk reduction the risk is accepted but actions are taken to reduce its likelihood e.g. prototypes ought to reduce the risk of incorrect requirements Risk transfer the risk is transferred to another person or organization. The risk of incorrect development estimates can be transferred by negotiating a fixed price contract with an outside software supplier. Risk mitigation tries to reduce the impact if the risk does occur e.g. taking backups to allow rapid recovery in the case of data corruption Evaluate the risks with PERT technique 1. Applying the PERT Technique: 235

236 Activity Optimistic Most likely Pessimistic Expected Standard deviation The method is very similar to the CPM technique but instead of using a single estimate for the duration of each tack, pert requires three estimates. Most likely time (m) the time we would expect the task to take normally Optimistic time (a) the shortest time could be realistically be expected Pessimistic (b) worst possible time (only 1% chance of being worse, say) Some straightforward activities might have little uncertainty and therefore have a low standard deviation, while others have more uncertainty and would have a bigger standard deviation. Pert then combines these three estimates to form a single expected duration using the formula: expected time t e = (a + 4m +b) / 6 A quantitative measure of the degree of uncertainity of activity duration estimate may be obtained by calculating the standard deviation S of an activity time using the formula: activity standard deviation S = (b-a)/6 236

237 (a) (m) (b) (te) (s) A B C D E F G H The PERT technique uses the following three step method for calculating the probability of meeting or missing a target date: Calculate the standard deviation of each project event; Calculate the z value for each event that has a target date; Convert z values to a probabilities. 237

238 Calculate the z value thus z = (T t e )/s Where te is the expected date and the T the target date. The z value for event 4 is ( )/0.53= There is about a 17% chance of not meeting the target of 52 days. 238

239 Sem V Core Course V Computer Graphics & Multimedia (RCCS10CA7) Unit I Overview of graphics systems: Video display devices Raster-scan systems Random-scan systems Graphics monitors and workstation Inputdevices Hard-copy devices Graphics software. Unit II Output primitives: Points and lines Line-drawing algorithms DDA algorithm Bresenham s line algorithm Attributes of output primitives: Line attributes Area-fill attributes Character attributes Bundled attributes. Unit III Two-dimensional Geometric transformations: Basic transformations Matrix representations Composite transformations Other transformations. Unit IV Multimedia in Use : Introducing Multimedia for Today and Tommorrow What is Multimedia using Multimedia: Applications, Benefits and Problems Technology : System Components Multimedia Platforms. Unit V Technology: Development Tools Image Audio Video. Text Books: 1. Computer Graphics C Version Second Edition, Donald Hearn and M.Pauline Baker, Pearson Education, Multimedia in Practice : Technology and Practice.Judith Jeffcoate, Pearson Education, Reference Books: 1. William M. Neuman, Robert R. Sprout, Principles of interactive Computer Graphics, McGraw Hill International Edition. 2.Buford J. F Koegel, Multimedia Systems, Twelfth Indian Reprint, Pearson Education 239

240 Unit - I Refresh CRT. One way to keep the phosphor glowing is to redraw the picture repeatedly by quickly directing the electron beam back over the same points. This type of display is called a refresh CRT. Resolution. The maximum number of points that can be displayed without overlap on a CRT is referred to as the resolution. Persistence. Persistence is defined as the time it takes the emitted light from the screen to decay to one-tenth of its original intensity. Although some phosphors have a persistence greater than 1 second, Graphics monitors are usually constructed with persistence in the range from 10 to 60 microseconds. Aspect Ratio. Another property of video monitors is aspect ratio. This number gives the ratio of vertical points to horizontal points necessary to produce equal length lines in both directions on the screen. X=Vertical points/horizontal points; An aspect ratio of 3/4 means that a vertical line plotted with three points has the same length as a horizontal line plotted with four points. Refresh Buffer. Picture definition is stored in a memory area called the refresh buffer or frame buffer. This memory area holds the set of intensity values for all the screen points. Stored intensity values are then retrieved from the refresh buffer and "painted" on the screen one row (scan line) at a time. Each screen point is referred to as a pixel or pel. Bitmap & Pixmap. On a black-and-white system with one bit per pixel, the frame buffer is commonly called a bitmap. For systems with multiple bits per pixel, the frame buffer is often referred to as a pix map. Input devices. Key board Mouse Scanner Touch Screen 240

241 Joy Stick Light pen Track ball Optical Character Reader(OCR) Optical Mark Reader(OMR) Magnetic Ink Character Reader(MICR) Barcode Reader Digital Camera & Tablets Output Devices. Monitors Plotter Printer Run length Encoding. One number of each pair indicates an intensity value, second number specific the number of adjacent pixels, this technique is called as run length encoding. Work Station. Work Station is nothing but a System. It cannot be Stored in Memory or System and to Store only in Server. Raster-Scan Display. Procedure: o The most common type of graphics monitor employing a CRT is the rasterscan display, based on television technology. o In a raster-scan system, the electron beam is swept across the screen, one row at a time from top to bottom. As the electron beam moves across each row, the beam intensity is turned on and off to create a pattern of illuminated spots. o The capability of a raster-scan system to store intensity information for each screen point makes it well suited for the realistic display of scenes containing subtle shading and color patterns. Stored intensity values are then retrieved from the refresh buffer and "painted" on the screen one row (scan line) at a time. o Refreshing on raster-scan displays is carried out at the rate of 60 to 80 frames per second, although some systems are designed for higher refresh rates. Sometimes, refresh rates are described in units of cycles per second, or Hertz (Hz), where a cycle corresponds to one frame. Using these units, we would describe a refresh rate of 60 frames per second as simply 60 Hz. 241

242 o Interlacing of the scan lines in this way allows us to see the entire screen displayed in one-half the time it would have taken to sweep across all the lines at once from top to bottom. Interlacing is primarily used with slower refreshing rates. Example: Home television sets and printers are examples of other systems using raster-scan methods. Refresh buffer or Frame buffer: Picture definition is stored in a memory area called the refresh buffer or frame buffer. This memory area holds the set of intensity values for all the screen points. Each screen point is referred to as a pixel or pel. BIT MAP & PIX MAP: On a black & white system with one bit per pixel, the frame buffer is commonly called a bitmap. For systems with multiple bits per pixel, the frame buffer is often referred to as a pix map. Random-Scan Display. When operated as a random-scan display unit, a CRT has the electron beam directed only to the parts of the screen where a picture is to be drawn. Random scan monitors draw a picture one line at a time and for this reason are also referred to as vector displays (or stroke-writing or calligraphic displays). The component lines of a picture can be drawn and refreshed by a random-scan system. Refresh rate on a random-scan system depends on the number of lines to be displayed. Picture definition is now stored as a set of line drawing commands in an area of memory referred to as the refresh display file. Sometimes the refresh display file is called the display list, display program, or simply the refresh buffer. Random-scan displays are designed to draw all the component lines of a picture 30 to 60 times each second. High quality vector systems are capable of handling approximately 100,000 "short" lines at this refresh rate. When a small set of lines is to be displayed, each refresh cycle is delayed to avoid refresh rates greater than 60 frames per second. Otherwise, faster refreshing of the set of lines could burn out the phosphor. Random-scan systems are designed for line drawing applications and cannot display realistic shaded scenes. Since picture definition is stored as a set of line drawing instructions and not as a set of intensity values for all screen points, vector displays generally have higher resolution than raster systems. Also, vector displays produce smooth line drawings because the CRT beam directly follows the line path. A raster system, in contrast, produces jagged lines that are plotted as the point sets. 242

243 A pen plotter operates in a similar way and is an example of a random-scan, hard- Example: copy device. Direct View Storage Tubes. An alternative method for maintaining a screen image is to store the picture information. Inside the CRT instead of refreshing the screen. A direct-view storage tube (DVST) stores the picture information as a charge distribution just behind the phosphor-coated screen. Two electron guns are used in a DVST. One, the primary gun, is used to store the picture pattern; the second, the flood gun, maintains the picture display. DVST Types: Primary gun; Flood gun; Advantages: Because no refreshing is needed, very complex pictures can be displayed at very high resolutions without flicker. Disadvantages: Disadvantages of DVST systems are that they ordinarily do not display color and that selected parts of a picture cannot he erased. To eliminate a picture section, the entire screen must be erased and the modified picture redrawn. The erasing and redrawing process can take Several seconds for a complex picture. Two methods of Color CRT Monitors. A CRT monitor displays color pictures by using a combination of phosphors that Emitted different-colored light. By combining the emitted light from the different phosphors, a range of colors can be generated. The two basic techniques for producing color displays with a CRT are, The Beam-penetration method and The Shadow-mask method. The Beam-penetration method: The beam-penetration method for displaying color pictures has been used with random-scan monitors. Two layers of phosphor, usually red and green, are A random-scan system draws the component lines of an object in any order specified coated onto the inside of the CRT screen, and the displayed color depends on how far the electron beam penetrates into the phosphor layers. A beam of slow electrons excites only the outer red layer. A beam of very fast electrons penetrates through the red layer and excites the inner green layer. At intermediate beam speeds, combinations of red and green light are emitted to show two additional colors, 243

244 orange and yellow. The speed of the electrons, and hence the screen color at any point, is controlled by the beam-acceleration voltage. Beam penetration has been an inexpensive way to produce color in random-scan monitors, but only four colors are possible, and the quality of pictures is not as good as with other methods. Shadow-mask method: Shadow-mask methods are commonly used in raster scan systems (including color TV) because they produce a much wider range of color than the beam penetration method. A shadow-mask CRT has three phosphor color dots at each pixel position. One phosphor dot emits a red light, another emits a green light, and the third emits a blue light. This type of CRT has three electron guns, one for each color dot, and a shadow-mask grid just behind the phosphor-coated screen. The delta shadow-mask method, commonly used in Color CRT systems. Three electron guns, aligned with the triangular color dot patterns on the screen,are directed to each dot triangle by a shadow mask. Another configuration for the three electron guns is an in-line arrangement in which the three electron guns, and the Corresponding redgreen-blue color dots on the screen, are aligned along one scan line instead of in a triangular pattern. By turning off the red and green guns, we get only the color coming the blue phosphor. A white (or gray) area is the result of activating all three dots with equal intensity. Yellow is produced with the green and red dots only, magenta is produced with the blue and red dots, and cyan shows up when blue and green are activated equally. In some low-cost systems, the electron beam can only be set to on or off, limiting displays to eight colors. Color CRTs in graphics systems are designed as RGB monitors. These monitors use shadow-mask methods and take the intensity level for each electron gun (red, green, and blue) directly from the computer system without any intermediate processing. High-quality rastergraphics systems have 24 bits per pixel in the same buffer, allowing 256 voltage settings for each electron gun and nearly 17 million color choices for each pixel. An RGB color system with 24 bits of storage per pixel is generally referred to as a full-color system or a true-color system. Output Devices. Monitors Printers Plotters Monitors: o There are two types Black and White screen and color screen. o The screen size will be 24 lines,80 columns and using text, character, images etc Printers & Plotters: Printers produce output by either impact or nonimpact methods. Impact Printers press formed character faces against an inked ribbon onto the paper. A Line printer is an example of an 244

245 impact device, with the typefaces mounted on bands, chains, drums, or wheels. Non impact printers and plotters use laser techniques, Ink-jet sprays, xerographic presses (as used in photocopying machines), electrostatic methods, and electro thermal methods to get images onto Paper. Character impact printers often have a dot-matrix print head containing a rectangular array of producing wire pins, with the number of pins depending on the quality of the printer. Electro thermal methods use heat in a dot matrix Print head to output patterns on heat sensitive paper. We can get limited color output on an impact printer by using different colored ribbons. Nonimpact devices use various techniques to combine three Color pigments (cyan, magenta, and yellow) to produce a range of color patterns. Laser and xerographic devices deposit the three pigments on separate passes; Ink-jet methods shoot the three colors simultaneously on a single pass along each print tine on the paper. Ink-jet methods produce output by squirt in ink in horizontal rows across a roll of paper wrapped on a drum. The electrically charged ink stream is deflected by an electric field to produce dot-matrix patterns. Three Dimensional Viewing Devices: Graphics monitors for the display of three-dimensional scenes have been devised using a technique that reflects a CRT image from a vibrating, flexible mirror. The operation of such a system. As the mirror vibrates, it changes focal length. These vibrations are synchronized with the display of an object on a CRT so that each point on the object is reflected from the mirror into a spatial position corresponding to the distance of that point from a specified viewing position. This allows us to walk around an object or scene and view it from different sides, which uses a vibrating mirror to project three-dimensional objects into a 25cm by 25cm by 25cm volume. This system is also capable of displaying two-dimensional cross-sectional "Slices" of objects selected at different depths. w Timing control system Projected 3D Images. CRT Vibrating Flexible Mirror Such systems have been used in medical applications to analyze data from ultrasonography and CAT scan devices, in geological applications to analyze topological and seismic data, in design 245

246 applications involving solid objects, and in three-dimensional simulations of systems, such as molecules and terrain. Stereoscopic and Virtual-Reality System. Another technique for representing 3dimensional objects is displaying stereoscopic views. This method does not produce have three-dimensional images, but it does provide a threedimensional effect by presenting a different view to each eye of an observer so that scenes do appear to have depth. To obtain a stereoscopic projection, we first need to obtain two views of a scene generated from a viewing direction corresponding to each eye (left and Right). When we simultaneous look at the left view with the left eye and the right view with the right eye, the views merge into a single image and we perceive a scene with depth in two views of a computer generated scene for stereoscopic. To increase viewing comfort, the areas at the left and right edges of scene that are visible to only one eye have been eliminated. One way to produce a stereoscopic effect is to display each of the two views with a raster system on alternate refresh cycles. The viewed through Display Devices glasses, with each lens designed to act as a rapidly alternating shutter that is synchronized to block out one of the views shows a pair of stereoscopic glasses constructed with liquid crystal shutters and an infrared emitter that synchronizes the glasses with the views on the screen. Stereoscopic viewing is also a component in virtual-reality systems, where users can step into a scene and interact with the environment. Interacting with a virtual-reality environment "walks through" and interacts with the display interaction with a virtual scene, using a headset and a data glove worn on the right hand. An interactive virtual-reality environment can also be viewed with stereoscopic glasses and a video monitor, instead of a headset. This provides a means for obtaining a lower cost virtual-reality system. Raster-Scan System. Interactive raster graphics systems typically employ several processing units. In addition to the central processing unit, or CPU, a special-purpose processor, called the video controller or display controller, is used to control the operation of the display device. Organization of a simple raster system. Here, the frame buffer can be anywhere in the system memory, and the video controller accesses the frame buffer to refresh the screen. In addition to the video controller, more sophisticated raster systems employ other processors as coprocessors and accelerators to implement various graphics operations. The origin of the coordinate system for identifying screen positions is usually specified in the lower-left corner. Origin is defined at the lower left screen comer. The screen surface is then represented as the first quadrant of a two-dimensional system, with positive x values increasing to the right and positive y values increasing from bottom to top. (On some personal computers, the coordinate origin is referenced at the upper left comer of the screen, so the y 246

247 values are inverted.) Scan lines are then labeled from y, at the top of the screen to 0 at the bottom. Along each scan line, screen pixel positions are labeled from 0 to x. In the basic refresh operations of the video controller. A fixed area of the system memory is reserved for the frame buffer, and the video controller is given direct access to the frame-buffer memory. Framebuffer locations, and the corresponding screen positions, are referenced in Cartesian coordinates. Two registers are used to store the coordinates of the screen pixels. Initially, the x register is set to 0 and the y register is, set to the value stored in the frame buffer for this pixel position is then retrieved and used to set the intensity of the CRT beam. Then the x register is incremented by 1, and the process repeated for the next pixel on the top scan line. This procedure is repeated for each pixel along the scan line. After the last pixel on the top scan line has been processed, the x register is reset to 0 and the y register is decremented by 1. CPU System Memory Video Controller System Bus I/O Devices Architecture of a raster-graphics system with a display processor controller can retrieve pixel intensities from different memory areas on different refresh cycles. In high quality systems, for example, two frame buffers are often provided so that one buffer can be used for refreshing while the other is being filled with intensity values. Then the two buffers can switch roles. This provides a fast mechanism-for generating real-time animations, since different views of moving objects can be successively loaded in to the refresh buffers. Also, some transformations can be accomplished by the video controller. Areas of the screen can be enlarged, reduced, or moved from one location to another during the refresh cycles. In addition, the video controller often contains a lookup table, so that pixel values in the frame buffer are used to access the lookup table instead of controlling the CRT beam intensity directly. This 247

248 provides a fast method for changing screen intensity values. Finally, some systems are designed to allow the video controller to mix the frame-buffer image with an input image from a television camera or other input device. Horizontal and Vertical Deflection Voltages Raster-Scan Generator Register Register Memory Address Pixel Register Frame Buffer Raster-Scan Display Process one way to set up the organization of a raster system containing a separate display processor, sometimes referred to as a graphics controller or a display coprocessor. The purpose of the display processor is to free the CPU from the graphics chores. In addition to the system memory, a separate display processor memory area can also be provided. The array size for character grids can vary from about 5 by 7 to 9 by 12 or more for higher-quality displays. A major task of the display processor is digitizing a picture definition given in an application program into a set of pixel-intensity values for storage in the frame buffer. This digitization process is cailed scan conversion. Graphics commands specifying straight lines and other geometric objects are scan converted A character defined as a in to a set of discrete intensity points. Scan converting a straight-line segment, for rectangular grid of pixel example, means that we have to locate the pixel positions closest to the line path positions and store the intensity for each position in the frame buffer. Similar methods are used for scan converting curved lines and polygon outlines. Characters can be defined with rectangular grids or they can be defined with curved 5 outlines. Disadvantages: The disadvantages of encoding runs are that intensity changes are difficult to make and storage requirements actually increase as the length of the runs decreases 248

249 Random-Scan Display. The organization of a simple random-scan (vector) system. An application program is input and stored in the system memory along with a graphics package. Graphics commands in the application program are translated by the graphics package into a display file stored in the system memory. This display file is then accessed by the display processor to refresh the screen. The display processor cycles through each command in the display file program once during every refresh cycle. Sometimes the display processor in a random-scan system is referred to as a display processing unit or a graphics controller. CPU System Memory System Bus I/O Devices Video Controller Monitor Architecture of a simple random scan system. Graphics patterns are drawn on a randomscan system by directing the electron beam along the component lines of the picture. Lines are defined by the Graphics Monitors values for their coordinate endpoints, and these input coordinate values are con- and Workstations vertex to x and y deflection voltages. A scene is then drawn one line at a time by positioning the beam to fill in the line between specified endpoints. Video Display Devices. The primary output device in a graphics system is a video monitor. The operation of most video monitors is based on the standard cathode-ray tube (CRT) design, but several other technologies monitors. Construction: CRT tube will be covered by cylindrical cathode. The end position has phosphor sealed or coated screen. In phosphor screen having two edges outer & inner edges. Electrons are travel through electron beam. Connector pins, Electron gun, focusing screen and Magnetic deflection coils are used. Vertical & Horizontal plates are fixed in CRT tube. Magnetic-Deflection CRT Focusing Magnetic Deflection Base System Coil Phosphor-coated Screen 249

250 Connector Electron Electron Beam Pins Gun Procedure: A beam of electrons (cathode rays) emitted by an electron gun, passes through focusing and deflection systems that direct the beam toward specified positions on the phosphor coated screen. The phosphor then emits a small spot of light at each position contacted by the electron beam. Because the light emitted by the phosphor fades very rapidly, some method is needed for maintaining the screen picture. Heat is supplied to the cathode by directing a current through a coil of wire, called the filament, inside the cylindrical cathode structure. In the vacuum inside the CRT envelope, the free, negatively charged electrons are then accelerated toward the phosphor coating by a high positive voltage. A high negative voltage applied to the control grid will shut off the beam by repelling electrons and stopping them from passing through the small hole at the end of the control grid structure. A smaller negative voltage on the control grid simply decreases the number of electrons passing through. Since the amount of light emitted by the phosphor coating depends on the number of electrons striking the screen. Cathode Accelerating anode Focusing Anode Electron Beam path Heating Filament Cathode Accelerating Anode Focusing is accomplished with either electric or magnetic fields. Electrostatic focusing is commonly used in television and computer graphics monitors. With 250

251 electrostatic as the beam moves to the outer edges of the screen, displayed images become blurred. Two pairs of coils are used, with the coils in each pair mounted on opposite sides of the neck of the CRT envelope. One pair is mounted on the top and bottom of the neck and the other pair is mounted on opposite sides of the neck. The magnetic, field produced by each pair of coils results in a transverse deflection force that is perpendicular both to the direction of the magnetic field and to the direction of travel of the electron beam. Horizontal deflection is accomplished with one pair of coils, and vertical deflection by the other pair. The proper deflection amounts are attained by adjusting the current through the coils. When electrostatic deflection is used, two pairs of parallel plates are mounted inside the CRT envelope. One pair of plates is mounted horizontally to control the vertical deflection, and the other pair is mounted vertically to control horizontal deflection. Refresh CRT: One way to keep the phosphor glowing is to redraw the picture repeatedly by quickly directing the electron beam back over the same points. This type of display is called a refresh CRT. Resolution: The maximum number of points that can be displayed without overlap on a CRT is referred to as the resolution. Persistence: Persistence is defined as the time it takes the emitted light from the screen to decay to one-tenth of its original intensity. Although some phosphors have persistence greater than 1 second, Graphics monitors are usually constructed with persistence in the range from 10 to 60 microseconds. Aspect Ratio: Another property of video monitors is aspect ratio. This number gives the ratio of vertical points to horizontal points necessary to produce equal length lines in both directions on the screen. X=Vertical points/horizontal points ; An aspect ratio of 3/4 means that a vertical line plotted with three points has the same length as a horizontal line plotted with four points. Flat-Panel Display. Although most graphics monitors are still constructed with CRTs, other technologies Are emerging that may soon replace CRT monitors. The term Bat-panel display refers to a class of video devices that have reduced volume, weight, and power requirements compared to a CRT. A significant feature of flat-panel displays is that they are thinner than CRTs, and we can hang 251

252 them on walls or wear them on our wrists. Since we can even write on some flat-panel displays, they will soon be available as pocket notepads. Current uses for flat-panel displays include small TV monitors, calculators, pocket video games, laptop computers, armrest viewing of movies on airlines, as advertisement boards in elevators, and as graphics displays in applications requiring rugged, portable monitors. We can separate flat-panel displays into two categories: Emissive displays and Non Emissive displays. Emissive displays:- The emissive displays (or emitters) are devices that convert electrical energy into light. Plasma panels, thin-film electroluminescent displays, and Light-emitting diodes are examples of emissive displays. Flat CRTs have also been devised, in which electron beams arts accelerated parallel to the screen, then deflected 90' to the screen. But flat CRTs have not proved to be as successful as other emissive devices. Non Emissive displays:- Non Emissive displays (or non emitters) use optical effects to convert sunlight or light from some other source into graphics patterns. The most important example of a non emissive flat-panel display is a liquid-crystal device. Plasma-Panel: Plasma panels, also called gas-discharge displays, are constructed by filling the region between two glass plates with a mixture of gases that usually in 2 dude s neon. A series of vertical conducting ribbons is placed on one glass panel, and a set of horizontal ribbons is built into the other glass panel. Firing voltages applied to a pair of horizontal and vertical conductors cause the gas at the intersection of the two conductors to break down into glowing plasma of electrons and ions. Picture definition is stored in a refresh buffer, and the firing voltages are applied to refresh the pixel positions (at the intersections of the conductors) 60 times per second. Alternating-methods are used to provide faster application of the firing voltages, and thus brighter displays. Separation between pixels is provided by the electric field of the conductor shows a high definition plasma panel. Disadvantage: Plasma Panels has been that they were strictly monochromatic devices, but systems have been developed that are now capable of displaying color and grayscale. 252

253 CONDUCTOR Horizontal plate Glass plate Vertical plate Glass plate Thin-Film Electroluminescent Display: o Thin-film electroluminescent displays are similar in construction to a plasma panel. The difference is that the region between the glass plates is filled with a phosphor, such as zinc sulfide doped with manganese, instead of a gas. When a high voltage is applied to a pair of crossing electrodes, the phosphor becomes a conductor in the area of the intersection of the two electrodes. Electrical energy is then absorbed by the manganese atoms, which then release the energy as a spot of light similar to the glowing plasma effect in a plasma panel. o Electroluminescent displays require more power than plasma panels, and good color and gray scale displays are hard to achieve. A third type of emissive device is the lightemitting diode (LED). A matrix of diodes is arranged to form the pixel positions in the display, and picture definition is stored in a refresh buffer. As in xan-line refreshing of a CRT, information. o A plasma-panel display with a resolution of 2048 by 2048 and a screen diagonal of 1.5 meters. Basic design of a thin-film electroluminescent display device is read from the refresh buffer and converted to voltage levels that are applied to small systems. Liquid-Crystal Display: o These Non-Emissive devices produce a picture by passing polarized light from the surroundings or from an internal light s through a liquid-crystal material that can be aligned to either block or transmit the light, such as calculators and portable laptop computers. 253

254 o The term liquid crystal refers to the fact that these compounds have a crystalline arrangement of molecules, yet they flow like a liquid. Flat-panel displays commonly use nematic (threadlike) liquid-crystal compounds that tend to keep the long axes of the rod-shaped molecules aligned. A flat-panel display can then be constructed with a nematic liquid crystal. Two glass plates, each containing a light polarizer at right angles to the-other plate, sandwich the liquid-crystal material. Rows of horizontal transparent conductors are built into one glass plate, and columns of vertical conductors are put into the other plate. The intersection of two conductors defines a pixel position. o Normally, the molecules are aligned as shown in the "on state". Polarized light passing through the material is twisted so that it will pass through the opposite polarizer. The light is then reflected back to the viewer. To turn off the pixel, we apply a voltage to the two intersecting conductors to align the molecules so that the light is not twisted. This type of flat-panel device is refferred to as a passive-matrix LCD. Picture definitions are stored in a refresh buffer, and the screen is refreshed at the rate of 60 frames per second, as in the emissive devices. o A hand calculator with an Back lighting is also commonly applied using solidstate electronic devices, so that the system is not completely dependent on outside light be displayed by using different materials or dyes and by placing a triad of color pixel set each &screen location. Another method for constructing LCD s is to place a transistor at each pixel location, using thin-film transistor technology. The transistors are used to control the voltage at pixel locations and to prevent charge from gradually leaking out of the liquid-crystal cells. These devices are called active-matrix displays. Input Devices. Various devices are available for data input on graphics workstations. Most system have a keyboard and one or more additional devices specially designed for interactive input. These include a mouse, trackball, space ball, joystick, digitizers, dials, and button boxes. Some other input devices in particular applications are data gloves, touch panels, image scanners, and voice systems. Keyboard: a) An alpha numeric keyboard on a graphics system is used primarily as a device for entering text strings. The keyboard is an efficient device for inputting such non graphic data as picture labels associated with a graphics display. Keyboards can also be provided with features to facilitate entry of screen coordinates, menu selections, 254

255 or graphics functions. Cursor-control keys and function keys are common features on general purpose keyboards. b) Function keys allow users to enter frequently used operations in a single keystroke, and cursor-control keys can be used to select displayed objects or coordinate positions by positioning the screen cursor. Other types of cursor-positioning devices, such as a trackball or joystick, are included on some keyboards. Additionally, a numeric keypad is, often included on the keyboard for fast entry of numeric data. c) For specialized applications, input to a graphics application may come from a set of buttons, dials, or switches that select data values or customized graphics operations an example of a button box and a set of input dials. Buttons and switches are often used to input predefined functions, and dials are common devices for entering scalar values. Real numbers within some defined range are selected for input with dial rotations. Potentiometers are used to measure dial rotations, which are then converted to deflection voltages for cursor movement. Mouse: a) A mouse is small hand-held box used to position the screen cursor. Wheels or rollers on the bottom of the mouse can be used to record the amount and directly designed keyboard with removable palm rests. Another method for detecting mouse motion is with an optical sensor. For these systems, the mouse is moved over a special mouse pad that has a rid of horizontal and vertical lines. The optical sensor detects movement across the lines in the grid. Since a mouse can be picked up and put down at another position without range in cursor movement, it is used for making relative change in the position of the screen cursor. One, two, or three buttons usually included on the top of the mouse for signaling the execution of some operation, such as recording position or invoking a function. Mast general-purpose graphics systems now include a mouse and a keyboard as the major input devices. b) Additional devices can be included in the basic mouse design to increase the number of allowable input parameters. The 2 mouse features three buttons, a mouse ball underneath, a thumbwheel on the side, and a track ball on top three buttons, a thumbwheel on the side, a trackball on the top, and a standard mouse ball underneath. This design provides six degrees of freedom to select Input Devices spatial positions, rotations, and other parameters up an object, rotate it, and move it in any direction, or we can navigate our viewing position and orientation through a three dimensional scene. Applications of the Z mouse include virtual reality, CAD, and animation. Trackball and Space ball: As the name implies, a trackball is a ball that can be rotated with the fingers or palm of the hand, as to produce screen-cursor movement. Potentiometers, attached to the ball, measure the amount and direction of rotation. Trackballs are often mounted on keyboards or other devices such as the Z mouse. While a trackball is a two-dimensional positioning device, a space 255

256 ball provides six degrees of freedom. Unlike the trackball, a space ball does not actually move. Strain gauges measure the amount of pressure applied to the space ball to provide input for spatial positioning and orientation as the ball is pushed or pulled in various directions. Space balls are used for three-dimensional positioning and selection operations in virtual-reality systems, modeling, animation, CAD, and other applications. Joystick: A joystick consists of a small, vertical lever (called the stick) mounted on a base that is used to steer the screen cursor around. Most joysticks select screen positions with actual stick movement; Some joysticks are mounted on a keyboard; The distance that the stick is moved in any direction from its center position corresponds to screen-cursor movement in that direction. Potentiometers mounted at the base of the joystick measure the amount of movement, and springs return the stick to the center position when it is released. One or more buttons can be programmed to act as input switches to signal certain actions once a screen position has been selected. In another type of movable joystick, the stick is used to activate switches that cause the screen cursor to move at a constant rate in the direction selected. Eight switches, arranged in a circle, are sometimes provided, so that the stick can select any one of eight directions for cursor movement. Pressure sensitive joysticks, also called isometric joysticks, have a non movable stick. Pressure on the stick is measured with strain gauges and converted to movement of the cursor in the direction specified. Data Glove: Data glove that can be used to grasp a "virtual" object. The glove is constructed with a series of sensors that detect hand and finger motions. Electromagnetic coupling between transmitting antennas and receiving antennas is used to provide information about the position and orientation of the hand. The transmitting and receiving antennas can each be structured as a set of three mutually perpendicular coils, forming a three-dimensional Cartesian coordinate System. Input from the glove can be used to position or manipulate objects in a virtual scene. A two-dimensional proportion of the scene can be viewed on a video monitor, or a threedimensional projection can be viewed with a headset. Digitizer: A common device for drawing, painting, or interactively selecting coordinate positions on an object is a digitizer. These devices can be used to input coordinate values in either a twodimensional or a three-dimensional space. Typically, a digitizer is used to scan over a drawing or object and to input a set of discrete coordinate positions, which can be joined with straight-line segments to approximate the curve or surface shapes. One type of digitizer is the graphics tablet (also referred to as a data tablet), which is used to input two-dimensional coordinates by activating a hand cursor or stylus at selected positions on a flat surface. A hand cursor contains cross hairs for sighting positions, while a stylus is a pencil-shaped device that is pointed. 256

257 A virtual-reality, displayed on a two-dimensional video monitor, with input from a data glove a d a space ball of desktop and floor-model tablets, using 2,4, or 16 buttons. This allows an artist to produce different brush strokes with different pressures on the tablet surface. Tablet size varies from 12 by 12 inches for desktop models to 44 by 60 inches or larger for floor models. Graphics tablets provide a highly accurate method for selecting coordinate positions, with an accuracy that varies from about 0.2 mm on desktop models to about 0.05 mm or less on larger models. Many graphics tablets are constructed with a rectangular grid of wires embedded in the tablet surface. Electromagnetic pulses are generated in sequence along the wires, and an electric signal is induced in a wire coil in an activated or hand cursor to record a tablet position. Depending on the technology, signal strength, coded pulses, or phase shifts can be used to determine the position on the tablet. Three-dimensional digitizers use sonic or electromagnetic transmissions to word positions. One electromagnetic transmission method is similar to that used in the data glove: A coupling between the transmitter and receiver is used to compute the location of a stylus as it moves over the surface of an object. As the points are selected on a non metallic object, a wire frame outline of the surface is displayed on the computer screen. Once the surface outline is constructed, it can be shaded with lighting effects to produce a realistic display of the object. Resolution of this system is 0.8 mm to 0.08 mm, depending on the model. Image Scanner: Drawings, graphs, color and black-and-white photos, or text can be stored for computer processing with an image scanner by passing an optical scanning mechanism over the information to be stored. The gradations of grey scale or color are then recorded and stored in an array. Once we have the internal representation of a picture, we can apply transformations to rotate, scale, or crop the picture to a particular screen area. We can also apply various imageprocessing methods to modify the array representation of the picture. For scanned text input, various editing operations can be performed on the stored documents. Some scanners are able to scan either graphical representations or text, and they come in a variety of sizes and capabilities. Touch Panel: As the name implies, touch panels allow displayed objects or screen positions to be selected with the touch of a finger. A typical application of touch panels is for the selection of processing options that are represented with graphical icons. Some systems, are designed with touch screens. Other systems can be adapted for touch input by fitting a transparent device with a touch sensing mechanism over the video monitor screen. Touch input can be recorded using optical, electrical, or acoustical methods. Optical touch panels employ a line of infrared light-emitting diodes (LEDs) along one vertical edge and along one horizontal edge of the frame. The opposite vertical and horizontal edges contain light detectors. These detectors are used to record which beams are interrupted when the panel is touched. 257

258 Voice System: Speech recognizers are used in some graphics workstations as input devices to accept voice commands The voice-system input can be used to initiate graphics A light pen activated with a button switch operations or to enter data. These systems operate by matching an input are predefined dictionary of words and phrase. A dictionary is set up for a particular operator by having, the operator speak the command words to be used into the system. Each word is spoke Several times, and the system analyzes the word and establishes a frequency pattern for that word in the dictionary along with the corresponding function to be performed. Later, when a voice command is given, the system searches the dictionary for a frequency-pattern match. Voice input is typically spoken into a microphone mounted on a headset. The microphone is designed to minimize input of other background sounds. If a different operator is to use the system, the dictionary must be re-established with that operator's voice patterns. Voice systems have some advantage over other input devices, since the attention of the operator does not have to be switched from one device to another to enter a command. Graphics Monitors &Workstations. Most graphics monitors today operate as raster scan displays, and here we survey a few of the many graphics hardware configurations available. Graphics systems range having small general-purpose computer systems with graphics capabilities to sophisticated full color systems that are designed specifically for graphics applications. I. Apple Quadra: A desktop general-purpose computer system that can be used for graphics applications. Overview of Graphics Systems though screen resolution and other system capabilities vary depending on the size and cost of the system. Diagonal screen dimensions for general-purpose personal computer systems can range from 12 to 21 inches, and allowable color selections range from 16 to over 32,000. II. Workstation: It specifically designed for graphics applications, such as the systems are typical screen resolution is 1280 by 1024, with a screen diagonal of 16 inches or more. Graphics workstations can be configured with from 8 to 24 bits per pixel (full-color systems), with higher screen resolutions, faster processors, and other options available in high-end systems. Uses: It shows a high-definition graphics monitor used in applications such as air traffic control, simulation, medical imaging, and CAD. This system has a diagonal s c m size of 27 inches, resolutions ranging from 2048 by 1536 to 2560 by 2048, with refresh rates of 80 Hz or 60 Hz non interlaced. III. Media Wall: A multi system called the Media Wall, provides a large "wall-sized display area. This system is designed for applications that required large area displays in brightly lighted environments, such as at trade shows, conventions, retail stores, museums, or passenger 258

259 terminals. Media Wall operates by splitting images into a number of Sections and distributing the sections over an array of monitors or projectors using a graphics adapter and satellite control units. An array of up to 5 by 5 monitors, each with a resolution of 640 by 480, can be used in the Media Wall to provide an overall resolution of 3200 by 2400 for either static scenes or animations. Scenes can be displayed behind mullions, or the mullions can be eliminated to display a continuous picture with no breaks between the various sections. IV. Two Monitor: Many graphics workstations, such as some of those, are configured with two monitors. One monitor can be used to show all features of an scene, while the second monitor displays the detail in some part of the picture. V. Dual Monitor: Another use for dual-monitor systems is to view a picture on one monitor and display graphics options (menus) for manipulating the picture components on the other monitor. A very high-resolution (2560 by 2048) color monitor. A multi screen display system. The image displayed on this 3-by-3 array of monitors was created by Single- and dual-monitor graphics workstations. A typical setup for CAD applications in various keyboards, button boxes, tablets, and mice are attached to the video monitors for use in the design process shows features of some types of artist's workstations. Graphics Software. There are two general classifications for graphics software: General programming packages and Special-purpose applications packages. A general graphics programming package provides an extensive set of graphics functions that can be used in a high-level programming language, such as C or FORTRAN. An example of a general graphics programming package is the GL (Graphics Library) system on Silicon Graphics equipment. Basic functions in a general package include those for generating picture components (straight lines, polygons, circles, and other figures), setting color and intensity values, selecting views, and applying formations. By contrast, application graphics packages are designed for nonprogrammers, so that users can generate displays without worrying about how graphics operations work. The interface to the graphics routines in such packages allows users to communicate with the programs in their own terms. Examples of such applications packages are the artist's painting programs and various business, medical, and CAD systems. Special-purpose packages: It may allow use of other coordinate frames that are appropriate to the application. In general several different Cartesian reference frames are used to construct and display a scene. We can construct the shape of individual objects, such as trees or furniture, in a scene within 259

260 separate coordinate reference frames called modeling coordinates, or sometimes local coordinates or master coordinates. Coordinate Representatio: General graphics packages are designed to be used with Cartesian coordinate specifications. If coordinate values for a picture are specified in some other reference frame (spherical, hyperbolic, etc.), they must be converted to Cartesian coordinates before they can be input to the graphics package. Once individual object shapes have been specified, we can place the into appropriate positions within the scene using a reference frame called world coordinates. Finally, the worldcoordinate description of the scene is transferred to one or more output-device reference frames for display. These display coordinate systems are referred to as device coordinates or screen coordinates in the case of a video monitor. Modelling and world coordinate definitions allow us to set any convenient floating-point or integer dimensions without being hampered by the constraints of a particular output device. For some scenes, we might want to speedy object dimensions in fractions of a foot, while for other applications we might want to use millimeters, kilometers, or light-years. Generally, a graphics system first converts world-coordinate positions to normalized device coordinates, in the range from 0 to 1, before final conversion to specific device coordinates. This makes the system independent of the various devices that might be used at a particular workstation. The sequence of coordinate transformations from modeling coordinates to device coordinates for a two-dimensional application. An initial modeling-coordinate position (x,y) in this is transferred to a device coordinate position differences in scales and aspect ratios, normalized coordinates are mapped into a square area of the output device so that proper proportions are maintained. Graphics Functions: A general-purpose graphics package provides users with a variety of functions for creating and manipulating pictures. These routines can be categorized according to whether they deal with output, input, attributes, transformations, viewing, or general control. The basic building blocks for pictures am referred to as output primitives. They include character strings and geometric entities, such as points, straight lines, curved Lines, filled areas (polygons, circles, etc.), and shapes defined with arrays of color points. Routines for generating output primitives provide the basic tools for constructing pictures. Attributes are the properties of the output primitives; that is, an attribute describes how a particular primitive is to be displayed. They include intensity and color specifications, line styles, text styles, and area-filling patterns. Functions within this category can be used to set attributes for an individual primitive class or for groups of output primitives. We can change the size, position, or orientation of an object within a scene using geometric transformations. Similar modeling transformations are used to construct a scene using object descriptions given in modeling coordinates. Given the 260

261 primitive and attribute definition of a picture in world coordinates, a graphics package projects a selected view of the picture on an output device. Viewing transformations are used to specify the view that is to be presented and the portion of the output display area that is to be used. Pictures can be subdivided into component parts, called structures or segments or objects, depending on the software package in use. Each structure defines one logical unit of the picture. A scene with several objects could reference each individual object in a-separate named structure. The transformation sequence from modeling coordinates to device coordinates for a two dimensional scene Object, shapes. PHlGS Workstation: Generally, the tern workstation refers to a computer system with a combination of input and output devices that is designed for a single user. In PHIGS and GKS, however, the term workstation is used to identify various combinations of graphics hardware and software. A PHIGS workstation can be a single output device, a single input device, a combination of input and output devices, a file, or even a window displayed on a video monitor. To define and use various "workstations" within an applications program, we need to specify a workstation identifier and the workstation type. The following statements give the general structure of a PHlGS program: openphigs (error File, memory Size) open Workstation (ws, connection, type) {create and display picture} close Workstation (ws) closephigs Where parameter error File is to contain any error messages that are generated, and parameter memory Size specifies the size of an internal storage area. The workstation identifier (an integer) is given in parameter ws, and parameter connection states the access mechanism for the workstation. Parameter type specifies the particular category for the workstation, such as an input device, an output device, a combination out in device, or an input or output metafile. Any number of workstations can be open in n particular application, with input coming from the various open input devices and output directed to all the open output devices. 261

262 Unit - II Output primitives. The basic elements constituting a graphic are called output primitives. GRPH1 has the following output primitives. Types of lines. Polyline Polymarker Text Tone Line types indicate solid, dashed, and doted lines. The following line types are allotted to numbers 1 through 4. Solid Dashed Dotted Alternate long and short dash DDA Algorithm. The digital differential analyzer (DDA) samples the line at unit intervals in one coordinate corresponding integer values nearest the line path of the other coordinate. Bresenham s Line Algorithm. An accurate, efficient raster line drawing algorithm developed by Bresenham, scan converts lines using only incremental integer calculations that can be adapted to display circles and other curves. Keeping in mind the symmetry property of lines, lets derive a more efficient way of drawing a line. Attributes of Output Primitives. Any parameter that affects the way a primitive is to be displayed is referred to as an attribute parameter. Example attribute parameters are color, size etc. A line drawing function for example could contain parameter to set color, width and other properties. 1. Line Attributes 2. Area Fill Attributes 3. Character Attributes 4. Bundled Attributes Fill area primitive. 262

263 Options for filling a defined region include a choice between a solid colour or a pattern fill and choices for particular colours and patterns. Scaling and its types. Concatenating transformation matrices for two successive scaling operations produces the following composite scaling matrix There are two types of Scaling. They are * Uniform scaling * Non Uniform Scaling Reflection A reflection is a transformation that produces a mirror image of an object. The mirror image for a two-dimensional reflection is generated relative to an axis of reflection by We can choose an axis of reflection in the xy plane or perpendicular to the x, y plane or coordinate origin. Line Attributes: Basic attributes of a straight line segment are its type, its width, and its color. In some graphics packages, lines can also be displayed using selected pen or brush options * Line Type * Line Width * Pen and Brush Options * Line Color Line type: Possible selection of line type attribute includes solid lines, dashed lines and dotted lines. setlinetype(lt) Where parameter lt is assigned a positive integer value of 1, 2, 3 or 4 to generate lines that are solid, dashed, dash dotted respectively. Other values for line type parameter it could be used to display variations in dot-dash patterns. Line width: Implementation of line width option depends on the capabilities of the output device to set the line width attributes. setlinewidthscalefactor (lw) Line width parameter lw is assigned a positive number to indicate the relative width of line to be displayed. A value of 1 specifies a standard width line. A user could set lw to a value of 0.5 to plot a line whose width is half that of the standard line. Values greater than 1 produce lines thicker than the standard. Line Cap: 263

264 We can adjust the shape of the line ends to give them a better appearance by adding line caps There are three types of line cap. They are * Butt cap * Round cap * Projecting square cap Butt cap obtained by adjusting the end positions of the component parallel lines so that the thick line is displayed with square ends that are perpendicular to the line path. Round cap obtained by adding a filled semicircle to each butt cap. The circular arcs are centered on the line endpoints and have a diameter equal to the line thickness. Projecting square cap extend the line and add butt caps that are positioned one-half of the line width beyond the specified end points. Pen and Brush Options: With some packages, lines can be displayed with pen or brush selections. Options in this category include shape, size, and pattern. Line color: A poly line routine displays a line in the current color by setting this color value in the frame buffer at pixel locations along the line path using the set pixel procedure. Line drawing Algorithm: Design of Line and Circle Algorithms Basic Math Review 264

265 1. Line drawing is accomplished by calculating intermediate positions along the line path between specified end points. Precise definition of line drawing 2. Given two points P and Q in the plane, both with integer coordinates, determine which pixels on a raster screen should be on in order to make a picture of a unit-width line segment starting from P and ending at Q. 265

266 3. The thinnest line is of one-pixel wide. We will concentrate on drawing a line of 1 pixel resolution. The Cartesian slope-intercept equation for a straight line is m is the slope of the line and b is the y intercept. 4. The endpoints of a line segment. m = y2-y1 / x2-x1 b= y1 - m.x1 5 Also for any given interval x along a line, we can compute the corresponding y interval y from y = m. x 6. Similarly we can obtain the x interval x corresponding to a specified y as x = y / m 7. These equations form the basis for determining deflection voltages in analog devices. 8. Also, for any given x interval x along a line, we can compute the corresponding y interval y from y= m. x 9. These equations form the basis for determining deflection voltages in analog devices. 10. On Raster systems, lines are plotted with pixels, and step sizes in the horizontal and vertical directions are constrained by pixel separations. Hence we ought to sample a line at discrete positions and determine the nearest pixel to the line at each sampled position DDA Algorithm: The digital differential analyzer (DDA) samples the line at unit intervals in one coordinate corresponding integer values nearest the line path of the other coordinate. The following is thus the basic incremental scan-conversion(dda) algorithm for line drawing for x from x0 to x1 Compute y = mx+b Draw_fn(x, round(y)) Major deficiency in the above approach : Uses floats has rounding operations 266

267 Reflection & Shear. 1. Reflection 2. Shear Reflection: A reflection is a transformation that produces a mirror image of an object. The mirror image for a two-dimensional reflection is generated relative to an axis of reflection by We can choose an axis of reflection in the xy plane or perpendicular to the xy plane or coordinate origin Reflection of an object about the x axis Reflection axis as the diagonal line y = x To obtain transformation matrix for reflection about diagonal y=x the transformation sequence is 1. Clock wise rotation by Reflection about x axis 3. Counter clock wise by 45 0 Reflection about the diagonal line y = x is accomplished with the transformation matrix,reflection axis as the diagonal line y = -x To obtain transformation matrix for reflection about diagonal y = - x the transformation sequence is 267

268 1. Clock wise rotation by Reflection about y axis 3. Counter clock wise by 45 0 Reflection about the diagonal line y = -x is accomplished with the transformation matrix Shear: A Transformation that slants the shape of an object is called the shear transformation. Two common shearing transformations are used. One shifts x coordinate values and other shift y coordinate values. However in both the cases only one coordinate (x or y) changes its coordinates and other preserves its values. X Shear: The x shear preserves the y coordinates, but changes the x values which cause vertical lines to tilt right or left as shown in the above figure.the Transformations matrix for x- shear is which transforms the coordinates as x = x+x sh x.y y = y Y Shear: The y shear preserves the x coordinates, but changes the y values which cause horizontal lines which slope up or down The Transformations matrix for y-shear is which transforms the coordinates as x = x y = y + y sh x.x XY Shear: The transformation matrix for xy-shear which transforms the coordinates as x = x + x sh x.y y = y + y sh x.x which transforms the coordinates as Example: x = x+x sh x (y ref y) y = y Sh x = ½ and y ref = -1 Y - shear with x reference line We can generate y-direction shears relative to other reference lines with the transformation matrix which transforms the coordinates as 268

269 Example: x = x y = sh y (x - x ref ) + y Sh y = ½ and x ref = -1 Bresenham s Line Algorithm. An accurate, efficient raster line drawing algorithm developed by Bresenham, scan converts lines using only incremental integer calculations that can be adapted to display circles and other curves. Keeping in mind the symmetry property of lines, lets derive a more efficient way of drawing a line. Starting from the left end point (x0,y0) of a given line, we step to each successive column (x position) and plot the pixel whose scan-line y value closest to the line path Assuming we have determined that the pixel at (xk,yk) is to be displayed, we next need to decide which pixel to plot in column xk+1. Choices are(xk +1, yk) and (xk+1, yk+1) d1 = y yk = m(xk + 1) + b yk d2 = (yk + 1) y = yk + 1- m(xk + 1) b The difference between these 2 separations is d1-d2 = 2m(xk + 1) 2 yk + 2b 1 A decision parameter pk for the kth step in the line algorithm can be obtained by rearranging above equation so that it involves only integer calculations Define Pk = x ( d1-d2) = 2 yxk-2 xyk + c The sign of Pk is the same as the sign of d1-d2, since x > 0. Parameter c is a constant and has the value 2 y + x(2b-1) (independent of pixel position) If pixel at yk is closer to line-path than pixel at yk +1 (i.e, if d1 < d2) then pk is negative. We plot lower pixel in such a case. Otherwise, upper pixel will be plotted. 269

270 At step k + 1, the decision parameter can be evaluated as, pk+1 = 2 yxk+1-2 xyk+1 + c Taking the difference of pk+ 1 and pk we get the following. pk+1 pk = 2 y(xk+1- xk)-2 x(yk+1 yk) But, xk+1 = xk +1, so that pk+1 = pk + 2 y - 2 x(yk+1 yk) Where the term yk+1-yk is either 0 or 1, depending on the sign of parameter pk The first parameter p0 is directly computed p0 = 2 yxk - 2 xyk + c = 2 yxk 2 y + x (2b-1) Since (x0,y0) satisfies the line equation, we also have y0 = y/ x * x0 + b Combining the above 2 equations, we will have p0 = 2 y x. The constants 2 y and 2 y-2 x are calculated once for each time to be scan converted. So, the arithmetic involves only integer addition and subtraction of 2 Constants. Characteristics of Attributes. The appearance of displayed character is controlled by attributes such as font, size, color and orientation. Attributes can be set both for entire character strings (text) and for individual characters defined as marker symbols Text Attributes: The choice of font or type face is set of characters with a particular design style as courier, Helvetica, times roman, and various symbol groups. The characters in a selected font also be displayed with styles. (solid, dotted, double) in bold face in Italics, and in Outline or shadow styles. integer code for the text font parameter tf in the function settextfont (tf) Control of text color (or intensity) is managed from an application program with settextcolourindex (tc) Where text color parameter tc specifies an allowable color code. Text size can be adjusted without changing the width to height ratio of characters with setcharacterheight (ch) 270

271 Parameter ch is assigned a real value greater than 0 to set the oordinate height of capital letters. The width only of text can be set with function. setcharacterexpansionfactor (cw) Where the character width parameter cw is set to a positive real value that scales the body width of character. Spacing between characters is controlled separately with setcharacterspacing (cs) Where the character-spacing parameter cs can he assigned any real value The orientation for a displayed character string is set according to the direction of the character up vector setcharacterupvector (upvect) Parameter upvect in this function is assigned two values that specify the x and y vector components. For example, with upvect = (1, 1), the direction of the up vector is 45o and text would be displayed. To arrange character strings vertically or horizontally settextpath (tp) can be assigned the value: right, left, up, or down Another handy attribute for character strings is alignment. This attribute specifies how text is to be positioned with respect to the $tart coordinates. Alignment attributes are set with settextalignment(h,v) where parameters h and v control horizontal and vertical alignment. Horizontal alignment is set by assigning h a value of left, center, or right. Vertical alignment is set by assigning v a value of top, cap, half, base or bottom. A precision specification for text display is given with settextprecision(tpr) tpr is assigned one of values string, char or stroke. Marker Attributes: A marker symbol is a single character that can he displayed in different colors and in different sizes. Marker attributes are implemented by procedures that load the chosen character into the raster at the defined positions with the specified color and size. We select a particular character to be the marker symbol with setmarkertype(mt) where marker type parameter mt is set to an integer code. Typical codes for marker type are the integers 1 through 5, specifying, respectively, a dot (.) a vertical cross (+), an asterisk (*), a circle (o), and a diagonal cross (X). We set the marker size with setmarkersizescalefactor (ms) 271

272 with parameter marker size ms assigned a positive number. This scaling parameter is applied to the nominal size for the particular marker symbol chosen. Values greater than 1 produce character enlargement; values less than 1 reduce the marker size. Marker color is specified with setpolymarkercolourindex (mc) A selected color code parameter mc is stored in the current attribute list and used to display subsequently specified marker primitives Bundled Attributes: A particular set of attributes values for a primitive on each output device is chosen by specifying appropriate table index. Attributes specified in this manner are called bundled attributes. setindividualasf( attributeptr, flagptr) where parameter attributer ptr points to a list of attributes and parameter flagptr points to the corresponding list of aspect source flags. Each aspect source flag can be assigned a value of individual or bundled. Bundled line Attributes: Entries in the bundle table for line attributes on a specified workstation are set with the function setpolylinerepresentation (ws, li, lt, lw, lc) Parameter ws is the workstation identifier and line index parameter li defines the bundle table position. Parameter lt, lw, tc are then bundled and assigned values to set the line type, line width, and line color specifications for designated table index. Example: setpolylinerepresentation (1, 3, 2, 0.5, 1) setpolylinerepresentation (4, 3, 1, 1, 7) Bundle area fill Attributes: Table entries for bundled area-fill attributes are set with setinteriorrepresentation (ws, fi, fs, pi, fc) Which defines the attributes list corresponding to fill index fi on workstation ws. Parameter fs, pi and fc are assigned values for the fill style pattern index and fill color. Bundled Text Attributes: settextrepresentation (ws, ti, tf, tp, te, ts, tc) Bundles values for text font, precision expansion factor size an color in a table position for work station ws that is specified by value assigned to text index parameter ti. Bundled marker Attributes: setpolymarkerrepresentation (ws, mi, mt, ms, mc) 272

273 That defines marker type marker scale factor marker color for index mi on workstation ws. Two Dimensional Geometric Transformations. Changes in orientations, size and shape are accomplished with geometric transformations that alter the coordinate description of objects. Basic transformation: * Translation > T(tx, ty) > Translation distances * Scale > S(sx,sy) > Scale factors * Rotation > R( ) > Rotation angle Translation: A translation is applied to an object by representing it along a straight line path from one coordinate location to another adding translation distances, tx, ty to original coordinate position (x, y) to move the point to a new position (x, y ) to x = x + tx, y = y + ty The translation distance point (tx,ty) is called translation vector or shift vector. Translation equation can be expressed as single matrix equation by using column vectors to represent the coordinate position and the translation vector as Moving a polygon from one position to another position with the translation vector (- 5.5, 3.75) Scaling: A scaling transformation alters the size of an object. This operation can be carried out for polygons by multiplying the coordinate values (x, y) to each vertex by scaling factor Sx & Sy to produce the transformed coordinates (x, y ) x = x.sx y = y.sy scaling factor Sx scales object in x direction while Sy scales in y direction. The transformation equation in matrix form (or) P = S. P Where S is 2 by 2 scaling matrix. Turning a square 273

274 (b) with scaling factors sx = 2 and sy = 1. (a) Into a rectangle Any positive numeric values are valid for scaling factors sx and sy. Values less than 1 reduce the size of the objects and values greater than 1 produce an enlarged object. There are two types of Scaling. They are * Uniform Scaling * Non Uniform Scaling To get uniform scaling it is necessary to assign same value for sx and sy. Unequal values for sx and sy result in a non uniform scaling. Rotations: A two-dimensional rotation is applied to an object by repositioning it along a circular path on xy plane. To generate a rotation, specify a rotation angle θ and the position (x r, y r ) of the rotation point (pivot point) about which the object is to be rotated. Positive values for the rotation angle define counter clock wise rotation 88about pivot point. Negative value of angle rotate objects in clock wise direction. The transformation can also be described as a rotation about a rotation axis perpendicular to xy plane and passes through pivot point. Rotation of a point from position (x, y) to position (x, y ) through angle θ relative to coordinate origin The transformation equations for rotation of a point position P when the pivot point is at coordinate origin. In figure r is constant distance of the point positions Ф is the original angular of the point from horizontal and θ is the rotation angle. The transformed coordinates in terms of angle θ and Ф x = rcos(θ+ф) = rcosθ cosф rsinθsinф y = rsin(θ+ф) = rsinθ cosф + rcosθsinф The original coordinates of the point in polar coordinates x = rcosф, y = rsinф the transformation equation for rotating a point at position (x,y) through an angle θ about origin x = xcosθ ysinθ y = xsinθ + ycosθ Rotation Equation P = R. P Rotation Matrix ********************* 274

275 Unit III Transformation. Transformation is the process of introducing changes in the shape size and orientation of the object using scaling rotation reflection shearing & translation etc. Active and passive transformations In the active transformation he points x and x represent different coordinates of the same coordinate system. Here all the points are acted upon by the same transformation and hence the shape of the object is not distorted. In a Passive transformation the points x and x represent same points in the space but in a different coordinate system. Here the change in the coordinates is merely due to the change in the type of the user coordinate system. Homogeneous coordinates. To perform more than one transformation at a time, use homogeneous coordinates or matrixes. They reduce unwanted calculations intermediate steps saves time and memory and produce a sequence of transformations. Projection. The process of displaying 3D into a 2D display unit is known as projection. The projection transforms 3D objects into a 2D projection plane. Ssteps involved in 3D transformation. Modelling Transformation Viewing Transformation Projection Transformation Workstation Transformation Types of Basic Transformations. 1.Translation 2.Scaling 3.Rotation Translation. Translation is the process of changing the position of an object in a straight-line path from one coordinate location to another. Every point (x, y) in the object must undergo a displacement to x,y ). the transformation is: x = x + tx y = y+ty 275

276 Scaling. The scaling transformations changes the shape of an object and can be carried out by multiplying each vertex (x,y) by scaling factor Sx,Sy where Sx is the scaling factor of x and Sy is the scaling factor of y. Rotation. A two-dimensional rotation is applied to an object by repositioning it along a circular path on xy plane. To generate a rotation, specify a rotation angle θ and the position (x r, y r ) of the rotation point (pivot point) about which the object is to be rotated. Shearing. The shearing transformation actually slants the object along the X direction or the Y direction as required.ie; this transformation slants the shape of an object along a required plane. Reflection. The reflection is actually the transformation that produces a mirror image of an object. For this use some angles and lines of reflection. Homogeneous Coordinates in 2 Dimensions Scaling and rotations are both handled using matrix multiplication, which can be combined as we will see shortly. The translations cause a difficulty, however, since they use addition instead of multiplication. We want to be able to treat all 3 transformations (translation, scaling, rotation) in the same way - as multiplications. The solution is to give each point a third coordinate (X, Y, W), which will allow translations to be handled as a multiplication also. ( Note that we are not really moving into the third dimension yet. The third coordinate is being added to the mathematics solely in order to combine the addition and multiplication of 2-D coordinates. ) Two triples (X,Y,W) and (X',Y',W') represent the same point if they are multiples of each other e.g. (1,2,3) and (2,4,6). At least one of the three coordinates must be nonzero. If W is 0 then the point is at infinity. This situation will rarely occur in practice in computer graphics. 276

277 If W is nonzero we can divide the triple by W to get the cartesian coordinates of X and Y which will be identical for triples representing the same point (X/W, Y/W, 1). This step can be considered as mapping the point from 3-D space onto the plane W=1. Conversely, if the 2-D cartesian coordinates of a point are known as ( X, Y ), then the homogenous coordinates can be given as ( X, Y, 1 ) Translation of 2D Homogenous Coordinates point (X,Y) is to be translated by amount Dx and Dy to location (X',Y') X' = Dx + X Y' = Dy + Y or P' = T * P where P' = X' Y' T = 1 0 Dx = T(Dx,Dy) 0 1 Dy P = X Y Hey Look! Translation is now a multiplication instead of an addition!scaling of 2D Homogenous Coordinates P' = S * P where P' = X' Y' 1 277

278 - - S = Sx 0 0 = S(Sx,Sy) 0 Sy P = X Y Rotation of 2D Homogenous Coordinates P' = R * P where P' = X' Y' R = cos(theta) -sin(theta) 0 = R(theta) sin(theta) cos(theta) P = X Y Composition of 2D Transformations There are many situations in which the final transformation of a point is a combination of several ( often many ) individual transformations. For example, the position of the finger of a robot might be a function of the rotation of the robots hand, arm, and torso, as well as the position of the robot on the rail road train and the position of the train in the world, and the rotation of the planet around the sun. Applying each transformation individually to all points in a model would take a lot of time. Instead of applying several transformations matrices to each point we want to combine the transformations to produce 1 matrix which can be applied to each point. 278

279 In the simplest case we want to apply the same type of transformation (translation, rotation, scaling) more than once. Translation is additive as expected Scaling is multiplicative as expected Rotation is additive as expected Implementation of composite transformations #include <math.h> #include <graphics.h> typedef float Matrix3x3 [3][3]; Matrix3x3 thematrix; void matrix3x3setidentity (Matrix3x3 m) { int i,j; for (i=0; i<3; i++) for (j=0: j<3; j++ ) m[il[j] = (i == j); } / * Multiplies matrix a times b, putting result in b */ void matrix3x3premultiply (Matrix3x3 a. Matrix3x3 b) { int r,c: Matrix3x3 tmp: for (r = 0; r < 3: r++) for (c = 0; c < 3; c++) tmp[r][c] =a[r][0]*b[0][c]+ a[r][1]*b[l][c] + a[r][2]*b[2][c]: for (r = 0: r < 3: r++) for Ic = 0; c < 3: c++) b[r][c]=- tmp[r][c]: } void translate2 (int tx, int ty) { Matrix3x3 m: rnatrix3x3setidentity (m) : m[0][2] = tx; m[1][2] = ty: matrix3x3premultiply (m, thematrix); } vold scale2 (float sx. float sy, wcpt2 refpt) ( 279

280 Matrix3x3 m. matrix3x3setidentity (m); m[0] [0] = sx; m[0][2] = (1 - sx)* refpt.x; m[l][l] = sy; m[10][2] = (1 - sy)* refpt.y; matrix3x3premultiply (m, thematrix); } void rotate2 (float a, wcpt2 refpt) { Matrix3x3 m; matrix3x3setidentity (m): a = ptoradians (a); m[0][0]= cosf (a); m[0][1] = -sinf (a) ; m[0] [2] = refpt.x * (1 - cosf (a)) + refpt.y sinf (a); m[1] [0] = sinf (a); m[l][l] = cosf (a]; m[l] [2] = refpt.y * (1 - cosf (a) - refpt.x * sinf ( a ) ; matrix3x3premultiply (m, thematrix); } void transformpoints2 (int npts, wcpt2 *pts) { int k: float tmp ; for (k = 0; k< npts: k++) { tmp = thematrix[0][0]* pts[k].x * thematrix[0][1] * pts[k].y+ thematrix[0][2]; pts[k].y = thematrix[1][0]* pts[k].x * thematrix[1][1] * pts[k].y+ thematrix[1][2]; pts[k].x =tmp; } } void main (int argc, char **argv) { wcpt2 pts[3]= { 50.0, 50.0, 150.0, 50.0, 100.0, 150.0}; wcpt2 refpt ={ }; long windowid = opengraphics (*argv,200, 350); setbackground (WHITE) ; setcolor (BLUE); pfillarea(3, pts): 280

281 matrix3x3setidentity(thematrix); scale2 (0.5, 0.5, refpt): rotate2 (90.0, refpt); translate2 (0, 150); transformpoints2 ( 3, pts) pfillarea(3.pts); sleep (10); closegraphics (windowid); } Two Dimensional Geometric Transformations Changes in orientations, size and shape are accomplished with geometric transformations that alter the coordinate description of objects. Basic transformation * Translation > T(tx, ty) > Translation distances * Scale > S(sx,sy) > Scale factors * Rotation > R( ) > Rotation angle Translation A translation is applied to an object by representing it along a straight line path from one coordinate location to another adding translation distances, tx, ty to original coordinate position (x,y) to move the point to a new position (x,y ) to x = x + tx, y = y + ty The translation distance point (tx,ty) is called translation vector or shift vector. Translation equation can be expressed as single matrix equation by using column vectors to represent the coordinate position and the translation vector as Moving a polygon from one position to another position with the translation vector (-5.5, 3.75) Scaling A scaling transformation alters the size of an object. This operation can be carried out for polygons by multiplying the coordinate values (x, y) to each vertex by scaling factor Sx & Sy to produce the transformed coordinates (x, y ) x = x.sx y = y.sy 281

282 scaling factor Sx scales object in x direction while Sy scales in y direction. The transformation equation in matrix form Where S is 2 by 2 scaling matrix (or) P = S. P Turning a square (a) Into a rectangle (b) with scaling factors sx = 2 and sy = 1. Any positive numeric values are valid for scaling factors sx and sy. Values less than 1 reduce the size of the objects and values greater than 1 produce an enlarged object. There are two types of Scaling. They are * Uniform scaling * Non Uniform Scaling To get uniform scaling it is necessary to assign same value for sx and sy. Unequal values for sx and sy result in a non uniform scaling. Rotations: A two-dimensional rotation is applied to an object by repositioning it along a circular path on xy plane. To generate a rotation, specify a rotation angle θ and the position (x r, y r ) of the rotation point (pivot point) about which the object is to be rotated. Positive values for the rotation angle define counter clock wise rotation about pivot point. Negative value of angle rotate objects in clock wise direction. The transformation can also be described as a rotation about a rotation axis perpendicular to xy plane and passes through pivot point Rotation of a point from position (x, y) to position (x, y ) through angle θ relative to coordinate origin The transformation equations for rotation of a point position P when the pivot point is at coordinate origin. In figure r is constant distance of the point positions Ф is the original angular of the point from horizontal and θ is the rotation angle. The transformed coordinates in terms of angle θ and Ф x = rcos(θ+ф) = rcosθ cosф rsinθsinф y = rsin(θ+ф) = rsinθ cosф + rcosθsinф The original coordinates of the point in polar coordinates x = rcosф, y = rsinф the transformation equation for rotating a point at position (x,y) through an angle θ about origin x = xcosθ ysinθ y = xsinθ + ycosθ 282

283 Rotation Equation P = R. P Rotation Matrix 1. Other Transformations 1. Reflection 2. Shear Reflection A reflection is a transformation that produces a mirror image of an object. The mirror image for a two-dimensional reflection is generated relative to an axis of reflection by We can choose an axis of reflection in the xy plane or perpendicular to the xy plane or coordinate origin Reflection of an object about the x axis Reflection the x axis is accomplished with the transformation matrix Reflection the y axis is accomplished with the transformation matrix Reflection of an object about the coordinate origin Reflection about origin is accomplished with the transformation matrix Reflection axis as the diagonal line y = x To obtain transformation matrix for reflection about diagonal y=x the transformation sequence is 1. Clock wise rotation by Reflection about x axis 3. Counter clock wise by 45 0 Reflection about the diagonal line y = x is accomplished with the transformation matrix Reflection axis as the diagonal line y = -x To obtain transformation matrix for reflection about diagonal y = -x the transformation sequence is 1. Clock wise rotation by Reflection about y axis 3. counter clock wise by

284 Reflection about the diagonal line y = -x is accomplished with the transformation matrix Shear A Transformation that slants the shape of an object is called the shear transformation. Two common shearing transformations are used. One shifts x coordinate values and other shift y coordinate values. However in both the cases only one coordinate (x or y) changes its coordinates and other preserves its values. X - Shear The x shear preserves the y coordinates, but changes the x values which cause vertical lines to tilt right or left as shown in figure The Transformations matrix for x-shear is which transforms the coordinates as x = x+x sh x.y y = y Y - Shear The y shear preserves the x coordinates, but changes the y values which cause horizontal lines which slope up or down The Transformations matrix for y-shear is which transforms the coordinates as x = x y = y + y sh x.x XY - Shear The transformation matrix for xy-shear which transforms the coordinates as x = x + x sh x.y y = y + y sh x.x Shearing Relative to other reference line We can apply x shear and y shear transformations relative to other reference lines. In x shear transformations we can use y reference line and in y shear we can use x reference line. X - shear with y reference line We can generate x-direction shears relative to other reference lines with the transformation matrix which transforms the coordinates as x = x+x sh x (y ref y) y = y 284

285 Example Sh x = ½ and y ref = -1 Y - shear with x reference line We can generate y-direction shears relative to other reference lines with the transformation matrix which transforms the coordinates as x = x y = sh y (x - x ref ) + y Example Sh y = ½ and x ref =

286 Multimedia Unit - IV Multimedia. Multimedia is defines as the interactive use of audio, still image and motion video to text and graphics. These can include text, record based data, numeric data, graphics, images and video. Multimedia is also means that speech and music, photographs and video have to be converted from analogue to digital forms. Elements of multimedia. A multimedia system combines elements that are familiar from the worlds of film, video, broadcast television, music and telecommunications as well as computing. Benefits of multimedia Organisations that use multimedia systems can experience both economic benefits and qualitative benefits Training Sales Communications Medicine Limitations of PC. Audio and video adapters Bus architecture Networking Problems with multimedia. Investment cost and legal problems Technical barriers Social and physical barrier MIS and TIFF. MIS - Management Information System. TIFF - Tagged Image File Format. Elements of multimedia system through devices. A multimedia system combines elements that are familiar from the worlds of film, video, broadcast, television, music and telecommunications as well as computing. Early systems consisted of the following basic components: 286

287 A processor, typically a personal computer or workstation that has been enhanced to handle audio and video. A variety of methods by which the user can interact with the system, such as keyboard, mouse, joystick or touch screen. A screen that can display high-quality still images and moving video as well as computer-generated text, graphics and animations. Speakers to allow speech and music to be output; A microphone is a way to play back pre-recorded source material, usually from some form of optical disk, such as a compact disk. Multimedia and its applications. A definition of multimedia the interactive use of audio, still image and motion video to text and graphics. and video. These can include text, record based data, numeric data, graphics, images Multimedia is also means that speech and music, photographs and video have to be converted from analogue to digital forms. Multimedia systems are potentially of great value to organisations. Suppliers of computer systems are greatly increasing the nature, volume and structure of information supported by their systems. Both suppliers and users can develop an infrastructure for the many business processes that mainstream management information systems (MIS) do not yet support. Multimedia has now become commercially feasible as the price of specialised hardware, such as camera, optical storage and processors. Multimedia is effectively an infrastructure technology, characterised by the ability to handle very diverse data types. It is used to improve electronic information representation, storage and manipulation in a wide range of applications. System components of technology. Multimedia is a group or a large group of infrastructure technologies with widely differing origins. It has two types of system components: Converging technologies Functions and subsystems 287

288 Converging technologies: It is now quite conventional to describe multimedia as lying at the convergence of three or four separate industries, namely computing, telecommunications, entertainment in the form of film and television and publishing. Training or marketing departments generally developed the earliest applications using outside consultants. Functions and subsystem: There are many simple multimedia platforms on the market at present. It may be consist of: A personal computer with a high-resolution bit mapped screen Speakers and microphones One or more adapter boards to decompress and play back audio and video material. Software libraries for basic functions, Application Programming Interfaces(APIs)and system support. Over view of Multimedia development functions This multimedia development system must perform three main functions: Input Output Development SOURCE INPUT DEVELOPMENT OUTPUT Input : STORAGE DELIVERY These consist of the capture and compression, processing and monitoring, and finally storage of data. Some multimedia functions are included such as a musical instrument or video camera, or pre-recorded such as an audio cassette or video tape. Output: These consist of the retrieval of data from store, final processing and recording of the completed application on some media for playback. 288

289 Development: Applications can be recorded in s standard format on videotape for playback. The development of multimedia application will generally be carried out using a variety of software tools. These tools allows the developer to carry out tasks such as creating script for presentations, building links between items, editing, designing screens, overlaying video images with text and computer graphics and mixing audio input from different sources. Multimedia Advantages and problems. A definition of multimedia the interactive use of audio, still image and motion video to text and graphics. and video. These can include text, record based data, numeric data, graphics, images Multimedia is also means that speech and music, photographs and video have to be converted from analogue to digital forms. Advantages of using multimedia: Organisations that use multimedia systems can experience both economic benefits and qualitative benefits. Training: It includes: Training Sales Communications Medicine Successful organisations need to maintain high levels of staff training and development. Each course can be used by many more people; Time spent away from the office, including travel time can be reduced; Employees can work at their own pace so the average training time per employee is reduced. 289

290 Sales: In the retail field multimedia is changing the traditional methods and concepts of marketing. Both consumers and retailers benefit from the consistency of information that results from the introduction of point-of-sale systems. The benefits of to the retailers are saving on space, inventory and distribution, estimated at up to 50 percent of retail profit. For example, the introduction of remote consultations using video communications on personal computers. Communications: The economic benefits of multimedia are not confined to training systems. Savings in travel time can also achieved through the use of videoconferencing systems. Medicine: Multimedia can offer organisations the opportunity of diversification and expansion by opening up new business opportunities. For example, a number of hospitals in the USA are investigating ways to offer new radiology services based on the transmission of images. Problems with multimedia: Investment cost It is very expensive to create and maintain. Technical barriers Personal computers or workstations that can support and manage multimedia data, including real-time video. New file servers that can manage large volume of data stored on optical or magnetic media. Social and psychological barriers Training and problem solving sessions are often held off site. In such session members of staff, freed from the pressure of dealing with queries and telephone calls, can concentrate on the job at hand. 290

291 Legal problems One of the barriers to the growth of multimedia applications has been concern about the ownership of content. Copyright law protects library, musical, graphics, artistic and other works. A copyright owner whose rights have been infringed can sue for damages. ************************* 291

292 Unit V Multimedia authoring tools. In Multimedia Authoring tools are used for designing interactivity and the user interface, for presentation your project on screen and assembling multimedia elements into a single cohesive project. Authoring software provides an integrated environment for binding together the content and functions of your project. Authoring systems typically include the ability to create, edit and import specific types of data. Types of Authoring Tools. Card or page based tools Icon base, event driven tools Time base and presentation tools Card or page based tools. In these authoring systems, elements are organized as pages of a book or a stack of cards. These tools are best used when the bulk of your content consists of elements that can be viewed individually, like the pages of a book or cards in a card file. Icon based, event driven tools. In these authoring system, multimedia elements and interactions cues are organized as objects in structural framework or process. Icon-base, event-driven tools simplify the organization of the project. Time based tools. In these authoring systems, elements and events are organized along a timeline, with resolutions as high or higher than 1/30 second. There by adding navigation and interactive control. Features of Authoring Tools. Features of multimedia authoring tools are as mention below: Editing features Organizing features Programming features Interactive features Performance tuning features Playback features Delivery features Cross-Platform features Internet Playability 292

293 MIDI: Musical Instrument Digital Interface. A protocol that enables computer, synthesizers, keyboards, and other musical device to communicate with each other. To provide the means for conveying the musical performances efficiently 10 bits transmitted per byte (including 1 start & 1 stop bits, as zeros) MIDI interface on a MIDI device contains connectors IN OUT THRU Components of MIDI System? Synthesizer Sequencer Track Channel Pitch Voice Timbre Lossless Compression. Lossless Compression is a compression when we decompress there will be no loss in the quality of image Lossy Compression. It is a compression when we decompress the quality will not be clear as it is in the original data. MIDI to WAV Conversion. Some programs, such as early versions of Premiere, cannot include.mid files -- instead, they insist on.wav format files. a) Various shareware programs exist for approximating a reasonable conversion between MIDI and WAV formats. 293

294 b) These programs essentially consist of large lookup files that try to substitute predefined or shifted WAV output for MIDI messages, with inconsistent success. Components of a MIDI System. Synthesizer: Sequencer: Track: Channel: Timbre: Pitch: Voice: It is a sound generator (various pitch, loudness, tone colour). A good (musician's) synthesizer often has a microprocessor, keyboard, control panels, memory, etc. It can be a stand-alone unit or a software program for a personal computer. (It used to be a storage server for MIDI data. Nowadays it is more a software music editor on the computer. It has one or more MIDI INs and MIDI OUTs. Track in sequencer is used to organize the recordings. Tracks can be turned on or off on recording or playing back. MIDI channels are used to separate information in a MIDI system. There are 16 MIDI channels in one cable. Channel numbers are coded into each MIDI message. The quality of the sound, e.g., flute sound, cello sound, etc. Multitimbral - capable of playing many different sounds at the same time (e.g., piano, brass, drums, etc.) musical note that the instrument plays Voice is the portion of the synthesizer that produces sound. Synthesizers can have many (12, 20, 24, 36, etc.) voices. Each voice works independently and simultaneously to produce sounds of different timbre and pitch. 294

295 Messages are communicate by MIDI devices. MIDI messages are used by MIDI devices to communicate with each other. Structure of MIDI messages: MIDI message includes a status byte and up to two data bytes. Status byte o The most significant bit of status byte is set to 1. o The 4 low-order bits identify which channel it belongs to (four bits produce 16 possible channels). o The 3 remaining bits identify the message. The most significant bit of data byte is set to 0. Classification of MIDI messages: voice messages ---- channel messages mode messages MIDI messages common messages system messages real-time messages ---- exclusive messages A. Channel messages: - messages that are transmitted on individual channels rather that globally to all devices in the MIDI network. A.1. Channel voice messages: Instruct the receiving instrument to assign particular sounds to its voice Turn notes on and off Alter the sound of the currently active note or notes Voice Message Status Byte Data Byte1 Data Byte Note off 8x Key number Note Off velocity Note on 9x Key number Note on velocity Polyphonic Key PressureAx Key number Amount of pressure Control Change Bx Controller number Controller value Program Change Cx Program number None Channel Pressure Dx Pressure value None Pitch Bend Ex MSB LSB 295

296 Notes: `x' in status byte hex value stands for a channel number. Example: a Note On message is followed by two bytes, one to identify the note, and on to specify the velocity. To play note number 80 with maximum velocity on channel 13, the MIDI device would send these three hexadecimal byte values: 9C 50 7F A.2. Channel mode messages: - Channel mode messages are a special case of the Control Change message ( Bx or 1011nnnn). The difference between a Control message and a Channel Mode message, which share the same status byte value, is in the first data byte. Data byte values 121 through 127 have been reserved in the Control Change message for the channel mode messages. Channel mode messages determine how an instrument will process MIDI voice messages. 1st Data Byte Description Meaning of 2nd Data Byte Reset all controllers None; set to 0 7A Local control 0 = off; 127 = on 7B All notes off None; set to 0 7C Omni mode off None; set to 0 7D Omni mode on None; set to 0 7E Mono mode on (Poly mode off) ** 7F Poly mode on (Mono mode off) None; set to 0 ** if value = 0 then the number of channels used is determined by the receiver; all other values set a specific number of channels, beginning with the current basic channel. B. System Messages: System messages carry information that is not channel specific, such as timing signal for synchronization, positioning information in pre-recorded MIDI sequences, and detailed setup information for the destination device. B.1. System real-time messages: messages related to synchronization System Real-Time Message Status Timing Clock F8 Start Sequence FA Continue Sequence FB Stop Sequence FC 296

297 Active Sensing System Reset FE FF B.2. System common messages: contain the following unrelated messages System Common Message Status Byte Number of Data Bytes MIDI Timing Code F1 1 Song Position Pointer F2 2 Song Select F3 1 Tune Request F6 None B.3. System exclusive message: Patch: (a) Messages related to things that cannot be standardized, (b) addition to the original MIDI specification. It is just a stream of bytes, all with their high bits set to 0, bracketed by a pair of system exclusive start and end messages (F0 and F7). the control settings that define a particular timbre. Fundamental tools of multimedia. Computer Representation of Audio Quantization Sampling Digital Image Representation Color System Chrominance Sub sampling Digital Video Representation Hardware Requirements Computer Representation of Audio Sound is created by vibration of matter (i.e., air molecules). Sound is a continuous wave that travels through air: Amplitude of a sound is the measure of the displacement of air pressure wave from its mean or quiescent state (measured in decibels, db) Frequency represents the number of periods in a second (measured in hertz, Hz, cycles/second). Period is the reciprocal value of the frequency. 297

298 Nyquist Sampling Theorem If a signal f(t) is sampled at regular intervals of time and at a rate higher than twice the highest significant signal frequency, then the samples contain all the information of the original signal. Example Actual playback frequency for CD quality audio is 22,050 Hz Because of NyquistTheorem -we need to sample the signal twice this frequency, therefore sampling frequency is 44,100 Hz. Quantization Sample precision -the resolution of a sample value. Quantization depends on the number of bits used measuring the height of the waveform. 16-bit CD quality quantization results in 64K values. Audio formats are described by sample rate and quantization: Voice quality -8 bit quantization, 8,000 Hz mono (64 Kbps) CD quality -16 bit quantization, 44,100 Hz linear stereo (705.6 Kbps for mono, Mbps for stereo) Pulse Code Modulation (PCM) The two step process of sampling and quantization is known as Pulse Code Modulation. Based on the Nyquist sampling theorem.used in speech and CD encoding. Signal-to-Noise Ratio A measure of the quality of the signal. Let P signal and P noise be the signal power and noise power (variances), respectively SNR = 10 log10(p signal/p noise) Assuming quantization error is uniform, and the variance of signal is not too large compared to the maximum signal value V max, then each bit adds about 6 db of resolution. Digital Image Representation An image is a collection of an n m array of picture elements or pixels. Pixel representation can be bi-level, grey-scale, or color. Resolution specifies the distance between points accuracy. Pixels Images are made up of dots called pixels for picture elements The number of pixels affects the resolution of the monitor The higher the resolution,the better the image quality Color Depth (Pixel Depth) The amount of information per pixel is known as the color depth Monochrome (1 bit per pixel) Gray-scale (8 bits per pixel) 298

299 Color (8 or 16 bits per pixel) 8-bit indexes to a color palette 5 bits for each RGB + 1 bit Alpha (16 bits) True color (24 or 32 bits per pixel) RGB Color System RGB (Red-Green-Blue) is the most widely used color system. Represents each pixel as a color triplet in the form (R, G, B), e.g., for 24- bit color, each numerical values are 8 bits (varies from 0 to 255). (0, 0, 0) = black (255, 255, 255) = white (255, 0, 0) = red (0, 255, 255) = cyan (65, 65, 65) = a shade of gray YUV Color System PAL (Phase Alternating Line) standard. Humans are more sensitive to luminance (brightness) fidelity than color fidelity. Luminance(Y) -Encodes the brightness or intensity. Chrominance(U and V) -Encodes the color information. YUV uses 1 byte for luminance component, and 4 bits for each chrominance components. Requires only 2/3 of the space (RGB = 24 bits), so better compression! This coding ratio is called 4:2:2 sub sampling. RGB <=> YUV Y = 0.3R G B U = (B-Y) * V = (R-Y) * Features of Authoring Tools. Editing features The elements of multimedia image, animation, text, digital audio and MIDI music and video clips need to be created, edited and converted to standard file formats and the specialized applications provide these capabilities Organizing features The organization, design and production process for multimedia involves storyboarding and flowcharting. Some authoring tools provide a visual flowcharting system or overview facility for illustrating your project s structure at a macro level. 299

300 Programming features Authoring tools that offer a very high level language or interpreted scripting environment for navigation control and for enabling user inputs such as Macromedia Director, Macromedia Flash, HyperCard, Meta Card and Tool Book are more powerful. Interactivity features Interactivity empowers the end users of your project by letting them control the content and flow of information. Authoring tools should provide one or more levels of interactivity: Simple branching, which offers the ability to go to another sectionof the multimedia production. Conditional branching, which supports a go-to based on the result of IF-THEN decision or events. Performance tuning features Complex multimedia projects require extra synchronization of events. Accomplishing synchronization is difficult because performance varies widely among the different computers used for multimedia development and delivery. Some authoring tools allow you to lock a production s playback speed to specified computer platform, but other provides no ability what so ever to control performance on various systems. Playback features When you are developing multimedia project, you will continually assembling elements and testing to see how the assembly looks and performs. Your authoring system should let you build a segment or part of your project and then quickly test it as if the user were actually using it. Delivery features Delivering your project may require building a run-time version of the project using the multimedia authoring software. A run-time version allows your project to play back without requiring the full authoring software and all its tools and editors. Many times the run time version does not allow user to access or change the content, structure and programming of the project. If you are going to distribute your project widely, you should distribute it in the run-time version. Cross-Platform features It is also increasingly important to use tools that make transfer across platforms easy. For many developers, the Macintosh remains the multimedia authoring platform of choice, but 80% of that developer s target market may be Windows platforms. If you develop on a Macintosh, look for tools that provide a compatible authoring system for Windows or offer a run-time player for the other platform. Internet Playability Due to the Web has become a significant delivery medium for multimedia, authoring systems typically provide a means to convert their output so that it can be delivered within the context of HTML or DHTML, either with special plug-in or embedding Java, JavaScript or other code structures in the HTML document. 300

301 B.Sc. Computer Science Core Course XII MySQL LAB (RCCS10CA5P) 1. Consider the following relations: Student (snum: integer, sname: string, major: string, level: string, age: integer) Class (name: string, meets at: string, room: string, d: integer) Enrolled (snum: integer, cname: string) Faculty (fid: integer, fname: string, deptid: integer) The meaning of these relations is straightforward; for example, Enrolled has one record per student-class pair such that the student is enrolled in the class. Level is a two character code with 4 different values (example: Junior: JR etc) Write the following queries. No duplicates should be printed in any of the answers. i.find the names of all Juniors (level = JR) who are enrolled in a class taught by Prof. Anand. ii.find the names of all classes that either meet in room R18 or have five or more Students enrolled. iii.find the names of all students who are enrolled in two classes that meet at the same time. iv.find the names of faculty members who teach in every room in which some class is taught. v.find the names of faculty members for whom the combined enrollment of the courses that they teach is less than five. 2. The following relations keep track of airline flight information: Flights (no: integer, from: string, to: string, distance: integer, Departs: time, arrives: time, price: real) Aircraft (aid: integer, aname: string, cruisingrange: integer) Certified (eid: integer, aid: integer) Employees (eid: integer, ename: string, salary: integer) Note that the Employees relation describes pilots and other kinds of employees as well; Every pilot is certified for some aircraft, and only pilots are certified to fly. Write each of the following queries. i.find the names of aircraft such that all pilots certified to operate them have salaries more than Rs.80, 000. ii.for each pilot who is certified for more than three aircrafts, find the eid and the maximum cruisingrange of the aircraft for which she or he is certified. iii.find the names of pilots whose salary is less than the price of the cheapest route from Chennai to California. iv.for all aircraft with cruisingrange over 1000 Kms,.find the name of the aircraft and the average salary of all pilots certified for this aircraft. v.find the names of pilots certified for some Boeing aircraft. vi.find the aids of all aircraft that can be used on routes from Chennai to New Delhi. 3. Consider the following database of student enrollment in courses & books adopted for each course. STUDENT (regno: string, name: string, major: string, bdate:date) 301

302 COURSE (course #:int, cname:string, dept:string) ENROLL ( regno:string, course#:int, sem:int, marks:int) BOOK _ ADOPTION (course# :int, sem:int, book-isbn:int) TEXT (book-isbn:int, book-title:string, publisher:string, author:string) i.create the above tables by properly specifying the primary keys and the foreign keys. ii.enter at least five tuples for each relation. iii.demonstrate how you add a new text book to the database and make this book be adopted by some department. iv.produce a list of text books (include Course #, Book-ISBN, Book-title) in the alphabetical order for courses offered by the CS department that use more than two books. v.list any department that has allits adopted books published by a specific publisher. vi.generate suitable reports. vii.create suitable front end for querying and displaying the results. 4. The following tables are maintained by a book dealer. AUTHOR (author-id:int, name:string, city:string, country:string) PUBLISHER (publisher-id:int, name:string, city:string, country:string) CATALOG (book-id:int, title:string, author-id:int, publisher-id:int, category-id:int, year:int, price:int) CATEGORY (category-id:int, description:string) ORDER-DETAILS (order-no:int, book-id:int, quantity:int) i.create the above tables by properly specifying the primary keys and the foreign keys. ii.enter at least five tuples for each relation. iii.give the details of the authors who have 2 or more books in the catalog and the price of the books is greater than the average price of the books in the catalog and the year of publication is after iv.find the author of the book which has maximum sales. v.demonstrate how you increase the price of books published by a specific publisher by 10%. vi.generate suitable reports. vii.create suitable front end for querying and displaying the results. 5. Consider the following database for a banking enterprise BRANCH(branch-name:string, branch-city:string, assets:real) ACCOUNT(accno:int, branch-name:string, balance:real) DEPOSITOR(customer-name:string, accno:int) CUSTOMER(customer-name:string, customer-street:string, customer-city:string) LOAN(loannumber:int, branch-name:string, amount:real) BORROWER(customer-name:string, loan-number:int) i.create the above tables by properly specifying the primary keys and the foreign keys. ii.enter at least five tuples for each relation. iii.find all the customers who have at least two accounts at the Mainbranch. iv.find all the customers who have an account at all the branches located in a specific city. v.demonstrate how you delete all account tuples at every branch located in a specific city. 302

303 vi.generate suitable reports. vii.create suitable front end for querying and displaying the results. Ex 1 STUDENT DETAILS: Table1: student Field Snum Sname Major Level Age Time varchar(10) varchar(30) varchar(30) varchar(10) int(10) time Type TABLE2: CLASS Field Cname Meetat Room Dept Type varchar(30) varchar(30) varchar(10) int(10) TABLE3: ENROLL Snum Ename Field varchar(10) varchar(30) Type TABLE4: FACULTY Fid Fname Field int(10) varchar(30) Type 303

304 Dept id Field int(10) Type TABLE1: STUDENT Snum Sname Major Level Age Time cs001 Aarthy Bsc cs Jr 19 12:30:00 mat001 Anu Bsc maths Jr 19 12:30:00 It001 Banu Bsc IT Jr 20 12:30:00 It002 Dhivya Bsc IT Jr 19 12:30:00 com001 Dinesh Bcom ca Jr 19 12:30:00 ca002 suganya bca Jr 19 12:30:00 ca001 bala bca Sr 19 12:00:00 mat002 kala Bsc maths Sr 20 12:00:00 IT003 mala Bsc IT Sr 19 12:00:00 TABLE2: CLASS Cname Meetat Room Dept Bsc cs L block R15 1 Bca Z block R16 2 Bsc maths M block R17 3 Bsc IT A block R18 4 Bcom ca B block R19 5 Bsc IT A block R18 4 Bca Z block R16 2 Bsc maths M block R17 3 Bsc IT A block R18 4 Bsc cs L block R15 1 TABLE3: ENROLL Snum cs001 Ename Bsc cs 304

305 Snum Ename mat001 Bsc maths It001 Bsc IT It002 Bsc IT com001 Bcom ca ca001 bca ca002 Bca mat002 Bsc maths It003 Bsc IT cs002 Bsc cs TABLE4: FACULTY Fid Fname Dept id 1048 Anand Priya Lakshmi Chitra Latha 5 QUERY: 1) Find the name of all juniors (level=jr) who are enrolled in a class taught by prof.anand? Sql query: Select distinct Sname from student,class,faculty where student.level= Jr and student.major=class.cname and class.dept=faculty.deptid and Faculty.Fname= Anand. OUTPUT: Sname Aarthy 2) Find the name of all classes that either meetaat room R18 or have five more students enrolled? 305

306 Sql query: SELECT Cname from class WHERE Room='R18' Cname in (select Ename from enroll group by Ename having count(*)>=5) or OUTPUT: Cname Bsc IT Bsc IT Bsc IT 3) Find the name of all students who are enrolled in two classes that meetat the same time? Sql query: SELECT distinct Sname from student WHERE student.time='12:30:00' OUTPUT: Sname Aarthy Anu Banu Dhivya Dinesh suganya 4) Find the name of faculty members who teach in every room in which some class is taught? Sql query: SELECT distinct Fname from faculty,class,student WHERE faculty.deptid=class.dept and class.cname=student.major OUTPUT: Fname 306

307 Fname Anand Priya Lakshmi Chitra Latha 5) Find the name of faculty members for whom the combined enrollment of the courses that they teach<5? Sql query: SELECT distinct faculty.fname from faculty,enroll,class WHERE class.dept=faculty.deptid and class.cname=enroll.ename group by enroll.ename having count(*)<=5 OUTPUT: Fname Priya Latha Anand Lakshmi TABLE1: AIRCRAFT Ex 2 AIRLINES: Field Aid Aname Cruising_range Type int(10) varchar(30) int(10) TABLE2: CERTIFIED Field Type 307

308 Eid Aid Field int(10) int(10) Type Table3: employee Field Eid Ename Salary Type int(10) varchar(30) int(10) Table4: flight Field Flno Ffrom Tto Distance Depart Arrives Price Type int(10) varchar(30) varchar(30) int(10) time time int(10) TABLE1: AIRCRAFT Aid Aname Cruising_range 11 Spicejet Indianairlines Kingfisher Indianairlines Kingfisher Indianairlines

309 Aid Aname Cruising_range 17 Malaysianairlines Airindia Airindia Indianairlines 7600 TABLE2: CERTIFIED Eid Aid Table3: employee Eid Ename Salary 101 Karthik Mahesh Arjun Jagdesh

310 Eid Ename Salary 105 Karthika Surya Anu Samantha Krithik Shiva Table4: flight Flno Ffrom Tto Distance Depart Arrives Price 11 chennai delhi :00:00 12:00: kovai chennai :00:00 08:00: chennai singapore :00:00 09:00: chennai malaysia :00:00 07:00: singapore chennai :00:00 06:00: chennai california :00:00 09:00: london chennai :00:00 01:00: mauritius london :00:00 10:00: malayasia singapore :00:00 05:00: california chennai :00:00 06:00: chennai california :00:00 08:00: Query: 1) Find the names of aircraft such that all pilots certified to operate them have salaries more than Rs.80,000? Sql Query: SELECT distinct aircraft.aname,certified.aid from aircraft,certified,employee WHERE aircraft.aid =certified.aid and certified.eid=employee.eid and employee.salary>

311 Output: Aname Aid Spicejet 11 Indianairlines 12 Kingfisher 15 Airindia 19 Indianairlines 20 Kingfisher 13 Indianairlines 16 2) For each pilot who is certified for more than three aircrafts, find the name of the eid and maximum cruising_range of the aircraft for which he or she is certified? Sql Query: SELECT distinct c.eid,e.ename,max(a.cruising_range)from certified c,aircraft a,employee e WHERE c.eid=e.eid and c.aid=a.aid group by c.eid having count(c.eid)>3 Output: Eid max(a.cruising_range) ) Find the name of all pilots whose salary is less than the price of the cheapest route from chennai to california? Sql Query: SELECT distinct e.ename from employee e WHERE e.salary<(select min(f.price)from flight f WHERE f.ffrom="chennai" and f.tto="california") Output: Ename Arjun Jagdesh Surya 311

312 Ename Anu Samantha 4) For all aircraft with cruising_range over 10000kms, find the name of the aircraft and the avg salary of all pilots certified for this aircraft? Sql Query: SELECT distinct aircraft.aname,avg(employee.salary)from aircraft,certified,employee WHERE certified.aid=aircraft.aid and certified.eid=employee.eid and aircraft.cruising_range>10000 Output: Aname avg(employee.salary) Kingfisher ) Find the name of pilots certified for some boeing aircraft? Sql Query: SELECT distinct Ename from employee,certified,aircraft WHERE employee.eid=certified.eid and certified.aid=aircraft.aid and aircraft.aname="kingfisher" Output: Ename Arjun Karthika Karthik 6) Find the aid of all aircrafts that can be used on routes from Chennai to Delhi? Sql Query: SELECT distinct a.aid from aircraft a,flight f WHERE a.aid=f.flno and f.ffrom="chennai" and f.tto="delhi" 312

313 Output: Aid 11 Ex3_3.php Demonstrate how you add a new text book to the data base and make this book be adopted by some department. <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query1="insert INTO text(bookisbn,booktitle,publisher,author) VALUES (1666,'Data_structures','Tata','Horrowitz')"; mysql_query($query1)or die(mysql_error()); $query2="insert INTO book_adoption(course_no, Sem,Bookisbn) VALUES(5,5,1666)"; mysql_query($query2)or die(mysql_error()); $query3="select * from text"; $query4="select * from book_adoption"; $result1=mysql_query($query3)or die(mysql_error()); echo"<table border='2'><tr><th>bookisbn</th><th>booktitle</th><th>publisher</th><th >Author</th></tr>"; 313

314 echo"<caption>text Table After Insertion "; while($row=mysql_fetch_array($result1)) { echo"<tr><td>".$row['bookisbn']."</td><td>".$row ['Booktitle']."</td><td>".$row['Publisher']."</td><td>".$row ['Author']."</td></tr>"; } echo"</table>"; $result2=mysql_query($query4)or die(mysql_error()); echo"<table border='2'><tr><th>courseno.</th><th>semester</th><th>bookisbn</th></t r>"; echo"<caption>book_adoption Table After Insertion"; while($row=mysql_fetch_array($result2)) { echo"<tr><td>".$row['course_no']."</td><td>".$row['sem']."</td><td>".$row ['Bookisbn']."</td> </tr>"; } echo"</table>";?> 314

315 TABLE1: AUTHOR Ex-4 : BOOK DEALER DETAILS Field Author_id Name City Country Table2: publisher Field Publisher_id Name City Country Table3: catalog Field Book_id Title Author_id Publisher_id Category_id Year Price Table4: category Type int(10) varchar(30) varchar(30) varchar(30) Type int(10) varchar(30) varchar(30) varchar(30) Type int(10) varchar(30) int(10) int(10) int(10) int(10) int(10) Field Type Category_id int(10) Desc varchar(30) Table5: order _detail Field Book_id Order_no Quantity Type int(10) int(10) int(10) 315

316 TABLE1: AUTHOR Author_id Name City Country 101 Kavitha Trichy India 102 Anandhi Trichy India 103 Harini Trichy India 104 Surya Trichy India Table2: publisher Publisher_id Name City Country 1111 ABC Publications Trichy India 2222 XYZ Publications Trichy India 3333 STAR Publications 4444 MOON Publications Table3: catalog Trichy India Trichy India Book_id Title Author_id Publisher_id Category_id Year Price 1001 C_program Java_program Algorithm Network Programming in C Table4: category Category_id Desc 111 Good 222 Fair 333 Best 444 Good 316

317 Table5: order _detail Book_id Order_no Quantity Ex4_1.php <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select publisher.publisher_id,publisher.name,catalog.title,catalog.price, (catalog.price+catalog.price*(10/100) )as Percentage from catalog,publisher where catalog.publisher_id =publisher.publisher_id and publisher.name='xyz Publications'"; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'> <tr><th>publisher_id</th><th>publisher_name</th><th>book_name</th><th>book_price</t h><th>book_price+10%</th></tr>"; echo"<caption>book Details"; while($row=mysql_fetch_array($result)) { echo"<tr><td>".$row['publisher_id']."</td><td>".$row ['Name']."</td><td>".$row['Title']."</td><td>".$row ['Price']."</td><td>".$row['Percentage']."</td></tr>"; } 317

318 echo"</table>";?> Result: Book Details Publisher_id Publisher_Name Book_Name Book_Price Book_Price+10% 2222 XYZ Publications Java_program XYZ Publications Programming in C Ex4_2.php <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select author.name,catalog.title from author,catalog,order_detail where author.author_id=catalog.author_id and catalog.book_id=order_detail.book_id and order_detail.quantity= (select max(order_detail.quantity) from order_detail )"; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'><tr><th>author_name</th><th>book_title</th></tr>"; echo"<caption>book Details"; while($row=mysql_fetch_array($result)) { 318

319 echo"<tr><td>".$row['name']."</td><td>".$row['title']."</td></tr>"; } echo"</table>";?> Result: Book Details Author_Name Book_Title Kavitha C_program Ex4_3.php <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select author.name,catalog.title,catalog.year,catalog.price FROM author, catalog WHERE author.author_id = catalog.author_id GROUP BY catalog.author_id HAVING count( catalog.author_id ) >=2 AND catalog.price>avg (catalog.price) AND catalog.year >2000 "; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'><tr><th>author_name</th><th>book_name</th> <th>price</th><th>year</th></tr>"; echo"<caption>book Details"; while($row=mysql_fetch_array($result)) { 319

320 echo"<tr><td>".$row['name']."</td><td>".$row['title']."</td> <td>".$row['price']."</td><td>".$row['year']."</td></tr>"; } echo"</table>";?> Result Book Details Author_Name Book_Name Price Year Kavitha C_program Ex-5 MANIPULATION OF BANKING INFORMATION TABLE1: ACCOUNT Field Account_no Branch_name Balance Type varchar(30) varchar(30) int(10) TABLE2: BORROWER Field Type Cname Loan_no varchar(30) int(10) 320

321 TABLE3: BRANCH Field Branch_name Branch_city Assets Type varchar(30) varchar(30) int(10) TABLE4: CUSTOMER Field Customer_name Customer_street Customer_city Type varchar(30) varchar(30) varchar(30) TABLE5: DEPOSITOR Field Customer_name Account varchar(30) varchar(10) Type TABLE6: LOAN Field Type Loan_no Branch_name Amount int(10) varchar(30) int(10) 321

322 TABLE1: ACCOUNT Account_no Branch_name Balance A102 Redhill 700 A201 Perryridge 700 A101 Windmill 500 A220 Main 600 A215 Main 300 A420 Brooklyn 900 A840 Brownhill 750 A217 Main 700 TABLE2: BORROWER Cname Loan_no Dhana 1001 Jaya 1005 Siva 1006 Anu 1001 Abi 1001 TABLE3: BRANCH Branch_name Branch_city Assets Main Srirangam Perryridge Srirangam Redwood Tvkoil Brooklyn Tvkoil

323 Branch_name Branch_city Assets Windmill Main TABLE4: CUSTOMER Customer_name Customer_street Customer_city Vignesh Middle_street Trichy Anu Gandhi_nagar Trichy Anand Cross_road Trichy Sri Mgr_road Trichy Vicky Cross_road Trichy Jaya Carstreet Trichy Hema Crossroad Trichy Vignesh Carstreet Trichy TABLE5: DEPOSITOR Customer_name Vicky Anu Anand Sri Vignesh Jaya Hema Vignesh Account A101 A102 A201 A215 A217 A420 A840 A

324 TABLE6: LOAN Loan_no Branch_name Amount 1000 Perryridge Perryridge Perryridge Brooklyn Main EX5_1.PHP 1. Find all customers who have at least two accounts at main branch <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select customer_name FROM depositor d,account a WHERE d.account=a.account_no AND a.branch_name='main' GROUP BY d.customer_name HAVING COUNT(d.Customer_name)>=2 ; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'><tr><th>customer_name</th></tr>"; echo"<caption>customer having more than two A/C in Main branch "; while($row=mysql_fetch_array($result)) { 324

325 echo"<tr><td>".$row['customer_name']."</td></tr>"; } echo"</table>";?> OUTPUT: Ex5_2.php 2.Find all customers who have an account at all the branches located in a specific city. <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select distinct d.customer_name from depositor d,account a,branch b where d.account=a.account_no and a.branch_name=b.branch_name and Branch_city='Srirangam'"; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'><tr><th>customer_name</th></tr>"; 325

326 echo"<caption>manipulation "; while($row=mysql_fetch_array($result)) { echo"<tr><td>".$row['customer_name']."</td></tr>"; } echo"</table>";?> OUTPUT: 326

327 Ex5_3.php 3.Demonstrate how you delete all account tuples at every branch located in a specific city. <?php mysql_connect("localhost","root","") or die(mysql_error( )); mysql_select_db("3csa") or die(mysql_error( )); $query="select * from Account"; $result=mysql_query($query)or die(mysql_error()); echo"<table border='2'><tr><th>account</th><th>branch_name</th><th>balance</th></tr>"; echo"<caption>manipulation before deletion"; while($row=mysql_fetch_array($result)) { echo"<tr><td>".$row['account_no']."</td><td>".$row['branch_name']."</td><td>".$row['balan ce']."</td></tr>"; } echo"</table>"; $query1="delete from Account where Branch_name in(select Branch_name from branch where Branch_city='Srirangam')"; $result1=mysql_query($query1)or die(mysql_error()); $query2="select * from Account"; $result2=mysql_query($query2)or die(mysql_error()); echo"<table border='2'><tr><th>account_no</th><th>branch_name</th><th>balance</th></tr>"; echo"<caption>manipulation after deletion"; while($row=mysql_fetch_array($result2)) { 327

328 echo"<tr><td>".$row['account_no']."</td><td>".$row['branch_name']."</td><td>".$row['balan ce']."</td></tr>"; } OUTPUT: 328

329 CORE COURSE IX PROGRAMMING IN PHP ( RCCS10CA8) SEMESTER VI Unit I Essentials of PHP - Operators and Flow Control - Strings and Arrays. Unit II Creating Functions - Reading Data in Web Pages - PHP Browser - Handling Power. Unit III Object-Oriented Programming Advanced Object-Oriented Programming. Unit IV File Handling Working with Databases Sessions, Cookies, and FTP Unit V Ajax Advanced Ajax Drawing Images on the Server. Text Book: 1.The PHP Complete Reference, Steven Holzner, McGrawHillEducation, 2007 Reference Books: 1. PHP: A Beginner's Guide, Vikram Vaswani, McGraw Hill Education, 2008 ***** 329

330 UNIT I Introduction to PHP: PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. Before you continue you should have a basic understanding of the following: HTML/XHTML JavaScript What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software PHP is free to download and use What is a PHP File? PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" What is MySQL? MySQL is a database server MySQL is ideal for both small and large applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use PHP + MySQL Why PHP? PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform) PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) 330

331 PHP is FREE to download from the official PHP resource: PHP is easy to learn and runs efficiently on the server side PHP code is executed on the server, and the plain HTML result is sent to the browser. Basic PHP Syntax A PHP scripting block always starts with <?php and ends with?>. A PHP scripting block can be placed anywhere in the document. On servers with shorthand support enabled you can start a scripting block with <? and end with?>. For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. <?php?> A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser: <html> <body> <?php echo "Hello World";?> </body> </html> Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World". Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php 331

332 //This is a comment /* This is a comment block */?> </body> </html> Variables in PHP: Variables are used for storing values, like text strings, numbers or arrays. When a variable is declared, it can be used over and over again in your script. All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP: $var_name = value; New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work. Let's try creating a variable containing a string, and a variable containing a number: <?php $txt="hello World!"; $x=16;?> PHP is a Loosely Typed Language In PHP, a variable does not need to be declared before adding a value to it. In the example above, you see that you do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. In PHP, the variable is declared automatically when you use it. 332

333 Naming Rules for Variables A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($mystring) String Variables in PHP String variables are used for values that contain characters. In this chapter we are going to look at the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to a string variable called $txt: <?php $txt="hello World"; echo $txt;?> The output of the code above will be: Hello World Now, lets try to use some different functions and operators to manipulate the string. The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator: <?php $txt1="hello World!"; $txt2="what a nice day!"; echo $txt1. " ". $txt2;?> The output of the code above will be: 333

334 Hello World! What a nice day! If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings. The strlen() function The strlen() function is used to return the length of a string. Let's find the length of a string: <?php echo strlen("hello world!");?> The output of the code above will be: 12 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string). The strpos() function The strpos() function is used to search for a character/text within a string. If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string: <?php echo strpos("hello world!","world");?> The output of the code above will be: 6 The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1. PHP Operators Operators are used to operate on values. This section lists the different operators used in PHP. 334

335 Arithmetic Operators Operator Description Example Result + Addition x=2 x+2 - Subtraction x=2 5-x * Multiplication x=4 x*5 / Division 15/5 5/2 % Modulus (division remainder) 5%2 10%8 10%2 ++ Increment x=5 x++ -- Decrement x=5 x x=6 x=4 Assignment Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y 335

336 .= x.=y x=x.y %= x%=y x=x%y Comparison Operators Operator Description Example == is equal to 5==8 returns false!= is not equal 5!=8 returns true <> is not equal 5<>8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Logical Operators Operator Description Example && and x=6 y=3 or x=6 y=3! not x=6 y=3 (x < 10 && y > 1) returns true (x==5 y==5) returns false!(x==y) returns true 336

337 Conditional Statements Conditional statements are used to perform different actions based on different conditions. Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false if...elseif...else statement - use this statement to select one of several blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed The if Statement Use the if statement to execute some code only if a specified condition is true. Syntax if (condition) code to be executed if condition is true; The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("d"); if ($d=="fri") echo "Have a nice weekend!";?> </body> </html> Notice that there is no..else.. in this syntax. The code is executed only if the specified condition is true. 337

338 The if...else Statement Use the if...else statement to execute some code if a condition is true and another code if a condition is false. Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("d"); if ($d=="fri") echo "Have a nice weekend!"; else echo "Have a nice day!";?> </body> </html> If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces: <html> <body> <?php $d=date("d"); if ($d=="fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; 338

339 }?></body> </html> The if...elseif...else Statement Use the if...elseif...else statement to select one of several blocks of code to be executed. Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("d"); if ($d=="fri") echo "Have a nice weekend!"; elseif ($d=="sun") echo "Have a nice Sunday!"; else echo "Have a nice day!";?> </body> </html> Conditional statements are used to perform different actions based on different conditions. The PHP Switch Statement Use the switch statement to select one of many blocks of code to be executed. 339

340 Syntax switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found. Example <html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; }?> 340

341 </body> </html> ARRAY: An array stores multiple values in one single variable. A variable is a storage area holding a number or text. The problem is, a variable will hold only one value. An array is a special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1="saab"; $cars2="volvo"; $cars3="bmw"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The best solution here is to use an array! An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own index so that it can be easily accessed. In PHP, there are three kind of arrays: Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays Numeric Arrays A numeric array stores each array element with a numeric index. There are two methods to create a numeric array. 1. In the following example the index are automatically assigned (the index starts at 0): $cars=array("saab","volvo","bmw","toyota"); 341

342 2. In the following example we assign the index manually: $cars[0]="saab"; $cars[1]="volvo"; $cars[2]="bmw"; $cars[3]="toyota"; Example In the following example you access the variable values by referring to the array name and index: <?php $cars[0]="saab"; $cars[1]="volvo"; $cars[2]="bmw"; $cars[3]="toyota"; echo $cars[0]. " and ". $cars[1]. " are Swedish cars.";?> The code above will output: Saab and Volvo are Swedish cars. Associative Arrays An associative array, each ID key is associated with a value. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them. Example 1 In this example we use an array to assign ages to the different persons: $ages = array("peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2 This example is the same as example 1, but shows a different way of creating the array: 342

343 $ages['peter'] = "32"; $ages['quagmire'] = "30"; $ages['joe'] = "34"; The ID keys can be used in a script: <?php $ages['peter'] = "32"; $ages['quagmire'] = "30"; $ages['joe'] = "34"; echo "Peter is ". $ages['peter']. " years old.";?> The code above will output: Peter is 32 years old. Multidimensional Arrays In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example In this example we create a multidimensional array, with automatically assigned ID keys: $families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array 343

344 ( "Cleveland", "Loretta", "Junior" ) ); The array above would look like this if written to the output: Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) Example 2 Lets try displaying a single value from the array above: echo "Is ". $families['griffin'][2]. " a part of the Griffin family?"; The code above will output: Is Megan a part of the Griffin family? 344

345 PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In PHP, we have the following looping statements: while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array The while Loop The while loop executes a block of code while a condition is true. Syntax while (condition) { code to be executed; } Example The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is ". $i. "<br />"; $i++; }?> 345

346 </body> </html> Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The do...while Statement The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. Syntax do { code to be executed; } while (condition); Example The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5: <html> <body> <?php $i=1; do { $i++; echo "The number is ". $i. "<br />"; } 346

347 while ($i<=5);?> </body> </html> Output: The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (init; condition; increment) { code to be executed; } Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) Condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop) Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas). Example The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> 347

348 <?php for ($i=1; $i<=5; $i++) { echo "The number is ". $i. "<br />"; }?> </body> </html> Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The foreach Loop The foreach loop is used to loop through arrays. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value. Example The following example demonstrates a loop that will print the values of the given array: <html> <body> <?php 348

349 $x=array("one","two","three"); foreach ($x as $value) { echo $value. "<br />"; }?> </body> </html> Output: one two three 349

350 UNIT - II PHP Built-in Functions PHP Functions In this chapter we will show you how to create your own functions. To keep the script from being executed when the page loads, you can put it into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page. Create a PHP Function A function will be executed by a call to the function. Syntax function functionname() { code to be executed; } PHP function guidelines: Example Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number) A simple function that writes my name when it is called: <html> <body> <?php function writename() { echo "Kai Jim Refsnes"; } 350

351 echo "My name is "; writename();?> </body> </html> Output: My name is Kai Jim Refsnes PHP Functions - Adding parameters To add more functionality to a function, we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. Example 1 The following example will write different first names, but equal last name: <html> <body> <?php function writename($fname) { echo $fname. " Refsnes.<br />"; } echo "My name is "; writename("kai Jim"); echo "My sister's name is "; writename("hege"); echo "My brother's name is "; writename("stale");?> 351

352 </body> </html> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. Example 2 The following function has two parameters: <html> <body> <?php function writename($fname,$punctuation) { echo $fname. " Refsnes". $punctuation. "<br />"; } echo "My name is "; writename("kai Jim","."); echo "My sister's name is "; writename("hege","!"); echo "My brother's name is "; writename("ståle","?");?> </body> </html> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes? PHP Functions - Return values To let a function return a value, use the return statement. 352

353 Example <html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo " = ". add(1,16);?> </body> </html> Output: = 17 PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: 353

354 <html> <body> Welcome <?php echo $_POST["fname"];?>!<br /> You are <?php echo $_POST["age"];?> years old. </body> </html> Output could be something like this: Welcome You are 28 years old. John! The PHP $_GET and $_POST variables will be explained in the next chapters. Form Validation User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load. You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. In PHP, the predefined $_GET variable is used to collect values in a form with method="get". The $_GET Variable The predefined $_GET variable is used to collect values in a form with method="get" Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> 354

355 When the user clicks the "Submit" button, the URL sent to the server could look something like this: The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?php echo $_GET["fname"];?>.<br /> You are <?php echo $_GET["age"];?> years old! When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters. The $_POST Variable The predefined $_POST variable is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file). Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will look like this: 355

356 The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"];?>!<br /> You are <?php echo $_POST["age"];?> years old. When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The PHP $_REQUEST Variable The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["fname"];?>!<br /> You are <?php echo $_REQUEST["age"];?> years old. The PHP Date() Function The PHP date() function formats a timestamp to a more readable date and time. A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. Syntax date(format,timestamp) 356

357 Parameter format timestamp Description Required. Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time PHP Date() - Format the Date The required format parameter in the date() function specifies how to format the date/time. Here are some characters that can be used: d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits) Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting: <?php echo date("y/m/d"). "<br />"; echo date("y.m.d"). "<br />"; echo date("y-m-d");?> The output of the code above could be something like this: 2009/05/ PHP Date() - Adding a Timestamp The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used. The mktime() function returns the Unix timestamp for a date. 357

358 The Unix timestamp contains the number of seconds between the Unix Epoch (January :00:00 GMT) and the time specified. Syntax for mktime() mktime(hour,minute,second,month,day,year,is_dst) To go one day in the future we simply add one to the day argument of mktime(): <?php $tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("y")); echo "Tomorrow is ".date("y/m/d", $tomorrow);?> The output of the code above could be something like this: Tomorrow is 2009/05/12 Server Side Includes (SSI) You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors: include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages). PHP include() Function The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution. 358

359 Example 1 Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function: <html> <body> <?php include("header.php");?> <h1>welcome to my home page!</h1> <p>some text.</p> </body> </html> Example 2 Assume we have a standard menu file, called "menu.php", that should be used on all pages: <a href="/default.php">home</a> <a href="/tutorials.php">tutorials</a> <a href="/references.php">references</a> <a href="/examples.php">examples</a> <a href="/about.php">about Us</a> <a href="/contact.php">contact Us</a> All pages in the Web site should include this menu file. Here is how it can be done: <html> <body> <div class="leftmenu"> <?php include("menu.php");?> </div> <h1>welcome to my home page.</h1> <p>some text.</p> </body> </html> If you look at the source code of the page above (in a browser), it will look like this: <html> <body> 359

360 <div class="leftmenu"> <a href="/default.php">home</a> <a href="/tutorials.php">tutorials</a> <a href="/references.php">references</a> <a href="/examples.php">examples</a> <a href="/about.php">about Us</a> <a href="/contact.php">contact Us</a> </div> <h1>welcome to my home page!</h1> <p>some text.</p> </body> </html> PHP require() Function The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop. Error Example include() Function <html> <body> <?php include("wrongfile.php"); echo "Hello World!";?> </body> </html> Error message: Warning: include(wrongfile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 360

361 Warning: include() [function.include]: Failed opening 'wrongfile.php' for inclusion (include_path='.;c:\php5\pear') in C:\home\website\test.php on line 5 Hello World! Notice that the echo statement is executed! This is because a Warning does not stop the script execution. Error Example require() Function Now, let's run the same example with the require() function. <html> <body> <?php require("wrongfile.php"); echo "Hello World!";?> </body> </html> Error message: Warning: require(wrongfile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5 Fatal error: require() [function.require]: Failed opening required 'wrongfile.php' (include_path='.;c:\php5\pear') in C:\home\website\test.php on line 5 The echo statement is not executed, because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue after an error. 361

362 UNIT III Object-Oriented Programming Object-oriented programming (OOP) refers to the creation of reusable software objecttypes / classes that can be efficiently developed and easily incorporated into multiple programs. In OOP an object represents an entity in the real world (a student, a desk, a button, a file, a text input area, a loan, a web page, a shopping cart). An OOP program = a collection of objects that interact to solve a task / problem. Objects are self-contained, with data and operations that pertain to them assembled into a single entity. In procedural programming data and operations are separate this methodology requires sending data to methods! Objects have: Identity; ex: 2 OK buttons, same attributes separate handle vars State a set of attributes (aka member variables, properties, data fields) = properties or variables that relate to / describe the object, with their current values. Behavior a set of operations (aka methods) = actions or functions that the object can perform to modify itself its state, or perform for some external effect / result. Small Web projects Consist of web scripts designed and written using an ad-hoc approach; a functionoriented, procedural methodology Large Web software projects Need a properly thought-out development methodology OOP OO approach can help manage project complexity, increase code reusability, reduce costs. OO analysis and design process = decide what object types, what hidden data/operations and wrapper operations for each object type UML as tool in OO design, to allow to describe classes and class relationships A minimal class definition: class classname { // classname is a PHP identifier! } // the class body = data & function member definitions Attributes are declared as variables within the class definition using keywords that match their visibility: public, private, or protected. (Recall that PHP doesn't otherwise have declarations of variables data member declarations against the nature of PHP?) 362

363 Operations are created by declaring functions within the class definition. Constructor = function used to create an object of the class Declared as a function with a special name: function construct (param_list) { } Usually performs initialization tasks: e.g. sets attributes to appropriate starting values Called automatically when an object is created A default no-argument constructor is provided by the compiler only if a constructor function is not explicitly declared in the class Cannot be overloaded (= 2+ constructors for a class); if you need a variable # of parameters, use flexible parameter lists Destructor = opposite of constructor Declared as a function with a special name, cannot take parameters function destruct () { } Allows some functionality that will be automatically executed just before an object is destroyed An object is removed when there is no reference variable/handle left to it Usually during the "script shutdown phase", which is typically right before the execution of the PHP script finishes A default destructor provided by the compiler only if a destructor function is not explicitly declared in the class Create an object of a class = a particular individual that is a member of the class by using the new keyword: $newclassvariable = new ClassName(actual_param_list); Notes: Scope for PHP classes is global (program script level), as it is for functions Class names are case insensitive as are functions PHP 5 allows you to define multiple classes in a single program script The PHP parser reads classes into memory immediately after functions class construction does not fail because a class is not previously defined in the program scope. From operations within the class, class s data / methods can be accessed / called by using: $this = a variable that refers to the current instance of the class, and can be used only in the definition of the class, including the constructor & destructor The pointer operator -> (similar to Java s object member access operator. ) class Test { 363

364 public $attribute; function f ($val) { $this -> attribute = $val; // $this is mandatory! } // if omitted, $attribute is treated } // as a local var in the function From outside the class, accessible (as determined by access modifiers) data and methods are accessed through a variable holding an instance of the class, by using the same pointer operator. class Test { } $t = new Test(); $t->attribute = value ; echo $t->attribute; public $attribute; Defining and Using Variables, Constants and Functions Three access / visibility modifiers introduced in PHP 5, which affect the scope of access to class variables and functions: public : public class variables and functions can be accessed from inside and outside the class protected : hides a variable or function from direct external class access + protected members are available in subclasses private : hides a variable or function from direct external class access + protected members are hidden (NOT available) from all subclasses An access modifier has to be provided for each class instance variable Static class variables and functions can be declared without an access modifier default is public Getters and Setters Encapsulation : hide attributes from direct access from outside a class and provide controlled access through accessor and mutator functions You can write custom getvariable() / setvariable($var) functions or Overload the functionality with the get() and set() functions in PHP 364

365 get() and set() Prototype: mixed get($var); // param represents the name of an attribute, get returns the value of that attribute void set($var, $value); // params are the name of an attribute and the value to set it to get() and set() Can only be used for non-static attributes! You do not directly call these functions; For an instance $acc of the BankAccount class: $acc->balance = 1000; implicitly calls the set() function with the value of $name set to Balance, and the value of $value set to ( get() works in a similar way) Designing Classes Classes in Web development: Pages User-interface components Shopping carts Product categories Customers TLA Consulting example revisited - a Page class, goals: A consistent look and feel across the pages of the website Limit the amount of HTML needed to create a new page: easily generate common parts, describe only uncommon parts Easy maintainable when changes in the common parts Flexible enough: ex. allow proper navigation elements in each page Class Page Attributes: $content content of the page, a combination of HTML and text $title page s title, with a default title to avoid blank titles $keywords a list of keywords, to be used by search engines 365

366 $navigation an associative array with keys the text for the buttons and the value the URL of the target page Operations: set() Display() to display a page of HTML, calls other functions to display parts of the page: DisplayTitle(), DisplayKeywords(), DisplayStyles(), DisplayHeader(), DisplayMenu(), DisplayFooter() can be overridden in a possible subclass Advanced Object-Oriented Programming in PHP PHP is a server side scripting language used to develop web pages. In the recent times, PHP has become popular because of its simplicity. PHP code can be combined with HTML code and once the PHP code is executed, the web server sends the resulting content in the form of HTML or images that can be interpreted by the browser. We all know the power and importance of object-oriented programming or OOP. This is a technique that is widely used in the modern programming languages. OOP Concepts Used in PHP Inheritance Inheritance is the most important concept of Object-oriented programming used in most common programming language. Inheritance is based on the principle of parent and child classes. In PHP we achieve inheritance by extending the class. By extending a class, the child class inherits the properties of the parent class and additionally we can add a few more properties. Sample code to show inheritance class Employee { public $firstname = ""; public $lastname = ""; public $ecode = ""; public $dept = ""; public function dailycommontask() { // Code for routine job } } 366

367 class Accountant extends Employee { public function processmonthlysalary($ecode) { // Code for processing salary } } In the code snippet above we see that the class Accountant is extending the Employee class. An accountant is an employee first, so he performs the daily common jobs as other employees do. At the same time, it is the Accountant's job to process the salary of other employees. Public, Private and Protected As in any object-oriented language, PHP also includes the concept of Public, Private and Protected access modifiers. Public With having public access the code is visible and can be modified by any code from anywhere. Private With having private access the code is visible and can be modified from within the class only. Protected With having protected access the code is visible and can be modified from the same class or any of its child class. Overloading The overloading feature enables us to have two methods with same name but with different parameters. Shown in the following code snippet: Listing 2 Sample code to show overloading class Accountant extends Employee { public function processmonthlysalary($ecode) { 367

368 // Code for processing salary } { public function processmonthlysalary($ecode, $variablepayflag, $variablepercentage) if($variablepayflag) { echo "Please process the salary with variable pay "; } else { echo " Please process the salary without variable pay "; } } } In the code above, we have two methods with the same name ('processmonthlysalary'). In an organization, not all the employees will have the variable pay component in their salary. Hence the accountant will have to process the salary using two different approaches: With variable pay Without variable pay While processing the salary with variable pay, the accountant needs to mention the amount of the variable pay component. Note of clarification added after original article post date: In the above example, we explained the general concept of method overloading. But during actual implementation, we need a PHP function called func_get_args () to handle multiple method signature (having same method name) with different arguments. The func_get_args ()is used inside a PHP function which holds all the arguments (as an array) passed into it. So the same function can be called with different arguments. 368

369 For example, let us take a function called mytestfunction () and we want to use it as an overloaded function. { } function mytestfunction() print_r(func_get_args()); Acessors and Mutators Commonly known as getters and setters, or Accessors and Mutators, are widely used in every programming language. Accessors (or getters) are functions that are used to return or get the value of the class level variables. Mutators (or setters) are functions that are used to set or modify the value of a class level variable. These types of classes are used to transfer the data in a collective way from one layer to another. Let us consider the following example: Listing 3 Sample code for Accessors and Mutators class Employee { public $firstname = ""; public $lastname = ""; public $ecode = ""; public $dept = ""; public function getfirstname() { return $this->firstname(); } public function setfirstname($firstname) { $this->firstname = $firstname; } 369

370 public function getlastname() { return $this->lastname(); } public function setlastname($lastname) { $this->lastname = $lastname; } public function getecode() { return $this->ecode(); } public function setecode($ecode) { $this->ecode = $ecode; } public function getdept() { return $this->dept(); } public function setdept($dept) { $this->dept = $dept; } } These types of classes are very helpful when we have to transfer the entire Employee object from one layer to another. 370

371 Static Using a static keyword for both variable and method is a common practice in objectoriented programming. Static means that the variable or the method is available per instance of the class. Static methods or variables are used without creating an instance of the class. In fact, the static variables are not accessible via the instance of the class. While creating static methods you must take care that the $this variable is not allowed within a static method. Listing 4 Sample code for static keyword and method class StaticSample { } public static $my_static = 'Sample Static variable'; public function staticvalue() { } } return self::$my_static; public static function astaticmethod() { echo "This is the Hello message from static method"; class StaticShow extends StaticSample { public function checkstatic() { return parent::$my_static; } public function checkstaticmethod() { return parent::$astaticmethod; } } 371

372 Abstract Class In PHP, these two features of object-oriented programming are used very frequently. Abstract classes that can't be instantiated rather they can be inherited. The class that inherits an abstract class can also be another abstract class. In PHP we can create an abstract class by using the keyword 'abstract'. Listing 5 Sample code for Abstract Class abstract class testparentabstract { } public function mywrittenfunction() { } // body of your funciton class testchildabstract extends testparentabstract { public function mywrittenfunctioninchild() { // body of your function } } In the above example, we can create an instance of the child class testchildabstract, but we can't create the instance of the parent class testparentabstract. As we see that the child class is extending the parent class, we can use the property of the parent class in the child class. We can also implement an abstract method in our child class as per our need. Interface In object-oriented programming, the interface is a collection of definitions of some set of methods in a class. By implementing an interface, we force the class to follow the methods defined in the interface. In PHP, interface is defined like in any other language. First we need to 372

373 define the interface using the keyword 'interface'. When implementing, we just need to mention the 'implements' keyword in the implementing class. Listing 6 Sample Code for Interface interface myiface { } public function myfunction($name); class myimpl implements myiface { public function myfunction($name) { // function body } } 373

374 UNIT - IV File Handling Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: <html> <body> <?php $file=fopen("welcome.txt","r");?> </body> </html> The file may be opened in one of the following modes: Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file x Write only. Creates a new file. Returns FALSE and an error if file already exists 374

375 x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists Note: If the fopen() function is unable to open the specified file, it returns 0 (false). Example The following example generates a message if the fopen() function is unable to open the specified file: <html> <body> <?php $file=fopen("welcome.txt","r") or exit("unable to open file!");?> </body> </html> Closing a File The fclose() function is used to close an open file: <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file);?> Check End-of-file The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. Note: You cannot read from files opened in w, a, and x mode! if (feof($file)) echo "End of file"; 375

376 Reading a File Line by Line The fgets() function is used to read a single line from a file. Note: After a call to this function the file pointer has moved to the next line. Example The example below reads a file line by line, until the end of file is reached: <?php $file = fopen("welcome.txt", "r") or exit("unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file);?> Reading a File Character by Character The fgetc() function is used to read a single character from a file. Note: After a call to this function the file pointer moves to the next character. Example The example below reads a file character by character, until the end of file is reached: <?php $file=fopen("welcome.txt","r") or exit("unable to open file!"); while (!feof($file)) { echo fgetc($file); } fclose($file);?> Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: 376

377 <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="submit" /> </form> </body> </html> Notice the following about the HTML form above: The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads. Create The Upload Script The "upload_file.php" file contains the code for uploading a file: <?php if ($_FILES["file"]["error"] > 0) { echo "Error: ". $_FILES["file"]["error"]. "<br />"; } else { echo "Upload: ". $_FILES["file"]["name"]. "<br />"; echo "Type: ". $_FILES["file"]["type"]. "<br />"; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb<br />"; echo "Stored in: ". $_FILES["file"]["tmp_name"]; 377

378 }?> By using the global PHP $_FILES array you can upload files from a client computer to the remote server. The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this: $_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload. Restrictions on Upload In this script we add some restrictions to the file upload. The user may only upload.gif or.jpeg files and the file size must be under 20 kb: <?php if ((($_FILES["file"]["type"] == "image/gif") ($_FILES["file"]["type"] == "image/jpeg") ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: ". $_FILES["file"]["error"]. "<br />"; } else { echo "Upload: ". $_FILES["file"]["name"]. "<br />"; echo "Type: ". $_FILES["file"]["type"]. "<br />"; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb<br />"; echo "Stored in: ". $_FILES["file"]["tmp_name"]; } } else 378

379 { echo "Invalid file"; }?> Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. Saving the Uploaded File The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location: <?php if ((($_FILES["file"]["type"] == "image/gif") ($_FILES["file"]["type"] == "image/jpeg") ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: ". $_FILES["file"]["error"]. "<br />"; } else { echo "Upload: ". $_FILES["file"]["name"]. "<br />"; echo "Type: ". $_FILES["file"]["type"]. "<br />"; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb<br />"; echo "Temp file: ". $_FILES["file"]["tmp_name"]. "<br />"; if (file_exists("upload/". $_FILES["file"]["name"])) { echo $_FILES["file"]["name"]. " already exists. "; } else { move_uploaded_file($_files["file"]["tmp_name"], "upload/". $_FILES["file"]["name"]); echo "Stored in: ". "upload/". $_FILES["file"]["name"]; 379

380 } } } else { echo "Invalid file"; }?> The script above checks if the file already exists, if it does not, it copies the file to the specified folder. Note: This example saves the file to a new folder called "upload" A cookie is often used to identify a user. Cookies A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax setcookie(name, value, expire, path, domain); Example 1 In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: <?php setcookie("user", "Alex Porter", time()+3600);?> <html>

381 Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). Example 2 You can also set the expiration time of the cookie in another way. It may be easier than using seconds. <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire);?> <html>... In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days). How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_cookie);?> In the following example we use the isset() function to find out if a cookie has been set: <html> <body> <?php if (isset($_cookie["user"])) echo "Welcome ". $_COOKIE["user"]. "!<br />"; else echo "Welcome guest!<br />"; 381

382 ?> </body> </html> How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600);?> What if a Browser Does NOT Support Cookies? If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial). The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> Retrieve the values in the "welcome.php" file like this: <html> <body> 382

383 Welcome <?php echo $_POST["name"];?>.<br /> You are <?php echo $_POST["age"];?> years old. </body> </html> PHP Session Variables A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL. Starting a PHP Session Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start();?> <html> <body> </body> </html> The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session. 383

384 Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1;?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views'];?> </body> </html> Output: Pageviews=1 In the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: <?php session_start(); if(isset($_session['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views'];?> Destroying a Session If you wish to delete some session data, you can use the unset() or the session_destroy() function. 384

385 The unset() function is used to free the specified session variable: <?php unset($_session['views']);?> You can also completely destroy the session by calling the session_destroy() function: <?php session_destroy();?> Note: session_destroy() will reset your session and you will lose all your stored session data. What is FTP? File Transfer Protocol Transfers files between server and client Two Basic operations Downloading Uploading How to use FTP Requires username and password Anonymous not secure Easily accessible using web browser Different protocol identifier e.g. HTTP or FTP Command Line Using and Get and Put FTP Programs Provide a GUI CuteFTP, FileZilla, SmartFTP 385

386 UNIT V What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX is Based on Internet Standards AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) 386

387 CSS (to style the data) XML (often used as the format for transferring data) AJAX applications are browser- and platform-independent! Google Suggest AJAX was made popular in 2005 by Google, with Google Suggest. Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial. AJAX is used to create more interactive applications. AJAX PHP Example The following example will demonstrate how a web page can communicate with a web server while a user type characters in an input field: Example Start typing a name in the input field below: First name: Suggestions: 387

388 Example Explained - The HTML Page When a user types a character in the input field above, the function "showhint()" is executed. The function is triggered by the "onkeyup" event: <html> <head> <script type="text/javascript"> function showhint(str) { if (str.length==0) { document.getelementbyid("txthint").innerhtml=""; return; } if (window.xmlhttprequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext; } } xmlhttp.open("get","gethint.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <p><b>start typing a name in the input field below:</b></p> <form> First name: <input type="text" onkeyup="showhint(this.value)" size="20" /> </form> <p>suggestions: <span id="txthint"></span></p> 388

389 </body> </html> Source code explanation: If the input field is empty (str.length==0), the function clears the content of the txthint placeholder and exits the function. If the input field is not empty, the showhint() function executes the following: Create an XMLHttpRequest object Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the input field) The PHP File The page on the server called by the JavaScript above is a PHP file called "gethint.php". The source code in "gethint.php" checks an array of names, and returns the corresponding name(s) to the browser: <?php // Fill up array with names $a[]="anna"; $a[]="brittany"; $a[]="cinderella"; $a[]="diana"; $a[]="eva"; $a[]="fiona"; $a[]="gunda"; $a[]="hege"; $a[]="inga"; $a[]="johanna"; $a[]="kitty"; $a[]="linda"; $a[]="nina"; $a[]="ophelia"; $a[]="petunia"; $a[]="amanda"; 389

390 $a[]="raquel"; $a[]="cindy"; $a[]="doris"; $a[]="eve"; $a[]="evita"; $a[]="sunniva"; $a[]="tove"; $a[]="unni"; $a[]="violet"; $a[]="liza"; $a[]="elizabeth"; $a[]="ellen"; $a[]="wenche"; $a[]="vicky"; //get the q parameter from URL $q=$_get["q"]; //lookup all hints from array if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint.", ".$a[$i]; } } } } // Set output to "no suggestion" if no hint were found 390

391 // or to the correct values if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response;?> Explanation: If there is any text sent from the JavaScript (strlen($q) > 0), the following happens: 1. Find a name matching the characters sent from the JavaScript 2. If no match were found, set the response string to "no suggestion" 3. If one or more matching names were found, set the response string to all these names 4. The response is sent to the "txthint" placeholder AJAX can be used for interactive communication with a database. AJAX Database Example The following example will demonstrate how a web page can fetch information from a database with AJAX: Example Select a person: Person info will be listed here

392 Example Explained - The MySQL Database The database table we use in the example above looks like this: id FirstName LastName Age Hometown Job 1 Peter Griffin 41 Quahog Brewery 2 Lois Griffin 40 Newport Piano Teacher 3 Joseph Swanson 39 Quahog Police Officer 4 Glenn Quagmire 41 Quahog Pilot Example Explained - The HTML Page When a user selects a user in the dropdown list above, a function called "showuser()" is executed. The function is triggered by the "onchange" event: <html> <head> <script type="text/javascript"> function showuser(str) { if (str=="") { document.getelementbyid("txthint").innerhtml=""; return; } if (window.xmlhttprequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() 392

393 { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext; } } xmlhttp.open("get","getuser.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showuser(this.value)"> <option value="">select a person:</option> <option value="1">peter Griffin</option> <option value="2">lois Griffin</option> <option value="3">glenn Quagmire</option> <option value="4">joseph Swanson</option> </select> </form> <br /> <div id="txthint"><b>person info will be listed here.</b></div> </body> </html> The showuser() function does the following: Check if a person is selected Create an XMLHttpRequest object Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the dropdown list) 393

394 The PHP File The page on the server called by the JavaScript above is a PHP file called "getuser.php". The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table: <?php $q=$_get["q"]; $con = mysql_connect('localhost', 'peter', 'abc123'); if (!$con) { die('could not connect: '. mysql_error()); } mysql_select_db("ajax_demo", $con); $sql="select * FROM user WHERE id = '".$q."'"; $result = mysql_query($sql); echo "<table border='1'> <tr> <th>firstname</th> <th>lastname</th> <th>age</th> <th>hometown</th> <th>job</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>". $row['firstname']. "</td>"; echo "<td>". $row['lastname']. "</td>"; echo "<td>". $row['age']. "</td>"; echo "<td>". $row['hometown']. "</td>"; echo "<td>". $row['job']. "</td>"; echo "</tr>"; 394

395 } echo "</table>"; mysql_close($con);?> Explanation: When the query is sent from the JavaScript to the PHP file, the following happens: 1. PHP opens a connection to a MySQL server 2. The correct person is found 3. An HTML table is created, filled with data, and sent back to the "txthint" placeholder AJAX can be used for interactive communication with an XML file. AJAX XML Example The following example will demonstrate how a web page can fetch information from an XML file with AJAX: Example Select a CD: CD info will be listed here... Example Explained - The HTML Page When a user selects a CD in the dropdown list above, a function called "showcd()" is executed. The function is triggered by the "onchange" event: <html> <head> <script type="text/javascript"> function showcd(str) { if (str=="") { 395

396 document.getelementbyid("txthint").innerhtml=""; return; } if (window.xmlhttprequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext; } } xmlhttp.open("get","getcd.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> Select a CD: <select name="cds" onchange="showcd(this.value)"> <option value="">select a CD:</option> <option value="bob Dylan">Bob Dylan</option> <option value="bonnie Tyler">Bonnie Tyler</option> <option value="dolly Parton">Dolly Parton</option> </select> </form> <div id="txthint"><b>cd info will be listed here...</b></div> 396

397 </body> </html> The showcd() function does the following: Check if a CD is selected Create an XMLHttpRequest object Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the dropdown list) The PHP File The page on the server called by the JavaScript above is a PHP file called "getcd.php". The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file, and returns the result as HTML: <?php $q=$_get["q"]; $xmldoc = new DOMDocument(); $xmldoc->load("cd_catalog.xml"); $x=$xmldoc->getelementsbytagname('artist'); for ($i=0; $i<=$x->length-1; $i++) { //Process only element nodes if ($x->item($i)->nodetype==1) { if ($x->item($i)->childnodes->item(0)->nodevalue == $q) { $y=($x->item($i)->parentnode); } } } $cd=($y->childnodes); 397

398 for ($i=0;$i<$cd->length;$i++) { //Process only element nodes if ($cd->item($i)->nodetype==1) { echo("<b>". $cd->item($i)->nodename. ":</b> "); echo($cd->item($i)->childnodes->item(0)->nodevalue); echo("<br />"); } }?> When the CD query is sent from the JavaScript to the PHP page, the following happens: 1. PHP creates an XML DOM object 2. Find all <artist> elements that matches the name sent from the JavaScript 3. Output the album information (send to the "txthint" placeholder) Sample PHP Application PHP is commonly used to: Draw graphics on the fly Access a database Let s put these together to make an application that: Lets a user make a query on a web form Looks up some data from an Access database (similar if using SQL database) Displays a graph of the data from the database Simple Graphics First, let s see how to draw some simple graphics PHP 5 includes the GD graphics library, created by Boutell.com PHP 4 requires an extension be added to access this library PNG format used Similar but superior to GIF GIF patented by Unisys, expired 2003 Base image functions image imagecreate(width,height) Creates and returns an image of specified height color imagecolorallocate(image, R,G,B) Creates a color for image with the given Red, Green, and Blue colors boolean imagefill(image, x, y, color) 398

399 Flood fills at the given point with the given color header("content-type: image/png"); Displays the MIME header for a PNG image imagepng(image) Displays the data for the PNG image Example: Green image <? $image = imagecreate(300,200); $colorgreen = imagecolorallocate($image, 0, 255, 0); imagefill($image, 0, 0, $colorgreen); header("content-type: image/png"); imagepng($image);?> More image functions imagestring (image, int font, int x, int y, string s, int col) Draws the string s in the image at coordinates x, y in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used. imagefilledrectangle(image, x1,y1, x2,y2,color) Draws a filled rectangle at upper left corner x1,y1 bottom right corner x2,y2 imagefilledellipse(image, x1,y1, width,height,color) Draws a filled ellipse in the bounding rectangle specified by x1,y1,x2,y2 imagerectangle(image,x1,y1,x2,y2,color) Rectangle with no fill 399

Social Networking Site

Social Networking Site Governors State University OPUS Open Portal to University Scholarship All Capstone Projects Student Capstone Projects Fall 2010 Social Networking Site Navis Amalraj Governors State University Follow this

More information

WCF - WAS HOSTING. Click Start Menu Control Panel Programs and Features, and click "Turn Windows Components On or Off" in the left pane.

WCF - WAS HOSTING. Click Start Menu Control Panel Programs and Features, and click Turn Windows Components On or Off in the left pane. http://www.tutorialspoint.com/wcf/wcf_was_hosting.htm WCF - WAS HOSTING Copyright tutorialspoint.com To understand the concept of WAS hosting, we need to comprehend how a system is configured and how a

More information

MOSS2007 Write your own custom authentication provider (Part 4)

MOSS2007 Write your own custom authentication provider (Part 4) MOSS2007 Write your own custom authentication provider (Part 4) So in the last few posts we have created a member and role provider and configured MOSS2007 to use this for authentication. Now we will create

More information

ก ก Microsoft Visual Web Developer 2008 Express Edition 1. ก ( ก My Documents)

ก ก Microsoft Visual Web Developer 2008 Express Edition 1. ก ( ก My Documents) ก ก ก. ก ก 56 57 ก ก Microsoft Visual Web Developer 2008 Express Edition 1. ก ( ก My Documents) 1 ก ก 58 2. ก Next ก 2 ก Next 3. ก Microsoft SQL Server 2008 Express Edition (x86) (Download Size: 74 MB)

More information

Windows Communication Foundation

Windows Communication Foundation About the Tutorial WCF stands for Windows Communication Foundation. It is a framework for building, configuring, and deploying network-distributed services. Earlier known as Indigo, it enables hosting

More information

Introduction to Silverlight

Introduction to Silverlight Fox c01.tex V3-01/30/2009 4:56pm Page 1 Introduction to Silverlight As software development has evolved and the process and end result become more complex and sophisticated, so too has the expectation

More information

Insert Data into Table using C# Code

Insert Data into Table using C# Code Insert Data into Table using C# Code CREATE TABLE [registration]( [roll_no] [int] NULL, [name] [varchar](50), [class] [varchar](50), [sex] [varchar](50), [email] [varchar](50))

More information

ASP.NET Security. 7/26/2017 EC512 Prof. Skinner 1

ASP.NET Security. 7/26/2017 EC512 Prof. Skinner 1 ASP.NET Security 7/26/2017 EC512 Prof. Skinner 1 ASP.NET Security Architecture 7/26/2017 EC512 Prof. Skinner 2 Security Types IIS security Not ASP.NET specific Requires Windows accounts (NTFS file system)

More information

BİLGİLERİN GRIDVIEW İÇERİSİNDE EKLENMESİ, DÜZENLENMESİ VE SİLİNMESİ

BİLGİLERİN GRIDVIEW İÇERİSİNDE EKLENMESİ, DÜZENLENMESİ VE SİLİNMESİ BİLGİLERİN GRIDVIEW İÇERİSİNDE EKLENMESİ, DÜZENLENMESİ VE SİLİNMESİ default.aspx

More information

Stateless -Session Bean

Stateless -Session Bean Stateless -Session Bean Prepared by: A.Saleem Raja MCA.,M.Phil.,(M.Tech) Lecturer/MCA Chettinad College of Engineering and Technology-Karur E-Mail: asaleemrajasec@gmail.com Creating an Enterprise Application

More information

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS DATE: 30.9.11 Aim: To create a servlet program to display the students marks Hardware requirements: Intel Core 2 Quad 2GB RAM Software requirements:

More information

Displaying Views of Data (Part II)

Displaying Views of Data (Part II) Displaying Views of Data (Part II) In Chapter 6, we discussed how we can work with the GridView control in ASP. NET. This is the last part in the series of two chapters on how we can use the view controls

More information

XML with.net: Introduction

XML with.net: Introduction XML with.net: Introduction Extensible Markup Language (XML) strores and transports data. If we use a XML file to store the data then we can do operations with the XML file directly without using the database.

More information

ASP.NET Pearson Education, Inc. All rights reserved.

ASP.NET Pearson Education, Inc. All rights reserved. 1 ASP.NET 2 Rule One: Our client is always right. Rule Two: If you think our client is wrong, see Rule One. Anonymous 3 25.1 Introduction ASP.NET 2.0 and Web Forms and Controls Web application development

More information

Employee Attendance System module using ASP.NET (C#)

Employee Attendance System module using ASP.NET (C#) Employee Attendance System module using ASP.NET (C#) Home.aspx DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

More information

Sequence and ASP.NET Applications

Sequence and ASP.NET Applications PNMsoft Knowledge Base Sequence Best Practices Sequence and ASP.NET Applications Decmeber 2013 Product Version 7.x 2013 PNMsoft All Rights Reserved This document, including any supporting materials, is

More information

CIS 3952 [Part 2] Java Servlets and JSP tutorial

CIS 3952 [Part 2] Java Servlets and JSP tutorial Java Servlets Example 1 (Plain Servlet) SERVLET CODE import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet;

More information

To create a view for students, staffs and courses in your departments using servlet/jsp.

To create a view for students, staffs and courses in your departments using servlet/jsp. Aim To create a view for students, staffs and courses in your departments using servlet/jsp. Software Requirements: Java IDE Database Server JDK1.6 Netbean 6.9/Eclipse MySQL Tomcat/Glassfish Login Form

More information

Develop an Enterprise Java Bean for Banking Operations

Develop an Enterprise Java Bean for Banking Operations Develop an Enterprise Java Bean for Banking Operations Aim: Develop a Banking application using EJB3.0 Software and Resources: Software or Resource Version Required NetBeans IDE 6.7, Java version Java

More information

Teacher s Reference Manual

Teacher s Reference Manual UNIVERSITY OF MUMBAI Teacher s Reference Manual Subject: Advanced Web Programming with effect from the academic year 2018 2019 Practical 3(b).Demonstrate the use of Calendar control to perform following

More information

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session Kamnoetvidya Science Academy Object Oriented Programming using Java Ferdin Joe John Joseph Java Session Create the files as required in the below code and try using sessions in java servlets web.xml

More information

CP3343 Computer Science Project (Year) Technical Report Document. Mr Stephen Garner

CP3343 Computer Science Project (Year) Technical Report Document. Mr Stephen Garner CP3343 Computer Science Project (Year) Technical Report Document Mr Stephen Garner Colin Hopson 0482647 Wednesday 23 rd April 2008 i Contents 1 Introduction... 1 2 The Program Listing... 1 2.1 ASP.Net

More information

JAC444 - Lecture 11. Remote Method Invocation Segment 2 - Develop RMI Application. Jordan Anastasiade Java Programming Language Course

JAC444 - Lecture 11. Remote Method Invocation Segment 2 - Develop RMI Application. Jordan Anastasiade Java Programming Language Course JAC444 - Lecture 11 Remote Method Invocation Segment 2 - Develop RMI Application 1 Remote Method Invocation In this lesson you will be learning about: Designing RMI application Developing distributed object

More information

م ار ن ارم... ا ل. وفدم و Sandbox.PayPal وھورةن ور لPal Payود طوريا وا. دا &% ر-) طوات ط) وھ : - ( )

م ار ن ارم... ا ل. وفدم و Sandbox.PayPal وھورةن ور لPal Payود طوريا وا. دا &% ر-) طوات ط) وھ : - (   ) م ار ن ارم...... ASP.NetPayPal ا ل وفدم و Sandbox.PayPal وھورةن ور لPal Payود طوريا وا رب 'ر*مذاتا,تار)لط+*(ورة &)و'رھ&% ا$رتواب ذكب ) ا,تار)ا &+) $ والو+&* نبا%بار. دا &% ر-) طوات ط) وھ : - ( https://developer.paypal.com/

More information

ASP.NET - MANAGING STATE

ASP.NET - MANAGING STATE ASP.NET - MANAGING STATE http://www.tutorialspoint.com/asp.net/asp.net_managing_state.htm Copyright tutorialspoint.com Hyper Text Transfer Protocol HTTP is a stateless protocol. When the client disconnects

More information

1 NEW FACE OF MICROSOFT VISUAL STUDIO 2005

1 NEW FACE OF MICROSOFT VISUAL STUDIO 2005 Sborník vědeckých prací Vysoké školy báňské - Technické univerzity Ostrava číslo 2, rok 2005, ročník LI, řada strojní článek č. 1462 Marek BABIUCH * NEW FEATURES OF ASP.NET 2.0 TECHNOLOGY NOVÉ VLASTNOSTI

More information

What is ASP.NET? ASP.NET 2.0

What is ASP.NET? ASP.NET 2.0 What is ASP.NET? ASP.NET 2.0 is the current version of ASP.NET, Microsoft s powerful technology for creating dynamic Web content. is one of the key technologies of Microsoft's.NET Framework (which is both

More information

ACTIVE SERVER PAGES.NET 344 Module 5 Programming web applications with ASP.NET Writing HTML pages and forms Maintaining consistency with master pages Designing pages with ASP.NET controls Styling sites

More information

3 Customer records. Chapter 3: Customer records 57

3 Customer records. Chapter 3: Customer records 57 Chapter 3: Customer records 57 3 Customer records In this program we will investigate how records in a database can be displayed on a web page, and how new records can be entered on a web page and uploaded

More information

Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Page Language=C# AutoEventWireup=true CodeFile=Default.aspx.cs Inherits=_Default %> در این مقاله قصد داریم با استفاده از Ajax کاربر یک پیام را بدون الگین شدن و با استفاده از IP بتواند الیک و یا دیس الیک کند را در ASPآموزش دهیم. برای شروع یک بانک اطالعاتی به نام Test که حاوی دو جدول به

More information

INTRODUCTION & IMPLEMENTATION OF ASP.NET

INTRODUCTION & IMPLEMENTATION OF ASP.NET INTRODUCTION & IMPLEMENTATION OF ASP.NET CONTENTS I. Introduction to ASP.NET 1. Difference between ASP and ASP.NET 2. Introduction to IIS 3. What is Web Application? Why is it used? II. Implementation

More information

Web based of electronic document management systems

Web based of electronic document management systems Invention Journal of Research Technology in Engineering & Management (IJRTEM) ISSN: 2455-3689 www.ijrtem.com ǁ Volume 1 ǁ Issue 7 ǁ Web based of electronic document management systems Viliam Malcher 1,

More information

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans Installation pre-requisites: NetBeans 7.01 or above is installed; Tomcat 7.0.14.0 or above is installed properly with NetBeans; (see step 7

More information

Session 8. Introduction to Servlets. Semester Project

Session 8. Introduction to Servlets. Semester Project Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the

More information

Chapter 2 How to develop a one-page web application

Chapter 2 How to develop a one-page web application Chapter 2 How to develop a one-page web application Murach's ASP.NET 4.5/C#, C2 2013, Mike Murach & Associates, Inc. Slide 1 The aspx for a RequiredFieldValidator control

More information

ASP.NET Interview Questions

ASP.NET Interview Questions 1 P a g e ASP.NET Interview Questions 2 P a g e Table of Contents 1. About.Net?... 7 2. About.Net Framework... 8 3. About Common Language Runtime (CLR) and its Services?... 12 4. What is managed code in.net?...

More information

In the previous chapter we created a web site with images programmed into HTML page code using commands such as: <img src="images/train.

In the previous chapter we created a web site with images programmed into HTML page code using commands such as: <img src=images/train. Chapter 6: Mountain Bike Club 113 6 Mountain Bike Club In the previous chapter we created a web site with images programmed into HTML page code using commands such as: In

More information

ASP.NET - MULTI THREADING

ASP.NET - MULTI THREADING ASP.NET - MULTI THREADING http://www.tutorialspoint.com/asp.net/asp.net_multi_threading.htm Copyright tutorialspoint.com A thread is defined as the execution path of a program. Each thread defines a unique

More information

Developing User Controls in EPiServer

Developing User Controls in EPiServer Developing User Controls in EPiServer Abstract It is recommended that developers building Web sites based on EPiServer create their own user controls with links to base classes in EPiServer. This white

More information

Principles and Techniques of DBMS 6 JSP & Servlet

Principles and Techniques of DBMS 6 JSP & Servlet Principles and Techniques of DBMS 6 JSP & Servlet Haopeng Chen REliable, INtelligent and Scalable Systems Group (REINS) Shanghai Jiao Tong University Shanghai, China http://reins.se.sjtu.edu.cn/~chenhp

More information

Getting Started. DevForce and Report Sharp-Shooter Silverlight Bundle. Software Prerequisites

Getting Started. DevForce and Report Sharp-Shooter Silverlight Bundle. Software Prerequisites DevForce and Report Sharp-Shooter Silverlight Bundle Getting Started This document walks you through the process of adding reporting capabilities to a DevForce Silverlight application, using PerpetuumSoft

More information

Accessing EJB in Web applications

Accessing EJB in Web applications Accessing EJB in Web applications 1. 2. 3. 4. Developing Web applications Accessing JDBC in Web applications To run this tutorial, as a minimum you will be required to have installed the following prerequisite

More information

How to create a simple ASP.NET page to create/search data on baan using baan logic from the BOBS client sample.

How to create a simple ASP.NET page to create/search data on baan using baan logic from the BOBS client sample. How to create a simple ASP.NET page to create/search data on baan using baan logic from the BOBS client sample. Author: Carlos Kassab Date: July/24/2006 First install BOBS(BaaN Ole Broker Server), you

More information

Unit Notes. ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript

Unit Notes. ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript Unit Notes ICAWEB411A Produce basic client-side script for dynamic web pages Topic 1 Introduction to JavaScript Copyright, 2013 by TAFE NSW - North Coast Institute Date last saved: 18 September 2013 by

More information

3-tier Architecture Step by step Exercises Hans-Petter Halvorsen

3-tier Architecture Step by step Exercises Hans-Petter Halvorsen https://www.halvorsen.blog 3-tier Architecture Step by step Exercises Hans-Petter Halvorsen Software Architecture 3-Tier: A way to structure your code into logical parts. Different devices or software

More information

Session 9. Introduction to Servlets. Lecture Objectives

Session 9. Introduction to Servlets. Lecture Objectives Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 10/11/2018 1 Reading & Reference Reading Use the

More information

JdbcResultSet.java. import java.sql.*;

JdbcResultSet.java. import java.sql.*; 1)Write a program to display the current contents of the tables in the database where table name is Registration and attributes are id,firstname,lastname,age. JdbcResultSet.java import java.sql.*; public

More information

8 Library loan system

8 Library loan system Chapter 8: Library loan system 153 8 Library loan system In previous programs in this book, we have taken a traditional procedural approach in transferring data directly between web pages and the ASP database.

More information

Module 2: Using Master Pages

Module 2: Using Master Pages Module 2: Using Master Pages Contents Overview 1 Lesson: Advantages of Using Master Pages 2 Lesson: Writing Master and Content Pages 9 Lesson: Writing Nested Master Pages 21 Lesson: Programming Master

More information

Servlets by Example. Joe Howse 7 June 2011

Servlets by Example. Joe Howse 7 June 2011 Servlets by Example Joe Howse 7 June 2011 What is a servlet? A servlet is a Java application that receives HTTP requests as input and generates HTTP responses as output. As the name implies, it runs on

More information

PRACTICALES:- Navigation control

PRACTICALES:- Navigation control PRACTICALES:- Navigation control Navigation controls are use to shift control from one page to another. ASP.NET has three new navigation controls: Dynamic menus:- The control displays a standard

More information

32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio

32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio 32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio 1 2 Conexiune - Oracle.ManagedDataAccess.Client... 3 using Oracle.ManagedDataAccess.Client;... public partial class

More information

jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc.

jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc. jmaki Overview Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com Agenda What is and Why jmaki? jmaki widgets Using jmaki widget - List widget What makes up

More information

Unit-4 Working with Master page and Themes

Unit-4 Working with Master page and Themes MASTER PAGES Master pages allow you to create a consistent look and behavior for all the pages in web application. A master page provides a template for other pages, with shared layout and functionality.

More information

Web Programming Paper Solution (Chapter wise)

Web Programming Paper Solution (Chapter wise) .Net.net code to insert new record in database using C#. Database name: College.accdb Table name: students Table structure: std_id number std_name text std_age number Table content (before insert): 2 abcd

More information

Encrypt and Decrypt Username or Password stored in database in ASP.Net using C# and VB.Net

Encrypt and Decrypt Username or Password stored in database in ASP.Net using C# and VB.Net Encrypt and Decrypt Username or Password stored in database in ASP.Net using C# and VB.Net Here Mudassar Ahmed Khan has explained how to encrypt and store Username or Password in SQL Server Database Table

More information

HTML HTML. Chris Seddon CRS Enterprises Ltd 1

HTML HTML. Chris Seddon CRS Enterprises Ltd 1 Chris Seddon seddon-software@keme.co.uk 2000-12 CRS Enterprises Ltd 1 2000-12 CRS Enterprises Ltd 2 Reference Sites W3C W3C w3schools DevGuru Aptana GotAPI Dog http://www.w3.org/ http://www.w3schools.com

More information

Postback. ASP.NET Event Model 55

Postback. ASP.NET Event Model 55 ASP.NET Event Model 55 Because event handling requires a round-trip to the server, ASP.NET offers a smaller set of events in comparison to a totally client-based event system. Events that occur very frequently,

More information

Session 10. Form Dataset. Lecture Objectives

Session 10. Form Dataset. Lecture Objectives Session 10 Form Dataset Lecture Objectives Understand the relationship between HTML form elements and parameters that are passed to the servlet, particularly the form dataset 2 10/1/2018 1 Example Form

More information

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Welcome To PhillyJUG 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation Web Development With The Struts API Tom Janofsky Outline Background

More information

dnrtv! featuring Peter Blum

dnrtv! featuring Peter Blum dnrtv! featuring Peter Blum Overview Hello, I am Peter Blum. My expertise is in how users try to use web controls for data entry and what challenges they face. Being a developer of third party controls,

More information

The true beginning of our end. William Shakespeare, A Midsummer Night s Dream

The true beginning of our end. William Shakespeare, A Midsummer Night s Dream 1 Chapter INTRODUCING ASP.NET 2.0 The true beginning of our end. William Shakespeare, A Midsummer Night s Dream The end goal of this book is to teach and guide the reader through the increasingly large

More information

Web Forms User Security and Administration

Web Forms User Security and Administration Chapter 7 Web Forms User Security and Administration In this chapter: Administering an ASP.NET 2.0 Site...................................... 238 Provider Configuration................................................

More information

J2ME With Database Connection Program

J2ME With Database Connection Program J2ME With Database Connection Program Midlet Code: /* * To change this template, choose Tools Templates * and open the template in the editor. package hello; import java.io.*; import java.util.*; import

More information

Generation of a simple web-application in the Microsoft Visual Studio 2008 with the use of Silverlight Viewer for Reporting Services 2008

Generation of a simple web-application in the Microsoft Visual Studio 2008 with the use of Silverlight Viewer for Reporting Services 2008 Generation of a simple web-application in the Microsoft Visual Studio 2008 with the use of Silverlight Viewer for Reporting Services 2008 Prerequisites.NET Framework 3.5 SP1/4.0 Silverlight v3 Silverlight

More information

LINQ as Language Extensions

LINQ as Language Extensions (Language Integrated Query) The main Topics in this lecture are: What is LINQ? Main Advantages of LINQ. Working with LINQ in ASP.Net Introduction: Suppose you are writing an application using.net. Chances

More information

Caso de Estudio: Parte II. Diseño e implementación de. Integración de Sistemas. aplicaciones Web con.net

Caso de Estudio: Parte II. Diseño e implementación de. Integración de Sistemas. aplicaciones Web con.net Caso de Estudio: Diseño e Implementación de la Capa Web de MiniBank Integración de Sistemas Parte II Diseño e implementación de Parte II. Diseño e implementación de aplicaciones Web con.net Introducción

More information

Working with Data in ASP.NET 2.0 :: Adding Client Side Confirmation When Deleting Introduction

Working with Data in ASP.NET 2.0 :: Adding Client Side Confirmation When Deleting Introduction This tutorial is part of a set. Find out more about data access with ASP.NET in the Working with Data in ASP.NET 2.0 section of the ASP.NET site at http://www.asp.net/learn/dataaccess/default.aspx. Working

More information

Introducing the ASP.NET Membership API

Introducing the ASP.NET Membership API C H A P T E R 21 Membership On one hand, forms authentication solves the critical fundamentals for implementing secure, custom login forms for your ASP.NET applications. On the other hand, the tasks you

More information

ServletConfig Interface

ServletConfig Interface ServletConfig Interface Author : Rajat Categories : Advance Java An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from

More information

Syncfusion Report Platform. Version - v Release Date - March 22, 2017

Syncfusion Report Platform. Version - v Release Date - March 22, 2017 Syncfusion Report Platform Version - v2.1.0.8 Release Date - March 22, 2017 Overview... 5 Key features... 5 Create a support incident... 5 System Requirements... 5 Report Server... 5 Hardware Requirements...

More information

STEP 1: CREATING THE DATABASE

STEP 1: CREATING THE DATABASE Date: 18/02/2013 Procedure: Creating a simple registration form in ASP.NET (Programming) Source: LINK Permalink: LINK Created by: HeelpBook Staff Document Version: 1.0 CREATING A SIMPLE REGISTRATION FORM

More information

Unit-4: Servlet Sessions:

Unit-4: Servlet Sessions: 4.1 What Is Session Tracking? Unit-4: Servlet Sessions: Session tracking is the capability of a server to maintain the current state of a single client s sequential requests. Session simply means a particular

More information

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction. This course Software Architecture with Java will discuss the following topics: Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

CE212 Web Application Programming Part 3

CE212 Web Application Programming Part 3 CE212 Web Application Programming Part 3 30/01/2018 CE212 Part 4 1 Servlets 1 A servlet is a Java program running in a server engine containing methods that respond to requests from browsers by generating

More information

Java TM. JavaServer Faces. Jaroslav Porubän 2008

Java TM. JavaServer Faces. Jaroslav Porubän 2008 JavaServer Faces Jaroslav Porubän 2008 Web Applications Presentation-oriented Generates interactive web pages containing various types of markup language (HTML, XML, and so on) and dynamic content in response

More information

JavaServer Pages (JSP)

JavaServer Pages (JSP) JavaServer Pages (JSP) The Context The Presentation Layer of a Web App the graphical (web) user interface frequent design changes usually, dynamically generated HTML pages Should we use servlets? No difficult

More information

DEV BHOOMI INSTITUTE OF TECHNOLOGY Department of Computer Science and Engineering. Algorithm lab- PCS-553 LAB MANUAL

DEV BHOOMI INSTITUTE OF TECHNOLOGY Department of Computer Science and Engineering. Algorithm lab- PCS-553 LAB MANUAL Department of Computer Science and Engineering Year: 3rd Semester: 5th Algorithm lab- PCS-553 Prepared By: HOD(CSE) 1 Department of Computer Science and Engineering INDEX S.No Practical s Name Tools Remark

More information

Dreamweaver: Portfolio Site

Dreamweaver: Portfolio Site Dreamweaver: Portfolio Site Part 3 - Dreamweaver: Developing the Portfolio Site (L043) Create a new Site in Dreamweaver: Site > New Site (name the site something like: Portfolio, or Portfolio_c7) Go to

More information

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003 Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

Copyright 2011 Sakun Sharma

Copyright 2011 Sakun Sharma Maintaining Sessions in JSP We need sessions for security purpose and multiuser support. Here we are going to use sessions for security in the following manner: 1. Restrict user to open admin panel. 2.

More information

1Application and Page

1Application and Page 1Application and Page Frameworks WHAT S IN THIS CHAPTER? Choosing application location and page structure options Working with page directives, page events, and application folders Choosing compilation

More information

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC) Session 8 JavaBeans 1 Reading Reading & Reference Head First Chapter 3 (MVC) Reference JavaBeans Tutorialdocs.oracle.com/javase/tutorial/javabeans/ 2 2/27/2013 1 Lecture Objectives Understand how the Model/View/Controller

More information

Université Antonine - Baabda

Université Antonine - Baabda Université Antonine - Baabda Faculté d ingénieurs en Informatique, Multimédia, Systèmes, Réseaux et Télécommunications Applications mobiles (Pocket PC, etc ) Project: Manipulate School Database Préparé

More information

ajax1.html 1/2 lectures/7/src/ ajax1.html 2/2 lectures/7/src/

ajax1.html 1/2 lectures/7/src/ ajax1.html 2/2 lectures/7/src/ ajax1.html 1/2 3: ajax1.html 5: Gets stock quote from quote1.php via Ajax, displaying result with alert(). 6: 7: David J. Malan 8: Dan Armendariz 9: Computer Science E-75 10: Harvard Extension School 11:

More information

Overview of ASP.NET and Web Forms

Overview of ASP.NET and Web Forms ASP.NET with Web Forms Objectives Learn about Web Forms Learn the Web controls that are built into Web Forms Build a Web Form Assumptions The following should be true for you to get the most out of this

More information

J2EE Web Development 13/1/ Application Servers. Application Servers. Agenda. In the beginning, there was darkness and cold.

J2EE Web Development 13/1/ Application Servers. Application Servers. Agenda. In the beginning, there was darkness and cold. 1. Application Servers J2EE Web Development In the beginning, there was darkness and cold. Then, mainframe terminals terminals Centralized, non-distributed Agenda Application servers What is J2EE? Main

More information

Web Forms ASP.NET. 2/12/2018 EC512 - Prof. Skinner 1

Web Forms ASP.NET. 2/12/2018 EC512 - Prof. Skinner 1 Web Forms ASP.NET 2/12/2018 EC512 - Prof. Skinner 1 Active Server Pages (.asp) Used before ASP.NET and may still be in use. Merges the HTML with scripting on the server. Easier than CGI. Performance is

More information

Introduction & Controls. M.Madadyar.

Introduction & Controls. M.Madadyar. Introduction & Controls M.Madadyar. htt://www.students.madadyar.com ASP.NET Runtime Comilation and Execution default.asx Which language? C# Visual Basic.NET C# comiler Visual Basic.NET comiler JIT comiler

More information

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype=text/html; charset=windows-31j import=java.util.calendar %> A JSP A.1 JSP Servlet Java HTML JSP HTML Java ( HTML JSP ) JSP Servlet Servlet HTML JSP MyDate.jsp

More information

The main Topics in this lecture are:

The main Topics in this lecture are: Lecture 15: Working with Extensible Markup Language (XML) The main Topics in this lecture are: - Brief introduction to XML - Some advantages of XML - XML Structure: elements, attributes, entities - What

More information

Web Services DELMIA Apriso 2017 Implementation Guide

Web Services DELMIA Apriso 2017 Implementation Guide Web Services DELMIA Apriso 2017 Implementation Guide 2016 Dassault Systèmes. Apriso, 3DEXPERIENCE, the Compass logo and the 3DS logo, CATIA, SOLIDWORKS, ENOVIA, DELMIA, SIMULIA, GEOVIA, EXALEAD, 3D VIA,

More information

Final Documentation Solutions Inc TEAM SOLUTION Micheal Scott Trevor Moore Aurian James Wes Bailoni

Final Documentation Solutions Inc TEAM SOLUTION Micheal Scott Trevor Moore Aurian James Wes Bailoni Final Documentation Solutions Inc. 12.5.2017 TEAM SOLUTION Micheal Scott Trevor Moore Aurian James Wes Bailoni 1 P a g e Table of Contents SITE HIERARCHY... 3 Email/Password... 4 Information... 5 Web.config...

More information

Câu 1: (2 điểm) So sách giữa 2 đối tượng Response và Request. Cho ví dụ minh hoạ.

Câu 1: (2 điểm) So sách giữa 2 đối tượng Response và Request. Cho ví dụ minh hoạ. BỘ CÔNG THƯƠNG TRƯỜNG CĐ KỸ THUẬT CAO THẮNG ------------------------------------- ĐỀ 1 ĐỀ THI HỌC KỲ PHỤ - NĂM HỌC 2009-2010 MÔN : LẬP TRÌNH ỨNG DỤNG WEB 1 LỚP: CDTH07 Thời gian làm bài: 90 phút, không

More information

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD W HI TEPAPER www. p rogres s.com WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD In this whitepaper, we describe how to white label Progress Rollbase private cloud with your brand name by following a

More information

Working with Data in ASP.NET 2.0 :: Custom Formatting Based Upon Data Introduction

Working with Data in ASP.NET 2.0 :: Custom Formatting Based Upon Data Introduction This tutorial is part of a set. Find out more about data access with ASP.NET in the Working with Data in ASP.NET 2.0 section of the ASP.NET site at http://www.asp.net/learn/dataaccess/default.aspx. Working

More information

Introduction to HTML5

Introduction to HTML5 Introduction to HTML5 History of HTML 1991 HTML first published 1995 1997 1999 2000 HTML 2.0 HTML 3.2 HTML 4.01 XHTML 1.0 After HTML 4.01 was released, focus shifted to XHTML and its stricter standards.

More information