INDEX Sr. No. Name of the Assignment 1 To learn & understand VB and WinSock Control.

Develop a client application using TCP & UDP protocols. Implement a “Quote of the Day” Server 2 To learn & understand Internet Transfer Control in Visual Basic. To develop internet update program using Inet Control. 3 To learn & understand MAPI control. To develop a simple Email application using MAPI control. 4 To learn & understand the basic concepts of web page designing. To design web page using different types of tags. 5 To learn & understand XML DTD, XML Schema & XSLT. To create XML DTD, XML document & XML Schema for an application Use XSLT for formatting of XML document. 6 Learn & understand IIS/PWS/Apache server. To install and configure IIS/PWS/Apache server. Study and use various facilities/commands and features of IIS/PWS/Apache Server. 7 Develop a simple Web based application for joining report to the new class. Use ASP to store the same information in database & display the contents as per user request. 8 To learn & understand client side validation of web page. 9 Write a PHP Script that computes total cost of the ordered items from assignment 4, after adding sales tax. The script will show exactly what items have been ordered. 10 Write an application that should read a SQL query from the user based on some database in say MySQL, call a PHP script to process the query and display the results. 11 Write a program in C/C++ to implement an ECHO server, using Socket programming with both TCP and UDP protocols. 12 Assignment to learn and understand Linux and/or Novel Netware Network configurations and commands. 13 To study any protocol analyzer software (eg. LanExplorer) and to learn, use its important features, Study of network monitoring software like ETHREAL software. 14 Study of existing LAN and understand the design and various Page No. 1 11 20 28 31 51 58 72 77 80 88 96 108 109

15

components. Set up a small network of 3 to 4 computers and Hub/Switch as directed by the instructor. Use LAN Card, UTP Cables and Connectors. Install LAN Cards and Crimp the connectors. Assign unique IP addresses and share C drive on each machine. Test the network by using PING command. Use protocol analyzer Software. To learn and understand Windows 2003 server and it’s 110 associated domain operations, to configure RAS and DHCP, to add users and computers to a domain Assignment No: 1 Title: “Quote of the Day” Server using VB Winsock Control

OBJECTIVE: 1. To learn & understand VB and WinSock Control. 2. Develop a client application using TCP & UDP protocols. 3. Implement a “Quote of the Day” Server Theory: A WinSock control allows you to connect to a remote machine and exchange data using either the User Datagram Protocol (UDP) or the Transmission Control Protocol (TCP). Both protocols can be used to create client and server applications. Like the Timer control, the WinSock control doesn't have a visible interface at run time. Possible Uses
• • •

Create a client application that collects user information before sending it to a central server. Create a server application that function as a central collection point for data from several users. Create a "chat" application.

Selecting a Protocol When using the WinSock control, the first consideration is whether to use the TCP or the UDP protocol. The major difference between the two lies in their connection state:
2

The TCP protocol control is a connection-based protocol, and is analogous to a telephone — the user must establish a connection before proceeding. The UDP protocol is a connectionless protocol, and the transaction between two computers is like passing a note: a message is sent from one computer to another, but there is no explicit connection between the two. Additionally, the maximum data size of individual sends is determined by the network.

The nature of the application you are creating will generally determine which protocol you select. Here are a few questions that may help you select the appropriate protocol: 1. Will the application require acknowledgment from the server or client when data is sent or received? If so, the TCP protocol requires an explicit connection before sending or receiving data. 2. Will the data be extremely large (such as image or sound files)? Once a connection has been made, the TCP protocol maintains the connection and ensures the integrity of the data. This connection, however, uses more computing resources, making it more "expensive." 3. Will the data be sent intermittently, or in one session? For example, if you are creating an application that notifies specific computers when certain tasks have completed, the UDP protocol may be more appropriate. The UDP protocol is also more suited for sending small amounts of data. Setting the Protocol To set the protocol that your application will use: at design-time, on the Properties window, click Protocol and select either sckTCPProtocol, or sckUDPProtocol. You can also set the Protocol property in code, as shown below: Winsock1.Protocol = sckTCPProtocol

3

Determining the Name of Your Computer To connect to a remote computer, you must know either its IP address or its "friendly name." The IP address is a series of three digit numbers separated by periods (xxx.xxx.xxx.xxx). In general, it's much easier to remember the friendly name of a computer. To find your computer's name
1. On the Taskbar of your computer, click Start. 2. On the Settings item, click the Control Panel. 3. Double-click the Network icon. 4. Click the Identification tab. 5. The name of your computer will be found in the Computer name

box. Once you have found your computer's name, it can be used as a value for the RemoteHost property. TCP Connection Basics When creating an application that uses the TCP protocol, you must first decide if your application will be a server or a client. Creating a server means that your application will "listen," on a designated port. When the client makes a connection request, the server can then accept the request and thereby complete the connection. Once the connection is complete, the client and server can freely communicate with each other. The following steps create a rudimentary server: To create a TCP server 1. 2. 3. 4. Create a new Standard EXE project. Change the name of the default form to frmServer. Change the caption of the form to "TCP Server." Draw a Winsock control on the form and change its name to tcpServer. 5. Add two TextBox controls to the form. Name the first txtSendData, and the second txtOutput. 6. Add the code below to the form.

4

Private Sub Form_Load() ' Set the LocalPort property to an integer. Then invoke the Listen method. tcpServer.LocalPort = 1001 tcpServer.Listen frmClient.Show ' Show the client form. End Sub Private Sub tcpServer_ConnectionRequest _(ByVal requestID As Long) ' Check if the control's State is closed. If not, close the connection before ‘ accepting the new connection. If tcpServer.State <> sckClosed Then _ tcpServer.Close ' Accept the request with the requestID parameter. tcpServer.Accept requestID End Sub Private Sub txtSendData_Change() ' The TextBox control named txtSendData contains the data to be sent. ‘ Whenever the user types into the textbox, the string is sent using the ‘ SendData method. tcpServer.SendData txtSendData.Text End Sub Private Sub tcpServer_DataArrival _(ByVal bytesTotal As Long)

5

' Declare a variable for the incoming data. ' Invoke the GetData method and set the Text property of a TextBox named ‘ txtOutput to the data. Dim strData As String tcpServer.GetData strData txtOutput.Text = strData End Sub The procedures above create a simple server application. However, to complete the scenario, you must also create a client application. To create a TCP client 1. 2. 3. 4. Add a new form to the project, and name it frmClient. Change the caption of the form to TCP Client. Add a Winsock control to the form and name it tcpClient. Add two TextBox controls to frmClient. Name the first txtSend, and the second txtOutput. 5. Draw a CommandButton control on the form and name it cmdConnect. 6. Change the caption of the CommandButton control to Connect. 7. Add the code below to the form. Important Be sure to change the value of the RemoteHost property to the friendly name of your computer. Private Sub Form_Load() ' The name of the Winsock control is tcpClient. ' Note: to specify a remote host, you can use either the IP address (ex: "121.111.1.1") or ' the computer's "friendly" name, as shown here. tcpClient.RemoteHost = "RemoteComputerName"

6

tcpClient.RemotePort = 1001 End Sub Private Sub cmdConnect_Click() ' Invoke the Connect method to initiate a connection. tcpClient.Connect End Sub Private Sub txtSend_Change() tcpClient.SendData txtSend.Text End Sub Private Sub tcpClient_DataArrival _(ByVal bytesTotal As Long) Dim strData As String tcpClient.GetData strData txtOutput.Text = strData End Sub The code above creates a simple client-server application. To try the two together, run the project, and click Connect. Then type text into the txtSendData TextBox on either form, and the same text will appear in the txtOutput TextBox on the other form. Accepting More than One Connection Request The basic server outlined above accepts only one connection request. However, it is possible to accept several connection requests using the same control by creating a control array. In that case, you do not need to close the connection, but simply create a new instance of the control (by setting its Index property), and invoking the Accept method on the new instance.

7

The code below assumes there is a Winsock control on a form named sckServer, and that its Index property has been set to 0; thus the control is part of a control array. In the Declarations section, a module-level variable intMax is declared. In the form's Load event, intMax is set to 0, and the LocalPort property for the first control in the array is set to 1001. Then the Listen method is invoked on the control, making it the "listening control. As each connection request arrives, the code tests to see if the Index is 0 (the value of the "listening" control). If so, the listening control increments intMax, and uses that number to create a new control instance. The new control instance is then used to accept the connection request. Private intMax As Long Private Sub Form_Load() intMax = 0 sckServer(0).LocalPort = 1001 sckServer(0).Listen End Sub Private Sub sckServer_ConnectionRequest _(Index As Integer, ByVal requestID As Long) If Index = 0 Then intMax = intMax + 1 Load sckServer(intMax) sckServer(intMax).LocalPort = 0 sckServer(intMax).Accept requestID Load txtData(intMax) End If End Sub

8

UDP Basics Creating a UDP application is even simpler than creating a TCP application because the UDP protocol doesn't require an explicit connection. In the TCP application above, one Winsock control must explicitly be set to "listen," while the other must initiate a connection with the Connect method. In contrast, the UDP protocol doesn't require an explicit connection. To send data between two controls, three steps must be completed (on both sides of the connection): 1. Set the RemoteHost property to the name of the other computer. 2. Set the RemotePort property to the LocalPort property of the second control. 3. Invoke the Bind method specifying the LocalPort to be used. (This method is discussed in greater detail below.) Because both computers can be considered "equal" in the relationship, it could be called a peer-to-peer application. To demonstrate this, the code below creates a "chat" application that allows two people to "talk" in real time to each other: To create a UDP Peer 1. 2. 3. 4. Create a new Standard EXE project. Change the name of the default form to frmPeerA. Change the caption of the form to "Peer A." Draw a Winsock control on the form and name it udpPeerA. 5. On the Properties page, click Protocol and change the protocol to UDPProtocol. 6. Add two TextBox controls to the form. Name the first txtSend, and the second txtOutput. 7. Add the code below to the form. Private Sub Form_Load() ' The control's name is udpPeerA With udpPeerA ' IMPORTANT: be sure to change the RemoteHost value to the name of
9

‘ your computer. .RemoteHost= "PeerB" .RemotePort = 1001 ' Port to connect to. .Bind 1002 ' Bind to the local port. End With frmPeerB.Show ' Show the second form. End Sub Private Sub txtSend_Change() ' Send text as soon as it's typed. udpPeerA.SendData txtSend.Text End Sub Private Sub udpPeerA_DataArrival _(ByVal bytesTotal As Long) Dim strData As String udpPeerA.GetData strData txtOutput.Text = strData End Sub To create a second UDP Peer 1. 2. 3. 4. Add a standard form to the project. Change the name of the form to frmPeerB. Change the caption of the form to "Peer B." Draw a Winsock control on the form and name it udpPeerB. 5. On the Properties page, click Protocol and change the protocol to UDPProtocol. 6. Add two TextBox controls to the form. Name the TextBox txtSend, and the second txtOutput.
10

7. Add the code below to the form. Private Sub Form_Load() ' The control's name is udpPeerB. With udpPeerB ' IMPORTANT: be sure to change the RemoteHost ' value to the name of your computer. .RemoteHost= "PeerA" .RemotePort = 1002 ' Port to connect to. .Bind 1001 ' Bind to the local port. End With End Sub Private Sub txtSend_Change() ' Send text as soon as it's typed. udpPeerB.SendData txtSend.Text End Sub Private Sub udpPeerB_DataArrival _(ByVal bytesTotal As Long) Dim strData As String udpPeerB.GetData strData txtOutput.Text = strData End Sub

11

To try the example, press F5 to run the project, and type into the txtSend TextBox on either form. The text you type will appear in the txtOutput TextBox on the other form. About the Bind Method As shown in the code above, you must invoke the Bind method when creating a UDP application. The Bind method "reserves" a local port for use by the control. For example, when you bind the control to port number 1001, no other application can use that port to "listen" on. This may come in useful if you wish to prevent another application from using that port. The Bind method also features an optional second argument. If there is more than one network adapter present on the machine, the LocalIP argument allows you to specify which adapter to use. If you omit the argument, the control uses the first network adapter listed in the Network control panel dialog box of the computer's Control Panel Settings. When using the UDP protocol, you can freely switch the RemoteHost and RemotePort properties while remaining bound to the same LocalPort. However, with the TCP protocol, you must close the connection before changing the RemoteHost and RemotePort properties. Useful Winsock Functions:

• •

Winsock1.Listen: This function makes your Winsock control listen on the LocalPort specified either with the function below or in the properties for this control. Winsock1.LocalPort: This is the port where all incoming data arrives, including connection requests Winsock1.Connect [HostIP], [RemotePort]: This will attempt to connect to the HostIP on the RemotePort of that computer, which should be what that computer is listening on. Both parameters are optional. Winsock1.Accept [requestID]: This is how you accept a connection in the Winsock_ConnectionRequest Event. You must put Winsock1.Accept requestID. Winsock1.SendData [Data]: This is what you use to send data with Winsock, you can send any time, but we recommend Strings with a special Function to Process it. The only 2 logical data types to send would be a Byte Array or a String.
12

Winsock1.GetData [Data], [Type], [MaxLen]: This is how you receive all data from the Winsock control, Data = a variable, and Type = vbString, vbInteger etc. MaxLen is optional. This can only be used if data is sitting in the buffer, for instance using it in the Winsock_DataArrival event is a very practical use. Winsock1.RemoteHostIP [IPAddress]: Use this to specify an IP address to connect to ahead of time.

Procedure: To create a TCP/UDP server 1. Create a new Standard EXE project. 2. 3. 4. 5. 6. Draw two Winsock controls on the form, one for TCP & one for UDP. Accept Client’s request. If the request is for TCP, establish connection with Client. According the client’s request, send the quote of the day. If the request is UDP, send the quote of the day.

To create a TCP/UDP Client 1. 2. 3. 4. 5. 6. Create a new Standard EXE project. Add a Winsock control to the form. Allow client to select TCP or UDP Option. Provide the name of the Server and the Port Number. If Client selects “TCP” option, send connection request to server. When the user clicks a button “Get the Quote”, the client will receive the quote from the server. 7. If Client selects “UDP” option, &clicks a button “Get the Quote”, the client will receive the quote from the server. APPLICATIONS 1. Used to design the client server applications. FAQS 1. What is difference between TCP & UDP protocol ?

13

2. How to use “Winsock Control “?

Assignment No: 2 Title: “ Internet Update” program using Internet Transfer Control OBJECTIVES: 1. To learn & understand Internet Transfer Control in Visual Basic. 2. To develop internet update program using Inet Control. Theory: The Internet Transfer control implements two widely-used Internet protocols: the HyperText Transfer Protocol (HTTP) and the File Transfer Protocol (FTP). Using the Internet Transfer control, you can connect to any site that uses one of these protocols, and retrieve files using either the OpenURL or Execute method. Possible Uses
• • • •

To add an FTP browser to any application. To create an application that automatically downloads files from a public FTP site. To parse a World Wide Web site for graphics references and download the graphics only. To present a custom display of dynamic data retrieved from a Web page.

Basic Operation The functionality of the Internet Transfer control depends on the protocol you wish to use. Because the two supported protocols work differently, the operations you can perform depend on which protocol you are using. For example, the GetHeader method only works with HTTP (HTML documents).

14

However, there are a few procedures that are common to both protocols. Basically, in order to use either protocol, you must: 1. Set the AccessType property to a valid proxy server. 2. Invoke the OpenURL method with a valid URL. 3. Invoke the Execute method with a valid URL and command appropriate to the protocol. 4. Use the GetChunk method to retrieve data from the buffer. Setting the AccessType Property: Using a Proxy Server In order to make any kind of connection to the Internet, you must determine how your computer is connected to the Internet. If you are on an intranet, you will probably be connected to the Internet via a proxy server. In short, a proxy server is an intermediary between your computer and the Internet. All computers on an intranet that need to connect to the Internet must do so through a proxy server. Thus the proxy functions as a firewall between the intranet and the Internet, discarding invalid end-user and external requests, thereby protecting the intranet from hostile actions. To find the proxy settings on your computer Note The following steps apply only to Windows 95, Windows NT 4.0, or later systems. On the Taskbar of your computer, click Start. On the Settings item, click the Control Panel. Double-click the Internet icon. On the Internet Properties dialog box, click Connection. Under Proxy Server, confirm that the Connect Through a Proxy Server check box is selected. 6. If it is selected, click Settings. The name of proxy servers you use for various protocols will be found in the dialog box. If no proxy is defined, contact your system administrator for available proxy servers.
1. 2. 3. 4. 5.

If you intend to use a proxy other than that named in the dialog box, set the AccessType property to icNamedProxy (2). Then set the Proxy property to the name of the proxy, as shown in the code below: Inet1.Proxy = "myProxyName"
15

Inet1.AccessType = icNamedProxy On the other hand, if you are content to use the default proxy (as determined by your computer's registry), ignore the Proxy property, and simply set the AccessType to icUseDefault (0). The settings for AccessType are shown in the following table: Constant icUseDefault Description (Default) Use Defaults. The control uses default settings found in the registry to access the Internet. icDirect 1 Direct to Internet. The control has a direct connection to the Internet. icNamedProxy 2 Named Proxy. Instructs the control to use the proxy server specified in the Proxy property. Invoke the OpenURL Method After you set the AccessType property, the most basic operation is to use the OpenURL method with a valid URL. When you use the OpenURL method, the result will depend on the target URL. For example, the following URL will return the HTML document found at www.microsoft.com: ' A TextBox control named Text1 contains the ' result of the method. The Internet Transfer ' control is named Inet1. Text1.Text = Inet1.OpenURL("http://www.microsoft.com") As a result, the TextBox control is filled with the HTML source, which may resemble the figure below: In this case, the default action was to return the HTML document located at the URL. However, if the URL is modified to target a specific text file, the actual file would be retrieved. For example, the following code: Text1.Text = Inet1.OpenURL ("ftp://ftp.microsoft.com/disclaimer.txt") would result in the actual text of the file, as shown below:
16

Value 0

Tip When you use either the OpenURL or Execute method, you need not set the Protocol property. The Internet Transfer control will automatically set itself to the correct protocol, as determined by the protocol portion of the URL. Finally, you can use the OpenURL method with a URL that includes appended data. For example, many Web sites offer the ability to search a database. To search, send a URL that includes the search criteria. For example, the following code would use a search engine named "search.exe" with the criteria "find=Maui." Dim strURL As String strURL = "http://www.megaphone43.com/cgi-bin/search.exe?find=maui Text1.Text = Inet1.OpenURL (strURL) If the search engine finds a match for the criteria, an HTML document would be assembled and returned with the appropriate information. Saving to a File Using the OpenURL Method If you wish to save the data retrieved through the OpenURL method to a file, use the Open, Put, and Close statements, as shown in the code below. This example streams a binary file into a Byte array before saving the data to disk: Dim strURL As String Dim bData() As Byte ' Data variable Dim intFile As Integer ' FreeFile variable strURL = "ftp://ftp.microsoft.com/Softlib/Softlib.exe" intFile = FreeFile() ' Set intFile to an unused file. ' The result of the OpenURL method goes into the Byte array, and the Byte array is ‘ then saved to disk.

17

bData() = Inet1.OpenURL(strURL, icByteArray) Open "C:\Temp\Softlib.exe" For Binary Access Write As #intFile Put #intFile, , bData() Close #intFile A similar procedure can be used to write a text file to disk, except no Byte array is needed; the data is saved directly to the file: Dim strURL As String ' URL string Dim intFile As Integer ' FreeFile variable IntFile = FreeFile() strURL = "http://www.microsoft.com" Open "c:\temp\MSsource.txt" For Output _ As #IntFile Write #IntFile, Inet1.OpenURL(strURL) Close #IntFile Synchronous and Asynchronous Transmission The OpenURL method results in a synchronous transmission of data. In this context, synchronous means that the transfer operation occurs before any other procedures are executed. Thus the data transfer must be completed before any other code can be executed. On the other hand, the Execute method results in an asynchronous transmission. When the Execute method is invoked, the transfer operation occurs independently of other procedures. Thus, after invoking the Execute method, other code can execute while data is received in the background. What does this mean for the user of the Internet Transfer control? In short, using the OpenURL method results in a direct stream of data that you can save to disk (as shown above), or view directly in a TextBox control (if the
18

data was text). On the other hand, if you use the Execute method to retrieve data, you must monitor the control's connection state using the StateChanged event. When the appropriate state is reached, invoke the GetChunk method to retrieve data from the control's buffer. This operation is discussed in greater detail below. Using the Execute Method with the FTP Protocol The Execute method has four arguments: url, operation, data, and requestHeaders. FTP operations take only the operation argument and the url argument, which is optional. For example, to get a file from a remote computer, you could use the following code: Inet1.Execute "FTP://ftp.microsoft.com", "GET disclaimer.txt C:\Temp\Disclaimer.txt" If you are used to using FTP to retrieve files from anonymous FTP servers, you will be familiar with certain commands used to navigate through server trees, and to retrieve files to a local hard disk. For example, to change directory with the FTP protocol, you would use the command "CD" with the path of the directory you wish to change to. For the most common operations, such as putting a file on a server and retrieving a file from a server, the Internet Transfer control uses the same or a similar command with the Execute method. For example, the following code uses the "CD" command as an argument of the Execute method to change directory: ' The txtURL textbox contains the path to open. The txtRemotePath textbox contains ‘ the path to change to. Inet1.Execute txtURL.Text, "CD " & txtRemotePath.Text Note When using the Execute method with FTP commands, the data and requestHeaders arguments are not used. Instead, all of the operations and their parameters are passed as a single string in the operation argument; parameters are separated by a space. In the descriptions below, do not confuse the terms "file1" and "file2" with the data and requestHeaders arguments.
19

The syntax for FTP operations is: operationName file1 file2 For example, to get a file, the following code includes the operation name ("GET"), and the two file names required by the operation: ' Get the file named Disclaimer.txt and copy it to the location C:\Temp\Disclaimer.txt Inet1.Execute, "GET Disclaimer.txt C:\Temp\Disclaimer.txt" The following table lists the supported FTP commands of the control: Operation CD file1 Description Change Directory. Changes to the directory specified in file1. Change to Parent. Same as "CD .." Deletes the file specified in file1. Searches the directory specified in file1. If file1 isn't supplied, the current working directory is searched. Use the GetChunk method to return the data. Retrieves the remote file specified in file1, and creates a new local file specified in file2. Creates a directory as specified in file1. Success is dependent on user privileges on the remote host. Copies a local file specified in file1 to the remote host Example Execute , "CD docs\mydocs"

CDUP DELETE file1 DIR [ file1 ]

Execute , "CDUP" Execute , "DELETE discard.txt" Execute , "DIR /mydocs"

GET file1 file2

Execute , _ "GET getme.txt C:\gotme.txt" Execute , "MKDIR /myDir"

MKDIR file1

PUT file1 file2

Execute , _

20

specified in file2. PWD

Print Working Directory. Returns the current directory name. Use the GetChunk method to return the data. QUIT Terminate current Execute , "QUIT" connection RECV file1 file2 Same as GET. Execute , _ RENAME file1 file2 RMDIR file1

"PUT C:\putme.txt /putme.txt" Execute , "PWD"

SEND file1

SIZE file1

Renames a file. Success is dependent on user privileges "RENAME old.txt new.txt" on the remote host. Remove directory. Success Execute , "RMDIR oldDir" is dependent on user privileges on the remote host. Copies a file to the FTP site. Execute , _ (same as PUT.) "SEND C:\putme.txt /putme.txt" Returns the size of the file Execute "SIZE /largefile.txt" specified in file1.

"RECV getme.txt C:\gotme.txt" Execute ,

Important If your proxy server is a CERN proxy server, direct FTP connections (using the Execute method) are disallowed. In that case, to get a file, use the OpenURL method with the Open, Put, and Close statements, as shown earlier in "Saving to a File Using the OpenURL Method." You can also use the OpenURL method to get a directory listing by invoking the method and specifying the target directory as the URL. Using the Execute Method with the HTTP Protocol The HTTP protocol allows client machines to request data from the server using the GET, HEAD, POST, and PUT commands. These operations are shown in the following table:

21

Operation GET HEAD

Description Retrieves the file named in url.

Example Execute "http://www.microsoft.com" & _ "/default.htm", "GET" Execute , "HEAD"

Retrieves only the headers of the file named in the URL property. POST Provides Execute , "POST", strFormData additional data to support a request to the remote host. PUT Replaces data at Execute , "PUT", "replace.htm" the specified URL. The Common Gateway Interface and the Execute Method Many World Wide Web sites offer the ability to search a database. This is accomplished by using the HTTP protocol's ability to send queries using the Common Gateway Interface (CGI). It is not in the scope of this topic to explain the CGI; however, if you are familiar with the CGI, you can use the Execute method to construct an application that simulates the behavior of World Wide Web sites. For example, the code below shows a typical CGI query string: http://www.findThis2490.com/cgi-bin/find.exe?find=Hangzhou This same query could be sent using the Execute method as shown below: Dim strURL As String, strFormData As String strURL = "//www.findThis2490.com/cgi-bin/find.exe" strFormData = "find=Hangzhou" Inet1.Execute strURL, "POST", strFormData If you are expecting a result back from a server (as in the example above), you must use the GetChunk method to retrieve the resulting HTML document.
22

Using the State Event with the GetChunk Method When you are downloading data from a remote computer, an asynchronous connection will be made. For example, using the Execute method with the operation "GET", will cause the server to retrieve the requested file. When the entire file has been retrieved, the State argument will return icResponseCompleted (12). At that point, you can use the GetChunk method to retrieve the data from the buffer. This is shown in the example below: Private Sub Inet1_StateChanged(ByVal State As Integer) Dim vtData As Variant ' Data variable. Select Case State ' ... Other cases not shown. Case icResponseCompleted ' 12 ' Open a file to write to. Open txtOperation For Binary Access _ Write As #intFile ' Get the first chunk. NOTE: specify a Byte ' array (icByteArray) to retrieve a binary file. vtData = Inet1.GetChunk(1024, icString) Do While LenB(vtData) > 0 Put #intFile, , vtData ' Get next chunk. vtData = Inet1.GetChunk(1024, icString) Loop Put #intFile, , vtData
23

Close #intFile End Select End Sub Logging on to FTP Servers FTP servers come in two flavors: public and private. Public servers, as suggested by the name, are open to anyone. Private servers, on the other hand, won't let you log on unless you are a bona fide user of the server. In either case, the FTP protocol demands that you supply a user name and a password. The two are used to authenticate a user and allow (or disallow) subsequent actions. To log on to public servers the common practice is to log in as "anonymous," (UserName = "anonymous") and send your e-mail name as the password. However this process is simplified even further with the Internet Transfer control. By default, if you do not supply UserName and Password property values, the control sends "anonymous" as your UserName, and your e-mail name for the Password. If you are logging on to a private server, simply set the UserName, Password, and URL properties as appropriate, and invoke the Execute method, as shown in the example below: With Inet1 .URL = "ftp://ftp.someFTPSite1020.com" .UserName = "John Smith" .Password = "mAuI&9$6" .Execute ,"DIR" ' Returns the directory. .Execute ,"CLOSE" ' Close the connection. End With After you have invoked the Execute method, the FTP connection will remain open. You can then continue to use the Execute method to perform other
24

FTP operations such as CD and GET. When you have completed the session, close the connection using the Execute method with the CLOSE operation. You can also close the connection automatically by changing the URL property, and invoking either the OpenURL or Execute method; such action will close the current FTP connection, and open the new URL. Procedure: 1. 2. 3. 4. 5. 6. Create a new Standard EXE project. Add an Inet control to the form. Send ftp request with anonymous FTP login. Get the files from ftp server. Check for new version of existing files. If it is available then update the files.

APPLICATIONS 1. Used to develop applications related to file transfer.

FAQS 1. What are the different methods & properties of Inet control ? 2. Can we use Winsock Control instead of Inet control for Internet Update ? 3. How to use Inet control for file transfer ?

25

Assignment No: 3 Title: Email Application OBJECTIVES: 1. To learn & understand MAPI control. 2. To develop a simple Email application using MAPI control. Theory: The messaging application program interface (MAPI) controls allow you to create mail-enabled Visual Basic applications. MAPI is a set of core system components that seamlessly connect any mail-enabled or workgroup application to MAPI-compliant information services. For example, the Microsoft Exchange messaging system can be connected to most private or public e-mail systems through the use of MAPI drivers. In Visual Basic, the MAPI controls are used to interact with the underlying message subsystem. To use these controls, you must first install a MAPIcompliant e-mail system like Microsoft Exchange. The underlying messaging services are provided by the workgroup environment — the Microsoft Exchange Server running under Windows 95 (or later) or Windows NT, for instance. Using the MAPI controls involves two steps: establishing a MAPI session and then using various properties and methods to access and manage an individual Inbox. For example, create and send a message, include a file attachment, verify the recipient's address against the e-mail system's address book, etc. The MAPISession control signs on and establishes a MAPI session. It is also used to sign off from a MAPI session. The MAPIMessages control contains all the properties and methods needed to perform the messaging system functions described above. The MAPI controls are invisible at run time. In addition, there are no events for the controls. To use them you must set the appropriate properties or specify the appropriate methods.

26

Note If you attempt to run a program that uses the MAPI controls, make sure that you have the 32-bit MAPI DLLs installed properly or you may not be able to perform MAPI functions such as SignOn. For example, on Windows 95 or later, you must install Exchange during the operating system setup, or install it separately from the control panel to correctly use MAPI functions. Possible Uses
• •

To add messaging functionality to your application. To create a full-featured electronic mail application.

Using the MAPISession control The MAPISession control is used to sign in and out of a MAPI session. Assuming that MAPI services are present, logging in with the MAPISession control is merely a matter of providing a registered user name and password. The MAPISession control will determine the electronic mail settings specified in the operating system and invoke the underlying message subsystem (the mail server). The MAPISession control Setting MAPISession Properties You can set the MAPISession properties at design time using the MAPISession Property Pages. Right-click the MAPISession control and click Properties to display the Property Pages dialog box. Setting the MAPISession properties at design time The UserName and Password properties are used to provide a valid sign-on to the underlying messaging system. You can either set these properties at design time or prompt the user at run time. Setting the LogonUI property to True will provide the user with the sign-on dialog box of the underlying mail system. If such a dialog box does not exist, this property will be ignored. You can create a custom dialog box to prompt the user for this information. The NewSession property specifies whether a new mail session should be established. If a valid session is already established, setting the NewSession property will allow two sessions to run concurrently.
27

The DownloadMail property specifies whether the user's mail will be downloaded at the beginning of the current session automatically. Setting this value to True will download all the user's mail to their Inbox. Depending upon the mail system and the amount of incoming mail, this can be a processing-intensive operation. By setting this property to False, the user can choose to download mail at a later time or set the interval at which mail is automatically downloaded. The SignOn and SignOff Methods Once the UserName and Password properties have been set, use the SignOn method at run time to begin the MAPI session. For example: mpsSession.SignOn When the session is established, the session handle is stored in the SessionID property. Depending upon the value of the NewSession property, the session handle may refer to a newly created session or an existing session. To end the session uses the SignOff method. Note The Action property can also be used to sign in and out of a MAPI session. It is recommended, however, that you use the SignOn and SignOff methods instead. The Action property is included for compatibility with earlier versions of Visual Basic. The SessionID Property When the SignOn method is used to successfully establish a messaging session, the SessionID property will return a unique messaging session handle. The SessionID value will be used by the MAPIMessages control to create an association with a valid messaging session. By default, this value is 0.

28

Using the MAPIMessages Control Once you've logged into a messaging session using the MAPISession control, you use the MAPIMessages control to receive, send, or read messages from the Inbox, which was specified at sign-on time. The MAPIMessages control provides you with properties and methods to perform basic electronic mail tasks. For example, composing a message, addressing it to a recipient, verifying that the recipient's address is valid, or attaching a file. The MAPIMessages control In most cases, the MAPIMessage control is used to provide e-mail capabilities to certain functions within an application. For example, you may want to send a notification message to a workgroup alias after your application has automatically created a report. In other words, you can add e-mail capabilities to your application, without creating full-fledged e-mail applications. You can, however, use the MAPI controls to create very powerful mailenabled and workgroup applications. Associating SessionID Properties The SessionID property of the MAPIMessages control contains the messaging session handle returned by the SessionID property of the MAPISession control. To associate the MAPIMessages control with a valid messaging session, set this property to the SessionID of a MAPISession control that was successfully signed on. For example: mpmMessage.SessionID = mpsSession.SessionID This association to a valid MAPI session must be made before you can access messages and begin working with the MAPIMessages control. Accessing Messages Successfully logging into a MAPI session accesses the Inbox of the registered user specified by the UserName and Password properties of the

29

MAPISession control. The Inbox is the message store. When the Inbox is opened two buffers are created: the compose buffer and the read buffer. The read buffer is made up of an indexed set of messages fetched from the user's Inbox. The MsgIndex property is used to access individual messages within this set, starting with a value of 0 for the first message and incrementing by one for each message through the end of the set. The message set is built using the Fetch method. The set includes all messages of type FetchMsgType and is sorted as specified by the FetchSorted property. The value of the FetchMsgType property is controlled by the underlying message system. The FetchSorted property can be set to add messages to the message set (read buffer) in the order they are received or in the order specified by the user's Inbox. Previously read messages can be included or left out of the message set with the FetchUnreadOnly property. Messages in the read buffer can't be altered by the user, but can be copied to the compose buffer for alteration. Messages are created or edited in the compose buffer. The compose buffer is active when the MsgIndex property is set to –1. Many of the messaging actions are valid only within the compose buffer, such as sending messages, saving messages, or deleting recipients and attachments.

30

Composing and Managing Messages Method Compose Copy Description Composes a new message Copies the currently indexed message to the compose buffer Delete Deletes a message, recipient, or attachment Fetch Creates a message set from selected messages in the Inbox Forward Forwards a message Reply Replies to a message ReplyAll Replies to all message recipients Save Saves the message currently in the compose buffer Send Sends a message Managing messages is the primary function of the MAPIMessages control. Composing, sending, receiving, and deleting messages are performed by using methods that correspond to these basic functions (compose, copy, delete, etc.). The following table lists the MAPIMessages methods that specifically apply to messages: To perform an action on an individual message, it must first be selected using the MsgIndex property. The message identified by the MsgIndex property is called the currently indexed message. None of the other message properties can be set until a message is selected with the MsgIndex property. The index number can range from –1 to MsgCount –1 (the MsgCount property returns the total number of messages in the message set.) When a new message is created, the value of the MsgIndex property is set to –1. Composing a Message Use the Compose method to create a new message. When the Compose method is used, the compose buffer is cleared and the MsgIndex property is set to –1. 'Compose new message
31

mpmMessage.Compose Completing a message involves several steps: determining the recipient of the message, choosing a subject title, and writing the message. Addressing the Message To set the recipient's name and address, use the RecipDisplayName and the RecipAddress properties. The RecipDisplayName is the proper name of the recipient, for example, "Richard Tull". The RecipAddress property contains the recipient's e-mail address: "richtull", for example. 'Address message mpmMessage.RecipDisplayName = "Richard Tull" mpmMessage.RecipAddress = "richtull" Addresses for recipients outside the local workgroup (a message sent to someone at another company via the Internet, for example) require a complete Internet e-mail address: "richtull@littlemag.com". Verifying the Recipient's Name The recipient's name is verified when the message is sent by checking it against the list of registered users in the e-mail system, using the ResolveName method. Name verification for recipients outside the local workgroup is handled in various ways by the underlying message system. The following example resolves the recipient's valid e-mail name by invoking the ResolveName method and setting the AddressResolveUI property to True. ' Resolve recipient name mpmMessage.AddressResolveUI = True mpmMessage.ResolveName The AddressResolveUI property can be set to either display a details dialog box (True) or generate an error (False) when an ambiguous or invalid

32

recipient address is encountered when the message is sent. The details dialog box will offer you an alternative address if a close match is found.

The Message Subject and Text The MsgSubject property specifies the subject line for the message. You may enter up to 64 characters, including the Null character. The body of the message is contained in the MsgNoteText property. For inbound messages, each paragraph is terminated with a carriage return-line feed pair (vbCrLf). Outbound messages can be delimited with a carriage return (vbCr), line feed (vbLf), or a carriage return-line feed pair. 'Create the message mpmMessage.MsgSubject = "Status Report" mpmMessage.MsgNoteText = "Build successful!" Sending the Message Managing Messages Many of the remaining properties and methods of the MAPIMessages control can be used to manage messages just as you would in a full-featured e-mail application. By accessing messages in the read buffer you can sort, delete, or forward one or a number of messages. The following table lists the properties you can use to manage messages:

Property MsgConversationID MsgCount

Description Specifies the conversation thread identification value for the currently indexed message. Returns the total number of messages present in the message set during the current messaging session.

33

MsgDateReceived MsgID MsgIndex MsgOrigAddress MsgOrigDisplayName MsgRead MsgReceiptRequested MsgSent MsgType

Returns the date on which the currently indexed message was received. Returns the string identifier of the currently indexed message. Specifies the index number of the currently indexed message. Returns the mail address of the originator of the currently indexed message. Returns the originator's name for the currently indexed message. Returns a Boolean _expression indicating whether the message has already been read. Specifies whether a return receipt is requested for the currently indexed message. Specifies whether the currently indexed message has already been sent to the mail server for distribution. Specifies the type of the currently indexed message.

To send the message, use the Send Method. The Send method allows you to send a message with or without user interaction. Setting the value to True will display the compose message dialog box of the underlying e-mail system (Microsoft Exchange, for example). Setting it to False will send the message without displaying the compose message dialog. The following example sends the message without prompting for user interaction: 'Send the message mpmMessage.Send False APPLICATIONS 2. Used to develop messaging applications. FAQS 1. What are the different methods & properties of MAPI control ?

34

Assignment No: 4 Title: HTML Page OBJECTIVES: 1. To learn & understand the basic concepts of web page designing. 2. To design web page using different types of tags. Theory: What is an HTML File?
• • • • •

HTML stands for Hyper Text Markup Language An HTML file is a text file containing small markup tags The markup tags tell the Web browser how to display the page An HTML file must have an htm or html file extension An HTML file can be created using a simple text editor

HTML Tags
• • • • • • •

HTML tags are used to mark-up HTML elements HTML tags are surrounded by the two characters < and > The surrounding characters are called angle brackets HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag The text between the start and end tags is the element content HTML tags are not case sensitive, <b> means the same as <B> HTML Text Formatting

HTML defines a lot of elements for formatting output, like bold or italic text. Text Formatting Tags Tag Description <b> Defines bold text
35

<big> <em> <i> <small> <strong> <sub> <sup> <ins> <del> <s> <strike> <u>

Defines big text Defines emphasized text Defines italic text Defines small text Defines strong text Defines subscripted text Defines superscripted text Defines inserted text Defines deleted text Deprecated. Use <del> instead Deprecated. Use <del> instead Deprecated. Use styles instead HTML Tables :

Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). The letters td stands for "table data," which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc. Table Tags Tag <table> <th> <tr> <td> <caption> <colgroup> <col> <thead> <tbody> <tfoot> Description Defines a table Defines a table header Defines a table row Defines a table cell Defines a table caption Defines groups of table columns Defines the attribute values for one or more columns in a table Defines a table head Defines a table body Defines a table footer

36

With HTML you can display images in a document. Image Tags Tag Description <img> Defines an image <map> Defines an image map <area> Defines a clickable area inside an image map HTML Forms and Input HTML Forms are used to select different kinds of user input. Forms A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form. Form Tags Tag <form> <input> <textarea> <label> <fieldset> <legend> <select> <optgroup> <option> <button> <isindex> Procedure: Design said form using required tags. Description Defines a form for user input Defines an input field Defines a text-area (a multi-line text input control) Defines a label to a control Defines a fieldset Defines a caption for a fieldset Defines a selectable list (a drop-down box) Defines an option group Defines an option in the drop-down box Defines a push button Deprecated. Use <input> instead

37

APPLICATIONS 1.Used to design the web pages for web-based applications. FAQS 1. What are the different types of tags supported by HTML ? 2. What are the different issues used to design a web page ? 3. Whether the components of a web page affects the speed of access? How ?

Assignment No: 5 Title: XML DTD & XML Schema OBJECTIVES: 1. To learn & understand XML DTD, XML Schema & XSLT. 2. To create XML DTD, XML document & XML Schema for an application. 3. Use XSLT for formatting of XML document. Theory:

38

XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks. What is XML?
• • • • • • •

XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to describe data XML tags are not predefined. You must define your own tags XML uses a Document Type Definition (DTD) or an XML Schema to describe the data XML with a DTD or XML Schema is designed to be self-descriptive XML is a W3C Recommendation How can XML be Used?

XML was designed to store, carry, and exchange data. XML was not designed to display data. XML can Separate Data from HTML XML is used to Exchange Data XML can be used to Share Data XML can be used to Store Data XML can make your Data more Useful XML can be used to Create new Languages XML Syntax The syntax rules of XML are very simple and very strict. The rules are very easy to learn, and very easy to use. Because of this, creating software that can read and manipulate XML is very easy. An example XML document XML documents use a self-describing and simple syntax. <?xml versionfiltered="1.0" encoding="ISO-8859-1"?>
39

<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <XBODY>DON'T p weekend!<xbody>< this me forget> </note> The first line in the document - the XML declaration - defines the XML version and the character encoding used in the document. In this case the document conforms to the 1.0 specification of XML and uses the ISO-88591 (Latin-1/West European) character set. The next line describes the root element of the document (like it was saying: "this document is a note"): <note> The next 4 lines describe 4 child elements of the root (to, from, heading, and body): <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <XBODY>DON'T p weekend!<xbody>< this me forget> And finally the last line defines the end of the root element: </note> Can you detect from this example that the XML document contains a Note to Tove from Jani? Don't you agree that XML is pretty self-descriptive?

40

XML Elements XML Elements are extensible and they have relationships. XML Elements have simple naming rules. XML Elements are Extensible XML documents can be extended to carry more information. Look at the following XML NOTE example: <note> <to>Tove</to> <from>Jani</from> <XBODY>DON'T p weekend!<xbody>< this me forget> </note>

How to write an XML Document? All XML elements must have a closing tag. XML tags are case sensitive. All XML elements must be properly nested.

41

All XML documents must have a root element. Attribute values must always be quoted. With XML, white space is preserved. With XML, CR / LF is converted to LF. XML documents are Extensible. XML Elements have Relationships Elements are related as parents and children. Elements have Content Elements can have different content types. An XML element is everything from (including) the element's start tag to (including) the element's end tag. An element can have element content, mixed content, simple content, or empty content. An element can also have attributes. In the example above, book has element content, because it contains other elements. Chapter has mixed content because it contains both text and other elements. Para has simple content (or text content) because it contains only text. Prod has empty content, because it carries no information. XML Attributes XML elements can have attributes in the start tag, just like HTML. Attributes are used to provide additional information about elements. Element Naming XML elements must follow these naming rules:
• • • •

Names can contain letters, numbers, and other characters Names must not start with a number or punctuation character Names must not start with the letters xml (or XML or Xml.) Names cannot contain spaces

XML DTD A DTD defines the legal elements of an XML document.

42

The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements The purpose of a Document Type Definition is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference. Internal DOCTYPE declaration If the DTD is included in your XML source file, it should be wrapped in a DOCTYPE definition with the following syntax: <!DOCTYPE root-element [element-declarations]> Example XML document with a DTD: <?xml versionfiltered="1.0"?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Tove</to> <from>Jani</from>

43

<heading>Reminder</heading> <XBODY>DON'T p this me forget weekend<xbody><> </note> The DTD above is interpreted like this: !DOCTYPE note (in line 2) defines that this is a document of the type note. !ELEMENT note (in line 3) defines the note element as having four elements: "to,from,heading,body". !ELEMENT to (in line 4) defines the to element to be of the type "#PCDATA". !ELEMENT from (in line 5) defines the from element to be of the type "#PCDATA" and so on..... External DOCTYPE declaration If the DTD is external to your XML source file, it should be wrapped in a DOCTYPE definition with the following syntax: <!DOCTYPE root-element SYSTEM "filename"> This is the same XML document as above, but with an external DTD <?xml versionfiltered="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading>

44

<XBODY>DON'T p weekend!<xbody>< this me forget> </note> And this is a copy of the file "note.dtd" containing the DTD: <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> Why use a DTD? With DTD, each of your XML files can carry a description of its own format with it. With a DTD, independent groups of people can agree to use a common DTD for interchanging data. Your application can use a standard DTD to verify that the data you receive from the outside world is valid. You can also use a DTD to verify your own data. DTD - XML building blocks The main building blocks of both XML and HTML documents are tags like <XBODY>....<XBODY>.< p> The building blocks of XML documents Seen from a DTD point of view, all XML documents (and HTML documents) are made up by the following simple building blocks:
• •

Elements Tags
45

• • • •

Attributes Entities PCDATA CDATA

The following is a brief explanation of each of the building blocks: Elements Elements are the main building blocks of both XML and HTML documents. Examples of HTML elements are "body" and "table". Examples of XML elements could be "note" and "message". Elements can contain text, other elements, or be empty. Examples of empty HTML elements are "hr", "br" and "img". Tags Tags are used to markup elements. A starting tag like <element_name> marks up the beginning of an element, and an ending tag like </element_name> marks up the end of an element. Examples: body element marked up with body tags: <XBODY>BODY p between<xbody>.< in text> message element marked up with message tags: <message>some message in between</message> Attributes Attributes provide extra information about elements. Attributes are always placed inside the starting tag of an element. Attributes always come in name/value pairs. The following "img" element has additional information about a source file:

46

<img src=http://mail.yahoo.com/config/login?/"computer.gif" /> The name of the element is "img". The name of the attribute is "src". The value of the attribute is "computer.gif". Since the element itself is empty it is closed by a " /". Entities Entities are variables used to define common text. Entity references are references to entities. Most of you will know the HTML entity reference: "&nbsp;". This "nobreaking-space" entity is used in HTML to insert an extra space in a document. Entities are expanded when an XML parser parses a document. The following entities are predefined in XML: Entity References &lt; &gt; &amp; &quot; &apos; Character < > & " '

PCDATA PCDATA means parsed character data. Think of character data as the text found between the start tag and the end tag of an XML element. PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded. CDATA CDATA also means character data.

47

CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and entities will not be expanded DTD – Elements In a DTD, XML elements are declared with a DTD element declaration. Declaring an Element In the DTD, XML elements are declared with an element declaration. An element declaration has the following syntax: <!ELEMENT element-name category> or <!ELEMENT element-name (element-content)> Empty elements Empty elements are declared with the category keyword EMPTY: <!ELEMENT element-name EMPTY> example: <!ELEMENT br EMPTY> XML example: <br /> Elements with only character data Elements with only character data are declared with #PCDATA inside parentheses: <!ELEMENT element-name (#PCDATA)> example: <!ELEMENT from (#PCDATA)>

48

Elements with any contents Elements declared with the category keyword ANY, can contain any combination of parsable data: <!ELEMENT element-name ANY> example: <!ELEMENT note ANY> Elements with children (sequences) Elements with one or more children are defined with the name of the children elements inside parentheses: <!ELEMENT element-name (child-element-name)> or <!ELEMENT element-name (child-element-name,child-element-name,.....)> example: <!ELEMENT note (to,from,heading,body)> When children are declared in a sequence separated by commas, the children must appear in the same sequence in the document. In a full declaration, the children must also be declared, and the children can also have children. The full declaration of the "note" element will be: <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)>

49

<!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> DTD - Attributes In a DTD, Attributes are declared with an ATTLIST declaration. Declaring Attributes An attribute declaration has the following syntax: <!ATTLIST element-name attribute-name attribute-type default-value> example: DTD example: <!ATTLIST payment type CDATA "check"> XML example: <payment type="check" /> The attribute-type can have the following values: Value CDATA (en1|en2|..) ID IDREF IDREFS NMTOKEN NMTOKENS ENTITY ENTITIES Explanation The value is character data The value must be one from an enumerated list The value is a unique id The value is the id of another element The value is a list of other ids The value is a valid XML name The value is a list of valid XML names The value is an entity The value is a list of entities
50

NOTATION xml:

The value is a name of a notation The value is a predefined xml value

The default-value can have the following values: Value Explanation value The default value of the attribute #REQUIRED The attribute value must be included in the element #IMPLIED The attribute does not have to be included #FIXED value The attribute value is fixed Enumerated attribute values Syntax: <!ATTLIST element-name attribute-name (en1|en2|..) default-value> DTD example: <!ATTLIST payment type (check|cash) "cash"> XML example: <payment type="check" /> or <payment type="cash" /> Use enumerated attribute values when you want the attribute values to be one of a fixed set of legal values XML Schema XML Schema is an XML based alternative to DTD. W3C supports an alternative to DTD called XML Schema. . XML Schema is an XML based alternative to DTD.
51

An XML schema describes the structure of an XML document. The XML Schema language is also referred to as XML Schema Definition (XSD). What is an XML Schema? The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD. An XML Schema:
• • • • • • • •

defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes defines default and fixed values for elements and attributes XML Schemas - Why?

There are a number of reasons why XML Schema is better than DTD. XML Schema has Support for Data Types XML Schemas use XML Syntax XML Schemas Secure Data Communication XML Schemas are Extensible Well-Formed is not Enough XSD How To XML documents can have a reference to a DTD or an XML Schema. A Simple XML Document Look at this simple XML document called "note.xml":
52

<?xml versionfiltered="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <XBODY>DON'T p weekend!<xbody>< this me forget> </note> A Simple DTD This is a simple DTD file called "note.dtd" that defines the elements of the XML document above ("note.xml"): <!ELEMENT note (to, from, heading, body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> Line 1 defines the note element to have four elements: "to, from, heading, body". Line 2-5 defines the to element to be of the type "#PCDATA", the from element to be of the type "#PCDATA", and so on... A Simple XML Schema This is a simple XML Schema file called "note.xsd" that defines the elements of the XML document above ("note.xml"): <?xml versionfiltered="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"

53

targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com" elementFormDefault="qualified"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> The note element is said to be of a complex type because it contains other elements. The other elements (to, from, heading, body) are said to be simple types because they do not contain other elements. XSD - The <schema> Element The <schema> element is the root element of every XML Schema! The <schema> Element The <schema> element is the root element of every XML Schema: <?xml versionfiltered="1.0"?>
54

<xs:schema> ... ... </xs:schema> The <schema> element may contain some attributes

XSD Elements

1. Simple Elements XML Schemas define the elements of your XML files.A simple element is an XML element that can contain only text. It cannot contain any other elements or attributes. How to Define a Simple Element The syntax for defining a simple element is: <xs:element name="xxx" type="yyy"/> where xxx is the name of the element and yyy is the data type of the element. Here are some XML elements: <lastname>Refsnes</lastname> <age>34</age> <dateborn>1968-03-27</dateborn> And here are the corresponding simple element definitions:
55

<xs:element name="lastname" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dateborn" type="xs:date"/> 2. Complex Elements A complex element contains other elements and/or attributes. What is a Complex Element? A complex element is an XML element that contains other elements and/or attributes. There are four kinds of complex elements:
• • • •

empty elements elements that contain only other elements elements that contain only text elements that contain both other elements and text

Note: Each of these elements may contain attributes as well! Examples of Complex XML Elements A complex XML element, "product", which is empty: <product pid="1345"/> A complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> A complex XML element, "food", which contains only text:

56

<food type="dessert">Ice cream</food> A complex XML element, "description", which contains both elements and text: <description> It happened on <date lang="norwegian">03.03.99</date> .... </description> How to Define a Complex Element Look at this complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> We can define a complex element in an XML Schema in different ways:. 1. The "employee" element can be declared directly by naming the element, like this: <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence>

57

</xs:complexType> </xs:element> If you use the method described above, only the "employee" element can use the specified complex type. Notice that the child elements, "firstname" and "lastname", are surrounded by the <sequence> indicator. This means that the child elements must appear in the same order as they are declared; "firstname" first and "lastname" second. 2. The "employee" element can have a type attribute that refers to the name of the complex type to use: <xs:element name="employee" type="personinfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType>

XSD Attributes All attributes are declared as simple types. Only complex elements can have attributes!

58

What is an Attribute? Simple elements cannot have attributes. If an element has attributes, it is considered to be of complex type. But the attribute itself is always declared as a simple type. This means that an element with attributes always has a complex type definition. How to Define an Attribute The syntax for defining an attribute is: <xs:attribute name="xxx" type="yyy"/> where xxx is the name of the attribute and yyy is the data type of the attribute. Here is an XML element with an attribute: <lastname lang="EN">Smith</lastname> And here is a corresponding simple attribute definition: <xs:attribute name="lang" type="xs:string"/> Common XML Schema Data Types

XML Schema has a lot of built-in data types. Here is a list of the most common types:
• • • • • •

xs:string xs:decimal xs:integer xs:boolean xs:date xs:time

59

Procedure : 1. Identify the appropriate elements for the given problem statement & write a DTD. 2. Write an XML document for the same. 3. Check the XML document for Well- Formed Documentation. 4. Validate the XML document against a DTD, against a schema & apply CSS. 5. See the XML output in a browser.

APPLICATIONS 1. Used to develop web based applications. FAQS 1. What is the different between XML & HTML ? 2. How XML is used to develop web applications? 3. Which is better XML DTD or XML schema for web development?

60

Assignment No: 6 Title: Installation of IIS/PWS/Apache server OBJECTIVES: Learn & understand IIS/PWS/Apache server. To install and configure IIS/PWS/ Apache server. Study and use various facilities/commands and features of IIS/PWS/Apache Server. Theory: Installing Personal Web Server This section concerns installing Microsoft's Personal Web Server (PWS) 4.0 on Windows 98 SE, since that's the system I had available to install and test on. PWS is also available for Windows 95 and NT. Note: If you are running Windows 2000 or Windows XP Professional you should install IIS instead of PWS. PWS is best described as a poor mans web server - it is not intended to be used in a production environment. However, it is perfect for use on your own computer, where it allows you to test your scripts before uploading to your production server or Internet Service Provider (ISP). Starting the Installation There are two places you can get PWS, both of which are free. The Windows 98 CD includes it, and you can download it from the Microsoft web site. Warning 1: Microsoft does not recommend installing PWS on Windows Me, although they admit it can if you are an "advanced user who regularly tests unsupported software configurations".

61

Warning 2: There is a fairly rare problem with MTS that may cause you problems later. Downloading from Microsoft.com If you don't have the Windows 98 CD, you can download the NT4 Option Pack which, believe it or not, contains Personal Web Server for Windows 95 and 98. Be aware that the download is 34mb, which will take nearly 3 hours to download with a 28.8 modem. To start the download, follow these steps: 1. Go to the microsoft.com web site. (clicking here opens a new window, so you can continue to read this tutorial) 2. Follow the instructions on the web site, choosing Windows 95 as the operating system even if you're running on Windows 98. 3. After the download, the installation starts - skip to step 5 below. Installing from Windows 98 CD The Windows 98 CD includes PWS, but you need to run a separate setup program to fully install and configure it. Microsoft recommends that you have at least a 90 MHz Pentium processor with 20-32 MB RAM, 40MB free disk space and a Super VGA monitor To start the installation, follow these steps: 1. Insert your Windows 98 CD in its drive. 2. Click Start and then click Run. 3. In the Run dialog box, type x:\add-ons\pws\setup.exe 4. Substitute the letter of your CD drive for x, and click OK. 5. The following screen will appear. Since we're installing PWS specifically for running ASP applications, we need to override Microsoft's recommendations, and go for the Custom button. The Typical installation doesn't include the excellent ASP documentation, so we'll ask the Setup to install it.

62

The custom installation has all the Typical components selected, so all we need to do is find the checkbox for the ASP documentation, and check it! It's 3 levels down… Highlight "Personal Web Server (PWS)", being careful not to uncheck the box, then choose "Show Subcomponents…" Second level down now, getting closer. Highlight "Documentation", again without unchecking the checkbox, then choose "Show Subcomponents Finally we arrive at the relevant page. Check the checkbox next to "Active Server Pages", then choose OK. Choose OK once more, and then Next to continue with the next step of the installation. Accept the default path, or change it - it's up to you! I recommend using the default. After waiting for the installation to complete, you'll be asked to restart your computer (but wait just a minute). When you do, you'll see something new in your system tray on the taskbar, which shows that your PWS is now up and running. Congratulations! A quick way to test it is to go to the following URL - write this down, and bookmark it in your browser later - http://localhost/iishelp. This brings up the excellent help that covers PWS and has a handy ASP reference too. Note: On some systems that URL has been reported as not working, so use the longhand version instead: http://localhost/iishelp/pws/misc/default.asp How to run ASP on Windows 98
1. An Inetpub folder will be created on your harddrive. Open it and find

the wwwroot folder. 2. Create a new folder, like "MyWeb", under wwwroot.
63

3. Use a text editor to write some ASP code, save the file as "test1.asp"

in the "MyWeb" folder. 4. Make sure your Web server is running - The installation program has added a new icon on your task bar (this is the PWS symbol). Click on the icon and press the Start button in the window that appears. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP page Installing Internet Information Services A few words before we start the guide. Windows 2000 Professional is a good operating system to run a webserver for several reasons. 1. Windows 2000 Professional is a very stable operating system. You can leave the server unattended for months at a time and not worry about system crashes and failures. 2. It's not as expensive as Windows 2000 Server or Advanced Server. A very important consideration! 3. IIS 5.0 can handle web, FTP, and email services nicely. The only drawback is that you are limited to 10 concurrent connections to your website which shouldn't be a problem for most people. 4. The webserver software is included with OS and is easy to setup. Okay, enough with the sales pitch, let's install this baby. Start -> Settings -> Control Panel -> Add/Remove Programs -> Add/Remove Windows Components Select "Internet Information Services (IIS)" then click on "Details". Some of the components you do not need, but for this example, we'll install the whole IIS package since we want the webserver, FTP server, and mail capabilities Click on "Next” The dialog box will show files being copied to your hard disk. After a few moments, you'll get this dialog box that ask you to insert the Windows 2000 CD into your CD-ROM drive. Put in the CD then click "OK".
64

The files will continue to be copied. This could take a while. When everything is done, you'll see this screen. Click on "Finish". Then all the windows close and you're left staring at your blank desktop again. In order to go configure your website, you need to go: Start -> Settings -> Control Panel -> Administrative Tools -> Internet Service Manager It would be smart to create a shortcut to "Internet Service Manager" on your desktop since this is where most of the configuration of your website takes place. The other way to manage your website is through the "Personal Web Manager". This is a scaled back version of the "Internet Service Manager" and it cannot control your FTP or mail services, so I do not recommend using it. However, it does have a cool bar graph showing how many people and connections you have to your website so that is pretty interesting. Personal Web Manager includes a nice Product Tour. The "Advanced Options" here is also much thinner than the Internet Service Manager. Double click on "Internet Service Manager" and let's get started. Click on the name of your computer to see the summary of what's going on with your computer. In my case, my computer is called "Brian" so the name I see and click on is "*brian". Since we chose to install all the IIS components, you will see the Web, FTP, and SMTP mail server all running. You can disable a particular service (Web, FTP, or SMTP) by right clicking on the service and choosing "pause" or "stop". You'll notice under "IP Address" it says "All Unassigned” This means that all requests to your server will be answered by your computer. If for some reason your server has several IP addresses, you will want to specify the exact IP address that the Internet Services is supposed to respond to.

65

If your computer only has 1 IP address, we can leave the IP address as "All Unassigned". Let's take a look at the Web Service. Right click on "Default Web Site" then select "Properties". As you explore the different tabs, you'll notice that there are several boxes and options that are grayed out. These options are only available in the Server Editions like Windows 2000 Server and Advanced Server. Since there are so many options I'll just hit the major points. Tab: Web Site Description - Can be changed to your liking IP Address - Can leave as "All unassigned" or the specific IP address of your computer. TCP Port - 80 is the standard and should remain that way unless you have a good reason to change it. Connections - Since we're using Windows 2000 Professional and not the Server Editions, we are limited to 10 concurrent web connections. Each visitor creates 2-3 connections so this means your webserver using this software is limited to 3-4 concurrent visitors which should not be a problem for a small website Tab: Performance Tab: ISAPI Filters Tab: Home Directory Local Path - This is where your files for your website reside. You can change this directory to whatever directory you like. Write - Unless you want your visitors to actually change your website, you must leave this unchecked. Directory Browsing - If you check this box, When a visitor comes to a directory that does not have a default document, the visitor will see an error message stating that they are not authorized to view the contents of that directory. If you uncheck this box, they will get a complete list of what files you have in the directory. It is best to leave the box unchecked

66

Tab: Documents There is a list of default documents that the webserver will look for when a visitor accesses a directory. The starting point of your website must be listed here. You can either rename your first page of your website to Default.htm or another defualt document type that you specify. Traditionally, the first page of most websites is "index.html" so you can add that to the list and promote it to the top using the up arrow on the left side. Tab: Directory Security Tab: HTTP Headers Tab: Custom Errors Tab: Server Extensions We can now check to see if your web service is working correctly. From your web browser from the same machine, type in the name of your computer or the IP number of your computer. This is what you should see. How run ASP on Windows 2000 An Inetpub folder will be created on your harddrive Open the Inetpub folder, and find a folder named wwwroot Create a new folder, like "MyWeb", under wwwroot. Use a text editor to write some ASP code, save the file as "test1.asp" in the "MyWeb" folder 5. Make sure your Web server is running - The installation program has added a new icon on your task bar (this is the IIS symbol). Click on the icon and press the Start button in the window that appears. 6. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP page
1. 2. 3. 4.

Install Apache 1.Run apache_2.0.55-win32-x86-no_ssl.msi. 2.Choose "I accept the terms in the license agreement", and then click Next >.
67

3.Click Next >. 4.Fill in the appropriate information. Select "for All Users, on Port 80, as a Service", and then click Next >. If you do not know what to enter, you can put in "localhost" for the network domain and server name. 5.Choose "Typical", and then click Next >. 6.Click Next >.
7. Click Install. 8. Click Finish 9. If you have Windows Firewall enabled, select Unblock on the

Windows Security Alert. For other firewalls, make sure port 80 is open.

Test: 1.Open http://localhost/ in a web browser. If you see something like the following, you’ve successfully installed Apache! 2. You'll also notice a new icon in your system tray. If you single left-click, you'll get a menu that allows you to start, stop, or restart the Apache HTTPD service. Apache stores it's configuration settings in a file called httpd.conf. This file is located at C:\Program Files\Apache Group\Apache2\conf. The file is well documented so feel free to snoop around. You can learn a lot just by looking through it. Although for this tutorial I left it alone, I usually change the default document root. This is where all of your website's files are stored. To change the document root 1. Change line 228. Notice that for Windows, you convert the backslashes to regular slashes. i.e. \ to /. 1. DocumentRoot "C:/Path to website files"
68

2. Change line 253 to match the same path as before. 1. <Directory "C:/Path to website files">

APPLICATIONS 1.Used to develop the client server applications using different technologies. FAQS 1. What is difference IIS / PWS & Apache Server? 2. How to run Apache on Windows Operating System? 3. Which is better server for web development?

cc

69

Assignment No: 8 Title: Client side Scripting OBJECTIVES: 1. To learn & understand client side validation of web page. Theory: What is JavaScript?
• • • • • •

JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a scripting language is a lightweight programming language) A JavaScript consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license

What can a JavaScript Do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

70

• •

JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer JavaScript Functions To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function. A function contains some code that will be executed only by an event or by a call to that function. You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Functions are defined at the beginning of a page, in the <head> section. Example <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!") } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" >

71

</form> </body> </html> If the line: alert("Hello world!!"), in the example above had not been written within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked. How to Define a Function The syntax for creating a function is: function functionname(var1,var2,...,varX) { some code } var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name: function functionname() { some code } Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. The return Statement The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.
72

Example The function below should return the product of two numbers (a and b): function total(a,b) { x=a*b return x } When you call the function above, you must pass along two parameters: product=total(2,3) The returned value from the total() function is 6, and it will be stored in the variable called product. Events By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events:
• • • • • •

A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke

The following table lists the events recognized by JavaScript: Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

73

onload and onUnload The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">; onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()">

74

onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"> <img src="w3schools.gif" width="100" height="30"> </a> Procedure : 1.Create an HTML form for joining report to the new class. 1. Identify the different events & write down the script with different functions. 2. Call the required functions using suitable events in the form for validation.

75

Assignment No: 9 Title: PHP Script. Problem Statement: Write a PHP Script that computes total cost of the ordered items from assignment 4, after adding sales tax. The script will show exactly what items have been ordered. Theory: PHP is a powerful tool for making dynamic and interactive Web pages. 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 (OSS) PHP is free to download and use

What is a PHP File?
• • •

PHP files may 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"

Why PHP?

PHP runs on different platforms (Windows, Linux, Unix, etc.)

76

• • •

PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side

Where to Start?
• •

Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine

Basic PHP Syntax 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> A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. 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". 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.

77

Look at the following example of an HTML form: <html> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> The example HTML page above contains two input fields and a submit button. When the user fills in this form and hits the submit button, the "welcome.php" file is called. The "welcome.php" file looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! </body> </html> A sample output of the above script may be: Welcome John. You are 28 years old! Here is how it works: The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. The $_POST contains all POST data. Note: If the method attribute of the form is GET, then the form information will be set in $_GET instead of $_POST. Procedure : 1. Write a PHP script to access the form information.

78

FAQ: What is PHP?

Assignment No: 10 Title: PHP MYSQL/Oracle. Problem Statement: Write an application that should read a SQL query from the user based on some database in say MySQL, call a PHP script to process the query and display the results. Theory:

79

ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an MS Access database). Create an ODBC Connection With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a MS Access Database:
1. 2. 3. 4. 5. 6. 7. 8.

Open the Administrative Tools icon in your Control Panel. Double-click on the Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Give the database a Data Source Name (DSN). Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use. Connecting to an ODBC The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type. The odbc_exec() function is used to execute an SQL statement. Example: The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: $conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql);
80

Retrieving Records The odbc_fetch_rows() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false. The function takes two parameters: the ODBC result identifier and an optional row number: odbc_fetch_row($rs) Retrieving Fields from a Record The odbc_result() function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name.

The code line below returns the value of the first field from the record: $compname=odbc_result($rs,1); The code line below returns the value of a field called "CompanyName": $compname=odbc_result($rs,"CompanyName"); Closing an ODBC Connection The odbc_close() function is used to close an ODBC connection. odbc_close($conn); An ODBC Example The following example shows how to first create a database connection, then a result-set, and then display the data in an HTML table. <html>

81

<body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) {exit("Connection Failed: " . $conn);} $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) {exit("Error in SQL");} echo "<table><tr>"; echo "<th>Companyname</th>"; echo "<th>Contactname</th></tr>"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "<tr><td>$compname</td>"; echo "<td>$conname</td></tr>"; } odbc_close($conn); echo "</table>"; ?> </body> </html>

What is MySQL?
• • • • •

MySQL is a small database server MySQL is ideal for small and medium applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use

PHP + MySQL

PHP combined with MySQL are cross-platform (means that you can develop in Windows and serve on a Unix platform)

82

Where to Start?
• • •

Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine

PHP and MySQL Database It is always a good practice to write the connection string for the database in a separate file and call it from each page wherever the database is required So lets first start creating a file by assigning values for the server, the database, the user name and password to variables. Let us save this file as 'conn.php'. <?php $strServer="66.9.65.200"; // Server IP Address 'or' Name $strDatabase="database name"; // Database Name $strUser="root"; // User ID $strPwd="pwd"; // Password ?> Connecting to the Server The 'mysql_connect' function is used for connecting PHP with MySQL database. It takes three arguments namely - Hostname/Server, Database username and password. This function returns a 'link identifier' when the connection is made successfully with the server. Syntax: $strDB=mysql_connect("ServerIP Address","Username","Password"); Example: $strDB=mysql_connect($strServer,$struser,$strPwd); Opening & Closing a Database connection The function ''mysql_select_db' is used for opening a database in PHP. It takes two arguments - Database name and the 'link identifier' (Optional). This function returns 'True' on success and 'False' in case of error. The

83

function 'mysql_close' is used for closing a database connection which has been opened. It takes the 'link identifier' as its argument and returns 'True' on success and 'False' on Error. Syntax: mysql_select_db("Database Name",$strDB); Example: $database=mysql_select_db("strDatabase",$strDB);

Syntax: mysql_close(Result Connection ID); Example: mysql_close($strDB); PHP Sample Code <?php include("conn.php") $strDB=mysql_connect($strServer,$struser,$strPwd); $database=mysql_select_db("$strDatabase",$strDB); // Code for database manipulation mysql_close($strDB); ?> 'conn.php' <?php $strServer="66.9.65.200"; // Server IP Address 'or' Name $strDatabase="database name"; // Database Name $strUser="root"; // User ID $strPwd="pwd"; // Password ?>

84

That's it you've learnt how to connect MySQL Database from PHP. Basic Query Commands in MySQL
• • • • • •

CREATE Command - is used to create a database/table. SELECT Command - is used to retrieve data from the database. DELETE Command - is used to delete data from the database. INSERT Command - is used to insert data into a database. UPDATE Command - is used to update the data in a table. DROP Command - is used to delete or drop the database/table.

Syntax for Query Commands CREATE Command The Create command is used to create a table by specifying the tablename, fieldnames and constraints as shown below:

Syntax: $createSQL=("CREATE TABLE tblName"); Example: $createSQL=("CREATE TABLE tblstudent(fldstudid int(10) NOTNULL AUTO_INCREMENT PRIMARY KEY,fldstudName VARCHAR(250) NOTNULL,fldstudentmark int(4) DEFAULT '0' "); SELECT Command The Select command is used to select the records from a table using its field names. To select all the fields in a table, '*' is used in the command. The result is assigned to a variable name as shown below: Syntax: $selectSQL=("SELECT field_names FROM tablename"); Example: $selectSQL=("SELECT * FROM tblstudent");

85

DELETE Command The Delete command is used to delete the records from a table using conditions as shown below: Syntax: $deleteSQL=("DELETE * FROM tablename WHERE condition"); Example: $deleteSQL=("DELETE * FROM tblstudent WHERE fldstudid=2"); INSERT Command The Insert command is used to insert records into a table. The values are assigned to the field names as shown below: Syntax: $insertSQL=("INSERT INTO tblname(fieldname1,fieldname2..) VALUES(value1,value2,...) ");

Example $insertSQL=("INSERT INTO Tblstudent(fldstudName,fldstudmark)VALUES(Baskar,75) "); UPDATE Command The Update command is used to update the field values using conditions. This is done using 'SET' and the fieldnames to assign new values to them. Syntax: $updateSQL=("UPDATE Tblname SET (fieldname1=value1,fieldname2=value2,...) WHERE fldstudid=IdNumber"); Example: $updateSQL=("UPDATE Tblstudent SET (fldstudName=siva,fldstudmark=100) WHERE fldstudid=2");
86

DROP Command The Drop command is used to delete all the records in a table using the table name as shown below: Syntax: $dropSQL=("DROP tblName"); Example $dropSQL=("DROP tblstudent"); Procedure : In database-driven applications, three different players produce the final output of the web page you view with your client: the web server, the scripting language (PHP), and the database back end (MySQL). When the client browser requests a page from your web site, the following steps occur: 1. The web server receives the request via HTTP for a particular web page and resolves and retrieves the requested file. 2. Depending on the nature of the file (i.e., if it ends in .php), it is preprocessed using, in our case, the PHP engine. 3. The script's application and presentation logic executes, performing database queries as necessary. 4. The PHP engine uses the results from the database in its application logic to construct the HTML document, returning it to the web server and, finally, the client. We will focus on steps three and four in our discussions here. Looking at those steps in more detail, we can summarize the process of accessing and working with a database connection from within a PHP script in the following steps. (The steps in parentheses are optional, depending on circumstance.)
• • • •

Establish a connection to the database server. (Validate any user input.) Select the database on the server to use. Execute the desired query against the database.
87

• • •

(Retrieve and process the results.) Create HTML or perform actions based on results. (Close the database connection.)

FAQ: 1.What is ODBC?

Assignment No: 11 Title: Echo Server Problem Statement:

88

Write a program in C/C++ to implement an ECHO server, using Socket programming with both TCP and UDP protocols. Theory: Network application software uses the socket interface. Funded by ARPA, developed at Berkeley Goal: transport TCP/IP software to Unix and develop an application-level interface. Result: Socket API in Berkeley Unix (BSD 4.2, 1983) Used a combination of existing Unix system calls and some new ones Integrated with Unix file system Implemented within the Unix kernel Eventually adapted as a standard by Unix vendors (SUN, HP, linux, etc.) and non-Unix systems (Windows, Java) Also developed early applications (telnet, ftp) Client/server model The interface is general enough to support a variety of protocols ("domains"), but on most systems, the only ones supported are: Stream sockets (TCP) Datagram sockets (UDP) Unix domain sockets (for interprocess communication on a single Unix system) raw sockets (direct access to IP packets) Once a socket connection is established, it supports symmetric, two-way communication. Conceptually, the socket is the endpoint of a communication link, similar to a telephone receiver:
89

Each process has a socket. Process 1 writes to its socket, process 2 reads from its socket Process 2 writes to its socket, process 1 reads from its socket Reading is sequential (stream) At each end, the socket appears to be two byte streams, one for reading and one for writing. It is represented by a Unix file descriptor, so normal file I/O system calls (read, write) can be used. The application designer can then design the application protocol, considering issues such as format of messages meaning of messages message sequences used to accomplish some goal (i.e., protocols) On the other hand, establishing the connection is asymmetric. Client and server have specific roles, and there are certain system calls specifically used for client or server (but not both). Establishing a connection: A server initializes itself to listen for incoming requests for connection by clients, then lies dormant until a client request arrives. The client initiates communication by sending a message to the server requesting connection, then waits for a reply. The server accepts the connection, gets a file descriptor to represent the server-side socket. The client connection request returns, passing to the client a file descriptor to represent the client-side socket. Socket-related system calls socket bind
90

listen accept connect socket: create a socket. (The created socket is not connected. This call just makes an entry in a table in the kernel.) bind: used by a server to bind a socket to an address an address consists of (host IP address, port number) common services use well-known port numbers, such as http: 80 ftp: 21 telnet: 23 listen: used by servers to make a socket into a listening socket that will listen for connection requests from clients. accept: used by servers to wait for connection requests on a listening socket. used only for sockets using a connection-oriented protocol connect: used by clients to request a connection to a remote server Note: A client must create a socket before calling connect, but does not need to bind it to a local address. The client socket is assigned to an "ephemeral" port number by the TCP/IP software. So, setting up a connection works like this: Server: Client: create socket

91

bind to local address convert to listening socket loop accept connection get request send response close connection end loop create socket request connection get reply send request get response close connection Once the connection is established, the request-response dialogue may continue repeatedly. More detail on system calls: int socket(int protofamily, // PF_INET or PF_UNIX int type, // SOCK_STREAM or SOCK_DGRAM int protocol); // IPPROTO_TCP or IPPROTO_UDP or 0 (use default) Creates a socket data structure within the Unix kernel.

92

Returns a file descriptor if successful, -1 if error. The file descriptor is used to identify the socket in subsequent calls. int connect(int socket, // file descriptor of a (local) socket struct sockaddr * saddr, // pointer to a structure containing the address of a remote socket int saddrlen); // length (in bytes) of the sockaddr struct Establishes a connection between a local socket and a remote socket. Returns 0 if OK, -1 if error. Possible errors: time out connection refused already connected bad file descriptor not a socket descriptor The sockaddr struct is very important. There is a generic version of the struct, defined as follows: struct sockaddr { u_char sa_len; // length of the struct u_char sa_family; // address family char sa_data[14]; // actual address; format depends on address family }; For internet addresses, use the address family AF_INET. A specialized struct is defined for internet addresses:

93

struct sockaddr_in { u_char sin_len; // length of the struct u_char sin_family; // address family (AF_INET) u_short sin_port; // port number struct in_addr sin_addr; // 32-bit binary IP address char sin_zero[8]; // set to zero }; Functions are supplied to generate IP addresses. int bind(int sockfd, // file descriptor for a local socket struct sockaddr * saddr, // socket address int addrlen); // length of sockaddr struct Binds a socket to an address. Returns 0 if OK, -1 if error saddr may be INADDR_ANY to bind to any local address int listen(int sockfd, // file descriptor for a local socket int backlog); // length of queue for waiting clients Makes a socket into a listening socket, establishes a queue for incoming connection requests. Returns 0 if OK, -1 if error. int accept(int sockfd, // file descriptor for a listening socket struct sockaddr * saddr, // address of local variable to be filled in with client's socket address

94

int * addrlen); // address of local variable to be filled in with length of client's socket address Accept a connection request from a client. Returns a file descriptor for data socket if OK, else -1. Also of interest are the low-level Unix system calls for reading and writing files (if you haven't seen these before): int read(int fd, // file descriptor to read char * buffer, // address of a local variable to be filled with incoming data int len); // number of bytes to read Read len bytes from fd to buffer. Return value is the number of bytes actually read, or -1 if error. int write(int fd, // file descriptor to write char * buffer, // address of a local variable containing data to be written int len); // number of bytes to write Write len bytes from buffer to fd. Return value is the number of bytes actually written, or -1 if error. Several additional system calls are available which are designed specifically for writing to and reading from sockets. int send(int fd, char * buffer, int len, int flags);

95

Equivalent to a write operation with one additional parameter. The flags parameter may be used to indicate "out-of-band" data. int recv(int fd, char * buffer, int len, int flags); Equivalent to a write operation with one additional parameter. The flags parameter may be used to indicate "out-of-band" data or a "peek" operation which reads data from the socket but does not consume it. The data is available to read by subsequent recv calls. Procedure: Procedure for UDP for client : 1. 2. 3. 4. 5. Create a socket on client side. Assign destination address & port to sockaddr_in structure. Client sends the string using Sentto function. Receive reply from echo server. Close the socket.

Procedure for UDP for server : 1. 2. 3. 4. 5. Create a socket on client side. Assign destination address & port to “sockaddr_in “structure. Server binds to the source address & port. Server receives request from client usibg recevprompt function. Sends reply to client using Send to function.

Procedure for TCP for client : 1. Create a socket on client side. Assign destination address & port to “sockaddr_in “structure. 2. Client connects to the server using “connect” function. 3. It sends message to server using ” write” function.
96

6. Receive reply from echo server using “read” function.. 7. Close the socket. Procedure for TCP for server : 6. Create a socket on client side. 7. Assign destination address & port to “sockaddr_in “structure. 8. Server binds to the source address & port. 9. Server listens client’s request using “listen” function. 10.Server will accept request from the client using “accept” function & it will create new socket for further communication between client & server. 11.Server will read the message sent by client using “read” function. 12.Sends reply to the Client using “write” function.

Assignment No: 12 Title: Linux configurations and commands. Problem Statement: Assignment to learn and understand Linux and/or Novel Netware Network configurations and commands. Theory: Details of Configuring Linux

97

TIP 1. When you need to find a particular file/directory then use the 'locate' command (on Fedora slocate works well too) to find things on your server. Like, typing: locate xinetd TIP 2. If you did not know this already, all of the web server html files for Fedora are placed under: /var/www/html Step 1. Which Processes are Running On Your Server? If you don't know, then you need to find out asap! Use the command: /sbin/chkconfig --list The output would look something like: … httpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off telnet: off … The above command will give you a long list of processes with info beside them like "off". Any process with the word "off" next to it can be assumed disabled by default during startup. You should look for your processes that are usually needed for running a webserver like httpd, telnet, wu-ftp, mysqld. All of these should be "on" by default. Step 2. Get Processes Started Starting up your webserver (httpd), mysql (mysqld), sendmail, etc. is easy so long as you follow the directions from the steps below. For your webserver and mysql, you can enable these things right away for use during this session. Change to the initialization (aka init) directory: cd /etc/rc.d/init.d/ This directory (when listed) shows all processes you can start like httpd and
98

mysqld. For now let's start our web server with the command : ./httpd start You should then see: Starting httpd: [ OK ] Now enable your webserver (httpd) for ALL future STARTUPS! 1. Edit the config files as applied to the "rc" directory of your choice. Remember that all resource files activated at different run times are in different rc.d directories. For instance, when your server is loaded at runtime level 5 (usual) then all the resources under rc5.d are activated. Change directory to: /etc/rc.d/rc5.d Remember that the rc5.d is a resource directory (under /etc) for run level 5... etc. You edit files in these directories to control what occurs at different run levels. Files with a prefix of K are NOT installed to run at startup. Files with S are ready to run at startup. Example names: K74ypserv or S14nfslock. You can always use something like the command: /sbin/chkconfig --add httpd to add the web server to the future startups. However, I prefer doing my change manually. 2. You can manually force this by simply using a command like: mv K15httpd S15httpd Summary for those needing one... You now should have your webserver started and ready as default for all future starts with:
• •

./httpd start mv k15httpd s15httpd

Step 3. What About telnet and ftp? Ok, you're smart enough to have noticed that following the steps above you

99

can not get telnet or ftp started. That's because they are not part of the initd process, but rather the xinetd process. The xinetd process handles the startup of all of your network related protocols etc. 1st Start telnet first by changing directories to xinetd: cd /etc/xinetd.d/ Next type ls to list all of the processes that can be configured. You'll notice for instance the file telnet. 2nd Edit the telnet file and change two lines: # default: on ... disabled = no These lines are not adjacent, but usually the first and last lines of the configuration file (in our case telnet). You need to edit all configuration files that apply to things you're trying to start. Many processes come by default turned off and disabled = yes. You can edit files like telnet, wu-ftp, etc. 3rd Once you have edited and saved the files with the default on and disabled = no, you can force an automatic restart of the xinetd to load without rebooting: /etc/rc.d/init.d/xinetd restart Finally, you should see: Stopping xinetd: [ OK ] Starting xinetd: [ OK ] Believe it or not, following all of this you should now have running:
• •

httpd (webserver) telnet

Now check to see what processes you have running again by using: /sbin/chkconfig –list or use the long "process" ps command like: ps -e | grep http. You can use these same steps above to get mysql and ftp running. Replace
100

httpd with mysql, and telnet with wu-ftpd. Always remember there is a difference between configuration and startup files under initd and xinetd. Hopes this helps you get going! Special thanks to John for his inspiration and to Tom for catching a typo that could have mislead readers!

All of these commands should work from your command prompt (regardless which shell you're using). Just in case some folks were not aware, you MUST press enter to invoke the command and the EX: stands for example and is not part of the command. Commands are denoted in courier type font. And of course, if they don't work or help you, we appologize! Basic Linux Commands NOTE: All of these commands should work from your command prompt (regardless which shell you're using). Command Summary Use Type cd followed by the name of a directory to access that directory. Keep in mind that you are always in a directory and allowed access to any directories hierarchically above or below. Ex: cd games Use cd to change If the directory games is not located hierarchically directories below the current directory, then the complete path must be written out. Ex: cd /usr/games To move up one directory, use the shortcut command. Ex: cd .. Typing finger allows you to see who else is on the system or get detailed information about a person who has access to the system. Use finger to see who's Type finger followed by the name of a user's on the system account to get information about that user. Or, type finger and press enter to see who's on the system and what they are doing. Ex: finger johndoe
101

Use logout to quit using the system

Use ls to list files and directories

Yep, you guessed it, typing logout will log your account out of the system. Type logout at the prompt to disconnect from your Linux machine or to logout a particular user session from the system. Keep in mind that although rudimentary, leaving your critical account logged on may be a security concern. We always recommend promptly using logout when you are finished using your root account! Ex: logout Type ls to see a list of the files and directories located in the current directory. If you’re in the directory named games and you type ls, a list will appear that contains files in the games directory and sub-directories in the games directory. Examples: ls Mail ls /usr/bin Type ls -alt to see a list of all files (including .rc files) and all directories located in the current directory. The listing will include detailed, often useful information. Examples: ls -alt ls -alt /usr/bin If the screen flies by and you miss seeing a number of files, try using the |more at the end like: ls -alt |more * In Bash (Linux shell) often the abbreviated command L is available. To get a verbose listing of files and directories you could therefore simply type: l Type man followed by a command to get detailed information about how to use the command. Ex: man ls Type man -k followed by a word to list all of the commands and descriptions that contain the word you specified. Ex: man -k finger Type more followed by the name of a text file to

Use man to pull up information about a Linux command Use more to read the

102

read the file’s contents. Why do we exmphasize using this on a "text" file? Because most other types contents of a file of files will look like garbage! Ex: more testfile.txt Type passwd and press enter. You'll see the message Changing password for yourname. At the Old password: prompt, type in your old password . Then, at the Enter new password: prompt, type in your new password . The system double checks your new password. Use passwd to change Beside the Verify: prompt, type the new password your current password and press again. Create a secure password that combines parts of words and numbers. For instance, your dog's name may be Rufus. He may have been born in 1999. Create a password that uses parts of both the name and date of birth, such as 99rufu. This is a fairly secure password and easy to remember. Type print filename . Be sure to replace the word filename with a name of a text file. Printing the file doesn’t take very long, so run over to the printer and see if it worked. Some alternative options: Want to print to a lan printer? You’ll have to refer to the network configuration section to make sure your Linux is ready for printing across the network. Of course, you could try and see what happens by holding shift and pressing Print Screen when viewing a file to see if it works. Want to print out on your own personal printer? Using the printscreen key or a screen capture command is most convenient. Type pwd and hit enter. You'll see the full name of the directory you are currently in. This is your directory path and is very handy. This is especially

Use print to print a file.

Use pwd to list the name of your current directory

103

handy when you forget which directory you’ve changed to and are trying to run other commands.

Manipulating Files Command Summary Use chmod The chmod command allows you to alter access rights to files and directories. All files and directories have security permissions that grant the user particular groups’ or all other users’ access. To view your files' settings, at the shell prompt type: ls -alt You should see some files with the following in front of them (an example follows): total 4 drwxrwsr-x 7 reallyli reallyli 1024 Apr 6 14:30 . drwxr-s--x 22 reallyli reallyli 1024 Mar 30 18:20 .. d-wx-wx-wx 3 reallyli reallyli 1024 Apr 6 14:30 content drwxr-xr-x 2 reallyli reallyli 1024 Mar 25 20:43 files What do the letters mean in front of the files/directories mean? r indicates that it is readable (someone can view the file’s contents) w indicates that it is writable (someone can edit the file’s contents) x indicates that it is executable (someone can run the file, if executable) - indicates that no permission to manipulate has been assigned When listing your files, the first character lets you know whether you’re looking at a file or a directory. It’s not part of the security settings. The next three characters indicate Your access restrictions. The next three indicate your group's permissions, and finally other users' permissions. Use chmod followed by the permission you are changing. In
104

very simple form this would be: chmod 755 filename The example above will grant you full rights, group rights to execute and read, and all others access to execute the file. # Permission 7 full 6 read and write read and 5 execute 4 read only write and 3 execute 2 write only 1 execute only 0 none Still confused? Use the table above to define the settings for the three "users." In the command, the first number refers to your permissions, the second refers to group, and the third refers to general users. Typing the command: chmod 751 filename gives you full access, the group read and execute, and all others execute only permission. cp Type cp followed by the name of an existing file and the name of the new file. Ex: cp newfile newerfile To copy a file to a different directory (without changing th e file’s name), specify the directory instead of the new filename. Ex: cp newfile testdir To copy a file to a different directory and create a new file

105

name, you need to specify a directory/a new file name. Ex: cp newfile testdir/newerfile cp newfile ../newerfile The .. represents one directory up in the hierarchy. file Type file followed by the name of an existing file in the directory. Ex: file emergency3_demo.exe OUTPUT: MS-DOS executable (EXE) This command allows you to figure out what the file type is and how to use it. For instance the command will tell you whether it is an executable, a compressed file and which type, or something unusual. This command is simplistic, but often can allow you to determine why a file does not respond the way you expect. mv Type mv followed by the current name of a file and the new name of the file. Ex: mv oldfile newfile Type mv followed by the name of a file and the new directory where you'd like to place the file. Ex: mv newfile testdir This moves the file named newfile to an existing directory named testdir. Be certain you’re specifying a directory name or the mv command alters the name of the file instead of moving it. rm Type rm followed by the name of a file to remove the file. Ex: rm newfile Use the wildcard character to remove several files at once. Ex:
106

rm n* This command removes all files beginning with n. Type rm -i followed by a filename if you’d like to be prompted before the file is actually removed. Ex: rm -i newfile rm -i n* By using this option, you have a chance to verify the removal of each file. The -i option is very handy when removing a number of files using the wildcard character *. Directory Related Commands Command Summary Use cd Use cd to change directories. Type cd followed by the name of a directory to access that directory. Keep in mind that you are always in a directory and can navigate to directories hierarchically above or below. Ex: cd games If the directory games is not located hierarchically below the current directory, then the complete path must be written out. Ex: cd /usr/games To move up one directory, use the shortcut command. Ex: cd .. Use cp -r to copy a directory and all of its contents Type cp -r followed by the name of an existing directory and the name of the new directory. Ex: cp -r testing newdir You must include the -r or you’ll see the following message: cp: testing is a directory and -r not specified. This command saves you time if you need to make a mirror image of a directory packed with files. mkdir Use mkdir to make/create a brand new directory Type mkdir followed by the name of a directory. Ex: mkdir testdir Use mv to change the name of a directory
107

mv

Type mv followed by the current name of a directory and the new name of the directory. Ex: mv testdir newnamedir Trying to find out where on your Linux server you currently are located? The pwd (print working directory) command will show you the full path to the directory you are currently in. This is very handy to use, especially when performing some of the other commands on this page! Use rmdir to remove an existing directory (assuming you have permissions set to allow this). Type rmdir followed by a directory's name to remove it. Ex: rmdir testdir You CAN'T remove a directory that contains files with this command. A more useful command is rm -r that removes directories and files within the directories. You can read more about this in Commands for Beginning Admins The rmdir command is used mostly to remove empty directories. If you have a desire to use this command then you'll need to delete or move the files before attempting to remove a full directory. For more help please read the mv command and also File Related Commands.

pwd

rmdir

Some More commands Command Summary Use The du command prints a summary of the amount of information you have stored in your directories on the mounted disks. syntax: du [options] path ex: du -a /News Options: -s print the sum of bytes in your directories -a print a line for each file in your directory
108

du

grep

Head Tail

locate

Nice Nohup

ps related to "stopped jobs"

The grep command searches text files for a particular word or string of words. Very helpful when trying to find that needle in a haystack, like a particular line in a large log file. syntax: grep textstring filename(s) ex: grep century history.text.doc head: prints the beginning of a text file tail: prints the end of a text file These commands allow you to view parts of a text file. ex: tail -5 textfile.txt The example above will print the last 5 lines of the file textfile.txt. Trying to find out where on your Linux server a particular file resides? Having a real nasty time doing it? If you have the Bash shell you can try using the locate command to identify where it is on your mounted drives. Type: locate filename and press enter. Replace filename with the name of the file you are looking for. This is a real time saving command as you start navigating your Linux server! If locate does not work for you try using which. Nice: runs programs/commands at a lower system priority Nohup: runs nice programs even when you’re logged off the system By using the two commands simultaneously, your large processes can continue to run, even when you have logged off the system and are relaxing. Ex: nice nohup c program.c . This command will allow the c compiler to compile program.c even when you have logged off the system. The ps command displays all of the existing processes. This command is also directly linked to issues with stopped processes (also known as "stopped jobs"). Occasionally, you may see the message There are
109

Stopped Jobs. If you log off the system without properly stopping your jobs, some jobs/processes may remain in memory tying up the system and drawing unnecessary processing bandwidth. Type ps and hit enter. This will list all of your current processes running, or stopped. PID TT STAT TIME COMMAND 23036 pl S 0:00 -csh 23070 pl R 0:00 vi The number under PID is the process identification number. To kill a process that is stopped, type: kill pid. Replace pid with the exact number of the process. Ex: While in Vi, you accidentally press the wrong keys. Vi's operation is stopped and you are kicked back to the prompt. To kill the stopped Vi command, you may type: kill 23070. The stty command allows you to view a listing of your current terminal options. By using this command, you can also remap keyboard keys, tailoring to your needs. Ex: stty and hit enter. This lists your terminal settings. Ex: stty erase\^h . This remaps your erase key (backspace) to the Ctrl and h keys. From now on, holding down Ctrl and pressing h will cause a backspace. So you're scratching your head asking why is this handy? You'll see at some point how stty is also used for a number of other useful settings. In order to contact someone who is on the system, at the prompt you type: talk accountname . Replace accountname with the full account name of the person. If you don’t want anyone to disturb you using the talk command, at the prompt type: mesg n. This prevents others from using talk to

stty

talk

110

tar also related to gzip

reach you. You're bound to come across files that are g-zipped and tarred. Okay, now what? These are methods of compressing and storing directories and files in a single "file." Most new Linux programs come off the web as something like coolnew-game.4-4-01.gz. This file is likely a tar file that has then been gzipped for compression. The way to handle these files is simple, but requires that you put the file into an appropriate directory. In other words, don't plop the file in your root or /bin unless it belongs there. Now you can do a one fell swoop un-gzip it and untar it into its original form (usually multiple files in many sub directories) by typing: tar -xvzf *.gz This will programmatically un-gzip and then untar all files in the current directory into their full original form including sub-directories etc. Please be careful where and how you run this! This command allows you to list all users’ and their processes who are currently logged in to the Linux server, or a particular user’s processes. Type: w to view all users’ processes. Type: w jsmith to view jsmith’s processes. We use this all the time from a system admin standpoint. Please also see more commands to get user information on this page. You need to know who logs on to your system! Okay, so you have a stand alone Linux box and no one else uses it? Try this command just to be sure. ;) Don’t waste time and energy retyping commands at the prompt. Instead, use the ! option. To automatically re-display the last command you typed at the prompt, type: !! and press enter. Press again to invoke the command. You can also automatically redisplay a command you typed earlier by using the ! and the first few letters of the command. Ex: At the Linux prompt you had typed the command clear, followed by the command pico,

w

!!

111

followed by the command ftp. In order to re-display the clear command you type: !cl and press enter. In order to re-display the last command you typed, simply type: !! . Try it out. You’ll find this a time saver when dealing with long commands. Especially commands like tar!

112

Assignment No: 13 Title: LAN Explorer & ETHREAL software Objective: To study any protocol analyzer software (eg. LanExplorer) and to learn , use its important features, Study of network monitoring software like ETHREAL software. Theory: Please refer the separate manual on LAN Explorer & ETHREAL software.

113

Assignment No: 14 Title: LAN Setup Objective: Study of existing LAN and understand the design and various components. Set up a small network of 3 to 4 computers and Hub/Switch as directed by the instructor. Use LAN Card, UTP Cables and Connectors. Install LAN Cards and Crimp the connectors. Assign unique IP addresses and share C drive on each machine. Test the network by using PING command. Use protocol analyzer Software. Theory: Please refer the separate manual on LAN Setup

114

Assignment No: 15 Title: Windows 2000/2003 server Objective: To learn and understand Windows 2003 server and it’s associated domain operations, to configure RAS and DHCP, to add users and computers to a domain Theory: Adding a computer to Active Directory Preface: Earlier, I showed you how to add users to your Active Directory domain. This tutorial will focus on how to add computers. This step is not "really" necessary for workstation computers - at least, I was able to add a Windows XP machine to my domain without adding the computer name first. This is section is really for looking at which computers join, and allow other servers to join as DC's, etc. I will show you how to add the computer using "Active Directory Users and Computers", then in other tutorials, I will demonstrate how to add a Windows 2000 computer and Windows XP computer to this domain. Update:

115

Brian Desmond (Windows Server MVP) emailed me with the following information on why someone might want to add a computer to AD manually: "By default a computer will get dumped in the Computers container, unless a Windows 2003 Native Mode Domain is inplace, and redircomp has been run to change this. Precreating computer accounts in OUs will ensure that when the unit is joined, it is in the correct OU, which guarantees policy consistency, and other administrative things. One can also specify who can reset the machine’s password. This will allow an admin to create an account for a computer, and let a normal user join the machine with their credentials." Method: 1.Click Start, highlight "Administrative Tools" and select "Active Directory Users and Computers" 2.Expand your domain name, and right-click "Computers", highlight "New" then click "Computer” 3.In this dialog we have to type the name of the computer we want to add 4 In the next dialog just click "Next", then you will see a final report of what will be added, and you can click "Finish". Adding users to Active Directory Method: 1.Click Start, highlight "Administrative Tools" and select "Active Directory Users and Computers" 2. Now, expand your domain name on the left side, and go to the bottom where it says "Users". Once you click on that, you will see all of the automatically created users, you will also see all of the users you made before you ran dcpromo - that's because they all stay through the promotion to DC. Anyway, to add a user, you can either right click the "Users" folder on the left side, or the blank area on the right side, and highlight "New" then click "User"

116

3. In the next dialog we can set the user's First name, Last name and various other pieces of information, including their log-on name, and domain to which we want to add them. 4. After clicking "Next" you are presented with the password-settings screen. You can set the user's password and then have them change it on their first log-on by selecting "User must change password at next logon". But in this tutorial, I will set it as their password, and not allow them to ever change it without asking me (the administrator) to change it for them. 5.In the next dialog, we get a summary of the user to be created. Click "Finish" and the user has been created 6. And we're finished! Now, you might want to check out the tutorial on how to add a computer to Active Directory, that will help you get the full benefits of AD. APPLICATIONS: Used as an advanced operating system.

FAQS 1. How to add users to active directory of windows 2003 Server? 2. How to add computers to active directory of windows 2003 Server

117

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.